aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim/Region/Framework/Scenes
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--OpenSim/Region/Framework/Scenes/Animation/ScenePresenceAnimator.cs19
-rw-r--r--OpenSim/Region/Framework/Scenes/CollisionSounds.cs304
-rw-r--r--OpenSim/Region/Framework/Scenes/EventManager.cs43
-rw-r--r--OpenSim/Region/Framework/Scenes/KeyframeMotion.cs766
-rw-r--r--OpenSim/Region/Framework/Scenes/Prioritizer.cs16
-rw-r--r--OpenSim/Region/Framework/Scenes/SOPMaterial.cs95
-rw-r--r--OpenSim/Region/Framework/Scenes/SOPVehicle.cs791
-rw-r--r--OpenSim/Region/Framework/Scenes/Scene.Inventory.cs348
-rw-r--r--OpenSim/Region/Framework/Scenes/Scene.PacketHandlers.cs150
-rw-r--r--OpenSim/Region/Framework/Scenes/Scene.cs685
-rw-r--r--OpenSim/Region/Framework/Scenes/SceneBase.cs3
-rw-r--r--OpenSim/Region/Framework/Scenes/SceneCommunicationService.cs32
-rw-r--r--OpenSim/Region/Framework/Scenes/SceneGraph.cs454
-rw-r--r--OpenSim/Region/Framework/Scenes/SceneManager.cs246
-rw-r--r--OpenSim/Region/Framework/Scenes/SceneObjectGroup.Inventory.cs17
-rw-r--r--OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs1429
-rw-r--r--OpenSim/Region/Framework/Scenes/SceneObjectPart.cs1480
-rw-r--r--OpenSim/Region/Framework/Scenes/SceneObjectPartInventory.cs767
-rw-r--r--OpenSim/Region/Framework/Scenes/ScenePresence.cs1099
-rw-r--r--OpenSim/Region/Framework/Scenes/Serialization/SceneObjectSerializer.cs92
-rw-r--r--OpenSim/Region/Framework/Scenes/SimStatsReporter.cs124
-rw-r--r--OpenSim/Region/Framework/Scenes/Tests/SceneObjectResizeTests.cs2
-rw-r--r--OpenSim/Region/Framework/Scenes/Tests/SceneObjectUndoRedoTests.cs184
-rw-r--r--OpenSim/Region/Framework/Scenes/Tests/SceneObjectUserGroupTests.cs3
-rw-r--r--OpenSim/Region/Framework/Scenes/UndoState.cs367
-rw-r--r--OpenSim/Region/Framework/Scenes/UuidGatherer.cs4
26 files changed, 7221 insertions, 2299 deletions
diff --git a/OpenSim/Region/Framework/Scenes/Animation/ScenePresenceAnimator.cs b/OpenSim/Region/Framework/Scenes/Animation/ScenePresenceAnimator.cs
index e92a087..65c279e 100644
--- a/OpenSim/Region/Framework/Scenes/Animation/ScenePresenceAnimator.cs
+++ b/OpenSim/Region/Framework/Scenes/Animation/ScenePresenceAnimator.cs
@@ -80,12 +80,13 @@ namespace OpenSim.Region.Framework.Scenes.Animation
80 m_scenePresence = sp; 80 m_scenePresence = sp;
81 CurrentMovementAnimation = "CROUCH"; 81 CurrentMovementAnimation = "CROUCH";
82 } 82 }
83 83
84 public void AddAnimation(UUID animID, UUID objectID) 84 public void AddAnimation(UUID animID, UUID objectID)
85 { 85 {
86 if (m_scenePresence.IsChildAgent) 86 if (m_scenePresence.IsChildAgent)
87 return; 87 return;
88 88
89 // m_log.DebugFormat("[SCENE PRESENCE ANIMATOR]: Adding animation {0} for {1}", animID, m_scenePresence.Name);
89 if (m_scenePresence.Scene.DebugAnimations) 90 if (m_scenePresence.Scene.DebugAnimations)
90 m_log.DebugFormat( 91 m_log.DebugFormat(
91 "[SCENE PRESENCE ANIMATOR]: Adding animation {0} {1} for {2}", 92 "[SCENE PRESENCE ANIMATOR]: Adding animation {0} {1} for {2}",
@@ -134,6 +135,22 @@ namespace OpenSim.Region.Framework.Scenes.Animation
134 SendAnimPack(); 135 SendAnimPack();
135 } 136 }
136 137
138 public void avnChangeAnim(UUID animID, bool addRemove, bool sendPack)
139 {
140 if (m_scenePresence.IsChildAgent)
141 return;
142
143 if (animID != UUID.Zero)
144 {
145 if (addRemove)
146 m_animations.Add(animID, m_scenePresence.ControllingClient.NextAnimationSequenceNumber, UUID.Zero);
147 else
148 m_animations.Remove(animID, true);
149 }
150 if(sendPack)
151 SendAnimPack();
152 }
153
137 // Called from scripts 154 // Called from scripts
138 public void RemoveAnimation(string name) 155 public void RemoveAnimation(string name)
139 { 156 {
diff --git a/OpenSim/Region/Framework/Scenes/CollisionSounds.cs b/OpenSim/Region/Framework/Scenes/CollisionSounds.cs
new file mode 100644
index 0000000..075724e
--- /dev/null
+++ b/OpenSim/Region/Framework/Scenes/CollisionSounds.cs
@@ -0,0 +1,304 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27// Ubit 2012
28
29using System;
30using System.Reflection;
31using System.Collections.Generic;
32using OpenMetaverse;
33using OpenSim.Framework;
34using log4net;
35
36namespace OpenSim.Region.Framework.Scenes
37{
38 public struct CollisionForSoundInfo
39 {
40 public uint colliderID;
41 public Vector3 position;
42 public float relativeVel;
43 }
44
45 public static class CollisionSounds
46 {
47 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
48
49 private const int MaxMaterials = 7;
50 // part part
51
52 private static UUID snd_StoneStone = new UUID("be7295c0-a158-11e1-b3dd-0800200c9a66");
53 private static UUID snd_StoneMetal = new UUID("be7295c0-a158-11e1-b3dd-0800201c9a66");
54 private static UUID snd_StoneGlass = new UUID("be7295c0-a158-11e1-b3dd-0800202c9a66");
55 private static UUID snd_StoneWood = new UUID("be7295c0-a158-11e1-b3dd-0800203c9a66");
56 private static UUID snd_StoneFlesh = new UUID("be7295c0-a158-11e1-b3dd-0800204c9a66");
57 private static UUID snd_StonePlastic = new UUID("be7295c0-a158-11e1-b3dd-0800205c9a66");
58 private static UUID snd_StoneRubber = new UUID("be7295c0-a158-11e1-b3dd-0800206c9a66");
59
60 private static UUID snd_MetalMetal = new UUID("be7295c0-a158-11e1-b3dd-0801201c9a66");
61 private static UUID snd_MetalGlass = new UUID("be7295c0-a158-11e1-b3dd-0801202c9a66");
62 private static UUID snd_MetalWood = new UUID("be7295c0-a158-11e1-b3dd-0801203c9a66");
63 private static UUID snd_MetalFlesh = new UUID("be7295c0-a158-11e1-b3dd-0801204c9a66");
64 private static UUID snd_MetalPlastic = new UUID("be7295c0-a158-11e1-b3dd-0801205c9a66");
65 private static UUID snd_MetalRubber = new UUID("be7295c0-a158-11e1-b3dd-0801206c9a66");
66
67 private static UUID snd_GlassGlass = new UUID("be7295c0-a158-11e1-b3dd-0802202c9a66");
68 private static UUID snd_GlassWood = new UUID("be7295c0-a158-11e1-b3dd-0802203c9a66");
69 private static UUID snd_GlassFlesh = new UUID("be7295c0-a158-11e1-b3dd-0802204c9a66");
70 private static UUID snd_GlassPlastic = new UUID("be7295c0-a158-11e1-b3dd-0802205c9a66");
71 private static UUID snd_GlassRubber = new UUID("be7295c0-a158-11e1-b3dd-0802206c9a66");
72
73 private static UUID snd_WoodWood = new UUID("be7295c0-a158-11e1-b3dd-0803203c9a66");
74 private static UUID snd_WoodFlesh = new UUID("be7295c0-a158-11e1-b3dd-0803204c9a66");
75 private static UUID snd_WoodPlastic = new UUID("be7295c0-a158-11e1-b3dd-0803205c9a66");
76 private static UUID snd_WoodRubber = new UUID("be7295c0-a158-11e1-b3dd-0803206c9a66");
77
78 private static UUID snd_FleshFlesh = new UUID("be7295c0-a158-11e1-b3dd-0804204c9a66");
79 private static UUID snd_FleshPlastic = new UUID("be7295c0-a158-11e1-b3dd-0804205c9a66");
80 private static UUID snd_FleshRubber = new UUID("be7295c0-a158-11e1-b3dd-0804206c9a66");
81
82 private static UUID snd_PlasticPlastic = new UUID("be7295c0-a158-11e1-b3dd-0805205c9a66");
83 private static UUID snd_PlasticRubber = new UUID("be7295c0-a158-11e1-b3dd-0805206c9a66");
84
85 private static UUID snd_RubberRubber = new UUID("be7295c0-a158-11e1-b3dd-0806206c9a66");
86
87 // terrain part
88 private static UUID snd_TerrainStone = new UUID("be7295c0-a158-11e1-b3dd-0807200c9a66");
89 private static UUID snd_TerrainMetal = new UUID("be7295c0-a158-11e1-b3dd-0807200c9a66");
90 private static UUID snd_TerrainGlass = new UUID("be7295c0-a158-11e1-b3dd-0807200c9a66");
91 private static UUID snd_TerrainWood = new UUID("be7295c0-a158-11e1-b3dd-0807200c9a66");
92 private static UUID snd_TerrainFlesh = new UUID("be7295c0-a158-11e1-b3dd-0807200c9a66");
93 private static UUID snd_TerrainPlastic = new UUID("be7295c0-a158-11e1-b3dd-0807200c9a66");
94 private static UUID snd_TerrainRubber = new UUID("be7295c0-a158-11e1-b3dd-0807200c9a66");
95
96 public static UUID[] m_TerrainPart = {
97 snd_TerrainStone,
98 snd_TerrainMetal,
99 snd_TerrainGlass,
100 snd_TerrainWood,
101 snd_TerrainFlesh,
102 snd_TerrainPlastic,
103 snd_TerrainRubber
104 };
105
106 // simetric sounds
107 public static UUID[] m_PartPart = {
108 snd_StoneStone, snd_StoneMetal, snd_StoneGlass, snd_StoneWood, snd_StoneFlesh, snd_StonePlastic, snd_StoneRubber,
109 snd_StoneMetal, snd_MetalMetal, snd_MetalGlass, snd_MetalWood, snd_MetalFlesh, snd_MetalPlastic, snd_MetalRubber,
110 snd_StoneGlass, snd_MetalGlass, snd_GlassGlass, snd_GlassWood, snd_GlassFlesh, snd_GlassPlastic, snd_GlassRubber,
111 snd_StoneWood, snd_MetalWood, snd_GlassWood, snd_WoodWood, snd_WoodFlesh, snd_WoodPlastic, snd_WoodRubber,
112 snd_StoneFlesh, snd_MetalFlesh, snd_GlassFlesh, snd_WoodFlesh, snd_FleshFlesh, snd_FleshPlastic, snd_FleshRubber,
113 snd_StonePlastic, snd_MetalPlastic, snd_GlassPlastic, snd_WoodPlastic, snd_FleshPlastic, snd_PlasticPlastic, snd_PlasticRubber,
114 snd_StoneRubber, snd_MetalRubber, snd_GlassRubber, snd_WoodRubber, snd_FleshRubber, snd_PlasticRubber, snd_RubberRubber
115 };
116
117 public static void PartCollisionSound(SceneObjectPart part, List<CollisionForSoundInfo> collidersinfolist)
118 {
119 if (collidersinfolist.Count == 0 || part == null)
120 return;
121
122 if (part.VolumeDetectActive || (part.Flags & PrimFlags.Physics) == 0)
123 return;
124
125 if (part.ParentGroup == null)
126 return;
127
128 if (part.CollisionSoundType < 0)
129 return;
130
131 float volume = 0.0f;
132 bool HaveSound = false;
133
134 UUID soundID = part.CollisionSound;
135
136 if (part.CollisionSoundType > 0)
137 {
138 // soundID = part.CollisionSound;
139 volume = part.CollisionSoundVolume;
140 if (volume == 0.0f)
141 return;
142 HaveSound = true;
143 }
144
145 bool doneownsound = false;
146
147 int thisMaterial = (int)part.Material;
148 if (thisMaterial >= MaxMaterials)
149 thisMaterial = 3;
150 int thisMatScaled = thisMaterial * MaxMaterials;
151
152 CollisionForSoundInfo colInfo;
153 uint id;
154
155 for(int i = 0; i< collidersinfolist.Count; i++)
156 {
157 colInfo = collidersinfolist[i];
158
159 id = colInfo.colliderID;
160 if (id == 0) // terrain collision
161 {
162 if (!doneownsound)
163 {
164 if (!HaveSound)
165 {
166 volume = Math.Abs(colInfo.relativeVel);
167 if (volume < 0.2f)
168 continue;
169
170 volume *= volume * .0625f; // 4m/s == full volume
171 if (volume > 1.0f)
172 volume = 1.0f;
173
174 soundID = m_TerrainPart[thisMaterial];
175 }
176 part.SendCollisionSound(soundID, volume, colInfo.position);
177 doneownsound = true;
178 }
179 continue;
180 }
181
182 SceneObjectPart otherPart = part.ParentGroup.Scene.GetSceneObjectPart(id);
183 if (otherPart != null)
184 {
185 if (otherPart.CollisionSoundType < 0 || otherPart.VolumeDetectActive)
186 continue;
187
188 if (!HaveSound)
189 {
190 if (otherPart.CollisionSoundType > 0)
191 {
192 soundID = otherPart.CollisionSound;
193 volume = otherPart.CollisionSoundVolume;
194 if (volume == 0.0f)
195 continue;
196 }
197 else
198 {
199 volume = Math.Abs(colInfo.relativeVel);
200 if (volume < 0.2f)
201 continue;
202
203 volume *= volume * .0625f; // 4m/s == full volume
204 if (volume > 1.0f)
205 volume = 1.0f;
206
207 int otherMaterial = (int)otherPart.Material;
208 if (otherMaterial >= MaxMaterials)
209 otherMaterial = 3;
210
211 soundID = m_PartPart[thisMatScaled + otherMaterial];
212 }
213 }
214
215 if (doneownsound)
216 otherPart.SendCollisionSound(soundID, volume, colInfo.position);
217 else
218 {
219 part.SendCollisionSound(soundID, volume, colInfo.position);
220 doneownsound = true;
221 }
222 }
223 }
224 }
225
226 public static void AvatarCollisionSound(ScenePresence av, List<CollisionForSoundInfo> collidersinfolist)
227 {
228 if (collidersinfolist.Count == 0 || av == null)
229 return;
230
231 UUID soundID;
232 int otherMaterial;
233
234 int thisMaterial = 4; // flesh
235
236 int thisMatScaled = thisMaterial * MaxMaterials;
237
238 // bool doneownsound = false;
239
240 CollisionForSoundInfo colInfo;
241 uint id;
242 float volume;
243
244 for(int i = 0; i< collidersinfolist.Count; i++)
245 {
246 colInfo = collidersinfolist[i];
247
248 id = colInfo.colliderID;
249
250 if (id == 0) // no terrain collision sounds for now
251 {
252 continue;
253// volume = Math.Abs(colInfo.relativeVel);
254// if (volume < 0.2f)
255// continue;
256
257 }
258
259 SceneObjectPart otherPart = av.Scene.GetSceneObjectPart(id);
260 if (otherPart != null)
261 {
262 if (otherPart.CollisionSoundType < 0)
263 continue;
264 if (otherPart.CollisionSoundType > 0 && otherPart.CollisionSoundVolume > 0f)
265 otherPart.SendCollisionSound(otherPart.CollisionSound, otherPart.CollisionSoundVolume, colInfo.position);
266 else
267 {
268 volume = Math.Abs(colInfo.relativeVel);
269 // Most noral collisions (running into walls, stairs)
270 // should never be heard.
271 if (volume < 3.2f)
272 continue;
273// m_log.DebugFormat("Collision speed was {0}", volume);
274
275 // Cap to 0.2 times volume because climbing stairs should not be noisy
276 // Also changed scaling
277 volume *= volume * .0125f; // 4m/s == volume 0.2
278 if (volume > 0.2f)
279 volume = 0.2f;
280 otherMaterial = (int)otherPart.Material;
281 if (otherMaterial >= MaxMaterials)
282 otherMaterial = 3;
283
284 soundID = m_PartPart[thisMatScaled + otherMaterial];
285 otherPart.SendCollisionSound(soundID, volume, colInfo.position);
286 }
287 continue;
288 }
289/*
290 else if (!doneownsound)
291 {
292 ScenePresence otherav = av.Scene.GetScenePresence(Id);
293 if (otherav != null && (!otherav.IsChildAgent))
294 {
295 soundID = snd_FleshFlesh;
296 av.SendCollisionSound(soundID, 1.0);
297 doneownsound = true;
298 }
299 }
300 */
301 }
302 }
303 }
304}
diff --git a/OpenSim/Region/Framework/Scenes/EventManager.cs b/OpenSim/Region/Framework/Scenes/EventManager.cs
index 59d0148..4733547 100644
--- a/OpenSim/Region/Framework/Scenes/EventManager.cs
+++ b/OpenSim/Region/Framework/Scenes/EventManager.cs
@@ -90,6 +90,10 @@ namespace OpenSim.Region.Framework.Scenes
90 /// </remarks> 90 /// </remarks>
91 public event OnTerrainTickDelegate OnTerrainTick; 91 public event OnTerrainTickDelegate OnTerrainTick;
92 92
93 public delegate void OnTerrainUpdateDelegate();
94
95 public event OnTerrainUpdateDelegate OnTerrainUpdate;
96
93 public delegate void OnBackupDelegate(ISimulationDataService datastore, bool forceBackup); 97 public delegate void OnBackupDelegate(ISimulationDataService datastore, bool forceBackup);
94 98
95 /// <summary> 99 /// <summary>
@@ -339,8 +343,6 @@ namespace OpenSim.Region.Framework.Scenes
339 /// in <see cref="Scene.SetScriptRunning"/> 343 /// in <see cref="Scene.SetScriptRunning"/>
340 /// via <see cref="OpenSim.Framework.IClientAPI.OnSetScriptRunning"/>, 344 /// via <see cref="OpenSim.Framework.IClientAPI.OnSetScriptRunning"/>,
341 /// via <see cref="OpenSim.Region.ClientStack.LindenUDP.HandleSetScriptRunning"/> 345 /// via <see cref="OpenSim.Region.ClientStack.LindenUDP.HandleSetScriptRunning"/>
342 /// XXX: This is only triggered when it is the client that starts the script, not in other situations where
343 /// a script is started, unlike OnStopScript!
344 /// </remarks> 346 /// </remarks>
345 public event StartScript OnStartScript; 347 public event StartScript OnStartScript;
346 348
@@ -354,7 +356,6 @@ namespace OpenSim.Region.Framework.Scenes
354 /// in <see cref="SceneObjectPartInventory.CreateScriptInstance"/>, 356 /// in <see cref="SceneObjectPartInventory.CreateScriptInstance"/>,
355 /// <see cref="SceneObjectPartInventory.StopScriptInstance"/>, 357 /// <see cref="SceneObjectPartInventory.StopScriptInstance"/>,
356 /// <see cref="Scene.SetScriptRunning"/> 358 /// <see cref="Scene.SetScriptRunning"/>
357 /// XXX: This is triggered when a sciprt is stopped for any reason, unlike OnStartScript!
358 /// </remarks> 359 /// </remarks>
359 public event StopScript OnStopScript; 360 public event StopScript OnStopScript;
360 361
@@ -842,6 +843,10 @@ namespace OpenSim.Region.Framework.Scenes
842 public event ParcelPrimCountTainted OnParcelPrimCountTainted; 843 public event ParcelPrimCountTainted OnParcelPrimCountTainted;
843 public event GetScriptRunning OnGetScriptRunning; 844 public event GetScriptRunning OnGetScriptRunning;
844 845
846 public delegate void ThrottleUpdate(ScenePresence scenePresence);
847
848 public event ThrottleUpdate OnThrottleUpdate;
849
845 /// <summary> 850 /// <summary>
846 /// RegisterCapsEvent is called by Scene after the Caps object 851 /// RegisterCapsEvent is called by Scene after the Caps object
847 /// has been instantiated and before it is return to the 852 /// has been instantiated and before it is return to the
@@ -1423,6 +1428,26 @@ namespace OpenSim.Region.Framework.Scenes
1423 } 1428 }
1424 } 1429 }
1425 } 1430 }
1431 public void TriggerTerrainUpdate()
1432 {
1433 OnTerrainUpdateDelegate handlerTerrainUpdate = OnTerrainUpdate;
1434 if (handlerTerrainUpdate != null)
1435 {
1436 foreach (OnTerrainUpdateDelegate d in handlerTerrainUpdate.GetInvocationList())
1437 {
1438 try
1439 {
1440 d();
1441 }
1442 catch (Exception e)
1443 {
1444 m_log.ErrorFormat(
1445 "[EVENT MANAGER]: Delegate for TriggerTerrainUpdate failed - continuing. {0} {1}",
1446 e.Message, e.StackTrace);
1447 }
1448 }
1449 }
1450 }
1426 1451
1427 public void TriggerTerrainTick() 1452 public void TriggerTerrainTick()
1428 { 1453 {
@@ -1755,6 +1780,7 @@ namespace OpenSim.Region.Framework.Scenes
1755 m_log.ErrorFormat( 1780 m_log.ErrorFormat(
1756 "[EVENT MANAGER]: Delegate for TriggerRemoveScript failed - continuing. {0} {1}", 1781 "[EVENT MANAGER]: Delegate for TriggerRemoveScript failed - continuing. {0} {1}",
1757 e.Message, e.StackTrace); 1782 e.Message, e.StackTrace);
1783 m_log.ErrorFormat(Environment.StackTrace);
1758 } 1784 }
1759 } 1785 }
1760 } 1786 }
@@ -3033,6 +3059,7 @@ namespace OpenSim.Region.Framework.Scenes
3033 { 3059 {
3034 foreach (Action<Scene> d in handler.GetInvocationList()) 3060 foreach (Action<Scene> d in handler.GetInvocationList())
3035 { 3061 {
3062 m_log.InfoFormat("[EVENT MANAGER]: TriggerSceneShuttingDown invoque {0}", d.Method.Name.ToString());
3036 try 3063 try
3037 { 3064 {
3038 d(s); 3065 d(s);
@@ -3045,6 +3072,7 @@ namespace OpenSim.Region.Framework.Scenes
3045 } 3072 }
3046 } 3073 }
3047 } 3074 }
3075 m_log.Info("[EVENT MANAGER]: TriggerSceneShuttingDown done");
3048 } 3076 }
3049 3077
3050 public void TriggerOnRegionStarted(Scene scene) 3078 public void TriggerOnRegionStarted(Scene scene)
@@ -3214,5 +3242,14 @@ namespace OpenSim.Region.Framework.Scenes
3214 } 3242 }
3215 } 3243 }
3216 } 3244 }
3245
3246 public void TriggerThrottleUpdate(ScenePresence scenePresence)
3247 {
3248 ThrottleUpdate handler = OnThrottleUpdate;
3249 if (handler != null)
3250 {
3251 handler(scenePresence);
3252 }
3253 }
3217 } 3254 }
3218} 3255}
diff --git a/OpenSim/Region/Framework/Scenes/KeyframeMotion.cs b/OpenSim/Region/Framework/Scenes/KeyframeMotion.cs
new file mode 100644
index 0000000..b102e48
--- /dev/null
+++ b/OpenSim/Region/Framework/Scenes/KeyframeMotion.cs
@@ -0,0 +1,766 @@
1// Proprietary code of Avination Virtual Limited
2// (c) 2012 Melanie Thielker
3//
4
5using System;
6using System.Timers;
7using System.Collections;
8using System.Collections.Generic;
9using System.IO;
10using System.Diagnostics;
11using System.Reflection;
12using System.Threading;
13using OpenMetaverse;
14using OpenSim.Framework;
15using OpenSim.Region.Framework.Interfaces;
16using OpenSim.Region.Physics.Manager;
17using OpenSim.Region.Framework.Scenes.Serialization;
18using System.Runtime.Serialization.Formatters.Binary;
19using System.Runtime.Serialization;
20using Timer = System.Timers.Timer;
21using log4net;
22
23namespace OpenSim.Region.Framework.Scenes
24{
25 public class KeyframeTimer
26 {
27 private static Dictionary<Scene, KeyframeTimer>m_timers =
28 new Dictionary<Scene, KeyframeTimer>();
29
30 private Timer m_timer;
31 private Dictionary<KeyframeMotion, object> m_motions = new Dictionary<KeyframeMotion, object>();
32 private object m_lockObject = new object();
33 private object m_timerLock = new object();
34 private const double m_tickDuration = 50.0;
35 private Scene m_scene;
36
37 public double TickDuration
38 {
39 get { return m_tickDuration; }
40 }
41
42 public KeyframeTimer(Scene scene)
43 {
44 m_timer = new Timer();
45 m_timer.Interval = TickDuration;
46 m_timer.AutoReset = true;
47 m_timer.Elapsed += OnTimer;
48
49 m_scene = scene;
50
51 m_timer.Start();
52 }
53
54 private void OnTimer(object sender, ElapsedEventArgs ea)
55 {
56 if (!Monitor.TryEnter(m_timerLock))
57 return;
58
59 try
60 {
61 List<KeyframeMotion> motions;
62
63 lock (m_lockObject)
64 {
65 motions = new List<KeyframeMotion>(m_motions.Keys);
66 }
67
68 foreach (KeyframeMotion m in motions)
69 {
70 try
71 {
72 m.OnTimer(TickDuration);
73 }
74 catch (Exception inner)
75 {
76 // Don't stop processing
77 }
78 }
79 }
80 catch (Exception e)
81 {
82 // Keep running no matter what
83 }
84 finally
85 {
86 Monitor.Exit(m_timerLock);
87 }
88 }
89
90 public static void Add(KeyframeMotion motion)
91 {
92 KeyframeTimer timer;
93
94 if (motion.Scene == null)
95 return;
96
97 lock (m_timers)
98 {
99 if (!m_timers.TryGetValue(motion.Scene, out timer))
100 {
101 timer = new KeyframeTimer(motion.Scene);
102 m_timers[motion.Scene] = timer;
103 }
104 }
105
106 lock (timer.m_lockObject)
107 {
108 timer.m_motions[motion] = null;
109 }
110 }
111
112 public static void Remove(KeyframeMotion motion)
113 {
114 KeyframeTimer timer;
115
116 if (motion.Scene == null)
117 return;
118
119 lock (m_timers)
120 {
121 if (!m_timers.TryGetValue(motion.Scene, out timer))
122 {
123 return;
124 }
125 }
126
127 lock (timer.m_lockObject)
128 {
129 timer.m_motions.Remove(motion);
130 }
131 }
132 }
133
134 [Serializable]
135 public class KeyframeMotion
136 {
137 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
138
139 public enum PlayMode : int
140 {
141 Forward = 0,
142 Reverse = 1,
143 Loop = 2,
144 PingPong = 3
145 };
146
147 [Flags]
148 public enum DataFormat : int
149 {
150 Translation = 2,
151 Rotation = 1
152 }
153
154 [Serializable]
155 public struct Keyframe
156 {
157 public Vector3? Position;
158 public Quaternion? Rotation;
159 public Quaternion StartRotation;
160 public int TimeMS;
161 public int TimeTotal;
162 public Vector3 AngularVelocity;
163 };
164
165 private Vector3 m_serializedPosition;
166 private Vector3 m_basePosition;
167 private Quaternion m_baseRotation;
168
169 private Keyframe m_currentFrame;
170
171 private List<Keyframe> m_frames = new List<Keyframe>();
172
173 private Keyframe[] m_keyframes;
174
175 // skip timer events.
176 //timer.stop doesn't assure there aren't event threads still being fired
177 [NonSerialized()]
178 private bool m_timerStopped;
179
180 [NonSerialized()]
181 private bool m_isCrossing;
182
183 [NonSerialized()]
184 private bool m_waitingCrossing;
185
186 // retry position for cross fail
187 [NonSerialized()]
188 private Vector3 m_nextPosition;
189
190 [NonSerialized()]
191 private SceneObjectGroup m_group;
192
193 private PlayMode m_mode = PlayMode.Forward;
194 private DataFormat m_data = DataFormat.Translation | DataFormat.Rotation;
195
196 private bool m_running = false;
197
198 [NonSerialized()]
199 private bool m_selected = false;
200
201 private int m_iterations = 0;
202
203 private int m_skipLoops = 0;
204
205 [NonSerialized()]
206 private Scene m_scene;
207
208 public Scene Scene
209 {
210 get { return m_scene; }
211 }
212
213 public DataFormat Data
214 {
215 get { return m_data; }
216 }
217
218 public bool Selected
219 {
220 set
221 {
222 if (m_group != null)
223 {
224 if (!value)
225 {
226 // Once we're let go, recompute positions
227 if (m_selected)
228 UpdateSceneObject(m_group);
229 }
230 else
231 {
232 // Save selection position in case we get moved
233 if (!m_selected)
234 {
235 StopTimer();
236 m_serializedPosition = m_group.AbsolutePosition;
237 }
238 }
239 }
240 m_isCrossing = false;
241 m_waitingCrossing = false;
242 m_selected = value;
243 }
244 }
245
246 private void StartTimer()
247 {
248 KeyframeTimer.Add(this);
249 m_timerStopped = false;
250 }
251
252 private void StopTimer()
253 {
254 m_timerStopped = true;
255 KeyframeTimer.Remove(this);
256 }
257
258 public static KeyframeMotion FromData(SceneObjectGroup grp, Byte[] data)
259 {
260 KeyframeMotion newMotion = null;
261
262 try
263 {
264 MemoryStream ms = new MemoryStream(data);
265 BinaryFormatter fmt = new BinaryFormatter();
266
267 newMotion = (KeyframeMotion)fmt.Deserialize(ms);
268
269 newMotion.m_group = grp;
270
271 if (grp != null)
272 {
273 newMotion.m_scene = grp.Scene;
274 if (grp.IsSelected)
275 newMotion.m_selected = true;
276 }
277
278 newMotion.m_timerStopped = false;
279 newMotion.m_running = true;
280 newMotion.m_isCrossing = false;
281 newMotion.m_waitingCrossing = false;
282 }
283 catch
284 {
285 newMotion = null;
286 }
287
288 return newMotion;
289 }
290
291 public void UpdateSceneObject(SceneObjectGroup grp)
292 {
293 m_isCrossing = false;
294 m_waitingCrossing = false;
295 StopTimer();
296
297 if (grp == null)
298 return;
299
300 m_group = grp;
301 m_scene = grp.Scene;
302
303 Vector3 grppos = grp.AbsolutePosition;
304 Vector3 offset = grppos - m_serializedPosition;
305 // avoid doing it more than once
306 // current this will happen draging a prim to other region
307 m_serializedPosition = grppos;
308
309 m_basePosition += offset;
310 m_currentFrame.Position += offset;
311
312 m_nextPosition += offset;
313
314 for (int i = 0; i < m_frames.Count; i++)
315 {
316 Keyframe k = m_frames[i];
317 k.Position += offset;
318 m_frames[i]=k;
319 }
320
321 if (m_running)
322 Start();
323 }
324
325 public KeyframeMotion(SceneObjectGroup grp, PlayMode mode, DataFormat data)
326 {
327 m_mode = mode;
328 m_data = data;
329
330 m_group = grp;
331 if (grp != null)
332 {
333 m_basePosition = grp.AbsolutePosition;
334 m_baseRotation = grp.GroupRotation;
335 m_scene = grp.Scene;
336 }
337
338 m_timerStopped = true;
339 m_isCrossing = false;
340 m_waitingCrossing = false;
341 }
342
343 public void SetKeyframes(Keyframe[] frames)
344 {
345 m_keyframes = frames;
346 }
347
348 public KeyframeMotion Copy(SceneObjectGroup newgrp)
349 {
350 StopTimer();
351
352 KeyframeMotion newmotion = new KeyframeMotion(null, m_mode, m_data);
353
354 newmotion.m_group = newgrp;
355 newmotion.m_scene = newgrp.Scene;
356
357 if (m_keyframes != null)
358 {
359 newmotion.m_keyframes = new Keyframe[m_keyframes.Length];
360 m_keyframes.CopyTo(newmotion.m_keyframes, 0);
361 }
362
363 newmotion.m_frames = new List<Keyframe>(m_frames);
364
365 newmotion.m_basePosition = m_basePosition;
366 newmotion.m_baseRotation = m_baseRotation;
367
368 if (m_selected)
369 newmotion.m_serializedPosition = m_serializedPosition;
370 else
371 {
372 if (m_group != null)
373 newmotion.m_serializedPosition = m_group.AbsolutePosition;
374 else
375 newmotion.m_serializedPosition = m_serializedPosition;
376 }
377
378 newmotion.m_currentFrame = m_currentFrame;
379
380 newmotion.m_iterations = m_iterations;
381 newmotion.m_running = m_running;
382
383 if (m_running && !m_waitingCrossing)
384 StartTimer();
385
386 return newmotion;
387 }
388
389 public void Delete()
390 {
391 m_running = false;
392 StopTimer();
393 m_isCrossing = false;
394 m_waitingCrossing = false;
395 m_frames.Clear();
396 m_keyframes = null;
397 }
398
399 public void Start()
400 {
401 m_isCrossing = false;
402 m_waitingCrossing = false;
403 if (m_keyframes != null && m_group != null && m_keyframes.Length > 0)
404 {
405 StartTimer();
406 m_running = true;
407 }
408 else
409 {
410 m_running = false;
411 StopTimer();
412 }
413 }
414
415 public void Stop()
416 {
417 m_running = false;
418 m_isCrossing = false;
419 m_waitingCrossing = false;
420
421 StopTimer();
422
423 m_basePosition = m_group.AbsolutePosition;
424 m_baseRotation = m_group.GroupRotation;
425
426 m_group.RootPart.Velocity = Vector3.Zero;
427 m_group.RootPart.AngularVelocity = Vector3.Zero;
428 m_group.SendGroupRootTerseUpdate();
429// m_group.RootPart.ScheduleTerseUpdate();
430 m_frames.Clear();
431 }
432
433 public void Pause()
434 {
435 m_running = false;
436 StopTimer();
437
438 m_group.RootPart.Velocity = Vector3.Zero;
439 m_group.RootPart.AngularVelocity = Vector3.Zero;
440 m_group.SendGroupRootTerseUpdate();
441// m_group.RootPart.ScheduleTerseUpdate();
442
443 }
444
445 private void GetNextList()
446 {
447 m_frames.Clear();
448 Vector3 pos = m_basePosition;
449 Quaternion rot = m_baseRotation;
450
451 if (m_mode == PlayMode.Loop || m_mode == PlayMode.PingPong || m_iterations == 0)
452 {
453 int direction = 1;
454 if (m_mode == PlayMode.Reverse || ((m_mode == PlayMode.PingPong) && ((m_iterations & 1) != 0)))
455 direction = -1;
456
457 int start = 0;
458 int end = m_keyframes.Length;
459
460 if (direction < 0)
461 {
462 start = m_keyframes.Length - 1;
463 end = -1;
464 }
465
466 for (int i = start; i != end ; i += direction)
467 {
468 Keyframe k = m_keyframes[i];
469
470 if (k.Position.HasValue)
471 {
472 k.Position = (k.Position * direction);
473// k.Velocity = (Vector3)k.Position / (k.TimeMS / 1000.0f);
474 k.Position += pos;
475 }
476 else
477 {
478 k.Position = pos;
479// k.Velocity = Vector3.Zero;
480 }
481
482 k.StartRotation = rot;
483 if (k.Rotation.HasValue)
484 {
485 if (direction == -1)
486 k.Rotation = Quaternion.Conjugate((Quaternion)k.Rotation);
487 k.Rotation = rot * k.Rotation;
488 }
489 else
490 {
491 k.Rotation = rot;
492 }
493
494/* ang vel not in use for now
495
496 float angle = 0;
497
498 float aa = k.StartRotation.X * k.StartRotation.X + k.StartRotation.Y * k.StartRotation.Y + k.StartRotation.Z * k.StartRotation.Z + k.StartRotation.W * k.StartRotation.W;
499 float bb = ((Quaternion)k.Rotation).X * ((Quaternion)k.Rotation).X + ((Quaternion)k.Rotation).Y * ((Quaternion)k.Rotation).Y + ((Quaternion)k.Rotation).Z * ((Quaternion)k.Rotation).Z + ((Quaternion)k.Rotation).W * ((Quaternion)k.Rotation).W;
500 float aa_bb = aa * bb;
501
502 if (aa_bb == 0)
503 {
504 angle = 0;
505 }
506 else
507 {
508 float ab = k.StartRotation.X * ((Quaternion)k.Rotation).X +
509 k.StartRotation.Y * ((Quaternion)k.Rotation).Y +
510 k.StartRotation.Z * ((Quaternion)k.Rotation).Z +
511 k.StartRotation.W * ((Quaternion)k.Rotation).W;
512 float q = (ab * ab) / aa_bb;
513
514 if (q > 1.0f)
515 {
516 angle = 0;
517 }
518 else
519 {
520 angle = (float)Math.Acos(2 * q - 1);
521 }
522 }
523
524 k.AngularVelocity = (new Vector3(0, 0, 1) * (Quaternion)k.Rotation) * (angle / (k.TimeMS / 1000));
525 */
526 k.TimeTotal = k.TimeMS;
527
528 m_frames.Add(k);
529
530 pos = (Vector3)k.Position;
531 rot = (Quaternion)k.Rotation;
532 }
533
534 m_basePosition = pos;
535 m_baseRotation = rot;
536
537 m_iterations++;
538 }
539 }
540
541 public void OnTimer(double tickDuration)
542 {
543 if (m_skipLoops > 0)
544 {
545 m_skipLoops--;
546 return;
547 }
548
549 if (m_timerStopped) // trap events still in air even after a timer.stop
550 return;
551
552 if (m_group == null)
553 return;
554
555 bool update = false;
556
557 if (m_selected)
558 {
559 if (m_group.RootPart.Velocity != Vector3.Zero)
560 {
561 m_group.RootPart.Velocity = Vector3.Zero;
562 m_group.SendGroupRootTerseUpdate();
563
564 }
565 return;
566 }
567
568 if (m_isCrossing)
569 {
570 // if crossing and timer running then cross failed
571 // wait some time then
572 // retry to set the position that evtually caused the outbound
573 // if still outside region this will call startCrossing below
574 m_isCrossing = false;
575 m_group.AbsolutePosition = m_nextPosition;
576 if (!m_isCrossing)
577 {
578 StopTimer();
579 StartTimer();
580 }
581 return;
582 }
583
584 if (m_frames.Count == 0)
585 {
586 GetNextList();
587
588 if (m_frames.Count == 0)
589 {
590 Stop();
591 Scene scene = m_group.Scene;
592
593 IScriptModule[] scriptModules = scene.RequestModuleInterfaces<IScriptModule>();
594 foreach (IScriptModule m in scriptModules)
595 {
596 if (m == null)
597 continue;
598 m.PostObjectEvent(m_group.RootPart.UUID, "moving_end", new object[0]);
599 }
600
601 return;
602 }
603
604 m_currentFrame = m_frames[0];
605 m_currentFrame.TimeMS += (int)tickDuration;
606
607 //force a update on a keyframe transition
608 update = true;
609 }
610
611 m_currentFrame.TimeMS -= (int)tickDuration;
612
613 // Do the frame processing
614 double steps = (double)m_currentFrame.TimeMS / tickDuration;
615
616 if (steps <= 0.0)
617 {
618 m_group.RootPart.Velocity = Vector3.Zero;
619 m_group.RootPart.AngularVelocity = Vector3.Zero;
620
621 m_nextPosition = (Vector3)m_currentFrame.Position;
622 m_group.AbsolutePosition = m_nextPosition;
623
624 // we are sending imediate updates, no doing force a extra terseUpdate
625 // m_group.UpdateGroupRotationR((Quaternion)m_currentFrame.Rotation);
626
627 m_group.RootPart.RotationOffset = (Quaternion)m_currentFrame.Rotation;
628 m_frames.RemoveAt(0);
629 if (m_frames.Count > 0)
630 m_currentFrame = m_frames[0];
631
632 update = true;
633 }
634 else
635 {
636 float complete = ((float)m_currentFrame.TimeTotal - (float)m_currentFrame.TimeMS) / (float)m_currentFrame.TimeTotal;
637
638 Vector3 v = (Vector3)m_currentFrame.Position - m_group.AbsolutePosition;
639 Vector3 motionThisFrame = v / (float)steps;
640 v = v * 1000 / m_currentFrame.TimeMS;
641
642 if (Vector3.Mag(motionThisFrame) >= 0.05f)
643 {
644 // m_group.AbsolutePosition += motionThisFrame;
645 m_nextPosition = m_group.AbsolutePosition + motionThisFrame;
646 m_group.AbsolutePosition = m_nextPosition;
647
648 m_group.RootPart.Velocity = v;
649 update = true;
650 }
651
652 if ((Quaternion)m_currentFrame.Rotation != m_group.GroupRotation)
653 {
654 Quaternion current = m_group.GroupRotation;
655
656 Quaternion step = Quaternion.Slerp(m_currentFrame.StartRotation, (Quaternion)m_currentFrame.Rotation, complete);
657 step.Normalize();
658/* use simpler change detection
659* float angle = 0;
660
661 float aa = current.X * current.X + current.Y * current.Y + current.Z * current.Z + current.W * current.W;
662 float bb = step.X * step.X + step.Y * step.Y + step.Z * step.Z + step.W * step.W;
663 float aa_bb = aa * bb;
664
665 if (aa_bb == 0)
666 {
667 angle = 0;
668 }
669 else
670 {
671 float ab = current.X * step.X +
672 current.Y * step.Y +
673 current.Z * step.Z +
674 current.W * step.W;
675 float q = (ab * ab) / aa_bb;
676
677 if (q > 1.0f)
678 {
679 angle = 0;
680 }
681 else
682 {
683 angle = (float)Math.Acos(2 * q - 1);
684 }
685 }
686
687 if (angle > 0.01f)
688*/
689 if(Math.Abs(step.X - current.X) > 0.001f
690 || Math.Abs(step.Y - current.Y) > 0.001f
691 || Math.Abs(step.Z - current.Z) > 0.001f)
692 // assuming w is a dependente var
693
694 {
695// m_group.UpdateGroupRotationR(step);
696 m_group.RootPart.RotationOffset = step;
697
698 //m_group.RootPart.UpdateAngularVelocity(m_currentFrame.AngularVelocity / 2);
699 update = true;
700 }
701 }
702 }
703
704 if (update)
705 {
706 m_group.SendGroupRootTerseUpdate();
707 }
708 }
709
710 public Byte[] Serialize()
711 {
712 StopTimer();
713 MemoryStream ms = new MemoryStream();
714
715 BinaryFormatter fmt = new BinaryFormatter();
716 SceneObjectGroup tmp = m_group;
717 m_group = null;
718 if (!m_selected && tmp != null)
719 m_serializedPosition = tmp.AbsolutePosition;
720 fmt.Serialize(ms, this);
721 m_group = tmp;
722 if (m_running && !m_waitingCrossing)
723 StartTimer();
724
725 return ms.ToArray();
726 }
727
728 public void StartCrossingCheck()
729 {
730 // timer will be restart by crossingFailure
731 // or never since crossing worked and this
732 // should be deleted
733 StopTimer();
734
735 m_isCrossing = true;
736 m_waitingCrossing = true;
737
738 // to remove / retune to smoth crossings
739 if (m_group.RootPart.Velocity != Vector3.Zero)
740 {
741 m_group.RootPart.Velocity = Vector3.Zero;
742 m_group.SendGroupRootTerseUpdate();
743// m_group.RootPart.ScheduleTerseUpdate();
744 }
745 }
746
747 public void CrossingFailure()
748 {
749 m_waitingCrossing = false;
750
751 if (m_group != null)
752 {
753 m_group.RootPart.Velocity = Vector3.Zero;
754 m_group.SendGroupRootTerseUpdate();
755// m_group.RootPart.ScheduleTerseUpdate();
756
757 if (m_running)
758 {
759 StopTimer();
760 m_skipLoops = 1200; // 60 seconds
761 StartTimer();
762 }
763 }
764 }
765 }
766}
diff --git a/OpenSim/Region/Framework/Scenes/Prioritizer.cs b/OpenSim/Region/Framework/Scenes/Prioritizer.cs
index 1b10e3c..ddae073 100644
--- a/OpenSim/Region/Framework/Scenes/Prioritizer.cs
+++ b/OpenSim/Region/Framework/Scenes/Prioritizer.cs
@@ -157,7 +157,7 @@ namespace OpenSim.Region.Framework.Scenes
157 157
158 private uint GetPriorityByBestAvatarResponsiveness(IClientAPI client, ISceneEntity entity) 158 private uint GetPriorityByBestAvatarResponsiveness(IClientAPI client, ISceneEntity entity)
159 { 159 {
160 uint pqueue = ComputeDistancePriority(client,entity,true); 160 uint pqueue = ComputeDistancePriority(client,entity,false);
161 161
162 ScenePresence presence = m_scene.GetScenePresence(client.AgentId); 162 ScenePresence presence = m_scene.GetScenePresence(client.AgentId);
163 if (presence != null) 163 if (presence != null)
@@ -212,9 +212,15 @@ namespace OpenSim.Region.Framework.Scenes
212 } 212 }
213 213
214 // Use the camera position for local agents and avatar position for remote agents 214 // Use the camera position for local agents and avatar position for remote agents
215 Vector3 presencePos = (presence.IsChildAgent) ? 215 // Why would I want that? They could be camming but I still see them at the
216 presence.AbsolutePosition : 216 // avatar position, so why should I update them as if they were at their
217 presence.CameraPosition; 217 // camera positions? Makes no sense!
218 // TODO: Fix this mess
219 //Vector3 presencePos = (presence.IsChildAgent) ?
220 // presence.AbsolutePosition :
221 // presence.CameraPosition;
222
223 Vector3 presencePos = presence.AbsolutePosition;
218 224
219 // Compute the distance... 225 // Compute the distance...
220 double distance = Vector3.Distance(presencePos, entityPos); 226 double distance = Vector3.Distance(presencePos, entityPos);
@@ -226,7 +232,7 @@ namespace OpenSim.Region.Framework.Scenes
226 232
227 for (int i = 0; i < queues - 1; i++) 233 for (int i = 0; i < queues - 1; i++)
228 { 234 {
229 if (distance < 10 * Math.Pow(2.0,i)) 235 if (distance < 30 * Math.Pow(2.0,i))
230 break; 236 break;
231 pqueue++; 237 pqueue++;
232 } 238 }
diff --git a/OpenSim/Region/Framework/Scenes/SOPMaterial.cs b/OpenSim/Region/Framework/Scenes/SOPMaterial.cs
new file mode 100644
index 0000000..10ac37c
--- /dev/null
+++ b/OpenSim/Region/Framework/Scenes/SOPMaterial.cs
@@ -0,0 +1,95 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections.Generic;
30using OpenMetaverse;
31using OpenSim.Framework;
32
33namespace OpenSim.Region.Framework.Scenes
34{
35 public static class SOPMaterialData
36 {
37 public enum SopMaterial : int // redundante and not in use for now
38 {
39 Stone = 0,
40 Metal = 1,
41 Glass = 2,
42 Wood = 3,
43 Flesh = 4,
44 Plastic = 5,
45 Rubber = 6,
46 light = 7 // compatibility with old viewers
47 }
48
49 private struct MaterialData
50 {
51 public float friction;
52 public float bounce;
53 public MaterialData(float f, float b)
54 {
55 friction = f;
56 bounce = b;
57 }
58 }
59
60 private static MaterialData[] m_materialdata = {
61 new MaterialData(0.8f,0.4f), // Stone
62 new MaterialData(0.3f,0.4f), // Metal
63 new MaterialData(0.2f,0.7f), // Glass
64 new MaterialData(0.6f,0.5f), // Wood
65 new MaterialData(0.9f,0.3f), // Flesh
66 new MaterialData(0.4f,0.7f), // Plastic
67 new MaterialData(0.9f,0.95f), // Rubber
68 new MaterialData(0.0f,0.0f) // light ??
69 };
70
71 public static Material MaxMaterial
72 {
73 get { return (Material)(m_materialdata.Length - 1); }
74 }
75
76 public static float friction(Material material)
77 {
78 int indx = (int)material;
79 if (indx < m_materialdata.Length)
80 return (m_materialdata[indx].friction);
81 else
82 return 0;
83 }
84
85 public static float bounce(Material material)
86 {
87 int indx = (int)material;
88 if (indx < m_materialdata.Length)
89 return (m_materialdata[indx].bounce);
90 else
91 return 0;
92 }
93
94 }
95} \ No newline at end of file
diff --git a/OpenSim/Region/Framework/Scenes/SOPVehicle.cs b/OpenSim/Region/Framework/Scenes/SOPVehicle.cs
new file mode 100644
index 0000000..9cb901a
--- /dev/null
+++ b/OpenSim/Region/Framework/Scenes/SOPVehicle.cs
@@ -0,0 +1,791 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections.Generic;
30using OpenMetaverse;
31using OpenSim.Framework;
32using OpenSim.Region.Physics.Manager;
33using System.Text;
34using System.IO;
35using System.Xml;
36using OpenSim.Framework.Serialization;
37using OpenSim.Framework.Serialization.External;
38using OpenSim.Region.Framework.Scenes.Serialization;
39
40namespace OpenSim.Region.Framework.Scenes
41{
42 public class SOPVehicle
43 {
44 public VehicleData vd;
45
46 public Vehicle Type
47 {
48 get { return vd.m_type; }
49 }
50
51 public SOPVehicle()
52 {
53 vd = new VehicleData();
54 ProcessTypeChange(Vehicle.TYPE_NONE); // is needed?
55 }
56
57 public void ProcessFloatVehicleParam(Vehicle pParam, float pValue)
58 {
59 float len;
60 float timestep = 0.01f;
61 switch (pParam)
62 {
63 case Vehicle.ANGULAR_DEFLECTION_EFFICIENCY:
64 if (pValue < 0f) pValue = 0f;
65 if (pValue > 1f) pValue = 1f;
66 vd.m_angularDeflectionEfficiency = pValue;
67 break;
68 case Vehicle.ANGULAR_DEFLECTION_TIMESCALE:
69 if (pValue < timestep) pValue = timestep;
70 vd.m_angularDeflectionTimescale = pValue;
71 break;
72 case Vehicle.ANGULAR_MOTOR_DECAY_TIMESCALE:
73 if (pValue < timestep) pValue = timestep;
74 else if (pValue > 120) pValue = 120;
75 vd.m_angularMotorDecayTimescale = pValue;
76 break;
77 case Vehicle.ANGULAR_MOTOR_TIMESCALE:
78 if (pValue < timestep) pValue = timestep;
79 vd.m_angularMotorTimescale = pValue;
80 break;
81 case Vehicle.BANKING_EFFICIENCY:
82 if (pValue < -1f) pValue = -1f;
83 if (pValue > 1f) pValue = 1f;
84 vd.m_bankingEfficiency = pValue;
85 break;
86 case Vehicle.BANKING_MIX:
87 if (pValue < 0f) pValue = 0f;
88 if (pValue > 1f) pValue = 1f;
89 vd.m_bankingMix = pValue;
90 break;
91 case Vehicle.BANKING_TIMESCALE:
92 if (pValue < timestep) pValue = timestep;
93 vd.m_bankingTimescale = pValue;
94 break;
95 case Vehicle.BUOYANCY:
96 if (pValue < -1f) pValue = -1f;
97 if (pValue > 1f) pValue = 1f;
98 vd.m_VehicleBuoyancy = pValue;
99 break;
100 case Vehicle.HOVER_EFFICIENCY:
101 if (pValue < 0f) pValue = 0f;
102 if (pValue > 1f) pValue = 1f;
103 vd.m_VhoverEfficiency = pValue;
104 break;
105 case Vehicle.HOVER_HEIGHT:
106 vd.m_VhoverHeight = pValue;
107 break;
108 case Vehicle.HOVER_TIMESCALE:
109 if (pValue < timestep) pValue = timestep;
110 vd.m_VhoverTimescale = pValue;
111 break;
112 case Vehicle.LINEAR_DEFLECTION_EFFICIENCY:
113 if (pValue < 0f) pValue = 0f;
114 if (pValue > 1f) pValue = 1f;
115 vd.m_linearDeflectionEfficiency = pValue;
116 break;
117 case Vehicle.LINEAR_DEFLECTION_TIMESCALE:
118 if (pValue < timestep) pValue = timestep;
119 vd.m_linearDeflectionTimescale = pValue;
120 break;
121 case Vehicle.LINEAR_MOTOR_DECAY_TIMESCALE:
122 if (pValue < timestep) pValue = timestep;
123 else if (pValue > 120) pValue = 120;
124 vd.m_linearMotorDecayTimescale = pValue;
125 break;
126 case Vehicle.LINEAR_MOTOR_TIMESCALE:
127 if (pValue < timestep) pValue = timestep;
128 vd.m_linearMotorTimescale = pValue;
129 break;
130 case Vehicle.VERTICAL_ATTRACTION_EFFICIENCY:
131 if (pValue < 0f) pValue = 0f;
132 if (pValue > 1f) pValue = 1f;
133 vd.m_verticalAttractionEfficiency = pValue;
134 break;
135 case Vehicle.VERTICAL_ATTRACTION_TIMESCALE:
136 if (pValue < timestep) pValue = timestep;
137 vd.m_verticalAttractionTimescale = pValue;
138 break;
139
140 // These are vector properties but the engine lets you use a single float value to
141 // set all of the components to the same value
142 case Vehicle.ANGULAR_FRICTION_TIMESCALE:
143 if (pValue < timestep) pValue = timestep;
144 vd.m_angularFrictionTimescale = new Vector3(pValue, pValue, pValue);
145 break;
146 case Vehicle.ANGULAR_MOTOR_DIRECTION:
147 vd.m_angularMotorDirection = new Vector3(pValue, pValue, pValue);
148 len = vd.m_angularMotorDirection.Length();
149 if (len > 12.566f)
150 vd.m_angularMotorDirection *= (12.566f / len);
151 break;
152 case Vehicle.LINEAR_FRICTION_TIMESCALE:
153 if (pValue < timestep) pValue = timestep;
154 vd.m_linearFrictionTimescale = new Vector3(pValue, pValue, pValue);
155 break;
156 case Vehicle.LINEAR_MOTOR_DIRECTION:
157 vd.m_linearMotorDirection = new Vector3(pValue, pValue, pValue);
158 len = vd.m_linearMotorDirection.Length();
159 if (len > 30.0f)
160 vd.m_linearMotorDirection *= (30.0f / len);
161 break;
162 case Vehicle.LINEAR_MOTOR_OFFSET:
163 vd.m_linearMotorOffset = new Vector3(pValue, pValue, pValue);
164 len = vd.m_linearMotorOffset.Length();
165 if (len > 100.0f)
166 vd.m_linearMotorOffset *= (100.0f / len);
167 break;
168 }
169 }//end ProcessFloatVehicleParam
170
171 public void ProcessVectorVehicleParam(Vehicle pParam, Vector3 pValue)
172 {
173 float len;
174 float timestep = 0.01f;
175 switch (pParam)
176 {
177 case Vehicle.ANGULAR_FRICTION_TIMESCALE:
178 if (pValue.X < timestep) pValue.X = timestep;
179 if (pValue.Y < timestep) pValue.Y = timestep;
180 if (pValue.Z < timestep) pValue.Z = timestep;
181
182 vd.m_angularFrictionTimescale = new Vector3(pValue.X, pValue.Y, pValue.Z);
183 break;
184 case Vehicle.ANGULAR_MOTOR_DIRECTION:
185 vd.m_angularMotorDirection = new Vector3(pValue.X, pValue.Y, pValue.Z);
186 // Limit requested angular speed to 2 rps= 4 pi rads/sec
187 len = vd.m_angularMotorDirection.Length();
188 if (len > 12.566f)
189 vd.m_angularMotorDirection *= (12.566f / len);
190 break;
191 case Vehicle.LINEAR_FRICTION_TIMESCALE:
192 if (pValue.X < timestep) pValue.X = timestep;
193 if (pValue.Y < timestep) pValue.Y = timestep;
194 if (pValue.Z < timestep) pValue.Z = timestep;
195 vd.m_linearFrictionTimescale = new Vector3(pValue.X, pValue.Y, pValue.Z);
196 break;
197 case Vehicle.LINEAR_MOTOR_DIRECTION:
198 vd.m_linearMotorDirection = new Vector3(pValue.X, pValue.Y, pValue.Z);
199 len = vd.m_linearMotorDirection.Length();
200 if (len > 30.0f)
201 vd.m_linearMotorDirection *= (30.0f / len);
202 break;
203 case Vehicle.LINEAR_MOTOR_OFFSET:
204 vd.m_linearMotorOffset = new Vector3(pValue.X, pValue.Y, pValue.Z);
205 len = vd.m_linearMotorOffset.Length();
206 if (len > 100.0f)
207 vd.m_linearMotorOffset *= (100.0f / len);
208 break;
209 }
210 }//end ProcessVectorVehicleParam
211
212 public void ProcessRotationVehicleParam(Vehicle pParam, Quaternion pValue)
213 {
214 switch (pParam)
215 {
216 case Vehicle.REFERENCE_FRAME:
217 vd.m_referenceFrame = pValue;
218 break;
219 }
220 }//end ProcessRotationVehicleParam
221
222 public void ProcessVehicleFlags(int pParam, bool remove)
223 {
224 if (remove)
225 {
226 vd.m_flags &= ~((VehicleFlag)pParam);
227 }
228 else
229 {
230 vd.m_flags |= (VehicleFlag)pParam;
231 }
232 }//end ProcessVehicleFlags
233
234 public void ProcessTypeChange(Vehicle pType)
235 {
236 vd.m_linearMotorDirection = Vector3.Zero;
237 vd.m_angularMotorDirection = Vector3.Zero;
238 vd.m_linearMotorOffset = Vector3.Zero;
239 vd.m_referenceFrame = Quaternion.Identity;
240
241 // Set Defaults For Type
242 vd.m_type = pType;
243 switch (pType)
244 {
245 case Vehicle.TYPE_NONE:
246 vd.m_linearFrictionTimescale = new Vector3(1000, 1000, 1000);
247 vd.m_angularFrictionTimescale = new Vector3(1000, 1000, 1000);
248 vd.m_linearMotorTimescale = 1000;
249 vd.m_linearMotorDecayTimescale = 120;
250 vd.m_angularMotorTimescale = 1000;
251 vd.m_angularMotorDecayTimescale = 1000;
252 vd.m_VhoverHeight = 0;
253 vd.m_VhoverEfficiency = 1;
254 vd.m_VhoverTimescale = 1000;
255 vd.m_VehicleBuoyancy = 0;
256 vd.m_linearDeflectionEfficiency = 0;
257 vd.m_linearDeflectionTimescale = 1000;
258 vd.m_angularDeflectionEfficiency = 0;
259 vd.m_angularDeflectionTimescale = 1000;
260 vd.m_bankingEfficiency = 0;
261 vd.m_bankingMix = 1;
262 vd.m_bankingTimescale = 1000;
263 vd.m_verticalAttractionEfficiency = 0;
264 vd.m_verticalAttractionTimescale = 1000;
265
266 vd.m_flags = (VehicleFlag)0;
267 break;
268
269 case Vehicle.TYPE_SLED:
270 vd.m_linearFrictionTimescale = new Vector3(30, 1, 1000);
271 vd.m_angularFrictionTimescale = new Vector3(1000, 1000, 1000);
272 vd.m_linearMotorTimescale = 1000;
273 vd.m_linearMotorDecayTimescale = 120;
274 vd.m_angularMotorTimescale = 1000;
275 vd.m_angularMotorDecayTimescale = 120;
276 vd.m_VhoverHeight = 0;
277 vd.m_VhoverEfficiency = 1;
278 vd.m_VhoverTimescale = 10;
279 vd.m_VehicleBuoyancy = 0;
280 vd.m_linearDeflectionEfficiency = 1;
281 vd.m_linearDeflectionTimescale = 1;
282 vd.m_angularDeflectionEfficiency = 0;
283 vd.m_angularDeflectionTimescale = 1000;
284 vd.m_bankingEfficiency = 0;
285 vd.m_bankingMix = 1;
286 vd.m_bankingTimescale = 10;
287 vd.m_flags &=
288 ~(VehicleFlag.HOVER_WATER_ONLY | VehicleFlag.HOVER_TERRAIN_ONLY |
289 VehicleFlag.HOVER_GLOBAL_HEIGHT | VehicleFlag.HOVER_UP_ONLY);
290 vd.m_flags |= (VehicleFlag.NO_DEFLECTION_UP | VehicleFlag.LIMIT_ROLL_ONLY | VehicleFlag.LIMIT_MOTOR_UP);
291 break;
292 case Vehicle.TYPE_CAR:
293 vd.m_linearFrictionTimescale = new Vector3(100, 2, 1000);
294 vd.m_angularFrictionTimescale = new Vector3(1000, 1000, 1000);
295 vd.m_linearMotorTimescale = 1;
296 vd.m_linearMotorDecayTimescale = 60;
297 vd.m_angularMotorTimescale = 1;
298 vd.m_angularMotorDecayTimescale = 0.8f;
299 vd.m_VhoverHeight = 0;
300 vd.m_VhoverEfficiency = 0;
301 vd.m_VhoverTimescale = 1000;
302 vd.m_VehicleBuoyancy = 0;
303 vd.m_linearDeflectionEfficiency = 1;
304 vd.m_linearDeflectionTimescale = 2;
305 vd.m_angularDeflectionEfficiency = 0;
306 vd.m_angularDeflectionTimescale = 10;
307 vd.m_verticalAttractionEfficiency = 1f;
308 vd.m_verticalAttractionTimescale = 10f;
309 vd.m_bankingEfficiency = -0.2f;
310 vd.m_bankingMix = 1;
311 vd.m_bankingTimescale = 1;
312 vd.m_flags &= ~(VehicleFlag.HOVER_WATER_ONLY | VehicleFlag.HOVER_TERRAIN_ONLY | VehicleFlag.HOVER_GLOBAL_HEIGHT);
313 vd.m_flags |= (VehicleFlag.NO_DEFLECTION_UP | VehicleFlag.LIMIT_ROLL_ONLY |
314 VehicleFlag.LIMIT_MOTOR_UP | VehicleFlag.HOVER_UP_ONLY);
315 break;
316 case Vehicle.TYPE_BOAT:
317 vd.m_linearFrictionTimescale = new Vector3(10, 3, 2);
318 vd.m_angularFrictionTimescale = new Vector3(10, 10, 10);
319 vd.m_linearMotorTimescale = 5;
320 vd.m_linearMotorDecayTimescale = 60;
321 vd.m_angularMotorTimescale = 4;
322 vd.m_angularMotorDecayTimescale = 4;
323 vd.m_VhoverHeight = 0;
324 vd.m_VhoverEfficiency = 0.5f;
325 vd.m_VhoverTimescale = 2;
326 vd.m_VehicleBuoyancy = 1;
327 vd.m_linearDeflectionEfficiency = 0.5f;
328 vd.m_linearDeflectionTimescale = 3;
329 vd.m_angularDeflectionEfficiency = 0.5f;
330 vd.m_angularDeflectionTimescale = 5;
331 vd.m_verticalAttractionEfficiency = 0.5f;
332 vd.m_verticalAttractionTimescale = 5f;
333 vd.m_bankingEfficiency = -0.3f;
334 vd.m_bankingMix = 0.8f;
335 vd.m_bankingTimescale = 1;
336 vd.m_flags &= ~(VehicleFlag.HOVER_TERRAIN_ONLY |
337 VehicleFlag.HOVER_GLOBAL_HEIGHT |
338 VehicleFlag.HOVER_UP_ONLY |
339 VehicleFlag.LIMIT_ROLL_ONLY);
340 vd.m_flags |= (VehicleFlag.NO_DEFLECTION_UP |
341 VehicleFlag.LIMIT_MOTOR_UP |
342 VehicleFlag.HOVER_WATER_ONLY);
343 break;
344 case Vehicle.TYPE_AIRPLANE:
345 vd.m_linearFrictionTimescale = new Vector3(200, 10, 5);
346 vd.m_angularFrictionTimescale = new Vector3(20, 20, 20);
347 vd.m_linearMotorTimescale = 2;
348 vd.m_linearMotorDecayTimescale = 60;
349 vd.m_angularMotorTimescale = 4;
350 vd.m_angularMotorDecayTimescale = 8;
351 vd.m_VhoverHeight = 0;
352 vd.m_VhoverEfficiency = 0.5f;
353 vd.m_VhoverTimescale = 1000;
354 vd.m_VehicleBuoyancy = 0;
355 vd.m_linearDeflectionEfficiency = 0.5f;
356 vd.m_linearDeflectionTimescale = 0.5f;
357 vd.m_angularDeflectionEfficiency = 1;
358 vd.m_angularDeflectionTimescale = 2;
359 vd.m_verticalAttractionEfficiency = 0.9f;
360 vd.m_verticalAttractionTimescale = 2f;
361 vd.m_bankingEfficiency = 1;
362 vd.m_bankingMix = 0.7f;
363 vd.m_bankingTimescale = 2;
364 vd.m_flags &= ~(VehicleFlag.HOVER_WATER_ONLY |
365 VehicleFlag.HOVER_TERRAIN_ONLY |
366 VehicleFlag.HOVER_GLOBAL_HEIGHT |
367 VehicleFlag.HOVER_UP_ONLY |
368 VehicleFlag.NO_DEFLECTION_UP |
369 VehicleFlag.LIMIT_MOTOR_UP);
370 vd.m_flags |= (VehicleFlag.LIMIT_ROLL_ONLY);
371 break;
372 case Vehicle.TYPE_BALLOON:
373 vd.m_linearFrictionTimescale = new Vector3(5, 5, 5);
374 vd.m_angularFrictionTimescale = new Vector3(10, 10, 10);
375 vd.m_linearMotorTimescale = 5;
376 vd.m_linearMotorDecayTimescale = 60;
377 vd.m_angularMotorTimescale = 6;
378 vd.m_angularMotorDecayTimescale = 10;
379 vd.m_VhoverHeight = 5;
380 vd.m_VhoverEfficiency = 0.8f;
381 vd.m_VhoverTimescale = 10;
382 vd.m_VehicleBuoyancy = 1;
383 vd.m_linearDeflectionEfficiency = 0;
384 vd.m_linearDeflectionTimescale = 5;
385 vd.m_angularDeflectionEfficiency = 0;
386 vd.m_angularDeflectionTimescale = 5;
387 vd.m_verticalAttractionEfficiency = 0f;
388 vd.m_verticalAttractionTimescale = 1000f;
389 vd.m_bankingEfficiency = 0;
390 vd.m_bankingMix = 0.7f;
391 vd.m_bankingTimescale = 5;
392 vd.m_flags &= ~(VehicleFlag.HOVER_WATER_ONLY |
393 VehicleFlag.HOVER_TERRAIN_ONLY |
394 VehicleFlag.HOVER_UP_ONLY |
395 VehicleFlag.NO_DEFLECTION_UP |
396 VehicleFlag.LIMIT_MOTOR_UP);
397 vd.m_flags |= (VehicleFlag.LIMIT_ROLL_ONLY |
398 VehicleFlag.HOVER_GLOBAL_HEIGHT);
399 break;
400 }
401 }
402 public void SetVehicle(PhysicsActor ph)
403 {
404 if (ph == null)
405 return;
406 ph.SetVehicle(vd);
407 }
408
409 private XmlTextWriter writer;
410
411 private void XWint(string name, int i)
412 {
413 writer.WriteElementString(name, i.ToString());
414 }
415
416 private void XWfloat(string name, float f)
417 {
418 writer.WriteElementString(name, f.ToString(Utils.EnUsCulture));
419 }
420
421 private void XWVector(string name, Vector3 vec)
422 {
423 writer.WriteStartElement(name);
424 writer.WriteElementString("X", vec.X.ToString(Utils.EnUsCulture));
425 writer.WriteElementString("Y", vec.Y.ToString(Utils.EnUsCulture));
426 writer.WriteElementString("Z", vec.Z.ToString(Utils.EnUsCulture));
427 writer.WriteEndElement();
428 }
429
430 private void XWQuat(string name, Quaternion quat)
431 {
432 writer.WriteStartElement(name);
433 writer.WriteElementString("X", quat.X.ToString(Utils.EnUsCulture));
434 writer.WriteElementString("Y", quat.Y.ToString(Utils.EnUsCulture));
435 writer.WriteElementString("Z", quat.Z.ToString(Utils.EnUsCulture));
436 writer.WriteElementString("W", quat.W.ToString(Utils.EnUsCulture));
437 writer.WriteEndElement();
438 }
439
440 public void ToXml2(XmlTextWriter twriter)
441 {
442 writer = twriter;
443 writer.WriteStartElement("Vehicle");
444
445 XWint("TYPE", (int)vd.m_type);
446 XWint("FLAGS", (int)vd.m_flags);
447
448 // Linear properties
449 XWVector("LMDIR", vd.m_linearMotorDirection);
450 XWVector("LMFTIME", vd.m_linearFrictionTimescale);
451 XWfloat("LMDTIME", vd.m_linearMotorDecayTimescale);
452 XWfloat("LMTIME", vd.m_linearMotorTimescale);
453 XWVector("LMOFF", vd.m_linearMotorOffset);
454
455 //Angular properties
456 XWVector("AMDIR", vd.m_angularMotorDirection);
457 XWfloat("AMTIME", vd.m_angularMotorTimescale);
458 XWfloat("AMDTIME", vd.m_angularMotorDecayTimescale);
459 XWVector("AMFTIME", vd.m_angularFrictionTimescale);
460
461 //Deflection properties
462 XWfloat("ADEFF", vd.m_angularDeflectionEfficiency);
463 XWfloat("ADTIME", vd.m_angularDeflectionTimescale);
464 XWfloat("LDEFF", vd.m_linearDeflectionEfficiency);
465 XWfloat("LDTIME", vd.m_linearDeflectionTimescale);
466
467 //Banking properties
468 XWfloat("BEFF", vd.m_bankingEfficiency);
469 XWfloat("BMIX", vd.m_bankingMix);
470 XWfloat("BTIME", vd.m_bankingTimescale);
471
472 //Hover and Buoyancy properties
473 XWfloat("HHEI", vd.m_VhoverHeight);
474 XWfloat("HEFF", vd.m_VhoverEfficiency);
475 XWfloat("HTIME", vd.m_VhoverTimescale);
476 XWfloat("VBUO", vd.m_VehicleBuoyancy);
477
478 //Attractor properties
479 XWfloat("VAEFF", vd.m_verticalAttractionEfficiency);
480 XWfloat("VATIME", vd.m_verticalAttractionTimescale);
481
482 XWQuat("REF_FRAME", vd.m_referenceFrame);
483
484 writer.WriteEndElement();
485 writer = null;
486 }
487
488
489
490 XmlTextReader reader;
491
492 private int XRint()
493 {
494 return reader.ReadElementContentAsInt();
495 }
496
497 private float XRfloat()
498 {
499 return reader.ReadElementContentAsFloat();
500 }
501
502 public Vector3 XRvector()
503 {
504 Vector3 vec;
505 reader.ReadStartElement();
506 vec.X = reader.ReadElementContentAsFloat();
507 vec.Y = reader.ReadElementContentAsFloat();
508 vec.Z = reader.ReadElementContentAsFloat();
509 reader.ReadEndElement();
510 return vec;
511 }
512
513 public Quaternion XRquat()
514 {
515 Quaternion q;
516 reader.ReadStartElement();
517 q.X = reader.ReadElementContentAsFloat();
518 q.Y = reader.ReadElementContentAsFloat();
519 q.Z = reader.ReadElementContentAsFloat();
520 q.W = reader.ReadElementContentAsFloat();
521 reader.ReadEndElement();
522 return q;
523 }
524
525 public static bool EReadProcessors(
526 Dictionary<string, Action> processors,
527 XmlTextReader xtr)
528 {
529 bool errors = false;
530
531 string nodeName = string.Empty;
532 while (xtr.NodeType != XmlNodeType.EndElement)
533 {
534 nodeName = xtr.Name;
535
536 // m_log.DebugFormat("[ExternalRepresentationUtils]: Processing: {0}", nodeName);
537
538 Action p = null;
539 if (processors.TryGetValue(xtr.Name, out p))
540 {
541 // m_log.DebugFormat("[ExternalRepresentationUtils]: Found {0} processor, nodeName);
542
543 try
544 {
545 p();
546 }
547 catch (Exception e)
548 {
549 errors = true;
550 if (xtr.NodeType == XmlNodeType.EndElement)
551 xtr.Read();
552 }
553 }
554 else
555 {
556 // m_log.DebugFormat("[LandDataSerializer]: caught unknown element {0}", nodeName);
557 xtr.ReadOuterXml(); // ignore
558 }
559 }
560
561 return errors;
562 }
563
564
565 public string ToXml2()
566 {
567 MemoryStream ms = new MemoryStream(512);
568 UTF8Encoding enc = new UTF8Encoding();
569 XmlTextWriter xwriter = new XmlTextWriter(ms, enc);
570 ToXml2(xwriter);
571 xwriter.Flush();
572 string s = ms.GetStreamString();
573 xwriter.Close();
574 return s;
575 }
576
577 public static SOPVehicle FromXml2(string text)
578 {
579 if (text == String.Empty)
580 return null;
581
582 UTF8Encoding enc = new UTF8Encoding();
583 MemoryStream ms = new MemoryStream(enc.GetBytes(text));
584 XmlTextReader xreader = new XmlTextReader(ms);
585
586 SOPVehicle v = new SOPVehicle();
587 bool error;
588
589 v.FromXml2(xreader, out error);
590
591 xreader.Close();
592
593 if (error)
594 {
595 v = null;
596 return null;
597 }
598 return v;
599 }
600
601 public static SOPVehicle FromXml2(XmlTextReader reader)
602 {
603 SOPVehicle vehicle = new SOPVehicle();
604
605 bool errors = false;
606
607 vehicle.FromXml2(reader, out errors);
608 if (errors)
609 return null;
610
611 return vehicle;
612 }
613
614 private void FromXml2(XmlTextReader _reader, out bool errors)
615 {
616 errors = false;
617 reader = _reader;
618
619 Dictionary<string, Action> m_VehicleXmlProcessors
620 = new Dictionary<string, Action>();
621
622 m_VehicleXmlProcessors.Add("TYPE", ProcessXR_type);
623 m_VehicleXmlProcessors.Add("FLAGS", ProcessXR_flags);
624
625 // Linear properties
626 m_VehicleXmlProcessors.Add("LMDIR", ProcessXR_linearMotorDirection);
627 m_VehicleXmlProcessors.Add("LMFTIME", ProcessXR_linearFrictionTimescale);
628 m_VehicleXmlProcessors.Add("LMDTIME", ProcessXR_linearMotorDecayTimescale);
629 m_VehicleXmlProcessors.Add("LMTIME", ProcessXR_linearMotorTimescale);
630 m_VehicleXmlProcessors.Add("LMOFF", ProcessXR_linearMotorOffset);
631
632 //Angular properties
633 m_VehicleXmlProcessors.Add("AMDIR", ProcessXR_angularMotorDirection);
634 m_VehicleXmlProcessors.Add("AMTIME", ProcessXR_angularMotorTimescale);
635 m_VehicleXmlProcessors.Add("AMDTIME", ProcessXR_angularMotorDecayTimescale);
636 m_VehicleXmlProcessors.Add("AMFTIME", ProcessXR_angularFrictionTimescale);
637
638 //Deflection properties
639 m_VehicleXmlProcessors.Add("ADEFF", ProcessXR_angularDeflectionEfficiency);
640 m_VehicleXmlProcessors.Add("ADTIME", ProcessXR_angularDeflectionTimescale);
641 m_VehicleXmlProcessors.Add("LDEFF", ProcessXR_linearDeflectionEfficiency);
642 m_VehicleXmlProcessors.Add("LDTIME", ProcessXR_linearDeflectionTimescale);
643
644 //Banking properties
645 m_VehicleXmlProcessors.Add("BEFF", ProcessXR_bankingEfficiency);
646 m_VehicleXmlProcessors.Add("BMIX", ProcessXR_bankingMix);
647 m_VehicleXmlProcessors.Add("BTIME", ProcessXR_bankingTimescale);
648
649 //Hover and Buoyancy properties
650 m_VehicleXmlProcessors.Add("HHEI", ProcessXR_VhoverHeight);
651 m_VehicleXmlProcessors.Add("HEFF", ProcessXR_VhoverEfficiency);
652 m_VehicleXmlProcessors.Add("HTIME", ProcessXR_VhoverTimescale);
653
654 m_VehicleXmlProcessors.Add("VBUO", ProcessXR_VehicleBuoyancy);
655
656 //Attractor properties
657 m_VehicleXmlProcessors.Add("VAEFF", ProcessXR_verticalAttractionEfficiency);
658 m_VehicleXmlProcessors.Add("VATIME", ProcessXR_verticalAttractionTimescale);
659
660 m_VehicleXmlProcessors.Add("REF_FRAME", ProcessXR_referenceFrame);
661
662 vd = new VehicleData();
663
664 reader.ReadStartElement("Vehicle", String.Empty);
665
666 errors = EReadProcessors(
667 m_VehicleXmlProcessors,
668 reader);
669
670 reader.ReadEndElement();
671 reader = null;
672 }
673
674 private void ProcessXR_type()
675 {
676 vd.m_type = (Vehicle)XRint();
677 }
678 private void ProcessXR_flags()
679 {
680 vd.m_flags = (VehicleFlag)XRint();
681 }
682 // Linear properties
683 private void ProcessXR_linearMotorDirection()
684 {
685 vd.m_linearMotorDirection = XRvector();
686 }
687
688 private void ProcessXR_linearFrictionTimescale()
689 {
690 vd.m_linearFrictionTimescale = XRvector();
691 }
692
693 private void ProcessXR_linearMotorDecayTimescale()
694 {
695 vd.m_linearMotorDecayTimescale = XRfloat();
696 }
697 private void ProcessXR_linearMotorTimescale()
698 {
699 vd.m_linearMotorTimescale = XRfloat();
700 }
701 private void ProcessXR_linearMotorOffset()
702 {
703 vd.m_linearMotorOffset = XRvector();
704 }
705
706
707 //Angular properties
708 private void ProcessXR_angularMotorDirection()
709 {
710 vd.m_angularMotorDirection = XRvector();
711 }
712 private void ProcessXR_angularMotorTimescale()
713 {
714 vd.m_angularMotorTimescale = XRfloat();
715 }
716 private void ProcessXR_angularMotorDecayTimescale()
717 {
718 vd.m_angularMotorDecayTimescale = XRfloat();
719 }
720 private void ProcessXR_angularFrictionTimescale()
721 {
722 vd.m_angularFrictionTimescale = XRvector();
723 }
724
725 //Deflection properties
726 private void ProcessXR_angularDeflectionEfficiency()
727 {
728 vd.m_angularDeflectionEfficiency = XRfloat();
729 }
730 private void ProcessXR_angularDeflectionTimescale()
731 {
732 vd.m_angularDeflectionTimescale = XRfloat();
733 }
734 private void ProcessXR_linearDeflectionEfficiency()
735 {
736 vd.m_linearDeflectionEfficiency = XRfloat();
737 }
738 private void ProcessXR_linearDeflectionTimescale()
739 {
740 vd.m_linearDeflectionTimescale = XRfloat();
741 }
742
743 //Banking properties
744 private void ProcessXR_bankingEfficiency()
745 {
746 vd.m_bankingEfficiency = XRfloat();
747 }
748 private void ProcessXR_bankingMix()
749 {
750 vd.m_bankingMix = XRfloat();
751 }
752 private void ProcessXR_bankingTimescale()
753 {
754 vd.m_bankingTimescale = XRfloat();
755 }
756
757 //Hover and Buoyancy properties
758 private void ProcessXR_VhoverHeight()
759 {
760 vd.m_VhoverHeight = XRfloat();
761 }
762 private void ProcessXR_VhoverEfficiency()
763 {
764 vd.m_VhoverEfficiency = XRfloat();
765 }
766 private void ProcessXR_VhoverTimescale()
767 {
768 vd.m_VhoverTimescale = XRfloat();
769 }
770
771 private void ProcessXR_VehicleBuoyancy()
772 {
773 vd.m_VehicleBuoyancy = XRfloat();
774 }
775
776 //Attractor properties
777 private void ProcessXR_verticalAttractionEfficiency()
778 {
779 vd.m_verticalAttractionEfficiency = XRfloat();
780 }
781 private void ProcessXR_verticalAttractionTimescale()
782 {
783 vd.m_verticalAttractionTimescale = XRfloat();
784 }
785
786 private void ProcessXR_referenceFrame()
787 {
788 vd.m_referenceFrame = XRquat();
789 }
790 }
791}
diff --git a/OpenSim/Region/Framework/Scenes/Scene.Inventory.cs b/OpenSim/Region/Framework/Scenes/Scene.Inventory.cs
index 8ddaa60..d2e41f8 100644
--- a/OpenSim/Region/Framework/Scenes/Scene.Inventory.cs
+++ b/OpenSim/Region/Framework/Scenes/Scene.Inventory.cs
@@ -102,12 +102,12 @@ namespace OpenSim.Region.Framework.Scenes
102 engine.StartProcessing(); 102 engine.StartProcessing();
103 } 103 }
104 104
105 public void AddUploadedInventoryItem(UUID agentID, InventoryItemBase item) 105 public void AddUploadedInventoryItem(UUID agentID, InventoryItemBase item, uint cost)
106 { 106 {
107 IMoneyModule money = RequestModuleInterface<IMoneyModule>(); 107 IMoneyModule money = RequestModuleInterface<IMoneyModule>();
108 if (money != null) 108 if (money != null)
109 { 109 {
110 money.ApplyUploadCharge(agentID, money.UploadCharge, "Asset upload"); 110 money.ApplyUploadCharge(agentID, (int)cost, "Asset upload");
111 } 111 }
112 112
113 AddInventoryItem(item); 113 AddInventoryItem(item);
@@ -170,7 +170,7 @@ namespace OpenSim.Region.Framework.Scenes
170 return false; 170 return false;
171 } 171 }
172 } 172 }
173 173
174 if (InventoryService.AddItem(item)) 174 if (InventoryService.AddItem(item))
175 { 175 {
176 int userlevel = 0; 176 int userlevel = 0;
@@ -325,8 +325,7 @@ namespace OpenSim.Region.Framework.Scenes
325 325
326 // Update item with new asset 326 // Update item with new asset
327 item.AssetID = asset.FullID; 327 item.AssetID = asset.FullID;
328 if (group.UpdateInventoryItem(item)) 328 group.UpdateInventoryItem(item);
329 remoteClient.SendAgentAlertMessage("Script saved", false);
330 329
331 part.SendPropertiesToClient(remoteClient); 330 part.SendPropertiesToClient(remoteClient);
332 331
@@ -337,12 +336,7 @@ namespace OpenSim.Region.Framework.Scenes
337 { 336 {
338 // Needs to determine which engine was running it and use that 337 // Needs to determine which engine was running it and use that
339 // 338 //
340 part.Inventory.CreateScriptInstance(item.ItemID, 0, false, DefaultScriptEngine, 0); 339 errors = part.Inventory.CreateScriptInstanceEr(item.ItemID, 0, false, DefaultScriptEngine, 1);
341 errors = part.Inventory.GetScriptErrors(item.ItemID);
342 }
343 else
344 {
345 remoteClient.SendAgentAlertMessage("Script saved", false);
346 } 340 }
347 341
348 // Tell anyone managing scripts that a script has been reloaded/changed 342 // Tell anyone managing scripts that a script has been reloaded/changed
@@ -408,6 +402,7 @@ namespace OpenSim.Region.Framework.Scenes
408 if (item.Owner != remoteClient.AgentId) 402 if (item.Owner != remoteClient.AgentId)
409 return; 403 return;
410 404
405 item.Flags = (item.Flags & ~(uint)255) | (itemUpd.Flags & (uint)255);
411 item.Name = itemUpd.Name; 406 item.Name = itemUpd.Name;
412 item.Description = itemUpd.Description; 407 item.Description = itemUpd.Description;
413 408
@@ -835,6 +830,8 @@ namespace OpenSim.Region.Framework.Scenes
835 return; 830 return;
836 } 831 }
837 832
833 if (newName == null) newName = item.Name;
834
838 AssetBase asset = AssetService.Get(item.AssetID.ToString()); 835 AssetBase asset = AssetService.Get(item.AssetID.ToString());
839 836
840 if (asset != null) 837 if (asset != null)
@@ -895,6 +892,24 @@ namespace OpenSim.Region.Framework.Scenes
895 } 892 }
896 893
897 /// <summary> 894 /// <summary>
895 /// Move an item within the agent's inventory, and leave a copy (used in making a new outfit)
896 /// </summary>
897 public void MoveInventoryItemsLeaveCopy(IClientAPI remoteClient, List<InventoryItemBase> items, UUID destfolder)
898 {
899 List<InventoryItemBase> moveitems = new List<InventoryItemBase>();
900 foreach (InventoryItemBase b in items)
901 {
902 CopyInventoryItem(remoteClient, 0, remoteClient.AgentId, b.ID, b.Folder, null);
903 InventoryItemBase n = InventoryService.GetItem(b);
904 n.Folder = destfolder;
905 moveitems.Add(n);
906 remoteClient.SendInventoryItemCreateUpdate(n, 0);
907 }
908
909 MoveInventoryItem(remoteClient, moveitems);
910 }
911
912 /// <summary>
898 /// Move an item within the agent's inventory. 913 /// Move an item within the agent's inventory.
899 /// </summary> 914 /// </summary>
900 /// <param name="remoteClient"></param> 915 /// <param name="remoteClient"></param>
@@ -929,11 +944,22 @@ namespace OpenSim.Region.Framework.Scenes
929 public void CreateNewInventoryItem( 944 public void CreateNewInventoryItem(
930 IClientAPI remoteClient, string creatorID, string creatorData, UUID folderID, 945 IClientAPI remoteClient, string creatorID, string creatorData, UUID folderID,
931 string name, string description, uint flags, uint callbackID, 946 string name, string description, uint flags, uint callbackID,
932 AssetBase asset, sbyte invType, uint nextOwnerMask, int creationDate) 947 AssetBase asset, sbyte invType, uint nextOwnerMask, int creationDate, UUID transationID)
933 { 948 {
934 CreateNewInventoryItem( 949 CreateNewInventoryItem(
935 remoteClient, creatorID, creatorData, folderID, name, description, flags, callbackID, asset, invType, 950 remoteClient, creatorID, creatorData, folderID, name, description, flags, callbackID, asset, invType,
936 (uint)PermissionMask.All | (uint)PermissionMask.Export, (uint)PermissionMask.All | (uint)PermissionMask.Export, 0, nextOwnerMask, 0, creationDate); 951 (uint)PermissionMask.All | (uint)PermissionMask.Export, (uint)PermissionMask.All | (uint)PermissionMask.Export, 0, nextOwnerMask, 0, creationDate, transationID);
952 }
953
954
955 private void CreateNewInventoryItem(
956 IClientAPI remoteClient, string creatorID, string creatorData, UUID folderID,
957 string name, string description, uint flags, uint callbackID, AssetBase asset, sbyte invType,
958 uint baseMask, uint currentMask, uint everyoneMask, uint nextOwnerMask, uint groupMask, int creationDate)
959 {
960 CreateNewInventoryItem(remoteClient, creatorID, creatorData, folderID,
961 name, description, flags, callbackID, asset, invType,
962 baseMask, currentMask, everyoneMask, nextOwnerMask, groupMask, creationDate, UUID.Zero);
937 } 963 }
938 964
939 /// <summary> 965 /// <summary>
@@ -958,7 +984,7 @@ namespace OpenSim.Region.Framework.Scenes
958 private void CreateNewInventoryItem( 984 private void CreateNewInventoryItem(
959 IClientAPI remoteClient, string creatorID, string creatorData, UUID folderID, 985 IClientAPI remoteClient, string creatorID, string creatorData, UUID folderID,
960 string name, string description, uint flags, uint callbackID, AssetBase asset, sbyte invType, 986 string name, string description, uint flags, uint callbackID, AssetBase asset, sbyte invType,
961 uint baseMask, uint currentMask, uint everyoneMask, uint nextOwnerMask, uint groupMask, int creationDate) 987 uint baseMask, uint currentMask, uint everyoneMask, uint nextOwnerMask, uint groupMask, int creationDate,UUID transationID)
962 { 988 {
963 InventoryItemBase item = new InventoryItemBase(); 989 InventoryItemBase item = new InventoryItemBase();
964 item.Owner = remoteClient.AgentId; 990 item.Owner = remoteClient.AgentId;
@@ -981,7 +1007,7 @@ namespace OpenSim.Region.Framework.Scenes
981 1007
982 if (AddInventoryItem(item)) 1008 if (AddInventoryItem(item))
983 { 1009 {
984 remoteClient.SendInventoryItemCreateUpdate(item, callbackID); 1010 remoteClient.SendInventoryItemCreateUpdate(item, transationID, callbackID);
985 } 1011 }
986 else 1012 else
987 { 1013 {
@@ -1256,6 +1282,10 @@ namespace OpenSim.Region.Framework.Scenes
1256 { 1282 {
1257 SceneObjectPart part = GetSceneObjectPart(primLocalId); 1283 SceneObjectPart part = GetSceneObjectPart(primLocalId);
1258 1284
1285 // Can't move a null item
1286 if (itemId == UUID.Zero)
1287 return;
1288
1259 if (null == part) 1289 if (null == part)
1260 { 1290 {
1261 m_log.WarnFormat( 1291 m_log.WarnFormat(
@@ -1360,21 +1390,28 @@ namespace OpenSim.Region.Framework.Scenes
1360 return; 1390 return;
1361 } 1391 }
1362 1392
1363 if (part.OwnerID != destPart.OwnerID) 1393 // Can't transfer this
1394 //
1395 if (part.OwnerID != destPart.OwnerID && (srcTaskItem.CurrentPermissions & (uint)PermissionMask.Transfer) == 0)
1396 return;
1397
1398 bool overrideNoMod = false;
1399 if ((part.GetEffectiveObjectFlags() & (uint)PrimFlags.AllowInventoryDrop) != 0)
1400 overrideNoMod = true;
1401
1402 if (part.OwnerID != destPart.OwnerID && (destPart.GetEffectiveObjectFlags() & (uint)PrimFlags.AllowInventoryDrop) == 0)
1364 { 1403 {
1365 // Source must have transfer permissions 1404 // object cannot copy items to an object owned by a different owner
1366 if ((srcTaskItem.CurrentPermissions & (uint)PermissionMask.Transfer) == 0) 1405 // unless llAllowInventoryDrop has been called
1367 return;
1368 1406
1369 // Object cannot copy items to an object owned by a different owner 1407 return;
1370 // unless llAllowInventoryDrop has been called on the destination
1371 if ((destPart.GetEffectiveObjectFlags() & (uint)PrimFlags.AllowInventoryDrop) == 0)
1372 return;
1373 } 1408 }
1374 1409
1375 // must have both move and modify permission to put an item in an object 1410 // must have both move and modify permission to put an item in an object
1376 if ((part.OwnerMask & ((uint)PermissionMask.Move | (uint)PermissionMask.Modify)) == 0) 1411 if (((part.OwnerMask & (uint)PermissionMask.Modify) == 0) && (!overrideNoMod))
1412 {
1377 return; 1413 return;
1414 }
1378 1415
1379 TaskInventoryItem destTaskItem = new TaskInventoryItem(); 1416 TaskInventoryItem destTaskItem = new TaskInventoryItem();
1380 1417
@@ -1430,6 +1467,14 @@ namespace OpenSim.Region.Framework.Scenes
1430 1467
1431 public UUID MoveTaskInventoryItems(UUID destID, string category, SceneObjectPart host, List<UUID> items) 1468 public UUID MoveTaskInventoryItems(UUID destID, string category, SceneObjectPart host, List<UUID> items)
1432 { 1469 {
1470 SceneObjectPart destPart = GetSceneObjectPart(destID);
1471 if (destPart != null) // Move into a prim
1472 {
1473 foreach(UUID itemID in items)
1474 MoveTaskInventoryItem(destID, host, itemID);
1475 return destID; // Prim folder ID == prim ID
1476 }
1477
1433 InventoryFolderBase rootFolder = InventoryService.GetRootFolder(destID); 1478 InventoryFolderBase rootFolder = InventoryService.GetRootFolder(destID);
1434 1479
1435 UUID newFolderID = UUID.Random(); 1480 UUID newFolderID = UUID.Random();
@@ -1612,12 +1657,12 @@ namespace OpenSim.Region.Framework.Scenes
1612 AgentTransactionsModule.HandleTaskItemUpdateFromTransaction( 1657 AgentTransactionsModule.HandleTaskItemUpdateFromTransaction(
1613 remoteClient, part, transactionID, currentItem); 1658 remoteClient, part, transactionID, currentItem);
1614 1659
1615 if ((InventoryType)itemInfo.InvType == InventoryType.Notecard) 1660// if ((InventoryType)itemInfo.InvType == InventoryType.Notecard)
1616 remoteClient.SendAgentAlertMessage("Notecard saved", false); 1661// remoteClient.SendAgentAlertMessage("Notecard saved", false);
1617 else if ((InventoryType)itemInfo.InvType == InventoryType.LSL) 1662// else if ((InventoryType)itemInfo.InvType == InventoryType.LSL)
1618 remoteClient.SendAgentAlertMessage("Script saved", false); 1663// remoteClient.SendAgentAlertMessage("Script saved", false);
1619 else 1664// else
1620 remoteClient.SendAgentAlertMessage("Item saved", false); 1665// remoteClient.SendAgentAlertMessage("Item saved", false);
1621 } 1666 }
1622 1667
1623 // Base ALWAYS has move 1668 // Base ALWAYS has move
@@ -1987,23 +2032,32 @@ namespace OpenSim.Region.Framework.Scenes
1987 // build a list of eligible objects 2032 // build a list of eligible objects
1988 List<uint> deleteIDs = new List<uint>(); 2033 List<uint> deleteIDs = new List<uint>();
1989 List<SceneObjectGroup> deleteGroups = new List<SceneObjectGroup>(); 2034 List<SceneObjectGroup> deleteGroups = new List<SceneObjectGroup>();
1990 2035 List<SceneObjectGroup> takeGroups = new List<SceneObjectGroup>();
1991 // Start with true for both, then remove the flags if objects
1992 // that we can't derez are part of the selection
1993 bool permissionToTake = true;
1994 bool permissionToTakeCopy = true;
1995 bool permissionToDelete = true;
1996 2036
1997 foreach (uint localID in localIDs) 2037 foreach (uint localID in localIDs)
1998 { 2038 {
2039 // Start with true for both, then remove the flags if objects
2040 // that we can't derez are part of the selection
2041 bool permissionToTake = true;
2042 bool permissionToTakeCopy = true;
2043 bool permissionToDelete = true;
2044
1999 // Invalid id 2045 // Invalid id
2000 SceneObjectPart part = GetSceneObjectPart(localID); 2046 SceneObjectPart part = GetSceneObjectPart(localID);
2001 if (part == null) 2047 if (part == null)
2048 {
2049 //Client still thinks the object exists, kill it
2050 deleteIDs.Add(localID);
2002 continue; 2051 continue;
2052 }
2003 2053
2004 // Already deleted by someone else 2054 // Already deleted by someone else
2005 if (part.ParentGroup.IsDeleted) 2055 if (part.ParentGroup.IsDeleted)
2056 {
2057 //Client still thinks the object exists, kill it
2058 deleteIDs.Add(localID);
2006 continue; 2059 continue;
2060 }
2007 2061
2008 // Can't delete child prims 2062 // Can't delete child prims
2009 if (part != part.ParentGroup.RootPart) 2063 if (part != part.ParentGroup.RootPart)
@@ -2011,8 +2065,8 @@ namespace OpenSim.Region.Framework.Scenes
2011 2065
2012 SceneObjectGroup grp = part.ParentGroup; 2066 SceneObjectGroup grp = part.ParentGroup;
2013 2067
2014 deleteIDs.Add(localID); 2068 // If child prims have invalid perms, fix them
2015 deleteGroups.Add(grp); 2069 grp.AdjustChildPrimPermissions();
2016 2070
2017 // If child prims have invalid perms, fix them 2071 // If child prims have invalid perms, fix them
2018 grp.AdjustChildPrimPermissions(); 2072 grp.AdjustChildPrimPermissions();
@@ -2033,81 +2087,193 @@ namespace OpenSim.Region.Framework.Scenes
2033 } 2087 }
2034 else 2088 else
2035 { 2089 {
2036 if (!Permissions.CanTakeCopyObject(grp.UUID, remoteClient.AgentId)) 2090 if (action == DeRezAction.TakeCopy)
2091 {
2092 if (!Permissions.CanTakeCopyObject(grp.UUID, remoteClient.AgentId))
2093 permissionToTakeCopy = false;
2094 }
2095 else
2096 {
2037 permissionToTakeCopy = false; 2097 permissionToTakeCopy = false;
2038 2098 }
2039 if (!Permissions.CanTakeObject(grp.UUID, remoteClient.AgentId)) 2099 if (!Permissions.CanTakeObject(grp.UUID, remoteClient.AgentId))
2040 permissionToTake = false; 2100 permissionToTake = false;
2041 2101
2042 if (!Permissions.CanDeleteObject(grp.UUID, remoteClient.AgentId)) 2102 if (!Permissions.CanDeleteObject(grp.UUID, remoteClient.AgentId))
2043 permissionToDelete = false; 2103 permissionToDelete = false;
2044 } 2104 }
2045 }
2046 2105
2047 // Handle god perms 2106 // Handle god perms
2048 if ((remoteClient != null) && Permissions.IsGod(remoteClient.AgentId)) 2107 if ((remoteClient != null) && Permissions.IsGod(remoteClient.AgentId))
2049 { 2108 {
2050 permissionToTake = true; 2109 permissionToTake = true;
2051 permissionToTakeCopy = true; 2110 permissionToTakeCopy = true;
2052 permissionToDelete = true; 2111 permissionToDelete = true;
2053 } 2112 }
2054 2113
2055 // If we're re-saving, we don't even want to delete 2114 // If we're re-saving, we don't even want to delete
2056 if (action == DeRezAction.SaveToExistingUserInventoryItem) 2115 if (action == DeRezAction.SaveToExistingUserInventoryItem)
2057 permissionToDelete = false; 2116 permissionToDelete = false;
2058 2117
2059 // if we want to take a copy, we also don't want to delete 2118 // if we want to take a copy, we also don't want to delete
2060 // Note: after this point, the permissionToTakeCopy flag 2119 // Note: after this point, the permissionToTakeCopy flag
2061 // becomes irrelevant. It already includes the permissionToTake 2120 // becomes irrelevant. It already includes the permissionToTake
2062 // permission and after excluding no copy items here, we can 2121 // permission and after excluding no copy items here, we can
2063 // just use that. 2122 // just use that.
2064 if (action == DeRezAction.TakeCopy) 2123 if (action == DeRezAction.TakeCopy)
2065 { 2124 {
2066 // If we don't have permission, stop right here 2125 // If we don't have permission, stop right here
2067 if (!permissionToTakeCopy) 2126 if (!permissionToTakeCopy)
2068 return; 2127 return;
2069 2128
2070 permissionToTake = true; 2129 permissionToTake = true;
2071 // Don't delete 2130 // Don't delete
2072 permissionToDelete = false; 2131 permissionToDelete = false;
2073 } 2132 }
2074 2133
2075 if (action == DeRezAction.Return) 2134 if (action == DeRezAction.Return)
2076 {
2077 if (remoteClient != null)
2078 { 2135 {
2079 if (Permissions.CanReturnObjects( 2136 if (remoteClient != null)
2080 null,
2081 remoteClient.AgentId,
2082 deleteGroups))
2083 { 2137 {
2084 permissionToTake = true; 2138 if (Permissions.CanReturnObjects(
2085 permissionToDelete = true; 2139 null,
2086 2140 remoteClient.AgentId,
2087 foreach (SceneObjectGroup g in deleteGroups) 2141 new List<SceneObjectGroup>() {grp}))
2088 { 2142 {
2089 AddReturn(g.OwnerID == g.GroupID ? g.LastOwnerID : g.OwnerID, g.Name, g.AbsolutePosition, "parcel owner return"); 2143 permissionToTake = true;
2144 permissionToDelete = true;
2145
2146 AddReturn(grp.OwnerID == grp.GroupID ? grp.LastOwnerID : grp.OwnerID, grp.Name, grp.AbsolutePosition, "parcel owner return");
2090 } 2147 }
2091 } 2148 }
2149 else // Auto return passes through here with null agent
2150 {
2151 permissionToTake = true;
2152 permissionToDelete = true;
2153 }
2092 } 2154 }
2093 else // Auto return passes through here with null agent 2155
2156 if (permissionToTake && (!permissionToDelete))
2157 takeGroups.Add(grp);
2158
2159 if (permissionToDelete)
2094 { 2160 {
2095 permissionToTake = true; 2161 if (permissionToTake)
2096 permissionToDelete = true; 2162 deleteGroups.Add(grp);
2163 deleteIDs.Add(grp.LocalId);
2097 } 2164 }
2098 } 2165 }
2099 2166
2100 if (permissionToTake && (action != DeRezAction.Delete || this.m_useTrashOnDelete)) 2167 SendKillObject(deleteIDs);
2168
2169 if (deleteGroups.Count > 0)
2101 { 2170 {
2171 foreach (SceneObjectGroup g in deleteGroups)
2172 deleteIDs.Remove(g.LocalId);
2173
2102 m_asyncSceneObjectDeleter.DeleteToInventory( 2174 m_asyncSceneObjectDeleter.DeleteToInventory(
2103 action, destinationID, deleteGroups, remoteClient, 2175 action, destinationID, deleteGroups, remoteClient,
2104 permissionToDelete); 2176 true);
2177 }
2178 if (takeGroups.Count > 0)
2179 {
2180 m_asyncSceneObjectDeleter.DeleteToInventory(
2181 action, destinationID, takeGroups, remoteClient,
2182 false);
2105 } 2183 }
2106 else if (permissionToDelete) 2184 if (deleteIDs.Count > 0)
2107 { 2185 {
2108 foreach (SceneObjectGroup g in deleteGroups) 2186 foreach (SceneObjectGroup g in deleteGroups)
2109 DeleteSceneObject(g, false); 2187 DeleteSceneObject(g, true);
2188 }
2189 }
2190
2191 public UUID attachObjectAssetStore(IClientAPI remoteClient, SceneObjectGroup grp, UUID AgentId, out UUID itemID)
2192 {
2193 itemID = UUID.Zero;
2194 if (grp != null)
2195 {
2196 Vector3 inventoryStoredPosition = new Vector3
2197 (((grp.AbsolutePosition.X > (int)Constants.RegionSize)
2198 ? 250
2199 : grp.AbsolutePosition.X)
2200 ,
2201 (grp.AbsolutePosition.X > (int)Constants.RegionSize)
2202 ? 250
2203 : grp.AbsolutePosition.X,
2204 grp.AbsolutePosition.Z);
2205
2206 Vector3 originalPosition = grp.AbsolutePosition;
2207
2208 grp.AbsolutePosition = inventoryStoredPosition;
2209
2210 string sceneObjectXml = SceneObjectSerializer.ToOriginalXmlFormat(grp);
2211
2212 grp.AbsolutePosition = originalPosition;
2213
2214 AssetBase asset = CreateAsset(
2215 grp.GetPartName(grp.LocalId),
2216 grp.GetPartDescription(grp.LocalId),
2217 (sbyte)AssetType.Object,
2218 Utils.StringToBytes(sceneObjectXml),
2219 remoteClient.AgentId);
2220 AssetService.Store(asset);
2221
2222 InventoryItemBase item = new InventoryItemBase();
2223 item.CreatorId = grp.RootPart.CreatorID.ToString();
2224 item.CreatorData = grp.RootPart.CreatorData;
2225 item.Owner = remoteClient.AgentId;
2226 item.ID = UUID.Random();
2227 item.AssetID = asset.FullID;
2228 item.Description = asset.Description;
2229 item.Name = asset.Name;
2230 item.AssetType = asset.Type;
2231 item.InvType = (int)InventoryType.Object;
2232
2233 InventoryFolderBase folder = InventoryService.GetFolderForType(remoteClient.AgentId, AssetType.Object);
2234 if (folder != null)
2235 item.Folder = folder.ID;
2236 else // oopsies
2237 item.Folder = UUID.Zero;
2238
2239 // Set up base perms properly
2240 uint permsBase = (uint)(PermissionMask.Move | PermissionMask.Copy | PermissionMask.Transfer | PermissionMask.Modify);
2241 permsBase &= grp.RootPart.BaseMask;
2242 permsBase |= (uint)PermissionMask.Move;
2243
2244 // Make sure we don't lock it
2245 grp.RootPart.NextOwnerMask |= (uint)PermissionMask.Move;
2246
2247 if ((remoteClient.AgentId != grp.RootPart.OwnerID) && Permissions.PropagatePermissions())
2248 {
2249 item.BasePermissions = permsBase & grp.RootPart.NextOwnerMask;
2250 item.CurrentPermissions = permsBase & grp.RootPart.NextOwnerMask;
2251 item.NextPermissions = permsBase & grp.RootPart.NextOwnerMask;
2252 item.EveryOnePermissions = permsBase & grp.RootPart.EveryoneMask & grp.RootPart.NextOwnerMask;
2253 item.GroupPermissions = permsBase & grp.RootPart.GroupMask & grp.RootPart.NextOwnerMask;
2254 }
2255 else
2256 {
2257 item.BasePermissions = permsBase;
2258 item.CurrentPermissions = permsBase & grp.RootPart.OwnerMask;
2259 item.NextPermissions = permsBase & grp.RootPart.NextOwnerMask;
2260 item.EveryOnePermissions = permsBase & grp.RootPart.EveryoneMask;
2261 item.GroupPermissions = permsBase & grp.RootPart.GroupMask;
2262 }
2263 item.CreationDate = Util.UnixTimeSinceEpoch();
2264
2265 // sets itemID so client can show item as 'attached' in inventory
2266 grp.FromItemID = item.ID;
2267
2268 if (AddInventoryItem(item))
2269 remoteClient.SendInventoryItemCreateUpdate(item, 0);
2270 else
2271 m_dialogModule.SendAlertToUser(remoteClient, "Operation failed");
2272
2273 itemID = item.ID;
2274 return item.AssetID;
2110 } 2275 }
2276 return UUID.Zero;
2111 } 2277 }
2112 2278
2113 /// <summary> 2279 /// <summary>
@@ -2237,6 +2403,9 @@ namespace OpenSim.Region.Framework.Scenes
2237 2403
2238 public void SetScriptRunning(IClientAPI controllingClient, UUID objectID, UUID itemID, bool running) 2404 public void SetScriptRunning(IClientAPI controllingClient, UUID objectID, UUID itemID, bool running)
2239 { 2405 {
2406 if (!Permissions.CanEditScript(itemID, objectID, controllingClient.AgentId))
2407 return;
2408
2240 SceneObjectPart part = GetSceneObjectPart(objectID); 2409 SceneObjectPart part = GetSceneObjectPart(objectID);
2241 if (part == null) 2410 if (part == null)
2242 return; 2411 return;
@@ -2293,7 +2462,10 @@ namespace OpenSim.Region.Framework.Scenes
2293 } 2462 }
2294 else 2463 else
2295 { 2464 {
2296 if (!Permissions.CanEditObject(sog.UUID, remoteClient.AgentId)) 2465 if (!Permissions.IsGod(remoteClient.AgentId) && sog.OwnerID != remoteClient.AgentId)
2466 continue;
2467
2468 if (!Permissions.CanTransferObject(sog.UUID, groupID))
2297 continue; 2469 continue;
2298 2470
2299 if (sog.GroupID != groupID) 2471 if (sog.GroupID != groupID)
@@ -2405,6 +2577,12 @@ namespace OpenSim.Region.Framework.Scenes
2405 } 2577 }
2406 2578
2407 m_sceneGraph.LinkObjects(root, children); 2579 m_sceneGraph.LinkObjects(root, children);
2580
2581 ScenePresence sp;
2582 if (TryGetScenePresence(agentId, out sp))
2583 {
2584 root.SendPropertiesToClient(sp.ControllingClient);
2585 }
2408 } 2586 }
2409 2587
2410 private string PermissionString(uint permissions) 2588 private string PermissionString(uint permissions)
diff --git a/OpenSim/Region/Framework/Scenes/Scene.PacketHandlers.cs b/OpenSim/Region/Framework/Scenes/Scene.PacketHandlers.cs
index df43271..ce6415a 100644
--- a/OpenSim/Region/Framework/Scenes/Scene.PacketHandlers.cs
+++ b/OpenSim/Region/Framework/Scenes/Scene.PacketHandlers.cs
@@ -50,7 +50,7 @@ namespace OpenSim.Region.Framework.Scenes
50 /// <param name='targetID'></param> 50 /// <param name='targetID'></param>
51 /// <param name='fromAgent'></param> 51 /// <param name='fromAgent'></param>
52 /// <param name='broadcast'></param> 52 /// <param name='broadcast'></param>
53 protected void SimChat(byte[] message, ChatTypeEnum type, int channel, Vector3 fromPos, string fromName, 53 public void SimChat(byte[] message, ChatTypeEnum type, int channel, Vector3 fromPos, string fromName,
54 UUID fromID, UUID targetID, bool fromAgent, bool broadcast) 54 UUID fromID, UUID targetID, bool fromAgent, bool broadcast)
55 { 55 {
56 OSChatMessage args = new OSChatMessage(); 56 OSChatMessage args = new OSChatMessage();
@@ -61,6 +61,7 @@ namespace OpenSim.Region.Framework.Scenes
61 args.Position = fromPos; 61 args.Position = fromPos;
62 args.SenderUUID = fromID; 62 args.SenderUUID = fromID;
63 args.Scene = this; 63 args.Scene = this;
64 args.Destination = targetID;
64 65
65 if (fromAgent) 66 if (fromAgent)
66 { 67 {
@@ -75,7 +76,7 @@ namespace OpenSim.Region.Framework.Scenes
75 } 76 }
76 77
77 args.From = fromName; 78 args.From = fromName;
78 args.TargetUUID = targetID; 79 //args.
79 80
80// m_log.DebugFormat( 81// m_log.DebugFormat(
81// "[SCENE]: Sending message {0} on channel {1}, type {2} from {3}, broadcast {4}", 82// "[SCENE]: Sending message {0} on channel {1}, type {2} from {3}, broadcast {4}",
@@ -86,7 +87,7 @@ namespace OpenSim.Region.Framework.Scenes
86 else 87 else
87 EventManager.TriggerOnChatFromWorld(this, args); 88 EventManager.TriggerOnChatFromWorld(this, args);
88 } 89 }
89 90
90 protected void SimChat(byte[] message, ChatTypeEnum type, int channel, Vector3 fromPos, string fromName, 91 protected void SimChat(byte[] message, ChatTypeEnum type, int channel, Vector3 fromPos, string fromName,
91 UUID fromID, bool fromAgent, bool broadcast) 92 UUID fromID, bool fromAgent, bool broadcast)
92 { 93 {
@@ -130,19 +131,6 @@ namespace OpenSim.Region.Framework.Scenes
130 { 131 {
131 SimChat(message, type, channel, fromPos, fromName, fromID, fromAgent, true); 132 SimChat(message, type, channel, fromPos, fromName, fromID, fromAgent, true);
132 } 133 }
133 /// <summary>
134 ///
135 /// </summary>
136 /// <param name="message"></param>
137 /// <param name="type"></param>
138 /// <param name="fromPos"></param>
139 /// <param name="fromName"></param>
140 /// <param name="fromAgentID"></param>
141 /// <param name="targetID"></param>
142 public void SimChatToAgent(UUID targetID, byte[] message, Vector3 fromPos, string fromName, UUID fromID, bool fromAgent)
143 {
144 SimChat(message, ChatTypeEnum.Say, 0, fromPos, fromName, fromID, targetID, fromAgent, false);
145 }
146 134
147 /// <summary> 135 /// <summary>
148 /// Invoked when the client requests a prim. 136 /// Invoked when the client requests a prim.
@@ -164,27 +152,47 @@ namespace OpenSim.Region.Framework.Scenes
164 /// <param name="remoteClient"></param> 152 /// <param name="remoteClient"></param>
165 public void SelectPrim(uint primLocalID, IClientAPI remoteClient) 153 public void SelectPrim(uint primLocalID, IClientAPI remoteClient)
166 { 154 {
155 /*
156 SceneObjectPart part = GetSceneObjectPart(primLocalID);
157
158 if (null == part)
159 return;
160
161 if (part.IsRoot)
162 {
163 SceneObjectGroup sog = part.ParentGroup;
164 sog.SendPropertiesToClient(remoteClient);
165
166 // A prim is only tainted if it's allowed to be edited by the person clicking it.
167 if (Permissions.CanEditObject(sog.UUID, remoteClient.AgentId)
168 || Permissions.CanMoveObject(sog.UUID, remoteClient.AgentId))
169 {
170 sog.IsSelected = true;
171 EventManager.TriggerParcelPrimCountTainted();
172 }
173 }
174 else
175 {
176 part.SendPropertiesToClient(remoteClient);
177 }
178 */
167 SceneObjectPart part = GetSceneObjectPart(primLocalID); 179 SceneObjectPart part = GetSceneObjectPart(primLocalID);
168 180
169 if (null == part) 181 if (null == part)
170 return; 182 return;
171 183
172 if (part.IsRoot) 184 SceneObjectGroup sog = part.ParentGroup;
173 { 185 if (sog == null)
174 SceneObjectGroup sog = part.ParentGroup; 186 return;
175 sog.SendPropertiesToClient(remoteClient);
176 sog.IsSelected = true;
177 187
178 // A prim is only tainted if it's allowed to be edited by the person clicking it. 188 part.SendPropertiesToClient(remoteClient);
179 if (Permissions.CanEditObject(sog.UUID, remoteClient.AgentId) 189
180 || Permissions.CanMoveObject(sog.UUID, remoteClient.AgentId)) 190 // A prim is only tainted if it's allowed to be edited by the person clicking it.
181 { 191 if (Permissions.CanEditObject(sog.UUID, remoteClient.AgentId)
182 EventManager.TriggerParcelPrimCountTainted(); 192 || Permissions.CanMoveObject(sog.UUID, remoteClient.AgentId))
183 }
184 }
185 else
186 { 193 {
187 part.SendPropertiesToClient(remoteClient); 194 part.IsSelected = true;
195 EventManager.TriggerParcelPrimCountTainted();
188 } 196 }
189 } 197 }
190 198
@@ -237,7 +245,7 @@ namespace OpenSim.Region.Framework.Scenes
237 SceneObjectPart part = GetSceneObjectPart(primLocalID); 245 SceneObjectPart part = GetSceneObjectPart(primLocalID);
238 if (part == null) 246 if (part == null)
239 return; 247 return;
240 248 /*
241 // A deselect packet contains all the local prims being deselected. However, since selection is still 249 // A deselect packet contains all the local prims being deselected. However, since selection is still
242 // group based we only want the root prim to trigger a full update - otherwise on objects with many prims 250 // group based we only want the root prim to trigger a full update - otherwise on objects with many prims
243 // we end up sending many duplicate ObjectUpdates 251 // we end up sending many duplicate ObjectUpdates
@@ -250,7 +258,9 @@ namespace OpenSim.Region.Framework.Scenes
250 // handled by group, but by prim. Legacy cruft. 258 // handled by group, but by prim. Legacy cruft.
251 // TODO: Make selection flagging per prim! 259 // TODO: Make selection flagging per prim!
252 // 260 //
253 part.ParentGroup.IsSelected = false; 261 if (Permissions.CanEditObject(part.ParentGroup.UUID, remoteClient.AgentId)
262 || Permissions.CanMoveObject(part.ParentGroup.UUID, remoteClient.AgentId))
263 part.ParentGroup.IsSelected = false;
254 264
255 if (part.ParentGroup.IsAttachment) 265 if (part.ParentGroup.IsAttachment)
256 isAttachment = true; 266 isAttachment = true;
@@ -270,6 +280,22 @@ namespace OpenSim.Region.Framework.Scenes
270 part.UUID, remoteClient.AgentId)) 280 part.UUID, remoteClient.AgentId))
271 EventManager.TriggerParcelPrimCountTainted(); 281 EventManager.TriggerParcelPrimCountTainted();
272 } 282 }
283 */
284
285 bool oldgprSelect = part.ParentGroup.IsSelected;
286
287 // This is wrong, wrong, wrong. Selection should not be
288 // handled by group, but by prim. Legacy cruft.
289 // TODO: Make selection flagging per prim!
290 //
291 if (Permissions.CanEditObject(part.ParentGroup.UUID, remoteClient.AgentId)
292 || Permissions.CanMoveObject(part.ParentGroup.UUID, remoteClient.AgentId))
293 {
294 part.IsSelected = false;
295 if (!part.ParentGroup.IsAttachment && oldgprSelect != part.ParentGroup.IsSelected)
296 EventManager.TriggerParcelPrimCountTainted();
297 }
298
273 } 299 }
274 300
275 public virtual void ProcessMoneyTransferRequest(UUID source, UUID destination, int amount, 301 public virtual void ProcessMoneyTransferRequest(UUID source, UUID destination, int amount,
@@ -412,6 +438,20 @@ namespace OpenSim.Region.Framework.Scenes
412 ); 438 );
413 } 439 }
414 440
441 private class DescendentsRequestData
442 {
443 public IClientAPI RemoteClient;
444 public UUID FolderID;
445 public UUID OwnerID;
446 public bool FetchFolders;
447 public bool FetchItems;
448 public int SortOrder;
449 }
450
451 private Queue<DescendentsRequestData> m_descendentsRequestQueue = new Queue<DescendentsRequestData>();
452 private Object m_descendentsRequestLock = new Object();
453 private bool m_descendentsRequestProcessing = false;
454
415 /// <summary> 455 /// <summary>
416 /// Tell the client about the various child items and folders contained in the requested folder. 456 /// Tell the client about the various child items and folders contained in the requested folder.
417 /// </summary> 457 /// </summary>
@@ -448,17 +488,38 @@ namespace OpenSim.Region.Framework.Scenes
448 } 488 }
449 } 489 }
450 490
451 // We're going to send the reply async, because there may be 491 lock (m_descendentsRequestLock)
452 // an enormous quantity of packets -- basically the entire inventory! 492 {
453 // We don't want to block the client thread while all that is happening. 493 if (!m_descendentsRequestProcessing)
454 SendInventoryDelegate d = SendInventoryAsync; 494 {
455 d.BeginInvoke(remoteClient, folderID, ownerID, fetchFolders, fetchItems, sortOrder, SendInventoryComplete, d); 495 m_descendentsRequestProcessing = true;
496
497 // We're going to send the reply async, because there may be
498 // an enormous quantity of packets -- basically the entire inventory!
499 // We don't want to block the client thread while all that is happening.
500 SendInventoryDelegate d = SendInventoryAsync;
501 d.BeginInvoke(remoteClient, folderID, ownerID, fetchFolders, fetchItems, sortOrder, SendInventoryComplete, d);
502
503 return;
504 }
505
506 DescendentsRequestData req = new DescendentsRequestData();
507 req.RemoteClient = remoteClient;
508 req.FolderID = folderID;
509 req.OwnerID = ownerID;
510 req.FetchFolders = fetchFolders;
511 req.FetchItems = fetchItems;
512 req.SortOrder = sortOrder;
513
514 m_descendentsRequestQueue.Enqueue(req);
515 }
456 } 516 }
457 517
458 delegate void SendInventoryDelegate(IClientAPI remoteClient, UUID folderID, UUID ownerID, bool fetchFolders, bool fetchItems, int sortOrder); 518 delegate void SendInventoryDelegate(IClientAPI remoteClient, UUID folderID, UUID ownerID, bool fetchFolders, bool fetchItems, int sortOrder);
459 519
460 void SendInventoryAsync(IClientAPI remoteClient, UUID folderID, UUID ownerID, bool fetchFolders, bool fetchItems, int sortOrder) 520 void SendInventoryAsync(IClientAPI remoteClient, UUID folderID, UUID ownerID, bool fetchFolders, bool fetchItems, int sortOrder)
461 { 521 {
522 Thread.Sleep(20);
462 SendInventoryUpdate(remoteClient, new InventoryFolderBase(folderID), fetchFolders, fetchItems); 523 SendInventoryUpdate(remoteClient, new InventoryFolderBase(folderID), fetchFolders, fetchItems);
463 } 524 }
464 525
@@ -466,6 +527,21 @@ namespace OpenSim.Region.Framework.Scenes
466 { 527 {
467 SendInventoryDelegate d = (SendInventoryDelegate)iar.AsyncState; 528 SendInventoryDelegate d = (SendInventoryDelegate)iar.AsyncState;
468 d.EndInvoke(iar); 529 d.EndInvoke(iar);
530
531 lock (m_descendentsRequestLock)
532 {
533 if (m_descendentsRequestQueue.Count > 0)
534 {
535 DescendentsRequestData req = m_descendentsRequestQueue.Dequeue();
536
537 d = SendInventoryAsync;
538 d.BeginInvoke(req.RemoteClient, req.FolderID, req.OwnerID, req.FetchFolders, req.FetchItems, req.SortOrder, SendInventoryComplete, d);
539
540 return;
541 }
542
543 m_descendentsRequestProcessing = false;
544 }
469 } 545 }
470 546
471 /// <summary> 547 /// <summary>
diff --git a/OpenSim/Region/Framework/Scenes/Scene.cs b/OpenSim/Region/Framework/Scenes/Scene.cs
index 69fe137..a2510a78 100644
--- a/OpenSim/Region/Framework/Scenes/Scene.cs
+++ b/OpenSim/Region/Framework/Scenes/Scene.cs
@@ -227,8 +227,8 @@ namespace OpenSim.Region.Framework.Scenes
227 // TODO: need to figure out how allow client agents but deny 227 // TODO: need to figure out how allow client agents but deny
228 // root agents when ACL denies access to root agent 228 // root agents when ACL denies access to root agent
229 public bool m_strictAccessControl = true; 229 public bool m_strictAccessControl = true;
230 230 public bool m_seeIntoBannedRegion = false;
231 public int MaxUndoCount { get; set; } 231 public int MaxUndoCount = 5;
232 232
233 // Using this for RegionReady module to prevent LoginsDisabled from changing under our feet; 233 // Using this for RegionReady module to prevent LoginsDisabled from changing under our feet;
234 public bool LoginLock = false; 234 public bool LoginLock = false;
@@ -244,11 +244,13 @@ namespace OpenSim.Region.Framework.Scenes
244 244
245 protected int m_splitRegionID; 245 protected int m_splitRegionID;
246 protected Timer m_restartWaitTimer = new Timer(); 246 protected Timer m_restartWaitTimer = new Timer();
247 protected Timer m_timerWatchdog = new Timer();
247 protected List<RegionInfo> m_regionRestartNotifyList = new List<RegionInfo>(); 248 protected List<RegionInfo> m_regionRestartNotifyList = new List<RegionInfo>();
248 protected List<RegionInfo> m_neighbours = new List<RegionInfo>(); 249 protected List<RegionInfo> m_neighbours = new List<RegionInfo>();
249 protected string m_simulatorVersion = "OpenSimulator Server"; 250 protected string m_simulatorVersion = "OpenSimulator Server";
250 protected AgentCircuitManager m_authenticateHandler; 251 protected AgentCircuitManager m_authenticateHandler;
251 protected SceneCommunicationService m_sceneGridService; 252 protected SceneCommunicationService m_sceneGridService;
253 protected ISnmpModule m_snmpService = null;
252 254
253 protected ISimulationDataService m_SimulationDataService; 255 protected ISimulationDataService m_SimulationDataService;
254 protected IEstateDataService m_EstateDataService; 256 protected IEstateDataService m_EstateDataService;
@@ -311,8 +313,8 @@ namespace OpenSim.Region.Framework.Scenes
311 private int m_update_presences = 1; // Update scene presence movements 313 private int m_update_presences = 1; // Update scene presence movements
312 private int m_update_events = 1; 314 private int m_update_events = 1;
313 private int m_update_backup = 200; 315 private int m_update_backup = 200;
314 private int m_update_terrain = 50; 316 private int m_update_terrain = 1000;
315// private int m_update_land = 1; 317 private int m_update_land = 10;
316 private int m_update_coarse_locations = 50; 318 private int m_update_coarse_locations = 50;
317 319
318 private int agentMS; 320 private int agentMS;
@@ -325,13 +327,13 @@ namespace OpenSim.Region.Framework.Scenes
325 private int backupMS; 327 private int backupMS;
326 private int terrainMS; 328 private int terrainMS;
327 private int landMS; 329 private int landMS;
328 private int spareMS;
329 330
330 /// <summary> 331 /// <summary>
331 /// Tick at which the last frame was processed. 332 /// Tick at which the last frame was processed.
332 /// </summary> 333 /// </summary>
333 private int m_lastFrameTick; 334 private int m_lastFrameTick;
334 335
336 public bool CombineRegions = false;
335 /// <summary> 337 /// <summary>
336 /// Tick at which the last maintenance run occurred. 338 /// Tick at which the last maintenance run occurred.
337 /// </summary> 339 /// </summary>
@@ -351,7 +353,7 @@ namespace OpenSim.Region.Framework.Scenes
351 private readonly Timer m_restartTimer = new Timer(15000); // Wait before firing 353 private readonly Timer m_restartTimer = new Timer(15000); // Wait before firing
352 private volatile bool m_backingup; 354 private volatile bool m_backingup;
353 private Dictionary<UUID, ReturnInfo> m_returns = new Dictionary<UUID, ReturnInfo>(); 355 private Dictionary<UUID, ReturnInfo> m_returns = new Dictionary<UUID, ReturnInfo>();
354 private Dictionary<UUID, SceneObjectGroup> m_groupsWithTargets = new Dictionary<UUID, SceneObjectGroup>(); 356 private Dictionary<UUID, int> m_groupsWithTargets = new Dictionary<UUID, int>();
355 357
356 private string m_defaultScriptEngine; 358 private string m_defaultScriptEngine;
357 359
@@ -360,6 +362,11 @@ namespace OpenSim.Region.Framework.Scenes
360 /// </summary> 362 /// </summary>
361 private int m_LastLogin; 363 private int m_LastLogin;
362 364
365 private int m_lastIncoming;
366 private int m_lastOutgoing;
367 private int m_hbRestarts = 0;
368
369
363 /// <summary> 370 /// <summary>
364 /// Thread that runs the scene loop. 371 /// Thread that runs the scene loop.
365 /// </summary> 372 /// </summary>
@@ -400,7 +407,7 @@ namespace OpenSim.Region.Framework.Scenes
400 private volatile bool m_active; 407 private volatile bool m_active;
401 408
402// private int m_lastUpdate; 409// private int m_lastUpdate;
403// private bool m_firstHeartbeat = true; 410 private bool m_firstHeartbeat = true;
404 411
405 private UpdatePrioritizationSchemes m_priorityScheme = UpdatePrioritizationSchemes.Time; 412 private UpdatePrioritizationSchemes m_priorityScheme = UpdatePrioritizationSchemes.Time;
406 private bool m_reprioritizationEnabled = true; 413 private bool m_reprioritizationEnabled = true;
@@ -444,6 +451,19 @@ namespace OpenSim.Region.Framework.Scenes
444 get { return m_sceneGridService; } 451 get { return m_sceneGridService; }
445 } 452 }
446 453
454 public ISnmpModule SnmpService
455 {
456 get
457 {
458 if (m_snmpService == null)
459 {
460 m_snmpService = RequestModuleInterface<ISnmpModule>();
461 }
462
463 return m_snmpService;
464 }
465 }
466
447 public ISimulationDataService SimulationDataService 467 public ISimulationDataService SimulationDataService
448 { 468 {
449 get 469 get
@@ -736,6 +756,8 @@ namespace OpenSim.Region.Framework.Scenes
736 m_SimulationDataService = simDataService; 756 m_SimulationDataService = simDataService;
737 m_EstateDataService = estateDataService; 757 m_EstateDataService = estateDataService;
738 m_regionHandle = RegionInfo.RegionHandle; 758 m_regionHandle = RegionInfo.RegionHandle;
759 m_lastIncoming = 0;
760 m_lastOutgoing = 0;
739 761
740 m_asyncSceneObjectDeleter = new AsyncSceneObjectGroupDeleter(this); 762 m_asyncSceneObjectDeleter = new AsyncSceneObjectGroupDeleter(this);
741 m_asyncSceneObjectDeleter.Enabled = true; 763 m_asyncSceneObjectDeleter.Enabled = true;
@@ -829,7 +851,7 @@ namespace OpenSim.Region.Framework.Scenes
829 851
830 StartDisabled = startupConfig.GetBoolean("StartDisabled", false); 852 StartDisabled = startupConfig.GetBoolean("StartDisabled", false);
831 853
832 m_defaultDrawDistance = startupConfig.GetFloat("DefaultDrawDistance", m_defaultDrawDistance); 854 m_defaultDrawDistance = startupConfig.GetFloat("DefaultDrawDistance",m_defaultDrawDistance);
833 UseBackup = startupConfig.GetBoolean("UseSceneBackup", UseBackup); 855 UseBackup = startupConfig.GetBoolean("UseSceneBackup", UseBackup);
834 if (!UseBackup) 856 if (!UseBackup)
835 m_log.InfoFormat("[SCENE]: Backup has been disabled for {0}", RegionInfo.RegionName); 857 m_log.InfoFormat("[SCENE]: Backup has been disabled for {0}", RegionInfo.RegionName);
@@ -837,10 +859,8 @@ namespace OpenSim.Region.Framework.Scenes
837 //Animation states 859 //Animation states
838 m_useFlySlow = startupConfig.GetBoolean("enableflyslow", false); 860 m_useFlySlow = startupConfig.GetBoolean("enableflyslow", false);
839 861
840 MaxUndoCount = startupConfig.GetInt("MaxPrimUndos", 20); 862 PhysicalPrims = startupConfig.GetBoolean("physical_prim", true);
841 863 CollidablePrims = startupConfig.GetBoolean("collidable_prim", true);
842 PhysicalPrims = startupConfig.GetBoolean("physical_prim", PhysicalPrims);
843 CollidablePrims = startupConfig.GetBoolean("collidable_prim", CollidablePrims);
844 864
845 m_minNonphys = startupConfig.GetFloat("NonPhysicalPrimMin", m_minNonphys); 865 m_minNonphys = startupConfig.GetFloat("NonPhysicalPrimMin", m_minNonphys);
846 if (RegionInfo.NonphysPrimMin > 0) 866 if (RegionInfo.NonphysPrimMin > 0)
@@ -861,11 +881,21 @@ namespace OpenSim.Region.Framework.Scenes
861 } 881 }
862 882
863 m_maxPhys = startupConfig.GetFloat("PhysicalPrimMax", m_maxPhys); 883 m_maxPhys = startupConfig.GetFloat("PhysicalPrimMax", m_maxPhys);
884
864 if (RegionInfo.PhysPrimMax > 0) 885 if (RegionInfo.PhysPrimMax > 0)
865 { 886 {
866 m_maxPhys = RegionInfo.PhysPrimMax; 887 m_maxPhys = RegionInfo.PhysPrimMax;
867 } 888 }
868 889
890 m_linksetCapacity = startupConfig.GetInt("LinksetPrims", m_linksetCapacity);
891 if (RegionInfo.LinksetCapacity > 0)
892 {
893 m_linksetCapacity = RegionInfo.LinksetCapacity;
894 }
895
896 SpawnPointRouting = startupConfig.GetString("SpawnPointRouting", "closest");
897 TelehubAllowLandmarks = startupConfig.GetBoolean("TelehubAllowLandmark", false);
898
869 // Here, if clamping is requested in either global or 899 // Here, if clamping is requested in either global or
870 // local config, it will be used 900 // local config, it will be used
871 // 901 //
@@ -875,13 +905,7 @@ namespace OpenSim.Region.Framework.Scenes
875 m_clampPrimSize = true; 905 m_clampPrimSize = true;
876 } 906 }
877 907
878 m_linksetCapacity = startupConfig.GetInt("LinksetPrims", m_linksetCapacity); 908 m_useTrashOnDelete = startupConfig.GetBoolean("UseTrashOnDelete",m_useTrashOnDelete);
879 if (RegionInfo.LinksetCapacity > 0)
880 {
881 m_linksetCapacity = RegionInfo.LinksetCapacity;
882 }
883
884 m_useTrashOnDelete = startupConfig.GetBoolean("UseTrashOnDelete", m_useTrashOnDelete);
885 m_trustBinaries = startupConfig.GetBoolean("TrustBinaries", m_trustBinaries); 909 m_trustBinaries = startupConfig.GetBoolean("TrustBinaries", m_trustBinaries);
886 m_allowScriptCrossings = startupConfig.GetBoolean("AllowScriptCrossing", m_allowScriptCrossings); 910 m_allowScriptCrossings = startupConfig.GetBoolean("AllowScriptCrossing", m_allowScriptCrossings);
887 m_dontPersistBefore = 911 m_dontPersistBefore =
@@ -892,11 +916,11 @@ namespace OpenSim.Region.Framework.Scenes
892 m_persistAfter *= 10000000; 916 m_persistAfter *= 10000000;
893 917
894 m_defaultScriptEngine = startupConfig.GetString("DefaultScriptEngine", "XEngine"); 918 m_defaultScriptEngine = startupConfig.GetString("DefaultScriptEngine", "XEngine");
895 919 m_log.InfoFormat("[SCENE]: Default script engine {0}", m_defaultScriptEngine);
896 SpawnPointRouting = startupConfig.GetString("SpawnPointRouting", "closest");
897 TelehubAllowLandmarks = startupConfig.GetBoolean("TelehubAllowLandmark", false);
898 920
899 m_strictAccessControl = startupConfig.GetBoolean("StrictAccessControl", m_strictAccessControl); 921 m_strictAccessControl = startupConfig.GetBoolean("StrictAccessControl", m_strictAccessControl);
922 m_seeIntoBannedRegion = startupConfig.GetBoolean("SeeIntoBannedRegion", m_seeIntoBannedRegion);
923 CombineRegions = startupConfig.GetBoolean("CombineContiguousRegions", false);
900 924
901 string[] possibleMapConfigSections = new string[] { "Map", "Startup" }; 925 string[] possibleMapConfigSections = new string[] { "Map", "Startup" };
902 926
@@ -941,7 +965,7 @@ namespace OpenSim.Region.Framework.Scenes
941 965
942 if (grant.Length > 0) 966 if (grant.Length > 0)
943 { 967 {
944 foreach (string viewer in grant.Split('|')) 968 foreach (string viewer in grant.Split(','))
945 { 969 {
946 m_AllowedViewers.Add(viewer.Trim().ToLower()); 970 m_AllowedViewers.Add(viewer.Trim().ToLower());
947 } 971 }
@@ -953,7 +977,7 @@ namespace OpenSim.Region.Framework.Scenes
953 977
954 if (grant.Length > 0) 978 if (grant.Length > 0)
955 { 979 {
956 foreach (string viewer in grant.Split('|')) 980 foreach (string viewer in grant.Split(','))
957 { 981 {
958 m_BannedViewers.Add(viewer.Trim().ToLower()); 982 m_BannedViewers.Add(viewer.Trim().ToLower());
959 } 983 }
@@ -1013,6 +1037,8 @@ namespace OpenSim.Region.Framework.Scenes
1013 StatsReporter = new SimStatsReporter(this); 1037 StatsReporter = new SimStatsReporter(this);
1014 StatsReporter.OnSendStatsResult += SendSimStatsPackets; 1038 StatsReporter.OnSendStatsResult += SendSimStatsPackets;
1015 StatsReporter.OnStatsIncorrect += m_sceneGraph.RecalculateStats; 1039 StatsReporter.OnStatsIncorrect += m_sceneGraph.RecalculateStats;
1040
1041 MainConsole.Instance.Commands.AddCommand("scene", false, "gc collect", "gc collect", "gc collect", "Cause the garbage collector to make a single pass", HandleGcCollect);
1016 } 1042 }
1017 1043
1018 public Scene(RegionInfo regInfo) : base(regInfo) 1044 public Scene(RegionInfo regInfo) : base(regInfo)
@@ -1308,8 +1334,11 @@ namespace OpenSim.Region.Framework.Scenes
1308 // Stop all client threads. 1334 // Stop all client threads.
1309 ForEachScenePresence(delegate(ScenePresence avatar) { avatar.ControllingClient.Close(); }); 1335 ForEachScenePresence(delegate(ScenePresence avatar) { avatar.ControllingClient.Close(); });
1310 1336
1311 m_log.Debug("[SCENE]: Persisting changed objects"); 1337 m_log.Debug("[SCENE]: TriggerSceneShuttingDown");
1312 EventManager.TriggerSceneShuttingDown(this); 1338 EventManager.TriggerSceneShuttingDown(this);
1339
1340 m_log.Debug("[SCENE]: Persisting changed objects");
1341
1313 Backup(false); 1342 Backup(false);
1314 m_sceneGraph.Close(); 1343 m_sceneGraph.Close();
1315 1344
@@ -1323,6 +1352,7 @@ namespace OpenSim.Region.Framework.Scenes
1323 // attempt to reference a null or disposed physics scene. 1352 // attempt to reference a null or disposed physics scene.
1324 if (PhysicsScene != null) 1353 if (PhysicsScene != null)
1325 { 1354 {
1355 m_log.Debug("[SCENE]: Dispose Physics");
1326 PhysicsScene phys = PhysicsScene; 1356 PhysicsScene phys = PhysicsScene;
1327 // remove the physics engine from both Scene and SceneGraph 1357 // remove the physics engine from both Scene and SceneGraph
1328 PhysicsScene = null; 1358 PhysicsScene = null;
@@ -1345,11 +1375,29 @@ namespace OpenSim.Region.Framework.Scenes
1345 //m_heartbeatTimer.Elapsed += new ElapsedEventHandler(Heartbeat); 1375 //m_heartbeatTimer.Elapsed += new ElapsedEventHandler(Heartbeat);
1346 if (m_heartbeatThread != null) 1376 if (m_heartbeatThread != null)
1347 { 1377 {
1378 m_hbRestarts++;
1379 if(m_hbRestarts > 10)
1380 Environment.Exit(1);
1381 m_log.ErrorFormat("[SCENE]: Restarting heartbeat thread because it hasn't reported in in region {0}", RegionInfo.RegionName);
1382
1383//int pid = System.Diagnostics.Process.GetCurrentProcess().Id;
1384//System.Diagnostics.Process proc = new System.Diagnostics.Process();
1385//proc.EnableRaisingEvents=false;
1386//proc.StartInfo.FileName = "/bin/kill";
1387//proc.StartInfo.Arguments = "-QUIT " + pid.ToString();
1388//proc.Start();
1389//proc.WaitForExit();
1390//Thread.Sleep(1000);
1391//Environment.Exit(1);
1348 m_heartbeatThread.Abort(); 1392 m_heartbeatThread.Abort();
1393 Watchdog.AbortThread(m_heartbeatThread.ManagedThreadId);
1349 m_heartbeatThread = null; 1394 m_heartbeatThread = null;
1350 } 1395 }
1351// m_lastUpdate = Util.EnvironmentTickCount(); 1396// m_lastUpdate = Util.EnvironmentTickCount();
1352 1397
1398// m_sceneGraph.PreparePhysicsSimulation();
1399
1400
1353 m_heartbeatThread 1401 m_heartbeatThread
1354 = Watchdog.StartThread( 1402 = Watchdog.StartThread(
1355 Heartbeat, string.Format("Heartbeat ({0})", RegionInfo.RegionName), ThreadPriority.Normal, false, false); 1403 Heartbeat, string.Format("Heartbeat ({0})", RegionInfo.RegionName), ThreadPriority.Normal, false, false);
@@ -1492,16 +1540,20 @@ namespace OpenSim.Region.Framework.Scenes
1492 endFrame = Frame + frames; 1540 endFrame = Frame + frames;
1493 1541
1494 float physicsFPS = 0f; 1542 float physicsFPS = 0f;
1495 int previousFrameTick, tmpMS; 1543 int tmpMS;
1496 int maintc = Util.EnvironmentTickCount(); 1544 int previousFrameTick;
1545 int maintc;
1546 int sleepMS;
1547 int framestart;
1497 1548
1498 while (!m_shuttingDown && ((endFrame == null && Active) || Frame < endFrame)) 1549 while (!m_shuttingDown && ((endFrame == null && Active) || Frame < endFrame))
1499 { 1550 {
1551 framestart = Util.EnvironmentTickCount();
1500 ++Frame; 1552 ++Frame;
1501 1553
1502// m_log.DebugFormat("[SCENE]: Processing frame {0} in {1}", Frame, RegionInfo.RegionName); 1554// m_log.DebugFormat("[SCENE]: Processing frame {0} in {1}", Frame, RegionInfo.RegionName);
1503 1555
1504 agentMS = tempOnRezMS = eventMS = backupMS = terrainMS = landMS = spareMS = 0; 1556 agentMS = tempOnRezMS = eventMS = backupMS = terrainMS = landMS = 0;
1505 1557
1506 try 1558 try
1507 { 1559 {
@@ -1553,6 +1605,7 @@ namespace OpenSim.Region.Framework.Scenes
1553 m_sceneGraph.UpdatePresences(); 1605 m_sceneGraph.UpdatePresences();
1554 1606
1555 agentMS += Util.EnvironmentTickCountSubtract(tmpMS); 1607 agentMS += Util.EnvironmentTickCountSubtract(tmpMS);
1608
1556 1609
1557 // Delete temp-on-rez stuff 1610 // Delete temp-on-rez stuff
1558 if (Frame % m_update_temp_cleaning == 0 && !m_cleaningTemps) 1611 if (Frame % m_update_temp_cleaning == 0 && !m_cleaningTemps)
@@ -1634,34 +1687,37 @@ namespace OpenSim.Region.Framework.Scenes
1634 1687
1635 Watchdog.UpdateThread(); 1688 Watchdog.UpdateThread();
1636 1689
1690 otherMS = tempOnRezMS + eventMS + backupMS + terrainMS + landMS;
1691
1692 StatsReporter.AddPhysicsFPS(physicsFPS);
1693 StatsReporter.AddTimeDilation(TimeDilation);
1694 StatsReporter.AddFPS(1);
1695
1696 StatsReporter.addAgentMS(agentMS);
1697 StatsReporter.addPhysicsMS(physicsMS + physicsMS2);
1698 StatsReporter.addOtherMS(otherMS);
1699 StatsReporter.addScriptLines(m_sceneGraph.GetScriptLPS());
1700
1637 previousFrameTick = m_lastFrameTick; 1701 previousFrameTick = m_lastFrameTick;
1638 m_lastFrameTick = Util.EnvironmentTickCount(); 1702 m_lastFrameTick = Util.EnvironmentTickCount();
1639 tmpMS = Util.EnvironmentTickCountSubtract(m_lastFrameTick, maintc); 1703 tmpMS = Util.EnvironmentTickCountSubtract(m_lastFrameTick, framestart);
1640 tmpMS = (int)(MinFrameTime * 1000) - tmpMS; 1704 tmpMS = (int)(MinFrameTime * 1000) - tmpMS;
1641 1705
1706 m_firstHeartbeat = false;
1707
1708 sleepMS = Util.EnvironmentTickCount();
1709
1642 if (tmpMS > 0) 1710 if (tmpMS > 0)
1643 {
1644 Thread.Sleep(tmpMS); 1711 Thread.Sleep(tmpMS);
1645 spareMS += tmpMS;
1646 }
1647 1712
1648 frameMS = Util.EnvironmentTickCountSubtract(maintc); 1713 sleepMS = Util.EnvironmentTickCountSubtract(sleepMS);
1649 maintc = Util.EnvironmentTickCount(); 1714 frameMS = Util.EnvironmentTickCountSubtract(framestart);
1650 1715 StatsReporter.addSleepMS(sleepMS);
1651 otherMS = tempOnRezMS + eventMS + backupMS + terrainMS + landMS; 1716 StatsReporter.addFrameMS(frameMS);
1652 1717
1653 // if (Frame%m_update_avatars == 0) 1718 // if (Frame%m_update_avatars == 0)
1654 // UpdateInWorldTime(); 1719 // UpdateInWorldTime();
1655 StatsReporter.AddPhysicsFPS(physicsFPS);
1656 StatsReporter.AddTimeDilation(TimeDilation);
1657 StatsReporter.AddFPS(1);
1658 1720
1659 StatsReporter.addFrameMS(frameMS);
1660 StatsReporter.addAgentMS(agentMS);
1661 StatsReporter.addPhysicsMS(physicsMS + physicsMS2);
1662 StatsReporter.addOtherMS(otherMS);
1663 StatsReporter.AddSpareMS(spareMS);
1664 StatsReporter.addScriptLines(m_sceneGraph.GetScriptLPS());
1665 1721
1666 // Optionally warn if a frame takes double the amount of time that it should. 1722 // Optionally warn if a frame takes double the amount of time that it should.
1667 if (DebugUpdates 1723 if (DebugUpdates
@@ -1678,7 +1734,7 @@ namespace OpenSim.Region.Framework.Scenes
1678 public void AddGroupTarget(SceneObjectGroup grp) 1734 public void AddGroupTarget(SceneObjectGroup grp)
1679 { 1735 {
1680 lock (m_groupsWithTargets) 1736 lock (m_groupsWithTargets)
1681 m_groupsWithTargets[grp.UUID] = grp; 1737 m_groupsWithTargets[grp.UUID] = 0;
1682 } 1738 }
1683 1739
1684 public void RemoveGroupTarget(SceneObjectGroup grp) 1740 public void RemoveGroupTarget(SceneObjectGroup grp)
@@ -1689,18 +1745,24 @@ namespace OpenSim.Region.Framework.Scenes
1689 1745
1690 private void CheckAtTargets() 1746 private void CheckAtTargets()
1691 { 1747 {
1692 List<SceneObjectGroup> objs = null; 1748 List<UUID> objs = null;
1693 1749
1694 lock (m_groupsWithTargets) 1750 lock (m_groupsWithTargets)
1695 { 1751 {
1696 if (m_groupsWithTargets.Count != 0) 1752 if (m_groupsWithTargets.Count != 0)
1697 objs = new List<SceneObjectGroup>(m_groupsWithTargets.Values); 1753 objs = new List<UUID>(m_groupsWithTargets.Keys);
1698 } 1754 }
1699 1755
1700 if (objs != null) 1756 if (objs != null)
1701 { 1757 {
1702 foreach (SceneObjectGroup entry in objs) 1758 foreach (UUID entry in objs)
1703 entry.checkAtTargets(); 1759 {
1760 SceneObjectGroup grp = GetSceneObjectGroup(entry);
1761 if (grp == null)
1762 m_groupsWithTargets.Remove(entry);
1763 else
1764 grp.checkAtTargets();
1765 }
1704 } 1766 }
1705 } 1767 }
1706 1768
@@ -1779,7 +1841,7 @@ namespace OpenSim.Region.Framework.Scenes
1779 msg.fromAgentName = "Server"; 1841 msg.fromAgentName = "Server";
1780 msg.dialog = (byte)19; // Object msg 1842 msg.dialog = (byte)19; // Object msg
1781 msg.fromGroup = false; 1843 msg.fromGroup = false;
1782 msg.offline = (byte)0; 1844 msg.offline = (byte)1;
1783 msg.ParentEstateID = RegionInfo.EstateSettings.ParentEstateID; 1845 msg.ParentEstateID = RegionInfo.EstateSettings.ParentEstateID;
1784 msg.Position = Vector3.Zero; 1846 msg.Position = Vector3.Zero;
1785 msg.RegionID = RegionInfo.RegionID.Guid; 1847 msg.RegionID = RegionInfo.RegionID.Guid;
@@ -2008,7 +2070,7 @@ namespace OpenSim.Region.Framework.Scenes
2008 return PhysicsScene.SupportsRaycastWorldFiltered(); 2070 return PhysicsScene.SupportsRaycastWorldFiltered();
2009 } 2071 }
2010 2072
2011 public object RayCastFiltered(Vector3 position, Vector3 direction, float length, int Count, RayFilterFlags filter) 2073 public object RayCastFiltered(Vector3 position, Vector3 direction, float length, int Count, RayFilterFlags filter)
2012 { 2074 {
2013 if (PhysicsScene == null) 2075 if (PhysicsScene == null)
2014 return null; 2076 return null;
@@ -2030,14 +2092,24 @@ namespace OpenSim.Region.Framework.Scenes
2030 /// <returns></returns> 2092 /// <returns></returns>
2031 public Vector3 GetNewRezLocation(Vector3 RayStart, Vector3 RayEnd, UUID RayTargetID, Quaternion rot, byte bypassRayCast, byte RayEndIsIntersection, bool frontFacesOnly, Vector3 scale, bool FaceCenter) 2093 public Vector3 GetNewRezLocation(Vector3 RayStart, Vector3 RayEnd, UUID RayTargetID, Quaternion rot, byte bypassRayCast, byte RayEndIsIntersection, bool frontFacesOnly, Vector3 scale, bool FaceCenter)
2032 { 2094 {
2095
2096 float wheight = (float)RegionInfo.RegionSettings.WaterHeight;
2097 Vector3 wpos = Vector3.Zero;
2098 // Check for water surface intersection from above
2099 if ( (RayStart.Z > wheight) && (RayEnd.Z < wheight) )
2100 {
2101 float ratio = (RayStart.Z - wheight) / (RayStart.Z - RayEnd.Z);
2102 wpos.X = RayStart.X - (ratio * (RayStart.X - RayEnd.X));
2103 wpos.Y = RayStart.Y - (ratio * (RayStart.Y - RayEnd.Y));
2104 wpos.Z = wheight;
2105 }
2106
2033 Vector3 pos = Vector3.Zero; 2107 Vector3 pos = Vector3.Zero;
2034 if (RayEndIsIntersection == (byte)1) 2108 if (RayEndIsIntersection == (byte)1)
2035 { 2109 {
2036 pos = RayEnd; 2110 pos = RayEnd;
2037 return pos;
2038 } 2111 }
2039 2112 else if (RayTargetID != UUID.Zero)
2040 if (RayTargetID != UUID.Zero)
2041 { 2113 {
2042 SceneObjectPart target = GetSceneObjectPart(RayTargetID); 2114 SceneObjectPart target = GetSceneObjectPart(RayTargetID);
2043 2115
@@ -2059,7 +2131,7 @@ namespace OpenSim.Region.Framework.Scenes
2059 EntityIntersection ei = target.TestIntersectionOBB(NewRay, Quaternion.Identity, frontFacesOnly, FaceCenter); 2131 EntityIntersection ei = target.TestIntersectionOBB(NewRay, Quaternion.Identity, frontFacesOnly, FaceCenter);
2060 2132
2061 // Un-comment out the following line to Get Raytrace results printed to the console. 2133 // Un-comment out the following line to Get Raytrace results printed to the console.
2062 // m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString()); 2134 // m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
2063 float ScaleOffset = 0.5f; 2135 float ScaleOffset = 0.5f;
2064 2136
2065 // If we hit something 2137 // If we hit something
@@ -2082,13 +2154,10 @@ namespace OpenSim.Region.Framework.Scenes
2082 //pos.Z -= 0.25F; 2154 //pos.Z -= 0.25F;
2083 2155
2084 } 2156 }
2085
2086 return pos;
2087 } 2157 }
2088 else 2158 else
2089 { 2159 {
2090 // We don't have a target here, so we're going to raytrace all the objects in the scene. 2160 // We don't have a target here, so we're going to raytrace all the objects in the scene.
2091
2092 EntityIntersection ei = m_sceneGraph.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection), true, false); 2161 EntityIntersection ei = m_sceneGraph.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection), true, false);
2093 2162
2094 // Un-comment the following line to print the raytrace results to the console. 2163 // Un-comment the following line to print the raytrace results to the console.
@@ -2097,13 +2166,12 @@ namespace OpenSim.Region.Framework.Scenes
2097 if (ei.HitTF) 2166 if (ei.HitTF)
2098 { 2167 {
2099 pos = new Vector3(ei.ipoint.X, ei.ipoint.Y, ei.ipoint.Z); 2168 pos = new Vector3(ei.ipoint.X, ei.ipoint.Y, ei.ipoint.Z);
2100 } else 2169 }
2170 else
2101 { 2171 {
2102 // fall back to our stupid functionality 2172 // fall back to our stupid functionality
2103 pos = RayEnd; 2173 pos = RayEnd;
2104 } 2174 }
2105
2106 return pos;
2107 } 2175 }
2108 } 2176 }
2109 else 2177 else
@@ -2114,8 +2182,12 @@ namespace OpenSim.Region.Framework.Scenes
2114 //increase height so its above the ground. 2182 //increase height so its above the ground.
2115 //should be getting the normal of the ground at the rez point and using that? 2183 //should be getting the normal of the ground at the rez point and using that?
2116 pos.Z += scale.Z / 2f; 2184 pos.Z += scale.Z / 2f;
2117 return pos; 2185// return pos;
2118 } 2186 }
2187
2188 // check against posible water intercept
2189 if (wpos.Z > pos.Z) pos = wpos;
2190 return pos;
2119 } 2191 }
2120 2192
2121 2193
@@ -2206,12 +2278,12 @@ namespace OpenSim.Region.Framework.Scenes
2206 { 2278 {
2207 if (m_sceneGraph.AddRestoredSceneObject(sceneObject, attachToBackup, alreadyPersisted, sendClientUpdates)) 2279 if (m_sceneGraph.AddRestoredSceneObject(sceneObject, attachToBackup, alreadyPersisted, sendClientUpdates))
2208 { 2280 {
2281 sceneObject.IsDeleted = false;
2209 EventManager.TriggerObjectAddedToScene(sceneObject); 2282 EventManager.TriggerObjectAddedToScene(sceneObject);
2210 return true; 2283 return true;
2211 } 2284 }
2212 2285
2213 return false; 2286 return false;
2214
2215 } 2287 }
2216 2288
2217 /// <summary> 2289 /// <summary>
@@ -2303,6 +2375,15 @@ namespace OpenSim.Region.Framework.Scenes
2303 /// </summary> 2375 /// </summary>
2304 public void DeleteAllSceneObjects() 2376 public void DeleteAllSceneObjects()
2305 { 2377 {
2378 DeleteAllSceneObjects(false);
2379 }
2380
2381 /// <summary>
2382 /// Delete every object from the scene. This does not include attachments worn by avatars.
2383 /// </summary>
2384 public void DeleteAllSceneObjects(bool exceptNoCopy)
2385 {
2386 List<SceneObjectGroup> toReturn = new List<SceneObjectGroup>();
2306 lock (Entities) 2387 lock (Entities)
2307 { 2388 {
2308 EntityBase[] entities = Entities.GetEntities(); 2389 EntityBase[] entities = Entities.GetEntities();
@@ -2311,11 +2392,24 @@ namespace OpenSim.Region.Framework.Scenes
2311 if (e is SceneObjectGroup) 2392 if (e is SceneObjectGroup)
2312 { 2393 {
2313 SceneObjectGroup sog = (SceneObjectGroup)e; 2394 SceneObjectGroup sog = (SceneObjectGroup)e;
2314 if (!sog.IsAttachment) 2395 if (sog != null && !sog.IsAttachment)
2315 DeleteSceneObject((SceneObjectGroup)e, false); 2396 {
2397 if (!exceptNoCopy || ((sog.GetEffectivePermissions() & (uint)PermissionMask.Copy) != 0))
2398 {
2399 DeleteSceneObject((SceneObjectGroup)e, false);
2400 }
2401 else
2402 {
2403 toReturn.Add((SceneObjectGroup)e);
2404 }
2405 }
2316 } 2406 }
2317 } 2407 }
2318 } 2408 }
2409 if (toReturn.Count > 0)
2410 {
2411 returnObjects(toReturn.ToArray(), UUID.Zero);
2412 }
2319 } 2413 }
2320 2414
2321 /// <summary> 2415 /// <summary>
@@ -2350,6 +2444,12 @@ namespace OpenSim.Region.Framework.Scenes
2350 2444
2351 foreach (SceneObjectPart part in partList) 2445 foreach (SceneObjectPart part in partList)
2352 { 2446 {
2447 if (part.KeyframeMotion != null)
2448 {
2449 part.KeyframeMotion.Delete();
2450 part.KeyframeMotion = null;
2451 }
2452
2353 if (part.IsJoint() && ((part.Flags & PrimFlags.Physics) != 0)) 2453 if (part.IsJoint() && ((part.Flags & PrimFlags.Physics) != 0))
2354 { 2454 {
2355 PhysicsScene.RequestJointDeletion(part.Name); // FIXME: what if the name changed? 2455 PhysicsScene.RequestJointDeletion(part.Name); // FIXME: what if the name changed?
@@ -2367,6 +2467,8 @@ namespace OpenSim.Region.Framework.Scenes
2367 } 2467 }
2368 2468
2369 group.DeleteGroupFromScene(silent); 2469 group.DeleteGroupFromScene(silent);
2470 if (!silent)
2471 SendKillObject(new List<uint>() { group.LocalId });
2370 2472
2371// m_log.DebugFormat("[SCENE]: Exit DeleteSceneObject() for {0} {1}", group.Name, group.UUID); 2473// m_log.DebugFormat("[SCENE]: Exit DeleteSceneObject() for {0} {1}", group.Name, group.UUID);
2372 } 2474 }
@@ -2656,7 +2758,7 @@ namespace OpenSim.Region.Framework.Scenes
2656 // If the user is banned, we won't let any of their objects 2758 // If the user is banned, we won't let any of their objects
2657 // enter. Period. 2759 // enter. Period.
2658 // 2760 //
2659 if (RegionInfo.EstateSettings.IsBanned(newObject.OwnerID)) 2761 if (RegionInfo.EstateSettings.IsBanned(newObject.OwnerID, 36))
2660 { 2762 {
2661 m_log.InfoFormat("[INTERREGION]: Denied prim crossing for banned avatar {0}", newObject.OwnerID); 2763 m_log.InfoFormat("[INTERREGION]: Denied prim crossing for banned avatar {0}", newObject.OwnerID);
2662 return false; 2764 return false;
@@ -2691,6 +2793,9 @@ namespace OpenSim.Region.Framework.Scenes
2691 // before we restart the scripts, or else some functions won't work. 2793 // before we restart the scripts, or else some functions won't work.
2692 newObject.RootPart.ParentGroup.CreateScriptInstances(0, false, DefaultScriptEngine, GetStateSource(newObject)); 2794 newObject.RootPart.ParentGroup.CreateScriptInstances(0, false, DefaultScriptEngine, GetStateSource(newObject));
2693 newObject.ResumeScripts(); 2795 newObject.ResumeScripts();
2796
2797 if (newObject.RootPart.KeyframeMotion != null)
2798 newObject.RootPart.KeyframeMotion.UpdateSceneObject(newObject);
2694 } 2799 }
2695 2800
2696 // Do this as late as possible so that listeners have full access to the incoming object 2801 // Do this as late as possible so that listeners have full access to the incoming object
@@ -2708,6 +2813,23 @@ namespace OpenSim.Region.Framework.Scenes
2708 /// <returns>True if the SceneObjectGroup was added, False if it was not</returns> 2813 /// <returns>True if the SceneObjectGroup was added, False if it was not</returns>
2709 public bool AddSceneObject(SceneObjectGroup sceneObject) 2814 public bool AddSceneObject(SceneObjectGroup sceneObject)
2710 { 2815 {
2816 if (sceneObject.OwnerID == UUID.Zero)
2817 {
2818 m_log.ErrorFormat("[SCENE]: Owner ID for {0} was zero", sceneObject.UUID);
2819 return false;
2820 }
2821
2822 // If the user is banned, we won't let any of their objects
2823 // enter. Period.
2824 //
2825 int flags = GetUserFlags(sceneObject.OwnerID);
2826 if (RegionInfo.EstateSettings.IsBanned(sceneObject.OwnerID, flags))
2827 {
2828 m_log.InfoFormat("[INTERREGION]: Denied prim crossing for banned avatar {0}", sceneObject.OwnerID);
2829
2830 return false;
2831 }
2832
2711 // Force allocation of new LocalId 2833 // Force allocation of new LocalId
2712 // 2834 //
2713 SceneObjectPart[] parts = sceneObject.Parts; 2835 SceneObjectPart[] parts = sceneObject.Parts;
@@ -2744,16 +2866,27 @@ namespace OpenSim.Region.Framework.Scenes
2744 // information that this is due to a teleport/border cross rather than an ordinary attachment. 2866 // information that this is due to a teleport/border cross rather than an ordinary attachment.
2745 // We currently do this in Scene.MakeRootAgent() instead. 2867 // We currently do this in Scene.MakeRootAgent() instead.
2746 if (AttachmentsModule != null) 2868 if (AttachmentsModule != null)
2747 AttachmentsModule.AttachObject(sp, grp, 0, false, false, true); 2869 AttachmentsModule.AttachObject(sp, grp, 0, false, false, false, true);
2748 } 2870 }
2749 else 2871 else
2750 { 2872 {
2873 m_log.DebugFormat("[SCENE]: Attachment {0} arrived and scene presence was not found, setting to temp", sceneObject.UUID);
2751 RootPrim.RemFlag(PrimFlags.TemporaryOnRez); 2874 RootPrim.RemFlag(PrimFlags.TemporaryOnRez);
2752 RootPrim.AddFlag(PrimFlags.TemporaryOnRez); 2875 RootPrim.AddFlag(PrimFlags.TemporaryOnRez);
2753 } 2876 }
2877 if (sceneObject.OwnerID == UUID.Zero)
2878 {
2879 m_log.ErrorFormat("[SCENE]: Owner ID for {0} was zero after attachment processing. BUG!", sceneObject.UUID);
2880 return false;
2881 }
2754 } 2882 }
2755 else 2883 else
2756 { 2884 {
2885 if (sceneObject.OwnerID == UUID.Zero)
2886 {
2887 m_log.ErrorFormat("[SCENE]: Owner ID for non-attachment {0} was zero", sceneObject.UUID);
2888 return false;
2889 }
2757 AddRestoredSceneObject(sceneObject, true, false); 2890 AddRestoredSceneObject(sceneObject, true, false);
2758 } 2891 }
2759 2892
@@ -2770,6 +2903,24 @@ namespace OpenSim.Region.Framework.Scenes
2770 return 2; // StateSource.PrimCrossing 2903 return 2; // StateSource.PrimCrossing
2771 } 2904 }
2772 2905
2906 public int GetUserFlags(UUID user)
2907 {
2908 //Unfortunately the SP approach means that the value is cached until region is restarted
2909 /*
2910 ScenePresence sp;
2911 if (TryGetScenePresence(user, out sp))
2912 {
2913 return sp.UserFlags;
2914 }
2915 else
2916 {
2917 */
2918 UserAccount uac = UserAccountService.GetUserAccount(RegionInfo.ScopeID, user);
2919 if (uac == null)
2920 return 0;
2921 return uac.UserFlags;
2922 //}
2923 }
2773 #endregion 2924 #endregion
2774 2925
2775 #region Add/Remove Avatar Methods 2926 #region Add/Remove Avatar Methods
@@ -2802,7 +2953,7 @@ namespace OpenSim.Region.Framework.Scenes
2802 = (aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaHGLogin) != 0 2953 = (aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaHGLogin) != 0
2803 || (aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaLogin) != 0; 2954 || (aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaLogin) != 0;
2804 2955
2805 // CheckHeartbeat(); 2956 CheckHeartbeat();
2806 2957
2807 sp = GetScenePresence(client.AgentId); 2958 sp = GetScenePresence(client.AgentId);
2808 2959
@@ -2820,6 +2971,13 @@ namespace OpenSim.Region.Framework.Scenes
2820 SubscribeToClientEvents(client); 2971 SubscribeToClientEvents(client);
2821 2972
2822 sp = m_sceneGraph.CreateAndAddChildScenePresence(client, aCircuit.Appearance, type); 2973 sp = m_sceneGraph.CreateAndAddChildScenePresence(client, aCircuit.Appearance, type);
2974 InventoryFolderBase cof = InventoryService.GetFolderForType(client.AgentId, (AssetType)46);
2975 if (cof == null)
2976 sp.COF = UUID.Zero;
2977 else
2978 sp.COF = cof.ID;
2979
2980 m_log.DebugFormat("[SCENE]: COF for {0} is {1}", client.AgentId, sp.COF);
2823 m_eventManager.TriggerOnNewPresence(sp); 2981 m_eventManager.TriggerOnNewPresence(sp);
2824 2982
2825 sp.TeleportFlags = (TPFlags)aCircuit.teleportFlags; 2983 sp.TeleportFlags = (TPFlags)aCircuit.teleportFlags;
@@ -2932,19 +3090,14 @@ namespace OpenSim.Region.Framework.Scenes
2932 // and the scene presence and the client, if they exist 3090 // and the scene presence and the client, if they exist
2933 try 3091 try
2934 { 3092 {
2935 // We need to wait for the client to make UDP contact first. 3093 ScenePresence sp = GetScenePresence(agentID);
2936 // It's the UDP contact that creates the scene presence 3094
2937 ScenePresence sp = WaitGetScenePresence(agentID);
2938 if (sp != null) 3095 if (sp != null)
2939 { 3096 {
2940 PresenceService.LogoutAgent(sp.ControllingClient.SessionId); 3097 PresenceService.LogoutAgent(sp.ControllingClient.SessionId);
2941
2942 sp.ControllingClient.Close(); 3098 sp.ControllingClient.Close();
2943 } 3099 }
2944 else 3100
2945 {
2946 m_log.WarnFormat("[SCENE]: Could not find scene presence for {0}", agentID);
2947 }
2948 // BANG! SLASH! 3101 // BANG! SLASH!
2949 m_authenticateHandler.RemoveCircuit(agentID); 3102 m_authenticateHandler.RemoveCircuit(agentID);
2950 3103
@@ -2989,6 +3142,8 @@ namespace OpenSim.Region.Framework.Scenes
2989 client.OnUpdatePrimGroupPosition += m_sceneGraph.UpdatePrimGroupPosition; 3142 client.OnUpdatePrimGroupPosition += m_sceneGraph.UpdatePrimGroupPosition;
2990 client.OnUpdatePrimSinglePosition += m_sceneGraph.UpdatePrimSinglePosition; 3143 client.OnUpdatePrimSinglePosition += m_sceneGraph.UpdatePrimSinglePosition;
2991 3144
3145 client.onClientChangeObject += m_sceneGraph.ClientChangeObject;
3146
2992 client.OnUpdatePrimGroupRotation += m_sceneGraph.UpdatePrimGroupRotation; 3147 client.OnUpdatePrimGroupRotation += m_sceneGraph.UpdatePrimGroupRotation;
2993 client.OnUpdatePrimGroupMouseRotation += m_sceneGraph.UpdatePrimGroupRotation; 3148 client.OnUpdatePrimGroupMouseRotation += m_sceneGraph.UpdatePrimGroupRotation;
2994 client.OnUpdatePrimSingleRotation += m_sceneGraph.UpdatePrimSingleRotation; 3149 client.OnUpdatePrimSingleRotation += m_sceneGraph.UpdatePrimSingleRotation;
@@ -3045,6 +3200,7 @@ namespace OpenSim.Region.Framework.Scenes
3045 client.OnFetchInventory += m_asyncInventorySender.HandleFetchInventory; 3200 client.OnFetchInventory += m_asyncInventorySender.HandleFetchInventory;
3046 client.OnUpdateInventoryItem += UpdateInventoryItemAsset; 3201 client.OnUpdateInventoryItem += UpdateInventoryItemAsset;
3047 client.OnCopyInventoryItem += CopyInventoryItem; 3202 client.OnCopyInventoryItem += CopyInventoryItem;
3203 client.OnMoveItemsAndLeaveCopy += MoveInventoryItemsLeaveCopy;
3048 client.OnMoveInventoryItem += MoveInventoryItem; 3204 client.OnMoveInventoryItem += MoveInventoryItem;
3049 client.OnRemoveInventoryItem += RemoveInventoryItem; 3205 client.OnRemoveInventoryItem += RemoveInventoryItem;
3050 client.OnRemoveInventoryFolder += RemoveInventoryFolder; 3206 client.OnRemoveInventoryFolder += RemoveInventoryFolder;
@@ -3116,6 +3272,8 @@ namespace OpenSim.Region.Framework.Scenes
3116 client.OnUpdatePrimGroupPosition -= m_sceneGraph.UpdatePrimGroupPosition; 3272 client.OnUpdatePrimGroupPosition -= m_sceneGraph.UpdatePrimGroupPosition;
3117 client.OnUpdatePrimSinglePosition -= m_sceneGraph.UpdatePrimSinglePosition; 3273 client.OnUpdatePrimSinglePosition -= m_sceneGraph.UpdatePrimSinglePosition;
3118 3274
3275 client.onClientChangeObject -= m_sceneGraph.ClientChangeObject;
3276
3119 client.OnUpdatePrimGroupRotation -= m_sceneGraph.UpdatePrimGroupRotation; 3277 client.OnUpdatePrimGroupRotation -= m_sceneGraph.UpdatePrimGroupRotation;
3120 client.OnUpdatePrimGroupMouseRotation -= m_sceneGraph.UpdatePrimGroupRotation; 3278 client.OnUpdatePrimGroupMouseRotation -= m_sceneGraph.UpdatePrimGroupRotation;
3121 client.OnUpdatePrimSingleRotation -= m_sceneGraph.UpdatePrimSingleRotation; 3279 client.OnUpdatePrimSingleRotation -= m_sceneGraph.UpdatePrimSingleRotation;
@@ -3218,7 +3376,7 @@ namespace OpenSim.Region.Framework.Scenes
3218 /// </summary> 3376 /// </summary>
3219 /// <param name="agentId">The avatar's Unique ID</param> 3377 /// <param name="agentId">The avatar's Unique ID</param>
3220 /// <param name="client">The IClientAPI for the client</param> 3378 /// <param name="client">The IClientAPI for the client</param>
3221 public virtual void TeleportClientHome(UUID agentId, IClientAPI client) 3379 public virtual bool TeleportClientHome(UUID agentId, IClientAPI client)
3222 { 3380 {
3223 if (EntityTransferModule != null) 3381 if (EntityTransferModule != null)
3224 { 3382 {
@@ -3229,6 +3387,7 @@ namespace OpenSim.Region.Framework.Scenes
3229 m_log.DebugFormat("[SCENE]: Unable to teleport user home: no AgentTransferModule is active"); 3387 m_log.DebugFormat("[SCENE]: Unable to teleport user home: no AgentTransferModule is active");
3230 client.SendTeleportFailed("Unable to perform teleports on this simulator."); 3388 client.SendTeleportFailed("Unable to perform teleports on this simulator.");
3231 } 3389 }
3390 return false;
3232 } 3391 }
3233 3392
3234 /// <summary> 3393 /// <summary>
@@ -3338,6 +3497,16 @@ namespace OpenSim.Region.Framework.Scenes
3338 /// <param name="flags"></param> 3497 /// <param name="flags"></param>
3339 public virtual void SetHomeRezPoint(IClientAPI remoteClient, ulong regionHandle, Vector3 position, Vector3 lookAt, uint flags) 3498 public virtual void SetHomeRezPoint(IClientAPI remoteClient, ulong regionHandle, Vector3 position, Vector3 lookAt, uint flags)
3340 { 3499 {
3500 //Add half the avatar's height so that the user doesn't fall through prims
3501 ScenePresence presence;
3502 if (TryGetScenePresence(remoteClient.AgentId, out presence))
3503 {
3504 if (presence.Appearance != null)
3505 {
3506 position.Z = position.Z + (presence.Appearance.AvatarHeight / 2);
3507 }
3508 }
3509
3341 if (GridUserService != null && GridUserService.SetHome(remoteClient.AgentId.ToString(), RegionInfo.RegionID, position, lookAt)) 3510 if (GridUserService != null && GridUserService.SetHome(remoteClient.AgentId.ToString(), RegionInfo.RegionID, position, lookAt))
3342 // FUBAR ALERT: this needs to be "Home position set." so the viewer saves a home-screenshot. 3511 // FUBAR ALERT: this needs to be "Home position set." so the viewer saves a home-screenshot.
3343 m_dialogModule.SendAlertToUser(remoteClient, "Home position set."); 3512 m_dialogModule.SendAlertToUser(remoteClient, "Home position set.");
@@ -3439,7 +3608,7 @@ namespace OpenSim.Region.Framework.Scenes
3439 // TODO: We shouldn't use closeChildAgents here - it's being used by the NPC module to stop 3608 // TODO: We shouldn't use closeChildAgents here - it's being used by the NPC module to stop
3440 // unnecessary operations. This should go away once NPCs have no accompanying IClientAPI 3609 // unnecessary operations. This should go away once NPCs have no accompanying IClientAPI
3441 if (closeChildAgents && CapsModule != null) 3610 if (closeChildAgents && CapsModule != null)
3442 CapsModule.RemoveCaps(agentID); 3611 CapsModule.RemoveCaps(agentID, avatar.ControllingClient.CircuitCode);
3443 3612
3444// // REFACTORING PROBLEM -- well not really a problem, but just to point out that whatever 3613// // REFACTORING PROBLEM -- well not really a problem, but just to point out that whatever
3445// // this method is doing is HORRIBLE!!! 3614// // this method is doing is HORRIBLE!!!
@@ -3475,6 +3644,7 @@ namespace OpenSim.Region.Framework.Scenes
3475 // It's possible for child agents to have transactions if changes are being made cross-border. 3644 // It's possible for child agents to have transactions if changes are being made cross-border.
3476 if (AgentTransactionsModule != null) 3645 if (AgentTransactionsModule != null)
3477 AgentTransactionsModule.RemoveAgentAssetTransactions(agentID); 3646 AgentTransactionsModule.RemoveAgentAssetTransactions(agentID);
3647 m_log.Debug("[Scene] The avatar has left the building");
3478 } 3648 }
3479 catch (Exception e) 3649 catch (Exception e)
3480 { 3650 {
@@ -3667,15 +3837,27 @@ namespace OpenSim.Region.Framework.Scenes
3667 agent.firstname, agent.lastname, agent.Viewer); 3837 agent.firstname, agent.lastname, agent.Viewer);
3668 reason = "Access denied, your viewer is banned by the region owner"; 3838 reason = "Access denied, your viewer is banned by the region owner";
3669 return false; 3839 return false;
3670 } 3840 }
3671 3841
3672 ILandObject land; 3842 ScenePresence sp = GetScenePresence(agent.AgentID);
3673 3843
3674 lock (agent) 3844 // If we have noo presence here or if that presence is a zombie root
3845 // presence that will be kicled, we need a new CAPS object.
3846 if (sp == null || (sp != null && !sp.IsChildAgent))
3675 { 3847 {
3676 ScenePresence sp = GetScenePresence(agent.AgentID); 3848 if (CapsModule != null)
3677 3849 {
3678 if (sp != null && !sp.IsChildAgent) 3850 lock (agent)
3851 {
3852 CapsModule.SetAgentCapsSeeds(agent);
3853 CapsModule.CreateCaps(agent.AgentID, agent.circuitcode);
3854 }
3855 }
3856 }
3857
3858 if (sp != null)
3859 {
3860 if (!sp.IsChildAgent)
3679 { 3861 {
3680 // We have a zombie from a crashed session. 3862 // We have a zombie from a crashed session.
3681 // Or the same user is trying to be root twice here, won't work. 3863 // Or the same user is trying to be root twice here, won't work.
@@ -3683,22 +3865,27 @@ namespace OpenSim.Region.Framework.Scenes
3683 m_log.WarnFormat( 3865 m_log.WarnFormat(
3684 "[SCENE]: Existing root scene presence detected for {0} {1} in {2} when connecting. Removing existing presence.", 3866 "[SCENE]: Existing root scene presence detected for {0} {1} in {2} when connecting. Removing existing presence.",
3685 sp.Name, sp.UUID, RegionInfo.RegionName); 3867 sp.Name, sp.UUID, RegionInfo.RegionName);
3686 3868
3687 sp.ControllingClient.Close(true); 3869 sp.ControllingClient.Close(true, true);
3688 sp = null; 3870 sp = null;
3689 } 3871 }
3690 3872 }
3691 land = LandChannel.GetLandObject(agent.startpos.X, agent.startpos.Y); 3873
3692 3874 lock (agent)
3875 {
3693 //On login test land permisions 3876 //On login test land permisions
3694 if (vialogin) 3877 if (vialogin)
3695 { 3878 {
3696 if (land != null && !TestLandRestrictions(agent, land, out reason)) 3879 IUserAccountCacheModule cache = RequestModuleInterface<IUserAccountCacheModule>();
3880 if (cache != null)
3881 cache.Remove(agent.firstname + " " + agent.lastname);
3882 if (!TestLandRestrictions(agent.AgentID, out reason, ref agent.startpos.X, ref agent.startpos.Y))
3697 { 3883 {
3884 m_log.DebugFormat("[CONNECTION BEGIN]: Denying access to {0} due to no land access", agent.AgentID.ToString());
3698 return false; 3885 return false;
3699 } 3886 }
3700 } 3887 }
3701 3888
3702 if (sp == null) // We don't have an [child] agent here already 3889 if (sp == null) // We don't have an [child] agent here already
3703 { 3890 {
3704 if (requirePresenceLookup) 3891 if (requirePresenceLookup)
@@ -3707,54 +3894,53 @@ namespace OpenSim.Region.Framework.Scenes
3707 { 3894 {
3708 if (!VerifyUserPresence(agent, out reason)) 3895 if (!VerifyUserPresence(agent, out reason))
3709 return false; 3896 return false;
3710 } 3897 } catch (Exception e)
3711 catch (Exception e)
3712 { 3898 {
3713 m_log.ErrorFormat( 3899 m_log.ErrorFormat(
3714 "[SCENE]: Exception verifying presence {0}{1}", e.Message, e.StackTrace); 3900 "[SCENE]: Exception verifying presence {0}{1}", e.Message, e.StackTrace);
3715
3716 return false; 3901 return false;
3717 } 3902 }
3718 } 3903 }
3719 3904
3720 try 3905 try
3721 { 3906 {
3722 if (!AuthorizeUser(agent, out reason)) 3907 // Always check estate if this is a login. Always
3723 return false; 3908 // check if banned regions are to be blacked out.
3909 if (vialogin || (!m_seeIntoBannedRegion))
3910 {
3911 if (!AuthorizeUser(agent, out reason))
3912 {
3913 return false;
3914 }
3915 }
3724 } 3916 }
3725 catch (Exception e) 3917 catch (Exception e)
3726 { 3918 {
3727 m_log.ErrorFormat( 3919 m_log.ErrorFormat(
3728 "[SCENE]: Exception authorizing user {0}{1}", e.Message, e.StackTrace); 3920 "[SCENE]: Exception authorizing user {0}{1}", e.Message, e.StackTrace);
3729
3730 return false; 3921 return false;
3731 } 3922 }
3732 3923
3733 m_log.InfoFormat( 3924 m_log.InfoFormat(
3734 "[SCENE]: Region {0} authenticated and authorized incoming {1} agent {2} {3} {4} (circuit code {5})", 3925 "[SCENE]: Region {0} authenticated and authorized incoming {1} agent {2} {3} {4} (circuit code {5})",
3735 RegionInfo.RegionName, (agent.child ? "child" : "root"), agent.firstname, agent.lastname, 3926 RegionInfo.RegionName, (agent.child ? "child" : "root"), agent.firstname, agent.lastname,
3736 agent.AgentID, agent.circuitcode); 3927 agent.AgentID, agent.circuitcode);
3737 3928
3738 if (CapsModule != null)
3739 {
3740 CapsModule.SetAgentCapsSeeds(agent);
3741 CapsModule.CreateCaps(agent.AgentID);
3742 }
3743 } 3929 }
3744 else 3930 else
3745 { 3931 {
3746 // Let the SP know how we got here. This has a lot of interesting 3932 // Let the SP know how we got here. This has a lot of interesting
3747 // uses down the line. 3933 // uses down the line.
3748 sp.TeleportFlags = (TPFlags)teleportFlags; 3934 sp.TeleportFlags = (TPFlags)teleportFlags;
3749 3935
3750 if (sp.IsChildAgent) 3936 if (sp.IsChildAgent)
3751 { 3937 {
3752 m_log.DebugFormat( 3938 m_log.DebugFormat(
3753 "[SCENE]: Adjusting known seeds for existing agent {0} in {1}", 3939 "[SCENE]: Adjusting known seeds for existing agent {0} in {1}",
3754 agent.AgentID, RegionInfo.RegionName); 3940 agent.AgentID, RegionInfo.RegionName);
3755 3941
3756 sp.AdjustKnownSeeds(); 3942 sp.AdjustKnownSeeds();
3757 3943
3758 if (CapsModule != null) 3944 if (CapsModule != null)
3759 CapsModule.SetAgentCapsSeeds(agent); 3945 CapsModule.SetAgentCapsSeeds(agent);
3760 } 3946 }
@@ -3765,6 +3951,11 @@ namespace OpenSim.Region.Framework.Scenes
3765 agent.teleportFlags = teleportFlags; 3951 agent.teleportFlags = teleportFlags;
3766 m_authenticateHandler.AddNewCircuit(agent.circuitcode, agent); 3952 m_authenticateHandler.AddNewCircuit(agent.circuitcode, agent);
3767 3953
3954 if (CapsModule != null)
3955 {
3956 CapsModule.ActivateCaps(agent.circuitcode);
3957 }
3958
3768 if (vialogin) 3959 if (vialogin)
3769 { 3960 {
3770// CleanDroppedAttachments(); 3961// CleanDroppedAttachments();
@@ -3856,6 +4047,8 @@ namespace OpenSim.Region.Framework.Scenes
3856 } 4047 }
3857 4048
3858 // Honor parcel landing type and position. 4049 // Honor parcel landing type and position.
4050 /*
4051 ILandObject land = LandChannel.GetLandObject(agent.startpos.X, agent.startpos.Y);
3859 if (land != null) 4052 if (land != null)
3860 { 4053 {
3861 if (land.LandData.LandingType == (byte)1 && land.LandData.UserLocation != Vector3.Zero) 4054 if (land.LandData.LandingType == (byte)1 && land.LandData.UserLocation != Vector3.Zero)
@@ -3863,25 +4056,43 @@ namespace OpenSim.Region.Framework.Scenes
3863 agent.startpos = land.LandData.UserLocation; 4056 agent.startpos = land.LandData.UserLocation;
3864 } 4057 }
3865 } 4058 }
4059 */// This is now handled properly in ScenePresence.MakeRootAgent
3866 } 4060 }
3867 4061
3868 return true; 4062 return true;
3869 } 4063 }
3870 4064
3871 private bool TestLandRestrictions(AgentCircuitData agent, ILandObject land, out string reason) 4065 public bool TestLandRestrictions(UUID agentID, out string reason, ref float posX, ref float posY)
3872 { 4066 {
3873 bool banned = land.IsBannedFromLand(agent.AgentID); 4067 if (posX < 0)
3874 bool restricted = land.IsRestrictedFromLand(agent.AgentID); 4068 posX = 0;
4069 else if (posX >= 256)
4070 posX = 255.999f;
4071 if (posY < 0)
4072 posY = 0;
4073 else if (posY >= 256)
4074 posY = 255.999f;
4075
4076 reason = String.Empty;
4077 if (Permissions.IsGod(agentID))
4078 return true;
4079
4080 ILandObject land = LandChannel.GetLandObject(posX, posY);
4081 if (land == null)
4082 return false;
4083
4084 bool banned = land.IsBannedFromLand(agentID);
4085 bool restricted = land.IsRestrictedFromLand(agentID);
3875 4086
3876 if (banned || restricted) 4087 if (banned || restricted)
3877 { 4088 {
3878 ILandObject nearestParcel = GetNearestAllowedParcel(agent.AgentID, agent.startpos.X, agent.startpos.Y); 4089 ILandObject nearestParcel = GetNearestAllowedParcel(agentID, posX, posY);
3879 if (nearestParcel != null) 4090 if (nearestParcel != null)
3880 { 4091 {
3881 //Move agent to nearest allowed 4092 //Move agent to nearest allowed
3882 Vector3 newPosition = GetParcelCenterAtGround(nearestParcel); 4093 Vector3 newPosition = GetParcelCenterAtGround(nearestParcel);
3883 agent.startpos.X = newPosition.X; 4094 posX = newPosition.X;
3884 agent.startpos.Y = newPosition.Y; 4095 posY = newPosition.Y;
3885 } 4096 }
3886 else 4097 else
3887 { 4098 {
@@ -3943,7 +4154,7 @@ namespace OpenSim.Region.Framework.Scenes
3943 4154
3944 if (!m_strictAccessControl) return true; 4155 if (!m_strictAccessControl) return true;
3945 if (Permissions.IsGod(agent.AgentID)) return true; 4156 if (Permissions.IsGod(agent.AgentID)) return true;
3946 4157
3947 if (AuthorizationService != null) 4158 if (AuthorizationService != null)
3948 { 4159 {
3949 if (!AuthorizationService.IsAuthorizedForRegion( 4160 if (!AuthorizationService.IsAuthorizedForRegion(
@@ -3958,7 +4169,7 @@ namespace OpenSim.Region.Framework.Scenes
3958 4169
3959 if (RegionInfo.EstateSettings != null) 4170 if (RegionInfo.EstateSettings != null)
3960 { 4171 {
3961 if (RegionInfo.EstateSettings.IsBanned(agent.AgentID)) 4172 if (RegionInfo.EstateSettings.IsBanned(agent.AgentID, 0))
3962 { 4173 {
3963 m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because the user is on the banlist", 4174 m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because the user is on the banlist",
3964 agent.AgentID, agent.firstname, agent.lastname, RegionInfo.RegionName); 4175 agent.AgentID, agent.firstname, agent.lastname, RegionInfo.RegionName);
@@ -4148,6 +4359,15 @@ namespace OpenSim.Region.Framework.Scenes
4148 4359
4149 // XPTO: if this agent is not allowed here as root, always return false 4360 // XPTO: if this agent is not allowed here as root, always return false
4150 4361
4362 // We have to wait until the viewer contacts this region after receiving EAC.
4363 // That calls AddNewClient, which finally creates the ScenePresence
4364 int flags = GetUserFlags(cAgentData.AgentID);
4365 if (RegionInfo.EstateSettings.IsBanned(cAgentData.AgentID, flags))
4366 {
4367 m_log.DebugFormat("[SCENE]: Denying root agent entry to {0}: banned", cAgentData.AgentID);
4368 return false;
4369 }
4370
4151 // TODO: This check should probably be in QueryAccess(). 4371 // TODO: This check should probably be in QueryAccess().
4152 ILandObject nearestParcel = GetNearestAllowedParcel(cAgentData.AgentID, Constants.RegionSize / 2, Constants.RegionSize / 2); 4372 ILandObject nearestParcel = GetNearestAllowedParcel(cAgentData.AgentID, Constants.RegionSize / 2, Constants.RegionSize / 2);
4153 if (nearestParcel == null) 4373 if (nearestParcel == null)
@@ -4212,7 +4432,7 @@ namespace OpenSim.Region.Framework.Scenes
4212 /// <param name='agentID'></param> 4432 /// <param name='agentID'></param>
4213 protected virtual ScenePresence WaitGetScenePresence(UUID agentID) 4433 protected virtual ScenePresence WaitGetScenePresence(UUID agentID)
4214 { 4434 {
4215 int ntimes = 10; 4435 int ntimes = 30;
4216 ScenePresence sp = null; 4436 ScenePresence sp = null;
4217 while ((sp = GetScenePresence(agentID)) == null && (ntimes-- > 0)) 4437 while ((sp = GetScenePresence(agentID)) == null && (ntimes-- > 0))
4218 Thread.Sleep(1000); 4438 Thread.Sleep(1000);
@@ -4242,6 +4462,16 @@ namespace OpenSim.Region.Framework.Scenes
4242 return false; 4462 return false;
4243 } 4463 }
4244 4464
4465 public bool IncomingCloseAgent(UUID agentID)
4466 {
4467 return IncomingCloseAgent(agentID, false);
4468 }
4469
4470 public bool IncomingCloseChildAgent(UUID agentID)
4471 {
4472 return IncomingCloseAgent(agentID, true);
4473 }
4474
4245 /// <summary> 4475 /// <summary>
4246 /// Tell a single agent to disconnect from the region. 4476 /// Tell a single agent to disconnect from the region.
4247 /// </summary> 4477 /// </summary>
@@ -4257,7 +4487,7 @@ namespace OpenSim.Region.Framework.Scenes
4257 ScenePresence presence = m_sceneGraph.GetScenePresence(agentID); 4487 ScenePresence presence = m_sceneGraph.GetScenePresence(agentID);
4258 if (presence != null) 4488 if (presence != null)
4259 { 4489 {
4260 presence.ControllingClient.Close(force); 4490 presence.ControllingClient.Close(force, force);
4261 return true; 4491 return true;
4262 } 4492 }
4263 4493
@@ -4890,7 +5120,7 @@ namespace OpenSim.Region.Framework.Scenes
4890 { 5120 {
4891 if ((grp.RootPart.Flags & PrimFlags.TemporaryOnRez) != 0) 5121 if ((grp.RootPart.Flags & PrimFlags.TemporaryOnRez) != 0)
4892 { 5122 {
4893 if (grp.RootPart.Expires <= DateTime.Now) 5123 if (grp.GetSittingAvatarsCount() == 0 && grp.RootPart.Expires <= DateTime.Now)
4894 DeleteSceneObject(grp, false); 5124 DeleteSceneObject(grp, false);
4895 } 5125 }
4896 } 5126 }
@@ -4904,35 +5134,81 @@ namespace OpenSim.Region.Framework.Scenes
4904 SimulationDataService.RemoveObject(uuid, RegionInfo.RegionID); 5134 SimulationDataService.RemoveObject(uuid, RegionInfo.RegionID);
4905 } 5135 }
4906 5136
4907 public int GetHealth() 5137 public int GetHealth(out int flags, out string message)
4908 { 5138 {
4909 // Returns: 5139 // Returns:
4910 // 1 = sim is up and accepting http requests. The heartbeat has 5140 // 1 = sim is up and accepting http requests. The heartbeat has
4911 // stopped and the sim is probably locked up, but a remote 5141 // stopped and the sim is probably locked up, but a remote
4912 // admin restart may succeed 5142 // admin restart may succeed
4913 // 5143 //
4914 // 2 = Sim is up and the heartbeat is running. The sim is likely 5144 // 2 = Sim is up and the heartbeat is running. The sim is likely
4915 // usable for people within and logins _may_ work 5145 // usable for people within
5146 //
5147 // 3 = Sim is up and one packet thread is running. Sim is
5148 // unstable and will not accept new logins
4916 // 5149 //
4917 // 3 = We have seen a new user enter within the past 4 minutes 5150 // 4 = Sim is up and both packet threads are running. Sim is
5151 // likely usable
5152 //
5153 // 5 = We have seen a new user enter within the past 4 minutes
4918 // which can be seen as positive confirmation of sim health 5154 // which can be seen as positive confirmation of sim health
4919 // 5155 //
5156
5157 flags = 0;
5158 message = String.Empty;
5159
5160 CheckHeartbeat();
5161
5162 if (m_firstHeartbeat || (m_lastIncoming == 0 && m_lastOutgoing == 0))
5163 {
5164 // We're still starting
5165 // 0 means "in startup", it can't happen another way, since
5166 // to get here, we must be able to accept http connections
5167 return 0;
5168 }
5169
4920 int health=1; // Start at 1, means we're up 5170 int health=1; // Start at 1, means we're up
4921 5171
4922 if ((Util.EnvironmentTickCountSubtract(m_lastFrameTick)) < 1000) 5172 if ((Util.EnvironmentTickCountSubtract(m_lastFrameTick)) < 1000)
4923 health += 1; 5173 {
5174 health+=1;
5175 flags |= 1;
5176 }
5177
5178 if (Util.EnvironmentTickCountSubtract(m_lastIncoming) < 1000)
5179 {
5180 health+=1;
5181 flags |= 2;
5182 }
5183
5184 if (Util.EnvironmentTickCountSubtract(m_lastOutgoing) < 1000)
5185 {
5186 health+=1;
5187 flags |= 4;
5188 }
4924 else 5189 else
5190 {
5191int pid = System.Diagnostics.Process.GetCurrentProcess().Id;
5192System.Diagnostics.Process proc = new System.Diagnostics.Process();
5193proc.EnableRaisingEvents=false;
5194proc.StartInfo.FileName = "/bin/kill";
5195proc.StartInfo.Arguments = "-QUIT " + pid.ToString();
5196proc.Start();
5197proc.WaitForExit();
5198Thread.Sleep(1000);
5199Environment.Exit(1);
5200 }
5201
5202 if (flags != 7)
4925 return health; 5203 return health;
4926 5204
4927 // A login in the last 4 mins? We can't be doing too badly 5205 // A login in the last 4 mins? We can't be doing too badly
4928 // 5206 //
4929 if ((Util.EnvironmentTickCountSubtract(m_LastLogin)) < 240000) 5207 if (Util.EnvironmentTickCountSubtract(m_LastLogin) < 240000)
4930 health++; 5208 health++;
4931 else 5209 else
4932 return health; 5210 return health;
4933 5211
4934// CheckHeartbeat();
4935
4936 return health; 5212 return health;
4937 } 5213 }
4938 5214
@@ -5020,7 +5296,7 @@ namespace OpenSim.Region.Framework.Scenes
5020 bool wasUsingPhysics = ((jointProxyObject.Flags & PrimFlags.Physics) != 0); 5296 bool wasUsingPhysics = ((jointProxyObject.Flags & PrimFlags.Physics) != 0);
5021 if (wasUsingPhysics) 5297 if (wasUsingPhysics)
5022 { 5298 {
5023 jointProxyObject.UpdatePrimFlags(false, false, true, false); // FIXME: possible deadlock here; check to make sure all the scene alterations set into motion here won't deadlock 5299 jointProxyObject.UpdatePrimFlags(false, false, true, false,false); // FIXME: possible deadlock here; check to make sure all the scene alterations set into motion here won't deadlock
5024 } 5300 }
5025 } 5301 }
5026 5302
@@ -5119,14 +5395,14 @@ namespace OpenSim.Region.Framework.Scenes
5119 return (((vsn.X * xdiff) + (vsn.Y * ydiff)) / (-1 * vsn.Z)) + p0.Z; 5395 return (((vsn.X * xdiff) + (vsn.Y * ydiff)) / (-1 * vsn.Z)) + p0.Z;
5120 } 5396 }
5121 5397
5122// private void CheckHeartbeat() 5398 private void CheckHeartbeat()
5123// { 5399 {
5124// if (m_firstHeartbeat) 5400 if (m_firstHeartbeat)
5125// return; 5401 return;
5126// 5402
5127// if (Util.EnvironmentTickCountSubtract(m_lastFrameTick) > 2000) 5403 if ((Util.EnvironmentTickCountSubtract(m_lastFrameTick)) > 5000)
5128// StartTimer(); 5404 Start();
5129// } 5405 }
5130 5406
5131 public override ISceneObject DeserializeObject(string representation) 5407 public override ISceneObject DeserializeObject(string representation)
5132 { 5408 {
@@ -5184,7 +5460,7 @@ namespace OpenSim.Region.Framework.Scenes
5184 Vector3 nearestRegionEdgePoint = GetNearestRegionEdgePosition(avatar); 5460 Vector3 nearestRegionEdgePoint = GetNearestRegionEdgePosition(avatar);
5185 5461
5186 //Debug.WriteLine("They are really in a place they don't belong, sending them to: " + nearestRegionEdgePoint.ToString()); 5462 //Debug.WriteLine("They are really in a place they don't belong, sending them to: " + nearestRegionEdgePoint.ToString());
5187 5463
5188 return nearestRegionEdgePoint; 5464 return nearestRegionEdgePoint;
5189 } 5465 }
5190 5466
@@ -5438,7 +5714,55 @@ namespace OpenSim.Region.Framework.Scenes
5438 mapModule.GenerateMaptile(); 5714 mapModule.GenerateMaptile();
5439 } 5715 }
5440 5716
5441 private void RegenerateMaptileAndReregister(object sender, ElapsedEventArgs e) 5717// public void CleanDroppedAttachments()
5718// {
5719// List<SceneObjectGroup> objectsToDelete =
5720// new List<SceneObjectGroup>();
5721//
5722// lock (m_cleaningAttachments)
5723// {
5724// ForEachSOG(delegate (SceneObjectGroup grp)
5725// {
5726// if (grp.RootPart.Shape.PCode == 0 && grp.RootPart.Shape.State != 0 && (!objectsToDelete.Contains(grp)))
5727// {
5728// UUID agentID = grp.OwnerID;
5729// if (agentID == UUID.Zero)
5730// {
5731// objectsToDelete.Add(grp);
5732// return;
5733// }
5734//
5735// ScenePresence sp = GetScenePresence(agentID);
5736// if (sp == null)
5737// {
5738// objectsToDelete.Add(grp);
5739// return;
5740// }
5741// }
5742// });
5743// }
5744//
5745// foreach (SceneObjectGroup grp in objectsToDelete)
5746// {
5747// m_log.InfoFormat("[SCENE]: Deleting dropped attachment {0} of user {1}", grp.UUID, grp.OwnerID);
5748// DeleteSceneObject(grp, true);
5749// }
5750// }
5751
5752 public void ThreadAlive(int threadCode)
5753 {
5754 switch(threadCode)
5755 {
5756 case 1: // Incoming
5757 m_lastIncoming = Util.EnvironmentTickCount();
5758 break;
5759 case 2: // Incoming
5760 m_lastOutgoing = Util.EnvironmentTickCount();
5761 break;
5762 }
5763 }
5764
5765 public void RegenerateMaptileAndReregister(object sender, ElapsedEventArgs e)
5442 { 5766 {
5443 RegenerateMaptile(); 5767 RegenerateMaptile();
5444 5768
@@ -5466,6 +5790,8 @@ namespace OpenSim.Region.Framework.Scenes
5466 /// <returns></returns> 5790 /// <returns></returns>
5467 public bool QueryAccess(UUID agentID, Vector3 position, out string reason) 5791 public bool QueryAccess(UUID agentID, Vector3 position, out string reason)
5468 { 5792 {
5793 reason = "You are banned from the region";
5794
5469 if (EntityTransferModule.IsInTransit(agentID)) 5795 if (EntityTransferModule.IsInTransit(agentID))
5470 { 5796 {
5471 reason = "Agent is still in transit from this region"; 5797 reason = "Agent is still in transit from this region";
@@ -5477,6 +5803,12 @@ namespace OpenSim.Region.Framework.Scenes
5477 return false; 5803 return false;
5478 } 5804 }
5479 5805
5806 if (Permissions.IsGod(agentID))
5807 {
5808 reason = String.Empty;
5809 return true;
5810 }
5811
5480 // FIXME: Root agent count is currently known to be inaccurate. This forces a recount before we check. 5812 // FIXME: Root agent count is currently known to be inaccurate. This forces a recount before we check.
5481 // However, the long term fix is to make sure root agent count is always accurate. 5813 // However, the long term fix is to make sure root agent count is always accurate.
5482 m_sceneGraph.RecalculateStats(); 5814 m_sceneGraph.RecalculateStats();
@@ -5497,6 +5829,41 @@ namespace OpenSim.Region.Framework.Scenes
5497 } 5829 }
5498 } 5830 }
5499 5831
5832 ScenePresence presence = GetScenePresence(agentID);
5833 IClientAPI client = null;
5834 AgentCircuitData aCircuit = null;
5835
5836 if (presence != null)
5837 {
5838 client = presence.ControllingClient;
5839 if (client != null)
5840 aCircuit = client.RequestClientInfo();
5841 }
5842
5843 // We may be called before there is a presence or a client.
5844 // Fake AgentCircuitData to keep IAuthorizationModule smiling
5845 if (client == null)
5846 {
5847 aCircuit = new AgentCircuitData();
5848 aCircuit.AgentID = agentID;
5849 aCircuit.firstname = String.Empty;
5850 aCircuit.lastname = String.Empty;
5851 }
5852
5853 try
5854 {
5855 if (!AuthorizeUser(aCircuit, out reason))
5856 {
5857 // m_log.DebugFormat("[SCENE]: Denying access for {0}", agentID);
5858 return false;
5859 }
5860 }
5861 catch (Exception e)
5862 {
5863 m_log.DebugFormat("[SCENE]: Exception authorizing agent: {0} "+ e.StackTrace, e.Message);
5864 return false;
5865 }
5866
5500 if (position == Vector3.Zero) // Teleport 5867 if (position == Vector3.Zero) // Teleport
5501 { 5868 {
5502 if (!RegionInfo.EstateSettings.AllowDirectTeleport) 5869 if (!RegionInfo.EstateSettings.AllowDirectTeleport)
@@ -5530,13 +5897,46 @@ namespace OpenSim.Region.Framework.Scenes
5530 } 5897 }
5531 } 5898 }
5532 } 5899 }
5900
5901 float posX = 128.0f;
5902 float posY = 128.0f;
5903
5904 if (!TestLandRestrictions(agentID, out reason, ref posX, ref posY))
5905 {
5906 // m_log.DebugFormat("[SCENE]: Denying {0} because they are banned on all parcels", agentID);
5907 return false;
5908 }
5909 }
5910 else // Walking
5911 {
5912 ILandObject land = LandChannel.GetLandObject(position.X, position.Y);
5913 if (land == null)
5914 return false;
5915
5916 bool banned = land.IsBannedFromLand(agentID);
5917 bool restricted = land.IsRestrictedFromLand(agentID);
5918
5919 if (banned || restricted)
5920 return false;
5533 } 5921 }
5534 5922
5535 reason = String.Empty; 5923 reason = String.Empty;
5536 return true; 5924 return true;
5537 } 5925 }
5538 5926
5539 /// <summary> 5927 public void StartTimerWatchdog()
5928 {
5929 m_timerWatchdog.Interval = 1000;
5930 m_timerWatchdog.Elapsed += TimerWatchdog;
5931 m_timerWatchdog.AutoReset = true;
5932 m_timerWatchdog.Start();
5933 }
5934
5935 public void TimerWatchdog(object sender, ElapsedEventArgs e)
5936 {
5937 CheckHeartbeat();
5938 }
5939
5540 /// This method deals with movement when an avatar is automatically moving (but this is distinct from the 5940 /// This method deals with movement when an avatar is automatically moving (but this is distinct from the
5541 /// autopilot that moves an avatar to a sit target!. 5941 /// autopilot that moves an avatar to a sit target!.
5542 /// </summary> 5942 /// </summary>
@@ -5615,6 +6015,11 @@ namespace OpenSim.Region.Framework.Scenes
5615 return m_SpawnPoint - 1; 6015 return m_SpawnPoint - 1;
5616 } 6016 }
5617 6017
6018 private void HandleGcCollect(string module, string[] args)
6019 {
6020 GC.Collect();
6021 }
6022
5618 /// <summary> 6023 /// <summary>
5619 /// Wrappers to get physics modules retrieve assets. 6024 /// Wrappers to get physics modules retrieve assets.
5620 /// </summary> 6025 /// </summary>
diff --git a/OpenSim/Region/Framework/Scenes/SceneBase.cs b/OpenSim/Region/Framework/Scenes/SceneBase.cs
index d3e968e..74c9582 100644
--- a/OpenSim/Region/Framework/Scenes/SceneBase.cs
+++ b/OpenSim/Region/Framework/Scenes/SceneBase.cs
@@ -143,7 +143,6 @@ namespace OpenSim.Region.Framework.Scenes
143 143
144 protected ulong m_regionHandle; 144 protected ulong m_regionHandle;
145 protected string m_regionName; 145 protected string m_regionName;
146 protected RegionInfo m_regInfo;
147 146
148 public ITerrainChannel Heightmap; 147 public ITerrainChannel Heightmap;
149 148
@@ -168,6 +167,8 @@ namespace OpenSim.Region.Framework.Scenes
168 get { return m_permissions; } 167 get { return m_permissions; }
169 } 168 }
170 169
170 protected string m_datastore;
171
171 /* Used by the loadbalancer plugin on GForge */ 172 /* Used by the loadbalancer plugin on GForge */
172 protected RegionStatus m_regStatus; 173 protected RegionStatus m_regStatus;
173 public RegionStatus RegionStatus 174 public RegionStatus RegionStatus
diff --git a/OpenSim/Region/Framework/Scenes/SceneCommunicationService.cs b/OpenSim/Region/Framework/Scenes/SceneCommunicationService.cs
index 305f8a4..775a4c2 100644
--- a/OpenSim/Region/Framework/Scenes/SceneCommunicationService.cs
+++ b/OpenSim/Region/Framework/Scenes/SceneCommunicationService.cs
@@ -194,10 +194,13 @@ namespace OpenSim.Region.Framework.Scenes
194 } 194 }
195 } 195 }
196 196
197 public delegate void SendCloseChildAgentDelegate(UUID agentID, ulong regionHandle);
198
197 /// <summary> 199 /// <summary>
198 /// Closes a child agent on a given region 200 /// This Closes child agents on neighboring regions
201 /// Calls an asynchronous method to do so.. so it doesn't lag the sim.
199 /// </summary> 202 /// </summary>
200 protected void SendCloseChildAgent(UUID agentID, ulong regionHandle) 203 protected void SendCloseChildAgentAsync(UUID agentID, ulong regionHandle)
201 { 204 {
202 // let's do our best, but there's not much we can do if the neighbour doesn't accept. 205 // let's do our best, but there's not much we can do if the neighbour doesn't accept.
203 206
@@ -206,30 +209,29 @@ namespace OpenSim.Region.Framework.Scenes
206 Utils.LongToUInts(regionHandle, out x, out y); 209 Utils.LongToUInts(regionHandle, out x, out y);
207 210
208 GridRegion destination = m_scene.GridService.GetRegionByPosition(m_regionInfo.ScopeID, (int)x, (int)y); 211 GridRegion destination = m_scene.GridService.GetRegionByPosition(m_regionInfo.ScopeID, (int)x, (int)y);
212 m_scene.SimulationService.CloseChildAgent(destination, agentID);
213 }
209 214
210 m_log.DebugFormat( 215 private void SendCloseChildAgentCompleted(IAsyncResult iar)
211 "[SCENE COMMUNICATION SERVICE]: Sending close agent ID {0} to {1}", agentID, destination.RegionName); 216 {
212 217 SendCloseChildAgentDelegate icon = (SendCloseChildAgentDelegate)iar.AsyncState;
213 m_scene.SimulationService.CloseAgent(destination, agentID); 218 icon.EndInvoke(iar);
214 } 219 }
215 220
216 /// <summary>
217 /// Closes a child agents in a collection of regions. Does so asynchronously
218 /// so that the caller doesn't wait.
219 /// </summary>
220 /// <param name="agentID"></param>
221 /// <param name="regionslst"></param>
222 public void SendCloseChildAgentConnections(UUID agentID, List<ulong> regionslst) 221 public void SendCloseChildAgentConnections(UUID agentID, List<ulong> regionslst)
223 { 222 {
224 foreach (ulong handle in regionslst) 223 foreach (ulong handle in regionslst)
225 { 224 {
226 SendCloseChildAgent(agentID, handle); 225 SendCloseChildAgentDelegate d = SendCloseChildAgentAsync;
226 d.BeginInvoke(agentID, handle,
227 SendCloseChildAgentCompleted,
228 d);
227 } 229 }
228 } 230 }
229 231
230 public List<GridRegion> RequestNamedRegions(string name, int maxNumber) 232 public List<GridRegion> RequestNamedRegions(string name, int maxNumber)
231 { 233 {
232 return m_scene.GridService.GetRegionsByName(UUID.Zero, name, maxNumber); 234 return m_scene.GridService.GetRegionsByName(UUID.Zero, name, maxNumber);
233 } 235 }
234 } 236 }
235} \ No newline at end of file 237}
diff --git a/OpenSim/Region/Framework/Scenes/SceneGraph.cs b/OpenSim/Region/Framework/Scenes/SceneGraph.cs
index a84f6d3..e599e90 100644
--- a/OpenSim/Region/Framework/Scenes/SceneGraph.cs
+++ b/OpenSim/Region/Framework/Scenes/SceneGraph.cs
@@ -41,6 +41,12 @@ namespace OpenSim.Region.Framework.Scenes
41{ 41{
42 public delegate void PhysicsCrash(); 42 public delegate void PhysicsCrash();
43 43
44 public delegate void AttachToBackupDelegate(SceneObjectGroup sog);
45
46 public delegate void DetachFromBackupDelegate(SceneObjectGroup sog);
47
48 public delegate void ChangedBackupDelegate(SceneObjectGroup sog);
49
44 /// <summary> 50 /// <summary>
45 /// This class used to be called InnerScene and may not yet truly be a SceneGraph. The non scene graph components 51 /// This class used to be called InnerScene and may not yet truly be a SceneGraph. The non scene graph components
46 /// should be migrated out over time. 52 /// should be migrated out over time.
@@ -54,11 +60,15 @@ namespace OpenSim.Region.Framework.Scenes
54 protected internal event PhysicsCrash UnRecoverableError; 60 protected internal event PhysicsCrash UnRecoverableError;
55 private PhysicsCrash handlerPhysicsCrash = null; 61 private PhysicsCrash handlerPhysicsCrash = null;
56 62
63 public event AttachToBackupDelegate OnAttachToBackup;
64 public event DetachFromBackupDelegate OnDetachFromBackup;
65 public event ChangedBackupDelegate OnChangeBackup;
66
57 #endregion 67 #endregion
58 68
59 #region Fields 69 #region Fields
60 70
61 protected object m_presenceLock = new object(); 71 protected OpenMetaverse.ReaderWriterLockSlim m_scenePresencesLock = new OpenMetaverse.ReaderWriterLockSlim();
62 protected Dictionary<UUID, ScenePresence> m_scenePresenceMap = new Dictionary<UUID, ScenePresence>(); 72 protected Dictionary<UUID, ScenePresence> m_scenePresenceMap = new Dictionary<UUID, ScenePresence>();
63 protected List<ScenePresence> m_scenePresenceArray = new List<ScenePresence>(); 73 protected List<ScenePresence> m_scenePresenceArray = new List<ScenePresence>();
64 74
@@ -127,13 +137,18 @@ namespace OpenSim.Region.Framework.Scenes
127 137
128 protected internal void Close() 138 protected internal void Close()
129 { 139 {
130 lock (m_presenceLock) 140 m_scenePresencesLock.EnterWriteLock();
141 try
131 { 142 {
132 Dictionary<UUID, ScenePresence> newmap = new Dictionary<UUID, ScenePresence>(); 143 Dictionary<UUID, ScenePresence> newmap = new Dictionary<UUID, ScenePresence>();
133 List<ScenePresence> newlist = new List<ScenePresence>(); 144 List<ScenePresence> newlist = new List<ScenePresence>();
134 m_scenePresenceMap = newmap; 145 m_scenePresenceMap = newmap;
135 m_scenePresenceArray = newlist; 146 m_scenePresenceArray = newlist;
136 } 147 }
148 finally
149 {
150 m_scenePresencesLock.ExitWriteLock();
151 }
137 152
138 lock (SceneObjectGroupsByFullID) 153 lock (SceneObjectGroupsByFullID)
139 SceneObjectGroupsByFullID.Clear(); 154 SceneObjectGroupsByFullID.Clear();
@@ -254,6 +269,33 @@ namespace OpenSim.Region.Framework.Scenes
254 protected internal bool AddRestoredSceneObject( 269 protected internal bool AddRestoredSceneObject(
255 SceneObjectGroup sceneObject, bool attachToBackup, bool alreadyPersisted, bool sendClientUpdates) 270 SceneObjectGroup sceneObject, bool attachToBackup, bool alreadyPersisted, bool sendClientUpdates)
256 { 271 {
272 if (!m_parentScene.CombineRegions)
273 {
274 // KF: Check for out-of-region, move inside and make static.
275 Vector3 npos = new Vector3(sceneObject.RootPart.GroupPosition.X,
276 sceneObject.RootPart.GroupPosition.Y,
277 sceneObject.RootPart.GroupPosition.Z);
278 if (!(((sceneObject.RootPart.Shape.PCode == (byte)PCode.Prim) && (sceneObject.RootPart.Shape.State != 0))) && (npos.X < 0.0 || npos.Y < 0.0 || npos.Z < 0.0 ||
279 npos.X > Constants.RegionSize ||
280 npos.Y > Constants.RegionSize))
281 {
282 if (npos.X < 0.0) npos.X = 1.0f;
283 if (npos.Y < 0.0) npos.Y = 1.0f;
284 if (npos.Z < 0.0) npos.Z = 0.0f;
285 if (npos.X > Constants.RegionSize) npos.X = Constants.RegionSize - 1.0f;
286 if (npos.Y > Constants.RegionSize) npos.Y = Constants.RegionSize - 1.0f;
287
288 foreach (SceneObjectPart part in sceneObject.Parts)
289 {
290 part.GroupPosition = npos;
291 }
292 sceneObject.RootPart.Velocity = Vector3.Zero;
293 sceneObject.RootPart.AngularVelocity = Vector3.Zero;
294 sceneObject.RootPart.Acceleration = Vector3.Zero;
295 sceneObject.RootPart.Velocity = Vector3.Zero;
296 }
297 }
298
257 if (attachToBackup && (!alreadyPersisted)) 299 if (attachToBackup && (!alreadyPersisted))
258 { 300 {
259 sceneObject.ForceInventoryPersistence(); 301 sceneObject.ForceInventoryPersistence();
@@ -317,9 +359,8 @@ namespace OpenSim.Region.Framework.Scenes
317 if (pa != null && pa.IsPhysical && vel != Vector3.Zero) 359 if (pa != null && pa.IsPhysical && vel != Vector3.Zero)
318 { 360 {
319 sceneObject.RootPart.ApplyImpulse((vel * sceneObject.GetMass()), false); 361 sceneObject.RootPart.ApplyImpulse((vel * sceneObject.GetMass()), false);
320 sceneObject.Velocity = vel;
321 } 362 }
322 363
323 return true; 364 return true;
324 } 365 }
325 366
@@ -344,6 +385,11 @@ namespace OpenSim.Region.Framework.Scenes
344 /// </returns> 385 /// </returns>
345 protected bool AddSceneObject(SceneObjectGroup sceneObject, bool attachToBackup, bool sendClientUpdates) 386 protected bool AddSceneObject(SceneObjectGroup sceneObject, bool attachToBackup, bool sendClientUpdates)
346 { 387 {
388 if (sceneObject == null)
389 {
390 m_log.ErrorFormat("[SCENEGRAPH]: Tried to add null scene object");
391 return false;
392 }
347 if (sceneObject.UUID == UUID.Zero) 393 if (sceneObject.UUID == UUID.Zero)
348 { 394 {
349 m_log.ErrorFormat( 395 m_log.ErrorFormat(
@@ -475,6 +521,30 @@ namespace OpenSim.Region.Framework.Scenes
475 m_updateList[obj.UUID] = obj; 521 m_updateList[obj.UUID] = obj;
476 } 522 }
477 523
524 public void FireAttachToBackup(SceneObjectGroup obj)
525 {
526 if (OnAttachToBackup != null)
527 {
528 OnAttachToBackup(obj);
529 }
530 }
531
532 public void FireDetachFromBackup(SceneObjectGroup obj)
533 {
534 if (OnDetachFromBackup != null)
535 {
536 OnDetachFromBackup(obj);
537 }
538 }
539
540 public void FireChangeBackup(SceneObjectGroup obj)
541 {
542 if (OnChangeBackup != null)
543 {
544 OnChangeBackup(obj);
545 }
546 }
547
478 /// <summary> 548 /// <summary>
479 /// Process all pending updates 549 /// Process all pending updates
480 /// </summary> 550 /// </summary>
@@ -519,12 +589,12 @@ namespace OpenSim.Region.Framework.Scenes
519 589
520 protected internal void AddPhysicalPrim(int number) 590 protected internal void AddPhysicalPrim(int number)
521 { 591 {
522 m_physicalPrim++; 592 m_physicalPrim += number;
523 } 593 }
524 594
525 protected internal void RemovePhysicalPrim(int number) 595 protected internal void RemovePhysicalPrim(int number)
526 { 596 {
527 m_physicalPrim--; 597 m_physicalPrim -= number;
528 } 598 }
529 599
530 protected internal void AddToScriptLPS(int number) 600 protected internal void AddToScriptLPS(int number)
@@ -592,7 +662,8 @@ namespace OpenSim.Region.Framework.Scenes
592 662
593 Entities[presence.UUID] = presence; 663 Entities[presence.UUID] = presence;
594 664
595 lock (m_presenceLock) 665 m_scenePresencesLock.EnterWriteLock();
666 try
596 { 667 {
597 Dictionary<UUID, ScenePresence> newmap = new Dictionary<UUID, ScenePresence>(m_scenePresenceMap); 668 Dictionary<UUID, ScenePresence> newmap = new Dictionary<UUID, ScenePresence>(m_scenePresenceMap);
598 List<ScenePresence> newlist = new List<ScenePresence>(m_scenePresenceArray); 669 List<ScenePresence> newlist = new List<ScenePresence>(m_scenePresenceArray);
@@ -616,6 +687,10 @@ namespace OpenSim.Region.Framework.Scenes
616 m_scenePresenceMap = newmap; 687 m_scenePresenceMap = newmap;
617 m_scenePresenceArray = newlist; 688 m_scenePresenceArray = newlist;
618 } 689 }
690 finally
691 {
692 m_scenePresencesLock.ExitWriteLock();
693 }
619 } 694 }
620 695
621 /// <summary> 696 /// <summary>
@@ -630,7 +705,8 @@ namespace OpenSim.Region.Framework.Scenes
630 agentID); 705 agentID);
631 } 706 }
632 707
633 lock (m_presenceLock) 708 m_scenePresencesLock.EnterWriteLock();
709 try
634 { 710 {
635 Dictionary<UUID, ScenePresence> newmap = new Dictionary<UUID, ScenePresence>(m_scenePresenceMap); 711 Dictionary<UUID, ScenePresence> newmap = new Dictionary<UUID, ScenePresence>(m_scenePresenceMap);
636 List<ScenePresence> newlist = new List<ScenePresence>(m_scenePresenceArray); 712 List<ScenePresence> newlist = new List<ScenePresence>(m_scenePresenceArray);
@@ -652,6 +728,10 @@ namespace OpenSim.Region.Framework.Scenes
652 m_log.WarnFormat("[SCENE GRAPH]: Tried to remove non-existent scene presence with agent ID {0} from scene ScenePresences list", agentID); 728 m_log.WarnFormat("[SCENE GRAPH]: Tried to remove non-existent scene presence with agent ID {0} from scene ScenePresences list", agentID);
653 } 729 }
654 } 730 }
731 finally
732 {
733 m_scenePresencesLock.ExitWriteLock();
734 }
655 } 735 }
656 736
657 protected internal void SwapRootChildAgent(bool direction_RC_CR_T_F) 737 protected internal void SwapRootChildAgent(bool direction_RC_CR_T_F)
@@ -1205,6 +1285,52 @@ namespace OpenSim.Region.Framework.Scenes
1205 1285
1206 #region Client Event handlers 1286 #region Client Event handlers
1207 1287
1288 protected internal void ClientChangeObject(uint localID, object odata, IClientAPI remoteClient)
1289 {
1290 SceneObjectPart part = GetSceneObjectPart(localID);
1291 ObjectChangeData data = (ObjectChangeData)odata;
1292
1293 if (part != null)
1294 {
1295 SceneObjectGroup grp = part.ParentGroup;
1296 if (grp != null)
1297 {
1298 if (m_parentScene.Permissions.CanEditObject(grp.UUID, remoteClient.AgentId))
1299 {
1300 // These two are exceptions SL makes in the interpretation
1301 // of the change flags. Must check them here because otherwise
1302 // the group flag (see below) would be lost
1303 if (data.change == ObjectChangeType.groupS)
1304 data.change = ObjectChangeType.primS;
1305 if (data.change == ObjectChangeType.groupPS)
1306 data.change = ObjectChangeType.primPS;
1307 part.StoreUndoState(data.change); // lets test only saving what we changed
1308 grp.doChangeObject(part, (ObjectChangeData)data);
1309 }
1310 else
1311 {
1312 // Is this any kind of group operation?
1313 if ((data.change & ObjectChangeType.Group) != 0)
1314 {
1315 // Is a move and/or rotation requested?
1316 if ((data.change & (ObjectChangeType.Position | ObjectChangeType.Rotation)) != 0)
1317 {
1318 // Are we allowed to move it?
1319 if (m_parentScene.Permissions.CanMoveObject(grp.UUID, remoteClient.AgentId))
1320 {
1321 // Strip all but move and rotation from request
1322 data.change &= (ObjectChangeType.Group | ObjectChangeType.Position | ObjectChangeType.Rotation);
1323
1324 part.StoreUndoState(data.change);
1325 grp.doChangeObject(part, (ObjectChangeData)data);
1326 }
1327 }
1328 }
1329 }
1330 }
1331 }
1332 }
1333
1208 /// <summary> 1334 /// <summary>
1209 /// Update the scale of an individual prim. 1335 /// Update the scale of an individual prim.
1210 /// </summary> 1336 /// </summary>
@@ -1219,7 +1345,17 @@ namespace OpenSim.Region.Framework.Scenes
1219 { 1345 {
1220 if (m_parentScene.Permissions.CanEditObject(part.ParentGroup.UUID, remoteClient.AgentId)) 1346 if (m_parentScene.Permissions.CanEditObject(part.ParentGroup.UUID, remoteClient.AgentId))
1221 { 1347 {
1348 bool physbuild = false;
1349 if (part.ParentGroup.RootPart.PhysActor != null)
1350 {
1351 part.ParentGroup.RootPart.PhysActor.Building = true;
1352 physbuild = true;
1353 }
1354
1222 part.Resize(scale); 1355 part.Resize(scale);
1356
1357 if (physbuild)
1358 part.ParentGroup.RootPart.PhysActor.Building = false;
1223 } 1359 }
1224 } 1360 }
1225 } 1361 }
@@ -1231,7 +1367,17 @@ namespace OpenSim.Region.Framework.Scenes
1231 { 1367 {
1232 if (m_parentScene.Permissions.CanEditObject(group.UUID, remoteClient.AgentId)) 1368 if (m_parentScene.Permissions.CanEditObject(group.UUID, remoteClient.AgentId))
1233 { 1369 {
1370 bool physbuild = false;
1371 if (group.RootPart.PhysActor != null)
1372 {
1373 group.RootPart.PhysActor.Building = true;
1374 physbuild = true;
1375 }
1376
1234 group.GroupResize(scale); 1377 group.GroupResize(scale);
1378
1379 if (physbuild)
1380 group.RootPart.PhysActor.Building = false;
1235 } 1381 }
1236 } 1382 }
1237 } 1383 }
@@ -1359,8 +1505,13 @@ namespace OpenSim.Region.Framework.Scenes
1359 { 1505 {
1360 if (group.IsAttachment || (group.RootPart.Shape.PCode == 9 && group.RootPart.Shape.State != 0)) 1506 if (group.IsAttachment || (group.RootPart.Shape.PCode == 9 && group.RootPart.Shape.State != 0))
1361 { 1507 {
1362 if (m_parentScene.AttachmentsModule != null) 1508 // Set the new attachment point data in the object
1363 m_parentScene.AttachmentsModule.UpdateAttachmentPosition(group, pos); 1509 byte attachmentPoint = group.GetAttachmentPoint();
1510 group.UpdateGroupPosition(pos);
1511 group.IsAttachment = false;
1512 group.AbsolutePosition = group.RootPart.AttachedPos;
1513 group.AttachmentPoint = attachmentPoint;
1514 group.HasGroupChanged = true;
1364 } 1515 }
1365 else 1516 else
1366 { 1517 {
@@ -1581,6 +1732,7 @@ namespace OpenSim.Region.Framework.Scenes
1581 { 1732 {
1582 part.Material = Convert.ToByte(material); 1733 part.Material = Convert.ToByte(material);
1583 group.HasGroupChanged = true; 1734 group.HasGroupChanged = true;
1735 remoteClient.SendPartPhysicsProprieties(part);
1584 } 1736 }
1585 } 1737 }
1586 } 1738 }
@@ -1645,6 +1797,12 @@ namespace OpenSim.Region.Framework.Scenes
1645 /// <param name="childPrims"></param> 1797 /// <param name="childPrims"></param>
1646 protected internal void LinkObjects(SceneObjectPart root, List<SceneObjectPart> children) 1798 protected internal void LinkObjects(SceneObjectPart root, List<SceneObjectPart> children)
1647 { 1799 {
1800 if (root.KeyframeMotion != null)
1801 {
1802 root.KeyframeMotion.Stop();
1803 root.KeyframeMotion = null;
1804 }
1805
1648 SceneObjectGroup parentGroup = root.ParentGroup; 1806 SceneObjectGroup parentGroup = root.ParentGroup;
1649 if (parentGroup == null) return; 1807 if (parentGroup == null) return;
1650 1808
@@ -1653,8 +1811,10 @@ namespace OpenSim.Region.Framework.Scenes
1653 return; 1811 return;
1654 1812
1655 Monitor.Enter(m_updateLock); 1813 Monitor.Enter(m_updateLock);
1814
1656 try 1815 try
1657 { 1816 {
1817
1658 List<SceneObjectGroup> childGroups = new List<SceneObjectGroup>(); 1818 List<SceneObjectGroup> childGroups = new List<SceneObjectGroup>();
1659 1819
1660 // We do this in reverse to get the link order of the prims correct 1820 // We do this in reverse to get the link order of the prims correct
@@ -1669,9 +1829,13 @@ namespace OpenSim.Region.Framework.Scenes
1669 // Make sure no child prim is set for sale 1829 // Make sure no child prim is set for sale
1670 // So that, on delink, no prims are unwittingly 1830 // So that, on delink, no prims are unwittingly
1671 // left for sale and sold off 1831 // left for sale and sold off
1672 child.RootPart.ObjectSaleType = 0; 1832
1673 child.RootPart.SalePrice = 10; 1833 if (child != null)
1674 childGroups.Add(child); 1834 {
1835 child.RootPart.ObjectSaleType = 0;
1836 child.RootPart.SalePrice = 10;
1837 childGroups.Add(child);
1838 }
1675 } 1839 }
1676 1840
1677 foreach (SceneObjectGroup child in childGroups) 1841 foreach (SceneObjectGroup child in childGroups)
@@ -1700,6 +1864,16 @@ namespace OpenSim.Region.Framework.Scenes
1700 } 1864 }
1701 finally 1865 finally
1702 { 1866 {
1867 lock (SceneObjectGroupsByLocalPartID)
1868 {
1869 foreach (SceneObjectPart part in parentGroup.Parts)
1870 SceneObjectGroupsByLocalPartID[part.LocalId] = parentGroup;
1871 }
1872
1873 parentGroup.AdjustChildPrimPermissions();
1874 parentGroup.HasGroupChanged = true;
1875 parentGroup.ProcessBackup(m_parentScene.SimulationDataService, true);
1876 parentGroup.ScheduleGroupForFullUpdate();
1703 Monitor.Exit(m_updateLock); 1877 Monitor.Exit(m_updateLock);
1704 } 1878 }
1705 } 1879 }
@@ -1722,6 +1896,11 @@ namespace OpenSim.Region.Framework.Scenes
1722 { 1896 {
1723 if (part != null) 1897 if (part != null)
1724 { 1898 {
1899 if (part.KeyframeMotion != null)
1900 {
1901 part.KeyframeMotion.Stop();
1902 part.KeyframeMotion = null;
1903 }
1725 if (part.ParentGroup.PrimCount != 1) // Skip single 1904 if (part.ParentGroup.PrimCount != 1) // Skip single
1726 { 1905 {
1727 if (part.LinkNum < 2) // Root 1906 if (part.LinkNum < 2) // Root
@@ -1736,21 +1915,23 @@ namespace OpenSim.Region.Framework.Scenes
1736 1915
1737 SceneObjectGroup group = part.ParentGroup; 1916 SceneObjectGroup group = part.ParentGroup;
1738 if (!affectedGroups.Contains(group)) 1917 if (!affectedGroups.Contains(group))
1918 {
1739 affectedGroups.Add(group); 1919 affectedGroups.Add(group);
1920 }
1740 } 1921 }
1741 } 1922 }
1742 } 1923 }
1743 1924
1744 foreach (SceneObjectPart child in childParts) 1925 if (childParts.Count > 0)
1745 { 1926 {
1746 // Unlink all child parts from their groups 1927 foreach (SceneObjectPart child in childParts)
1747 // 1928 {
1748 child.ParentGroup.DelinkFromGroup(child, true); 1929 // Unlink all child parts from their groups
1749 1930 //
1750 // These are not in affected groups and will not be 1931 child.ParentGroup.DelinkFromGroup(child, true);
1751 // handled further. Do the honors here. 1932 child.ParentGroup.HasGroupChanged = true;
1752 child.ParentGroup.HasGroupChanged = true; 1933 child.ParentGroup.ScheduleGroupForFullUpdate();
1753 child.ParentGroup.ScheduleGroupForFullUpdate(); 1934 }
1754 } 1935 }
1755 1936
1756 foreach (SceneObjectPart root in rootParts) 1937 foreach (SceneObjectPart root in rootParts)
@@ -1764,52 +1945,61 @@ namespace OpenSim.Region.Framework.Scenes
1764 List<SceneObjectPart> newSet = new List<SceneObjectPart>(group.Parts); 1945 List<SceneObjectPart> newSet = new List<SceneObjectPart>(group.Parts);
1765 int numChildren = newSet.Count; 1946 int numChildren = newSet.Count;
1766 1947
1948 if (numChildren == 1)
1949 break;
1950
1767 // If there are prims left in a link set, but the root is 1951 // If there are prims left in a link set, but the root is
1768 // slated for unlink, we need to do this 1952 // slated for unlink, we need to do this
1953 // Unlink the remaining set
1769 // 1954 //
1770 if (numChildren != 1) 1955 bool sendEventsToRemainder = true;
1771 { 1956 if (numChildren > 1)
1772 // Unlink the remaining set 1957 sendEventsToRemainder = false;
1773 //
1774 bool sendEventsToRemainder = true;
1775 if (numChildren > 1)
1776 sendEventsToRemainder = false;
1777 1958
1778 foreach (SceneObjectPart p in newSet) 1959 foreach (SceneObjectPart p in newSet)
1960 {
1961 if (p != group.RootPart)
1779 { 1962 {
1780 if (p != group.RootPart) 1963 group.DelinkFromGroup(p, sendEventsToRemainder);
1781 group.DelinkFromGroup(p, sendEventsToRemainder); 1964 if (numChildren > 2)
1965 {
1966 }
1967 else
1968 {
1969 p.ParentGroup.HasGroupChanged = true;
1970 p.ParentGroup.ScheduleGroupForFullUpdate();
1971 }
1782 } 1972 }
1973 }
1974
1975 // If there is more than one prim remaining, we
1976 // need to re-link
1977 //
1978 if (numChildren > 2)
1979 {
1980 // Remove old root
1981 //
1982 if (newSet.Contains(root))
1983 newSet.Remove(root);
1783 1984
1784 // If there is more than one prim remaining, we 1985 // Preserve link ordering
1785 // need to re-link
1786 // 1986 //
1787 if (numChildren > 2) 1987 newSet.Sort(delegate (SceneObjectPart a, SceneObjectPart b)
1788 { 1988 {
1789 // Remove old root 1989 return a.LinkNum.CompareTo(b.LinkNum);
1790 // 1990 });
1791 if (newSet.Contains(root))
1792 newSet.Remove(root);
1793
1794 // Preserve link ordering
1795 //
1796 newSet.Sort(delegate (SceneObjectPart a, SceneObjectPart b)
1797 {
1798 return a.LinkNum.CompareTo(b.LinkNum);
1799 });
1800 1991
1801 // Determine new root 1992 // Determine new root
1802 // 1993 //
1803 SceneObjectPart newRoot = newSet[0]; 1994 SceneObjectPart newRoot = newSet[0];
1804 newSet.RemoveAt(0); 1995 newSet.RemoveAt(0);
1805 1996
1806 foreach (SceneObjectPart newChild in newSet) 1997 foreach (SceneObjectPart newChild in newSet)
1807 newChild.ClearUpdateSchedule(); 1998 newChild.ClearUpdateSchedule();
1808 1999
1809 LinkObjects(newRoot, newSet); 2000 LinkObjects(newRoot, newSet);
1810 if (!affectedGroups.Contains(newRoot.ParentGroup)) 2001 if (!affectedGroups.Contains(newRoot.ParentGroup))
1811 affectedGroups.Add(newRoot.ParentGroup); 2002 affectedGroups.Add(newRoot.ParentGroup);
1812 }
1813 } 2003 }
1814 } 2004 }
1815 2005
@@ -1817,6 +2007,12 @@ namespace OpenSim.Region.Framework.Scenes
1817 // 2007 //
1818 foreach (SceneObjectGroup g in affectedGroups) 2008 foreach (SceneObjectGroup g in affectedGroups)
1819 { 2009 {
2010 // Child prims that have been unlinked and deleted will
2011 // return unless the root is deleted. This will remove them
2012 // from the database. They will be rewritten immediately,
2013 // minus the rows for the unlinked child prims.
2014 g.AdjustChildPrimPermissions();
2015 m_parentScene.SimulationDataService.RemoveObject(g.UUID, m_parentScene.RegionInfo.RegionID);
1820 g.TriggerScriptChangedEvent(Changed.LINK); 2016 g.TriggerScriptChangedEvent(Changed.LINK);
1821 g.HasGroupChanged = true; // Persist 2017 g.HasGroupChanged = true; // Persist
1822 g.ScheduleGroupForFullUpdate(); 2018 g.ScheduleGroupForFullUpdate();
@@ -1890,108 +2086,96 @@ namespace OpenSim.Region.Framework.Scenes
1890 /// <param name="GroupID"></param> 2086 /// <param name="GroupID"></param>
1891 /// <param name="rot"></param> 2087 /// <param name="rot"></param>
1892 /// <returns>null if duplication fails, otherwise the duplicated object</returns> 2088 /// <returns>null if duplication fails, otherwise the duplicated object</returns>
1893 public SceneObjectGroup DuplicateObject( 2089 /// <summary>
1894 uint originalPrimID, Vector3 offset, uint flags, UUID AgentID, UUID GroupID, Quaternion rot) 2090 public SceneObjectGroup DuplicateObject(uint originalPrimID, Vector3 offset, uint flags, UUID AgentID, UUID GroupID, Quaternion rot)
1895 { 2091 {
1896 Monitor.Enter(m_updateLock); 2092// m_log.DebugFormat(
2093// "[SCENE]: Duplication of object {0} at offset {1} requested by agent {2}",
2094// originalPrimID, offset, AgentID);
1897 2095
1898 try 2096 SceneObjectGroup original = GetGroupByPrim(originalPrimID);
2097 if (original != null)
1899 { 2098 {
1900 // m_log.DebugFormat( 2099 if (m_parentScene.Permissions.CanDuplicateObject(
1901 // "[SCENE]: Duplication of object {0} at offset {1} requested by agent {2}", 2100 original.PrimCount, original.UUID, AgentID, original.AbsolutePosition))
1902 // originalPrimID, offset, AgentID);
1903
1904 SceneObjectGroup original = GetGroupByPrim(originalPrimID);
1905 if (original == null)
1906 { 2101 {
1907 m_log.WarnFormat( 2102 SceneObjectGroup copy = original.Copy(true);
1908 "[SCENEGRAPH]: Attempt to duplicate nonexistant prim id {0} by {1}", originalPrimID, AgentID); 2103 copy.AbsolutePosition = copy.AbsolutePosition + offset;
1909 2104
1910 return null; 2105 if (original.OwnerID != AgentID)
1911 } 2106 {
2107 copy.SetOwnerId(AgentID);
2108 copy.SetRootPartOwner(copy.RootPart, AgentID, GroupID);
1912 2109
1913 if (!m_parentScene.Permissions.CanDuplicateObject( 2110 SceneObjectPart[] partList = copy.Parts;
1914 original.PrimCount, original.UUID, AgentID, original.AbsolutePosition)) 2111
1915 return null; 2112 if (m_parentScene.Permissions.PropagatePermissions())
2113 {
2114 foreach (SceneObjectPart child in partList)
2115 {
2116 child.Inventory.ChangeInventoryOwner(AgentID);
2117 child.TriggerScriptChangedEvent(Changed.OWNER);
2118 child.ApplyNextOwnerPermissions();
2119 }
2120 }
2121 }
1916 2122
1917 SceneObjectGroup copy = original.Copy(true); 2123 // FIXME: This section needs to be refactored so that it just calls AddSceneObject()
1918 copy.AbsolutePosition = copy.AbsolutePosition + offset; 2124 Entities.Add(copy);
1919 2125
1920 if (original.OwnerID != AgentID) 2126 lock (SceneObjectGroupsByFullID)
1921 { 2127 SceneObjectGroupsByFullID[copy.UUID] = copy;
1922 copy.SetOwnerId(AgentID);
1923 copy.SetRootPartOwner(copy.RootPart, AgentID, GroupID);
1924 2128
1925 SceneObjectPart[] partList = copy.Parts; 2129 SceneObjectPart[] children = copy.Parts;
1926 2130
1927 if (m_parentScene.Permissions.PropagatePermissions()) 2131 lock (SceneObjectGroupsByFullPartID)
1928 { 2132 {
1929 foreach (SceneObjectPart child in partList) 2133 SceneObjectGroupsByFullPartID[copy.UUID] = copy;
1930 { 2134 foreach (SceneObjectPart part in children)
1931 child.Inventory.ChangeInventoryOwner(AgentID); 2135 SceneObjectGroupsByFullPartID[part.UUID] = copy;
1932 child.TriggerScriptChangedEvent(Changed.OWNER);
1933 child.ApplyNextOwnerPermissions();
1934 }
1935 } 2136 }
1936 2137
1937 copy.RootPart.ObjectSaleType = 0; 2138 lock (SceneObjectGroupsByLocalPartID)
1938 copy.RootPart.SalePrice = 10; 2139 {
1939 } 2140 SceneObjectGroupsByLocalPartID[copy.LocalId] = copy;
2141 foreach (SceneObjectPart part in children)
2142 SceneObjectGroupsByLocalPartID[part.LocalId] = copy;
2143 }
2144 // PROBABLE END OF FIXME
1940 2145
1941 // FIXME: This section needs to be refactored so that it just calls AddSceneObject() 2146 // Since we copy from a source group that is in selected
1942 Entities.Add(copy); 2147 // state, but the copy is shown deselected in the viewer,
1943 2148 // We need to clear the selection flag here, else that
1944 lock (SceneObjectGroupsByFullID) 2149 // prim never gets persisted at all. The client doesn't
1945 SceneObjectGroupsByFullID[copy.UUID] = copy; 2150 // think it's selected, so it will never send a deselect...
1946 2151 copy.IsSelected = false;
1947 SceneObjectPart[] children = copy.Parts; 2152
1948 2153 m_numPrim += copy.Parts.Length;
1949 lock (SceneObjectGroupsByFullPartID) 2154
1950 { 2155 if (rot != Quaternion.Identity)
1951 SceneObjectGroupsByFullPartID[copy.UUID] = copy; 2156 {
1952 foreach (SceneObjectPart part in children) 2157 copy.UpdateGroupRotationR(rot);
1953 SceneObjectGroupsByFullPartID[part.UUID] = copy; 2158 }
1954 }
1955
1956 lock (SceneObjectGroupsByLocalPartID)
1957 {
1958 SceneObjectGroupsByLocalPartID[copy.LocalId] = copy;
1959 foreach (SceneObjectPart part in children)
1960 SceneObjectGroupsByLocalPartID[part.LocalId] = copy;
1961 }
1962 // PROBABLE END OF FIXME
1963
1964 // Since we copy from a source group that is in selected
1965 // state, but the copy is shown deselected in the viewer,
1966 // We need to clear the selection flag here, else that
1967 // prim never gets persisted at all. The client doesn't
1968 // think it's selected, so it will never send a deselect...
1969 copy.IsSelected = false;
1970
1971 m_numPrim += copy.Parts.Length;
1972
1973 if (rot != Quaternion.Identity)
1974 {
1975 copy.UpdateGroupRotationR(rot);
1976 }
1977 2159
1978 copy.CreateScriptInstances(0, false, m_parentScene.DefaultScriptEngine, 1); 2160 copy.CreateScriptInstances(0, false, m_parentScene.DefaultScriptEngine, 1);
1979 copy.HasGroupChanged = true; 2161 copy.HasGroupChanged = true;
1980 copy.ScheduleGroupForFullUpdate(); 2162 copy.ScheduleGroupForFullUpdate();
1981 copy.ResumeScripts(); 2163 copy.ResumeScripts();
1982 2164
1983 // required for physics to update it's position 2165 // required for physics to update it's position
1984 copy.AbsolutePosition = copy.AbsolutePosition; 2166 copy.AbsolutePosition = copy.AbsolutePosition;
1985 2167
1986 return copy; 2168 return copy;
2169 }
1987 } 2170 }
1988 finally 2171 else
1989 { 2172 {
1990 Monitor.Exit(m_updateLock); 2173 m_log.WarnFormat("[SCENE]: Attempted to duplicate nonexistant prim id {0}", GroupID);
1991 } 2174 }
2175
2176 return null;
1992 } 2177 }
1993 2178
1994 /// <summary>
1995 /// Calculates the distance between two Vector3s 2179 /// Calculates the distance between two Vector3s
1996 /// </summary> 2180 /// </summary>
1997 /// <param name="v1"></param> 2181 /// <param name="v1"></param>
diff --git a/OpenSim/Region/Framework/Scenes/SceneManager.cs b/OpenSim/Region/Framework/Scenes/SceneManager.cs
index 780bd01..c70342f 100644
--- a/OpenSim/Region/Framework/Scenes/SceneManager.cs
+++ b/OpenSim/Region/Framework/Scenes/SceneManager.cs
@@ -99,11 +99,11 @@ namespace OpenSim.Region.Framework.Scenes
99 } 99 }
100 } 100 }
101 101
102 private readonly List<Scene> m_localScenes = new List<Scene>(); 102 private readonly DoubleDictionary<UUID, string, Scene> m_localScenes = new DoubleDictionary<UUID, string, Scene>();
103 103
104 public List<Scene> Scenes 104 public List<Scene> Scenes
105 { 105 {
106 get { return new List<Scene>(m_localScenes); } 106 get { return new List<Scene>(m_localScenes.FindAll(delegate(Scene s) { return true; })); }
107 } 107 }
108 108
109 /// <summary> 109 /// <summary>
@@ -120,13 +120,10 @@ namespace OpenSim.Region.Framework.Scenes
120 { 120 {
121 if (CurrentScene == null) 121 if (CurrentScene == null)
122 { 122 {
123 lock (m_localScenes) 123 List<Scene> sceneList = Scenes;
124 { 124 if (sceneList.Count == 0)
125 if (m_localScenes.Count > 0) 125 return null;
126 return m_localScenes[0]; 126 return sceneList[0];
127 else
128 return null;
129 }
130 } 127 }
131 else 128 else
132 { 129 {
@@ -138,41 +135,35 @@ namespace OpenSim.Region.Framework.Scenes
138 public SceneManager() 135 public SceneManager()
139 { 136 {
140 m_instance = this; 137 m_instance = this;
141 m_localScenes = new List<Scene>(); 138 m_localScenes = new DoubleDictionary<UUID, string, Scene>();
142 } 139 }
143 140
144 public void Close() 141 public void Close()
145 { 142 {
143 List<Scene> localScenes = null;
144
146 lock (m_localScenes) 145 lock (m_localScenes)
147 { 146 {
148 for (int i = 0; i < m_localScenes.Count; i++) 147 localScenes = Scenes;
149 { 148 }
150 m_localScenes[i].Close(); 149
151 } 150 for (int i = 0; i < localScenes.Count; i++)
151 {
152 localScenes[i].Close();
152 } 153 }
153 } 154 }
154 155
155 public void Close(Scene cscene) 156 public void Close(Scene cscene)
156 { 157 {
157 lock (m_localScenes) 158 if (!m_localScenes.ContainsKey(cscene.RegionInfo.RegionID))
158 { 159 return;
159 if (m_localScenes.Contains(cscene)) 160 cscene.Close();
160 {
161 for (int i = 0; i < m_localScenes.Count; i++)
162 {
163 if (m_localScenes[i].Equals(cscene))
164 {
165 m_localScenes[i].Close();
166 }
167 }
168 }
169 }
170 } 161 }
171 162
172 public void Add(Scene scene) 163 public void Add(Scene scene)
173 { 164 {
174 lock (m_localScenes) 165 lock (m_localScenes)
175 m_localScenes.Add(scene); 166 m_localScenes.Add(scene.RegionInfo.RegionID, scene.RegionInfo.RegionName, scene);
176 167
177 scene.OnRestart += HandleRestart; 168 scene.OnRestart += HandleRestart;
178 scene.EventManager.OnRegionReadyStatusChange += HandleRegionReadyStatusChange; 169 scene.EventManager.OnRegionReadyStatusChange += HandleRegionReadyStatusChange;
@@ -184,15 +175,8 @@ namespace OpenSim.Region.Framework.Scenes
184 175
185 lock (m_localScenes) 176 lock (m_localScenes)
186 { 177 {
187 for (int i = 0; i < m_localScenes.Count; i++) 178 m_localScenes.TryGetValue(rdata.RegionID, out restartedScene);
188 { 179 m_localScenes.Remove(rdata.RegionID);
189 if (rdata.RegionName == m_localScenes[i].RegionInfo.RegionName)
190 {
191 restartedScene = m_localScenes[i];
192 m_localScenes.RemoveAt(i);
193 break;
194 }
195 }
196 } 180 }
197 181
198 // If the currently selected scene has been restarted, then we can't reselect here since we the scene 182 // If the currently selected scene has been restarted, then we can't reselect here since we the scene
@@ -207,39 +191,36 @@ namespace OpenSim.Region.Framework.Scenes
207 private void HandleRegionReadyStatusChange(IScene scene) 191 private void HandleRegionReadyStatusChange(IScene scene)
208 { 192 {
209 lock (m_localScenes) 193 lock (m_localScenes)
210 AllRegionsReady = m_localScenes.TrueForAll(s => s.Ready); 194 AllRegionsReady = m_localScenes.FindAll(s => !s.Ready).Count == 0;
211 } 195 }
212 196
213 public void SendSimOnlineNotification(ulong regionHandle) 197 public void SendSimOnlineNotification(ulong regionHandle)
214 { 198 {
215 RegionInfo Result = null; 199 RegionInfo Result = null;
216 200
217 lock (m_localScenes) 201 Scene s = m_localScenes.FindValue(delegate(Scene x)
218 {
219 for (int i = 0; i < m_localScenes.Count; i++)
220 {
221 if (m_localScenes[i].RegionInfo.RegionHandle == regionHandle)
222 { 202 {
223 // Inform other regions to tell their avatar about me 203 if (x.RegionInfo.RegionHandle == regionHandle)
224 Result = m_localScenes[i].RegionInfo; 204 return true;
225 } 205 return false;
226 } 206 });
207
208 if (s != null)
209 {
210 List<Scene> sceneList = Scenes;
227 211
228 if (Result != null) 212 for (int i = 0; i < sceneList.Count; i++)
229 { 213 {
230 for (int i = 0; i < m_localScenes.Count; i++) 214 if (sceneList[i]!= s)
231 { 215 {
232 if (m_localScenes[i].RegionInfo.RegionHandle != regionHandle) 216 // Inform other regions to tell their avatar about me
233 { 217 //sceneList[i].OtherRegionUp(Result);
234 // Inform other regions to tell their avatar about me
235 //m_localScenes[i].OtherRegionUp(Result);
236 }
237 } 218 }
238 } 219 }
239 else 220 }
240 { 221 else
241 m_log.Error("[REGION]: Unable to notify Other regions of this Region coming up"); 222 {
242 } 223 m_log.Error("[REGION]: Unable to notify Other regions of this Region coming up");
243 } 224 }
244 } 225 }
245 226
@@ -368,16 +349,12 @@ namespace OpenSim.Region.Framework.Scenes
368 } 349 }
369 else 350 else
370 { 351 {
371 lock (m_localScenes) 352 Scene s;
353
354 if (m_localScenes.TryGetValue(regionName, out s))
372 { 355 {
373 foreach (Scene scene in m_localScenes) 356 CurrentScene = s;
374 { 357 return true;
375 if (String.Compare(scene.RegionInfo.RegionName, regionName, true) == 0)
376 {
377 CurrentScene = scene;
378 return true;
379 }
380 }
381 } 358 }
382 359
383 return false; 360 return false;
@@ -386,18 +363,14 @@ namespace OpenSim.Region.Framework.Scenes
386 363
387 public bool TrySetCurrentScene(UUID regionID) 364 public bool TrySetCurrentScene(UUID regionID)
388 { 365 {
389 m_log.Debug("Searching for Region: '" + regionID + "'"); 366// m_log.Debug("Searching for Region: '" + regionID + "'");
390 367
391 lock (m_localScenes) 368 Scene s;
369
370 if (m_localScenes.TryGetValue(regionID, out s))
392 { 371 {
393 foreach (Scene scene in m_localScenes) 372 CurrentScene = s;
394 { 373 return true;
395 if (scene.RegionInfo.RegionID == regionID)
396 {
397 CurrentScene = scene;
398 return true;
399 }
400 }
401 } 374 }
402 375
403 return false; 376 return false;
@@ -405,52 +378,24 @@ namespace OpenSim.Region.Framework.Scenes
405 378
406 public bool TryGetScene(string regionName, out Scene scene) 379 public bool TryGetScene(string regionName, out Scene scene)
407 { 380 {
408 lock (m_localScenes) 381 return m_localScenes.TryGetValue(regionName, out scene);
409 {
410 foreach (Scene mscene in m_localScenes)
411 {
412 if (String.Compare(mscene.RegionInfo.RegionName, regionName, true) == 0)
413 {
414 scene = mscene;
415 return true;
416 }
417 }
418 }
419
420 scene = null;
421 return false;
422 } 382 }
423 383
424 public bool TryGetScene(UUID regionID, out Scene scene) 384 public bool TryGetScene(UUID regionID, out Scene scene)
425 { 385 {
426 lock (m_localScenes) 386 return m_localScenes.TryGetValue(regionID, out scene);
427 {
428 foreach (Scene mscene in m_localScenes)
429 {
430 if (mscene.RegionInfo.RegionID == regionID)
431 {
432 scene = mscene;
433 return true;
434 }
435 }
436 }
437
438 scene = null;
439 return false;
440 } 387 }
441 388
442 public bool TryGetScene(uint locX, uint locY, out Scene scene) 389 public bool TryGetScene(uint locX, uint locY, out Scene scene)
443 { 390 {
444 lock (m_localScenes) 391 List<Scene> sceneList = Scenes;
392 foreach (Scene mscene in sceneList)
445 { 393 {
446 foreach (Scene mscene in m_localScenes) 394 if (mscene.RegionInfo.RegionLocX == locX &&
395 mscene.RegionInfo.RegionLocY == locY)
447 { 396 {
448 if (mscene.RegionInfo.RegionLocX == locX && 397 scene = mscene;
449 mscene.RegionInfo.RegionLocY == locY) 398 return true;
450 {
451 scene = mscene;
452 return true;
453 }
454 } 399 }
455 } 400 }
456 401
@@ -460,16 +405,14 @@ namespace OpenSim.Region.Framework.Scenes
460 405
461 public bool TryGetScene(IPEndPoint ipEndPoint, out Scene scene) 406 public bool TryGetScene(IPEndPoint ipEndPoint, out Scene scene)
462 { 407 {
463 lock (m_localScenes) 408 List<Scene> sceneList = Scenes;
409 foreach (Scene mscene in sceneList)
464 { 410 {
465 foreach (Scene mscene in m_localScenes) 411 if ((mscene.RegionInfo.InternalEndPoint.Equals(ipEndPoint.Address)) &&
412 (mscene.RegionInfo.InternalEndPoint.Port == ipEndPoint.Port))
466 { 413 {
467 if ((mscene.RegionInfo.InternalEndPoint.Equals(ipEndPoint.Address)) && 414 scene = mscene;
468 (mscene.RegionInfo.InternalEndPoint.Port == ipEndPoint.Port)) 415 return true;
469 {
470 scene = mscene;
471 return true;
472 }
473 } 416 }
474 } 417 }
475 418
@@ -534,15 +477,10 @@ namespace OpenSim.Region.Framework.Scenes
534 477
535 public RegionInfo GetRegionInfo(UUID regionID) 478 public RegionInfo GetRegionInfo(UUID regionID)
536 { 479 {
537 lock (m_localScenes) 480 Scene s;
481 if (m_localScenes.TryGetValue(regionID, out s))
538 { 482 {
539 foreach (Scene scene in m_localScenes) 483 return s.RegionInfo;
540 {
541 if (scene.RegionInfo.RegionID == regionID)
542 {
543 return scene.RegionInfo;
544 }
545 }
546 } 484 }
547 485
548 return null; 486 return null;
@@ -560,14 +498,12 @@ namespace OpenSim.Region.Framework.Scenes
560 498
561 public bool TryGetScenePresence(UUID avatarId, out ScenePresence avatar) 499 public bool TryGetScenePresence(UUID avatarId, out ScenePresence avatar)
562 { 500 {
563 lock (m_localScenes) 501 List<Scene> sceneList = Scenes;
502 foreach (Scene scene in sceneList)
564 { 503 {
565 foreach (Scene scene in m_localScenes) 504 if (scene.TryGetScenePresence(avatarId, out avatar))
566 { 505 {
567 if (scene.TryGetScenePresence(avatarId, out avatar)) 506 return true;
568 {
569 return true;
570 }
571 } 507 }
572 } 508 }
573 509
@@ -577,15 +513,13 @@ namespace OpenSim.Region.Framework.Scenes
577 513
578 public bool TryGetRootScenePresence(UUID avatarId, out ScenePresence avatar) 514 public bool TryGetRootScenePresence(UUID avatarId, out ScenePresence avatar)
579 { 515 {
580 lock (m_localScenes) 516 List<Scene> sceneList = Scenes;
517 foreach (Scene scene in sceneList)
581 { 518 {
582 foreach (Scene scene in m_localScenes) 519 avatar = scene.GetScenePresence(avatarId);
583 {
584 avatar = scene.GetScenePresence(avatarId);
585 520
586 if (avatar != null && !avatar.IsChildAgent) 521 if (avatar != null && !avatar.IsChildAgent)
587 return true; 522 return true;
588 }
589 } 523 }
590 524
591 avatar = null; 525 avatar = null;
@@ -595,21 +529,19 @@ namespace OpenSim.Region.Framework.Scenes
595 public void CloseScene(Scene scene) 529 public void CloseScene(Scene scene)
596 { 530 {
597 lock (m_localScenes) 531 lock (m_localScenes)
598 m_localScenes.Remove(scene); 532 m_localScenes.Remove(scene.RegionInfo.RegionID);
599 533
600 scene.Close(); 534 scene.Close();
601 } 535 }
602 536
603 public bool TryGetAvatarByName(string avatarName, out ScenePresence avatar) 537 public bool TryGetAvatarByName(string avatarName, out ScenePresence avatar)
604 { 538 {
605 lock (m_localScenes) 539 List<Scene> sceneList = Scenes;
540 foreach (Scene scene in sceneList)
606 { 541 {
607 foreach (Scene scene in m_localScenes) 542 if (scene.TryGetAvatarByName(avatarName, out avatar))
608 { 543 {
609 if (scene.TryGetAvatarByName(avatarName, out avatar)) 544 return true;
610 {
611 return true;
612 }
613 } 545 }
614 } 546 }
615 547
@@ -619,14 +551,12 @@ namespace OpenSim.Region.Framework.Scenes
619 551
620 public bool TryGetRootScenePresenceByName(string firstName, string lastName, out ScenePresence sp) 552 public bool TryGetRootScenePresenceByName(string firstName, string lastName, out ScenePresence sp)
621 { 553 {
622 lock (m_localScenes) 554 List<Scene> sceneList = Scenes;
555 foreach (Scene scene in sceneList)
623 { 556 {
624 foreach (Scene scene in m_localScenes) 557 sp = scene.GetScenePresence(firstName, lastName);
625 { 558 if (sp != null && !sp.IsChildAgent)
626 sp = scene.GetScenePresence(firstName, lastName); 559 return true;
627 if (sp != null && !sp.IsChildAgent)
628 return true;
629 }
630 } 560 }
631 561
632 sp = null; 562 sp = null;
@@ -635,8 +565,8 @@ namespace OpenSim.Region.Framework.Scenes
635 565
636 public void ForEachScene(Action<Scene> action) 566 public void ForEachScene(Action<Scene> action)
637 { 567 {
638 lock (m_localScenes) 568 List<Scene> sceneList = Scenes;
639 m_localScenes.ForEach(action); 569 sceneList.ForEach(action);
640 } 570 }
641 } 571 }
642} 572}
diff --git a/OpenSim/Region/Framework/Scenes/SceneObjectGroup.Inventory.cs b/OpenSim/Region/Framework/Scenes/SceneObjectGroup.Inventory.cs
index dcb62f8..f8624e7 100644
--- a/OpenSim/Region/Framework/Scenes/SceneObjectGroup.Inventory.cs
+++ b/OpenSim/Region/Framework/Scenes/SceneObjectGroup.Inventory.cs
@@ -82,10 +82,6 @@ namespace OpenSim.Region.Framework.Scenes
82 /// <summary> 82 /// <summary>
83 /// Stop and remove the scripts contained in all the prims in this group 83 /// Stop and remove the scripts contained in all the prims in this group
84 /// </summary> 84 /// </summary>
85 /// <param name="sceneObjectBeingDeleted">
86 /// Should be true if these scripts are being removed because the scene
87 /// object is being deleted. This will prevent spurious updates to the client.
88 /// </param>
89 public void RemoveScriptInstances(bool sceneObjectBeingDeleted) 85 public void RemoveScriptInstances(bool sceneObjectBeingDeleted)
90 { 86 {
91 SceneObjectPart[] parts = m_parts.GetArray(); 87 SceneObjectPart[] parts = m_parts.GetArray();
@@ -248,6 +244,11 @@ namespace OpenSim.Region.Framework.Scenes
248 244
249 public uint GetEffectivePermissions() 245 public uint GetEffectivePermissions()
250 { 246 {
247 return GetEffectivePermissions(false);
248 }
249
250 public uint GetEffectivePermissions(bool useBase)
251 {
251 uint perms=(uint)(PermissionMask.Modify | 252 uint perms=(uint)(PermissionMask.Modify |
252 PermissionMask.Copy | 253 PermissionMask.Copy |
253 PermissionMask.Move | 254 PermissionMask.Move |
@@ -259,7 +260,10 @@ namespace OpenSim.Region.Framework.Scenes
259 for (int i = 0; i < parts.Length; i++) 260 for (int i = 0; i < parts.Length; i++)
260 { 261 {
261 SceneObjectPart part = parts[i]; 262 SceneObjectPart part = parts[i];
262 ownerMask &= part.OwnerMask; 263 if (useBase)
264 ownerMask &= part.BaseMask;
265 else
266 ownerMask &= part.OwnerMask;
263 perms &= part.Inventory.MaskEffectivePermissions(); 267 perms &= part.Inventory.MaskEffectivePermissions();
264 } 268 }
265 269
@@ -401,6 +405,9 @@ namespace OpenSim.Region.Framework.Scenes
401 405
402 public void ResumeScripts() 406 public void ResumeScripts()
403 { 407 {
408 if (m_scene.RegionInfo.RegionSettings.DisableScripts)
409 return;
410
404 SceneObjectPart[] parts = m_parts.GetArray(); 411 SceneObjectPart[] parts = m_parts.GetArray();
405 for (int i = 0; i < parts.Length; i++) 412 for (int i = 0; i < parts.Length; i++)
406 parts[i].Inventory.ResumeScripts(); 413 parts[i].Inventory.ResumeScripts();
diff --git a/OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs b/OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs
index 9e7a986..69fb6df 100644
--- a/OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs
+++ b/OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs
@@ -24,12 +24,13 @@
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */ 26 */
27 27
28using System; 28using System;
29using System.ComponentModel; 29using System.ComponentModel;
30using System.Collections.Generic; 30using System.Collections.Generic;
31using System.Drawing; 31using System.Drawing;
32using System.IO; 32using System.IO;
33using System.Diagnostics;
33using System.Linq; 34using System.Linq;
34using System.Threading; 35using System.Threading;
35using System.Xml; 36using System.Xml;
@@ -44,6 +45,7 @@ using PermissionMask = OpenSim.Framework.PermissionMask;
44 45
45namespace OpenSim.Region.Framework.Scenes 46namespace OpenSim.Region.Framework.Scenes
46{ 47{
48
47 [Flags] 49 [Flags]
48 public enum scriptEvents 50 public enum scriptEvents
49 { 51 {
@@ -78,14 +80,14 @@ namespace OpenSim.Region.Framework.Scenes
78 object_rez = 4194304 80 object_rez = 4194304
79 } 81 }
80 82
81 struct scriptPosTarget 83 public struct scriptPosTarget
82 { 84 {
83 public Vector3 targetPos; 85 public Vector3 targetPos;
84 public float tolerance; 86 public float tolerance;
85 public uint handle; 87 public uint handle;
86 } 88 }
87 89
88 struct scriptRotTarget 90 public struct scriptRotTarget
89 { 91 {
90 public Quaternion targetRot; 92 public Quaternion targetRot;
91 public float tolerance; 93 public float tolerance;
@@ -116,8 +118,12 @@ namespace OpenSim.Region.Framework.Scenes
116 /// since the group's last persistent backup 118 /// since the group's last persistent backup
117 /// </summary> 119 /// </summary>
118 private bool m_hasGroupChanged = false; 120 private bool m_hasGroupChanged = false;
119 private long timeFirstChanged; 121 private long timeFirstChanged = 0;
120 private long timeLastChanged; 122 private long timeLastChanged = 0;
123 private long m_maxPersistTime = 0;
124 private long m_minPersistTime = 0;
125// private Random m_rand;
126 private List<ScenePresence> m_linkedAvatars = new List<ScenePresence>();
121 127
122 /// <summary> 128 /// <summary>
123 /// This indicates whether the object has changed such that it needs to be repersisted to permenant storage 129 /// This indicates whether the object has changed such that it needs to be repersisted to permenant storage
@@ -134,9 +140,44 @@ namespace OpenSim.Region.Framework.Scenes
134 { 140 {
135 if (value) 141 if (value)
136 { 142 {
143
144 if (m_isBackedUp)
145 {
146 m_scene.SceneGraph.FireChangeBackup(this);
147 }
137 timeLastChanged = DateTime.Now.Ticks; 148 timeLastChanged = DateTime.Now.Ticks;
138 if (!m_hasGroupChanged) 149 if (!m_hasGroupChanged)
139 timeFirstChanged = DateTime.Now.Ticks; 150 timeFirstChanged = DateTime.Now.Ticks;
151 if (m_rootPart != null && m_rootPart.UUID != null && m_scene != null)
152 {
153/*
154 if (m_rand == null)
155 {
156 byte[] val = new byte[16];
157 m_rootPart.UUID.ToBytes(val, 0);
158 m_rand = new Random(BitConverter.ToInt32(val, 0));
159 }
160 */
161 if (m_scene.GetRootAgentCount() == 0)
162 {
163 //If the region is empty, this change has been made by an automated process
164 //and thus we delay the persist time by a random amount between 1.5 and 2.5.
165
166// float factor = 1.5f + (float)(m_rand.NextDouble());
167 float factor = 2.0f;
168 m_maxPersistTime = (long)((float)m_scene.m_persistAfter * factor);
169 m_minPersistTime = (long)((float)m_scene.m_dontPersistBefore * factor);
170 }
171 else
172 {
173 //If the region is not empty, we want to obey the minimum and maximum persist times
174 //but add a random factor so we stagger the object persistance a little
175// m_maxPersistTime = (long)((float)m_scene.m_persistAfter * (1.0d - (m_rand.NextDouble() / 5.0d))); //Multiply by 1.0-1.5
176// m_minPersistTime = (long)((float)m_scene.m_dontPersistBefore * (1.0d + (m_rand.NextDouble() / 2.0d))); //Multiply by 0.8-1.0
177 m_maxPersistTime = m_scene.m_persistAfter;
178 m_minPersistTime = m_scene.m_dontPersistBefore;
179 }
180 }
140 } 181 }
141 m_hasGroupChanged = value; 182 m_hasGroupChanged = value;
142 183
@@ -151,7 +192,7 @@ namespace OpenSim.Region.Framework.Scenes
151 /// Has the group changed due to an unlink operation? We record this in order to optimize deletion, since 192 /// Has the group changed due to an unlink operation? We record this in order to optimize deletion, since
152 /// an unlinked group currently has to be persisted to the database before we can perform an unlink operation. 193 /// an unlinked group currently has to be persisted to the database before we can perform an unlink operation.
153 /// </summary> 194 /// </summary>
154 public bool HasGroupChangedDueToDelink { get; private set; } 195 public bool HasGroupChangedDueToDelink { get; set; }
155 196
156 private bool isTimeToPersist() 197 private bool isTimeToPersist()
157 { 198 {
@@ -161,8 +202,19 @@ namespace OpenSim.Region.Framework.Scenes
161 return false; 202 return false;
162 if (m_scene.ShuttingDown) 203 if (m_scene.ShuttingDown)
163 return true; 204 return true;
205
206 if (m_minPersistTime == 0 || m_maxPersistTime == 0)
207 {
208 m_maxPersistTime = m_scene.m_persistAfter;
209 m_minPersistTime = m_scene.m_dontPersistBefore;
210 }
211
164 long currentTime = DateTime.Now.Ticks; 212 long currentTime = DateTime.Now.Ticks;
165 if (currentTime - timeLastChanged > m_scene.m_dontPersistBefore || currentTime - timeFirstChanged > m_scene.m_persistAfter) 213
214 if (timeLastChanged == 0) timeLastChanged = currentTime;
215 if (timeFirstChanged == 0) timeFirstChanged = currentTime;
216
217 if (currentTime - timeLastChanged > m_minPersistTime || currentTime - timeFirstChanged > m_maxPersistTime)
166 return true; 218 return true;
167 return false; 219 return false;
168 } 220 }
@@ -265,26 +317,38 @@ namespace OpenSim.Region.Framework.Scenes
265 get { return RootPart.VolumeDetectActive; } 317 get { return RootPart.VolumeDetectActive; }
266 } 318 }
267 319
268 private Vector3 lastPhysGroupPos;
269 private Quaternion lastPhysGroupRot;
270
271 private bool m_isBackedUp; 320 private bool m_isBackedUp;
272 321
322 public bool IsBackedUp
323 {
324 get { return m_isBackedUp; }
325 }
326
273 protected MapAndArray<UUID, SceneObjectPart> m_parts = new MapAndArray<UUID, SceneObjectPart>(); 327 protected MapAndArray<UUID, SceneObjectPart> m_parts = new MapAndArray<UUID, SceneObjectPart>();
274 328
275 protected ulong m_regionHandle; 329 protected ulong m_regionHandle;
276 protected SceneObjectPart m_rootPart; 330 protected SceneObjectPart m_rootPart;
277 // private Dictionary<UUID, scriptEvents> m_scriptEvents = new Dictionary<UUID, scriptEvents>(); 331 // private Dictionary<UUID, scriptEvents> m_scriptEvents = new Dictionary<UUID, scriptEvents>();
278 332
279 private Dictionary<uint, scriptPosTarget> m_targets = new Dictionary<uint, scriptPosTarget>(); 333 private SortedDictionary<uint, scriptPosTarget> m_targets = new SortedDictionary<uint, scriptPosTarget>();
280 private Dictionary<uint, scriptRotTarget> m_rotTargets = new Dictionary<uint, scriptRotTarget>(); 334 private SortedDictionary<uint, scriptRotTarget> m_rotTargets = new SortedDictionary<uint, scriptRotTarget>();
335
336 public SortedDictionary<uint, scriptPosTarget> AtTargets
337 {
338 get { return m_targets; }
339 }
340
341 public SortedDictionary<uint, scriptRotTarget> RotTargets
342 {
343 get { return m_rotTargets; }
344 }
281 345
282 private bool m_scriptListens_atTarget; 346 private bool m_scriptListens_atTarget;
283 private bool m_scriptListens_notAtTarget; 347 private bool m_scriptListens_notAtTarget;
284
285 private bool m_scriptListens_atRotTarget; 348 private bool m_scriptListens_atRotTarget;
286 private bool m_scriptListens_notAtRotTarget; 349 private bool m_scriptListens_notAtRotTarget;
287 350
351 public bool m_dupeInProgress = false;
288 internal Dictionary<UUID, string> m_savedScriptState; 352 internal Dictionary<UUID, string> m_savedScriptState;
289 353
290 #region Properties 354 #region Properties
@@ -321,6 +385,16 @@ namespace OpenSim.Region.Framework.Scenes
321 get { return m_parts.Count; } 385 get { return m_parts.Count; }
322 } 386 }
323 387
388// protected Quaternion m_rotation = Quaternion.Identity;
389//
390// public virtual Quaternion Rotation
391// {
392// get { return m_rotation; }
393// set {
394// m_rotation = value;
395// }
396// }
397
324 public Quaternion GroupRotation 398 public Quaternion GroupRotation
325 { 399 {
326 get { return m_rootPart.RotationOffset; } 400 get { return m_rootPart.RotationOffset; }
@@ -427,7 +501,15 @@ namespace OpenSim.Region.Framework.Scenes
427 { 501 {
428 return (IsAttachment || (m_rootPart.Shape.PCode == 9 && m_rootPart.Shape.State != 0)); 502 return (IsAttachment || (m_rootPart.Shape.PCode == 9 && m_rootPart.Shape.State != 0));
429 } 503 }
430 504
505
506
507 private struct avtocrossInfo
508 {
509 public ScenePresence av;
510 public uint ParentID;
511 }
512
431 /// <summary> 513 /// <summary>
432 /// The absolute position of this scene object in the scene 514 /// The absolute position of this scene object in the scene
433 /// </summary> 515 /// </summary>
@@ -455,10 +537,129 @@ namespace OpenSim.Region.Framework.Scenes
455 || Scene.TestBorderCross(val, Cardinals.S)) 537 || Scene.TestBorderCross(val, Cardinals.S))
456 && !IsAttachmentCheckFull() && (!Scene.LoadingPrims)) 538 && !IsAttachmentCheckFull() && (!Scene.LoadingPrims))
457 { 539 {
458 m_scene.CrossPrimGroupIntoNewRegion(val, this, true); 540 IEntityTransferModule entityTransfer = m_scene.RequestModuleInterface<IEntityTransferModule>();
541 uint x = 0;
542 uint y = 0;
543 string version = String.Empty;
544 Vector3 newpos = Vector3.Zero;
545 OpenSim.Services.Interfaces.GridRegion destination = null;
546
547 if (m_rootPart.KeyframeMotion != null)
548 m_rootPart.KeyframeMotion.StartCrossingCheck();
549
550 bool canCross = true;
551 foreach (ScenePresence av in m_linkedAvatars)
552 {
553 // We need to cross these agents. First, let's find
554 // out if any of them can't cross for some reason.
555 // We have to deny the crossing entirely if any
556 // of them are banned. Alternatively, we could
557 // unsit banned agents....
558
559
560 // We set the avatar position as being the object
561 // position to get the region to send to
562 if ((destination = entityTransfer.GetDestination(m_scene, av.UUID, val, out x, out y, out version, out newpos)) == null)
563 {
564 canCross = false;
565 break;
566 }
567
568 m_log.DebugFormat("[SCENE OBJECT]: Avatar {0} needs to be crossed to {1}", av.Name, destination.RegionName);
569 }
570
571 if (canCross)
572 {
573 // We unparent the SP quietly so that it won't
574 // be made to stand up
575
576 List<avtocrossInfo> avsToCross = new List<avtocrossInfo>();
577
578 foreach (ScenePresence av in m_linkedAvatars)
579 {
580 avtocrossInfo avinfo = new avtocrossInfo();
581 SceneObjectPart parentPart = m_scene.GetSceneObjectPart(av.ParentID);
582 if (parentPart != null)
583 av.ParentUUID = parentPart.UUID;
584
585 avinfo.av = av;
586 avinfo.ParentID = av.ParentID;
587 avsToCross.Add(avinfo);
588
589 av.ParentID = 0;
590 }
591
592 // m_linkedAvatars.Clear();
593 m_scene.CrossPrimGroupIntoNewRegion(val, this, true);
594
595 // Normalize
596 if (val.X >= Constants.RegionSize)
597 val.X -= Constants.RegionSize;
598 if (val.Y >= Constants.RegionSize)
599 val.Y -= Constants.RegionSize;
600 if (val.X < 0)
601 val.X += Constants.RegionSize;
602 if (val.Y < 0)
603 val.Y += Constants.RegionSize;
604
605 // If it's deleted, crossing was successful
606 if (IsDeleted)
607 {
608 // foreach (ScenePresence av in m_linkedAvatars)
609 foreach (avtocrossInfo avinfo in avsToCross)
610 {
611 ScenePresence av = avinfo.av;
612 if (!av.IsInTransit) // just in case...
613 {
614 m_log.DebugFormat("[SCENE OBJECT]: Crossing avatar {0} to {1}", av.Name, val);
615
616 av.IsInTransit = true;
617
618 CrossAgentToNewRegionDelegate d = entityTransfer.CrossAgentToNewRegionAsync;
619 d.BeginInvoke(av, val, destination, av.Flying, version, CrossAgentToNewRegionCompleted, d);
620 }
621 else
622 m_log.DebugFormat("[SCENE OBJECT]: Crossing avatar alreasy in transit {0} to {1}", av.Name, val);
623 }
624 avsToCross.Clear();
625 return;
626 }
627 else // cross failed, put avas back ??
628 {
629 foreach (avtocrossInfo avinfo in avsToCross)
630 {
631 ScenePresence av = avinfo.av;
632 av.ParentUUID = UUID.Zero;
633 av.ParentID = avinfo.ParentID;
634// m_linkedAvatars.Add(av);
635 }
636 }
637 avsToCross.Clear();
638
639 }
640 else
641 {
642 if (m_rootPart.KeyframeMotion != null)
643 m_rootPart.KeyframeMotion.CrossingFailure();
644
645 if (RootPart.PhysActor != null)
646 {
647 RootPart.PhysActor.CrossingFailure();
648 }
649 }
650 Vector3 oldp = AbsolutePosition;
651 val.X = Util.Clamp<float>(oldp.X, 0.5f, (float)Constants.RegionSize - 0.5f);
652 val.Y = Util.Clamp<float>(oldp.Y, 0.5f, (float)Constants.RegionSize - 0.5f);
653 val.Z = Util.Clamp<float>(oldp.Z, 0.5f, 4096.0f);
459 } 654 }
460 } 655 }
461 656
657/* don't see the need but worse don't see where is restored to false if things stay in
658 foreach (SceneObjectPart part in m_parts.GetArray())
659 {
660 part.IgnoreUndoUpdate = true;
661 }
662 */
462 if (RootPart.GetStatusSandbox()) 663 if (RootPart.GetStatusSandbox())
463 { 664 {
464 if (Util.GetDistanceTo(RootPart.StatusSandboxPos, value) > 10) 665 if (Util.GetDistanceTo(RootPart.StatusSandboxPos, value) > 10)
@@ -476,9 +677,38 @@ namespace OpenSim.Region.Framework.Scenes
476 // Restuff the new GroupPosition into each SOP of the linkset. 677 // Restuff the new GroupPosition into each SOP of the linkset.
477 // This has the affect of resetting and tainting the physics actors. 678 // This has the affect of resetting and tainting the physics actors.
478 SceneObjectPart[] parts = m_parts.GetArray(); 679 SceneObjectPart[] parts = m_parts.GetArray();
479 for (int i = 0; i < parts.Length; i++) 680 bool triggerScriptEvent = m_rootPart.GroupPosition != val;
480 parts[i].GroupPosition = val; 681 if (m_dupeInProgress)
682 triggerScriptEvent = false;
683 foreach (SceneObjectPart part in parts)
684 {
685 part.GroupPosition = val;
686 if (triggerScriptEvent)
687 part.TriggerScriptChangedEvent(Changed.POSITION);
688 }
481 689
690/*
691 This seems not needed and should not be needed:
692 sp absolute position depends on sit part absolute position fixed above.
693 sp ParentPosition is not used anywhere.
694 Since presence is sitting, viewer considers it 'linked' to root prim, so it will move/rotate it
695 Sending a extra packet with avatar position is not only bandwidth waste, but may cause jitter in viewers due to UPD nature.
696
697 if (!m_dupeInProgress)
698 {
699 foreach (ScenePresence av in m_linkedAvatars)
700 {
701 SceneObjectPart p = m_scene.GetSceneObjectPart(av.ParentID);
702 if (p != null && m_parts.TryGetValue(p.UUID, out p))
703 {
704 Vector3 offset = p.GetWorldPosition() - av.ParentPosition;
705 av.AbsolutePosition += offset;
706// av.ParentPosition = p.GetWorldPosition(); //ParentPosition gets cleared by AbsolutePosition
707 av.SendAvatarDataToAllAgents();
708 }
709 }
710 }
711*/
482 //if (m_rootPart.PhysActor != null) 712 //if (m_rootPart.PhysActor != null)
483 //{ 713 //{
484 //m_rootPart.PhysActor.Position = 714 //m_rootPart.PhysActor.Position =
@@ -492,6 +722,40 @@ namespace OpenSim.Region.Framework.Scenes
492 } 722 }
493 } 723 }
494 724
725 public override Vector3 Velocity
726 {
727 get { return RootPart.Velocity; }
728 set { RootPart.Velocity = value; }
729 }
730
731 private void CrossAgentToNewRegionCompleted(IAsyncResult iar)
732 {
733 CrossAgentToNewRegionDelegate icon = (CrossAgentToNewRegionDelegate)iar.AsyncState;
734 ScenePresence agent = icon.EndInvoke(iar);
735
736 //// If the cross was successful, this agent is a child agent
737 if (agent.IsChildAgent)
738 {
739 if (agent.ParentUUID != UUID.Zero)
740 {
741 agent.ParentPart = null;
742// agent.ParentPosition = Vector3.Zero;
743// agent.ParentUUID = UUID.Zero;
744 }
745 }
746
747 agent.ParentUUID = UUID.Zero;
748
749// agent.Reset();
750// else // Not successful
751// agent.RestoreInCurrentScene();
752
753 // In any case
754 agent.IsInTransit = false;
755
756 m_log.DebugFormat("[SCENE OBJECT]: Crossing agent {0} {1} completed.", agent.Firstname, agent.Lastname);
757 }
758
495 public override uint LocalId 759 public override uint LocalId
496 { 760 {
497 get { return m_rootPart.LocalId; } 761 get { return m_rootPart.LocalId; }
@@ -562,6 +826,11 @@ namespace OpenSim.Region.Framework.Scenes
562 m_isSelected = value; 826 m_isSelected = value;
563 // Tell physics engine that group is selected 827 // Tell physics engine that group is selected
564 828
829 // this is not right
830 // but ode engines should only really need to know about root part
831 // so they can put entire object simulation on hold and not colliding
832 // keep as was for now
833
565 PhysicsActor pa = m_rootPart.PhysActor; 834 PhysicsActor pa = m_rootPart.PhysActor;
566 if (pa != null) 835 if (pa != null)
567 { 836 {
@@ -578,6 +847,42 @@ namespace OpenSim.Region.Framework.Scenes
578 childPa.Selected = value; 847 childPa.Selected = value;
579 } 848 }
580 } 849 }
850 if (RootPart.KeyframeMotion != null)
851 RootPart.KeyframeMotion.Selected = value;
852 }
853 }
854
855 public void PartSelectChanged(bool partSelect)
856 {
857 // any part selected makes group selected
858 if (m_isSelected == partSelect)
859 return;
860
861 if (partSelect)
862 {
863 IsSelected = partSelect;
864// if (!IsAttachment)
865// ScheduleGroupForFullUpdate();
866 }
867 else
868 {
869 // bad bad bad 2 heavy for large linksets
870 // since viewer does send lot of (un)selects
871 // this needs to be replaced by a specific list or count ?
872 // but that will require extra code in several places
873
874 SceneObjectPart[] parts = m_parts.GetArray();
875 for (int i = 0; i < parts.Length; i++)
876 {
877 SceneObjectPart part = parts[i];
878 if (part.IsSelected)
879 return;
880 }
881 IsSelected = partSelect;
882 if (!IsAttachment)
883 {
884 ScheduleGroupForFullUpdate();
885 }
581 } 886 }
582 } 887 }
583 888
@@ -675,6 +980,7 @@ namespace OpenSim.Region.Framework.Scenes
675 /// </summary> 980 /// </summary>
676 public SceneObjectGroup() 981 public SceneObjectGroup()
677 { 982 {
983
678 } 984 }
679 985
680 /// <summary> 986 /// <summary>
@@ -692,8 +998,8 @@ namespace OpenSim.Region.Framework.Scenes
692 /// Constructor. This object is added to the scene later via AttachToScene() 998 /// Constructor. This object is added to the scene later via AttachToScene()
693 /// </summary> 999 /// </summary>
694 public SceneObjectGroup(UUID ownerID, Vector3 pos, Quaternion rot, PrimitiveBaseShape shape) 1000 public SceneObjectGroup(UUID ownerID, Vector3 pos, Quaternion rot, PrimitiveBaseShape shape)
695 :this(new SceneObjectPart(ownerID, shape, pos, rot, Vector3.Zero)) 1001 {
696 { 1002 SetRootPart(new SceneObjectPart(ownerID, shape, pos, rot, Vector3.Zero));
697 } 1003 }
698 1004
699 /// <summary> 1005 /// <summary>
@@ -728,6 +1034,9 @@ namespace OpenSim.Region.Framework.Scenes
728 /// </summary> 1034 /// </summary>
729 public virtual void AttachToBackup() 1035 public virtual void AttachToBackup()
730 { 1036 {
1037 if (IsAttachment) return;
1038 m_scene.SceneGraph.FireAttachToBackup(this);
1039
731 if (InSceneBackup) 1040 if (InSceneBackup)
732 { 1041 {
733 //m_log.DebugFormat( 1042 //m_log.DebugFormat(
@@ -770,6 +1079,13 @@ namespace OpenSim.Region.Framework.Scenes
770 1079
771 ApplyPhysics(); 1080 ApplyPhysics();
772 1081
1082 if (RootPart.PhysActor != null)
1083 RootPart.Force = RootPart.Force;
1084 if (RootPart.PhysActor != null)
1085 RootPart.Torque = RootPart.Torque;
1086 if (RootPart.PhysActor != null)
1087 RootPart.Buoyancy = RootPart.Buoyancy;
1088
773 // Don't trigger the update here - otherwise some client issues occur when multiple updates are scheduled 1089 // Don't trigger the update here - otherwise some client issues occur when multiple updates are scheduled
774 // for the same object with very different properties. The caller must schedule the update. 1090 // for the same object with very different properties. The caller must schedule the update.
775 //ScheduleGroupForFullUpdate(); 1091 //ScheduleGroupForFullUpdate();
@@ -785,6 +1101,10 @@ namespace OpenSim.Region.Framework.Scenes
785 EntityIntersection result = new EntityIntersection(); 1101 EntityIntersection result = new EntityIntersection();
786 1102
787 SceneObjectPart[] parts = m_parts.GetArray(); 1103 SceneObjectPart[] parts = m_parts.GetArray();
1104
1105 // Find closest hit here
1106 float idist = float.MaxValue;
1107
788 for (int i = 0; i < parts.Length; i++) 1108 for (int i = 0; i < parts.Length; i++)
789 { 1109 {
790 SceneObjectPart part = parts[i]; 1110 SceneObjectPart part = parts[i];
@@ -799,11 +1119,6 @@ namespace OpenSim.Region.Framework.Scenes
799 1119
800 EntityIntersection inter = part.TestIntersectionOBB(hRay, parentrotation, frontFacesOnly, faceCenters); 1120 EntityIntersection inter = part.TestIntersectionOBB(hRay, parentrotation, frontFacesOnly, faceCenters);
801 1121
802 // This may need to be updated to the maximum draw distance possible..
803 // We might (and probably will) be checking for prim creation from other sims
804 // when the camera crosses the border.
805 float idist = Constants.RegionSize;
806
807 if (inter.HitTF) 1122 if (inter.HitTF)
808 { 1123 {
809 // We need to find the closest prim to return to the testcaller along the ray 1124 // We need to find the closest prim to return to the testcaller along the ray
@@ -814,10 +1129,11 @@ namespace OpenSim.Region.Framework.Scenes
814 result.obj = part; 1129 result.obj = part;
815 result.normal = inter.normal; 1130 result.normal = inter.normal;
816 result.distance = inter.distance; 1131 result.distance = inter.distance;
1132
1133 idist = inter.distance;
817 } 1134 }
818 } 1135 }
819 } 1136 }
820
821 return result; 1137 return result;
822 } 1138 }
823 1139
@@ -829,25 +1145,27 @@ namespace OpenSim.Region.Framework.Scenes
829 /// <returns></returns> 1145 /// <returns></returns>
830 public void GetAxisAlignedBoundingBoxRaw(out float minX, out float maxX, out float minY, out float maxY, out float minZ, out float maxZ) 1146 public void GetAxisAlignedBoundingBoxRaw(out float minX, out float maxX, out float minY, out float maxY, out float minZ, out float maxZ)
831 { 1147 {
832 maxX = -256f; 1148 maxX = float.MinValue;
833 maxY = -256f; 1149 maxY = float.MinValue;
834 maxZ = -256f; 1150 maxZ = float.MinValue;
835 minX = 256f; 1151 minX = float.MaxValue;
836 minY = 256f; 1152 minY = float.MaxValue;
837 minZ = 8192f; 1153 minZ = float.MaxValue;
838 1154
839 SceneObjectPart[] parts = m_parts.GetArray(); 1155 SceneObjectPart[] parts = m_parts.GetArray();
840 for (int i = 0; i < parts.Length; i++) 1156 foreach (SceneObjectPart part in parts)
841 { 1157 {
842 SceneObjectPart part = parts[i];
843
844 Vector3 worldPos = part.GetWorldPosition(); 1158 Vector3 worldPos = part.GetWorldPosition();
845 Vector3 offset = worldPos - AbsolutePosition; 1159 Vector3 offset = worldPos - AbsolutePosition;
846 Quaternion worldRot; 1160 Quaternion worldRot;
847 if (part.ParentID == 0) 1161 if (part.ParentID == 0)
1162 {
848 worldRot = part.RotationOffset; 1163 worldRot = part.RotationOffset;
1164 }
849 else 1165 else
1166 {
850 worldRot = part.GetWorldRotation(); 1167 worldRot = part.GetWorldRotation();
1168 }
851 1169
852 Vector3 frontTopLeft; 1170 Vector3 frontTopLeft;
853 Vector3 frontTopRight; 1171 Vector3 frontTopRight;
@@ -859,6 +1177,8 @@ namespace OpenSim.Region.Framework.Scenes
859 Vector3 backBottomLeft; 1177 Vector3 backBottomLeft;
860 Vector3 backBottomRight; 1178 Vector3 backBottomRight;
861 1179
1180 // Vector3[] corners = new Vector3[8];
1181
862 Vector3 orig = Vector3.Zero; 1182 Vector3 orig = Vector3.Zero;
863 1183
864 frontTopLeft.X = orig.X - (part.Scale.X / 2); 1184 frontTopLeft.X = orig.X - (part.Scale.X / 2);
@@ -893,6 +1213,38 @@ namespace OpenSim.Region.Framework.Scenes
893 backBottomRight.Y = orig.Y + (part.Scale.Y / 2); 1213 backBottomRight.Y = orig.Y + (part.Scale.Y / 2);
894 backBottomRight.Z = orig.Z - (part.Scale.Z / 2); 1214 backBottomRight.Z = orig.Z - (part.Scale.Z / 2);
895 1215
1216
1217
1218 //m_log.InfoFormat("pre corner 1 is {0} {1} {2}", frontTopLeft.X, frontTopLeft.Y, frontTopLeft.Z);
1219 //m_log.InfoFormat("pre corner 2 is {0} {1} {2}", frontTopRight.X, frontTopRight.Y, frontTopRight.Z);
1220 //m_log.InfoFormat("pre corner 3 is {0} {1} {2}", frontBottomRight.X, frontBottomRight.Y, frontBottomRight.Z);
1221 //m_log.InfoFormat("pre corner 4 is {0} {1} {2}", frontBottomLeft.X, frontBottomLeft.Y, frontBottomLeft.Z);
1222 //m_log.InfoFormat("pre corner 5 is {0} {1} {2}", backTopLeft.X, backTopLeft.Y, backTopLeft.Z);
1223 //m_log.InfoFormat("pre corner 6 is {0} {1} {2}", backTopRight.X, backTopRight.Y, backTopRight.Z);
1224 //m_log.InfoFormat("pre corner 7 is {0} {1} {2}", backBottomRight.X, backBottomRight.Y, backBottomRight.Z);
1225 //m_log.InfoFormat("pre corner 8 is {0} {1} {2}", backBottomLeft.X, backBottomLeft.Y, backBottomLeft.Z);
1226
1227 //for (int i = 0; i < 8; i++)
1228 //{
1229 // corners[i] = corners[i] * worldRot;
1230 // corners[i] += offset;
1231
1232 // if (corners[i].X > maxX)
1233 // maxX = corners[i].X;
1234 // if (corners[i].X < minX)
1235 // minX = corners[i].X;
1236
1237 // if (corners[i].Y > maxY)
1238 // maxY = corners[i].Y;
1239 // if (corners[i].Y < minY)
1240 // minY = corners[i].Y;
1241
1242 // if (corners[i].Z > maxZ)
1243 // maxZ = corners[i].Y;
1244 // if (corners[i].Z < minZ)
1245 // minZ = corners[i].Z;
1246 //}
1247
896 frontTopLeft = frontTopLeft * worldRot; 1248 frontTopLeft = frontTopLeft * worldRot;
897 frontTopRight = frontTopRight * worldRot; 1249 frontTopRight = frontTopRight * worldRot;
898 frontBottomLeft = frontBottomLeft * worldRot; 1250 frontBottomLeft = frontBottomLeft * worldRot;
@@ -914,6 +1266,15 @@ namespace OpenSim.Region.Framework.Scenes
914 backTopLeft += offset; 1266 backTopLeft += offset;
915 backTopRight += offset; 1267 backTopRight += offset;
916 1268
1269 //m_log.InfoFormat("corner 1 is {0} {1} {2}", frontTopLeft.X, frontTopLeft.Y, frontTopLeft.Z);
1270 //m_log.InfoFormat("corner 2 is {0} {1} {2}", frontTopRight.X, frontTopRight.Y, frontTopRight.Z);
1271 //m_log.InfoFormat("corner 3 is {0} {1} {2}", frontBottomRight.X, frontBottomRight.Y, frontBottomRight.Z);
1272 //m_log.InfoFormat("corner 4 is {0} {1} {2}", frontBottomLeft.X, frontBottomLeft.Y, frontBottomLeft.Z);
1273 //m_log.InfoFormat("corner 5 is {0} {1} {2}", backTopLeft.X, backTopLeft.Y, backTopLeft.Z);
1274 //m_log.InfoFormat("corner 6 is {0} {1} {2}", backTopRight.X, backTopRight.Y, backTopRight.Z);
1275 //m_log.InfoFormat("corner 7 is {0} {1} {2}", backBottomRight.X, backBottomRight.Y, backBottomRight.Z);
1276 //m_log.InfoFormat("corner 8 is {0} {1} {2}", backBottomLeft.X, backBottomLeft.Y, backBottomLeft.Z);
1277
917 if (frontTopRight.X > maxX) 1278 if (frontTopRight.X > maxX)
918 maxX = frontTopRight.X; 1279 maxX = frontTopRight.X;
919 if (frontTopLeft.X > maxX) 1280 if (frontTopLeft.X > maxX)
@@ -1057,17 +1418,118 @@ namespace OpenSim.Region.Framework.Scenes
1057 1418
1058 #endregion 1419 #endregion
1059 1420
1421 public void GetResourcesCosts(SceneObjectPart apart,
1422 out float linksetResCost, out float linksetPhysCost, out float partCost, out float partPhysCost)
1423 {
1424 // this information may need to be cached
1425
1426 float cost;
1427 float tmpcost;
1428
1429 bool ComplexCost = false;
1430
1431 SceneObjectPart p;
1432 SceneObjectPart[] parts;
1433
1434 lock (m_parts)
1435 {
1436 parts = m_parts.GetArray();
1437 }
1438
1439 int nparts = parts.Length;
1440
1441
1442 for (int i = 0; i < nparts; i++)
1443 {
1444 p = parts[i];
1445
1446 if (p.UsesComplexCost)
1447 {
1448 ComplexCost = true;
1449 break;
1450 }
1451 }
1452
1453 if (ComplexCost)
1454 {
1455 linksetResCost = 0;
1456 linksetPhysCost = 0;
1457 partCost = 0;
1458 partPhysCost = 0;
1459
1460 for (int i = 0; i < nparts; i++)
1461 {
1462 p = parts[i];
1463
1464 cost = p.StreamingCost;
1465 tmpcost = p.SimulationCost;
1466 if (tmpcost > cost)
1467 cost = tmpcost;
1468 tmpcost = p.PhysicsCost;
1469 if (tmpcost > cost)
1470 cost = tmpcost;
1471
1472 linksetPhysCost += tmpcost;
1473 linksetResCost += cost;
1474
1475 if (p == apart)
1476 {
1477 partCost = cost;
1478 partPhysCost = tmpcost;
1479 }
1480 }
1481 }
1482 else
1483 {
1484 partPhysCost = 1.0f;
1485 partCost = 1.0f;
1486 linksetResCost = (float)nparts;
1487 linksetPhysCost = linksetResCost;
1488 }
1489 }
1490
1491 public void GetSelectedCosts(out float PhysCost, out float StreamCost, out float SimulCost)
1492 {
1493 SceneObjectPart p;
1494 SceneObjectPart[] parts;
1495
1496 lock (m_parts)
1497 {
1498 parts = m_parts.GetArray();
1499 }
1500
1501 int nparts = parts.Length;
1502
1503 PhysCost = 0;
1504 StreamCost = 0;
1505 SimulCost = 0;
1506
1507 for (int i = 0; i < nparts; i++)
1508 {
1509 p = parts[i];
1510
1511 StreamCost += p.StreamingCost;
1512 SimulCost += p.SimulationCost;
1513 PhysCost += p.PhysicsCost;
1514 }
1515 }
1516
1060 public void SaveScriptedState(XmlTextWriter writer) 1517 public void SaveScriptedState(XmlTextWriter writer)
1061 { 1518 {
1519 SaveScriptedState(writer, false);
1520 }
1521
1522 public void SaveScriptedState(XmlTextWriter writer, bool oldIDs)
1523 {
1062 XmlDocument doc = new XmlDocument(); 1524 XmlDocument doc = new XmlDocument();
1063 Dictionary<UUID,string> states = new Dictionary<UUID,string>(); 1525 Dictionary<UUID,string> states = new Dictionary<UUID,string>();
1064 1526
1065 SceneObjectPart[] parts = m_parts.GetArray(); 1527 SceneObjectPart[] parts = m_parts.GetArray();
1066 for (int i = 0; i < parts.Length; i++) 1528 for (int i = 0; i < parts.Length; i++)
1067 { 1529 {
1068 Dictionary<UUID, string> pstates = parts[i].Inventory.GetScriptStates(); 1530 Dictionary<UUID, string> pstates = parts[i].Inventory.GetScriptStates(oldIDs);
1069 foreach (KeyValuePair<UUID, string> kvp in pstates) 1531 foreach (KeyValuePair<UUID, string> kvp in pstates)
1070 states.Add(kvp.Key, kvp.Value); 1532 states[kvp.Key] = kvp.Value;
1071 } 1533 }
1072 1534
1073 if (states.Count > 0) 1535 if (states.Count > 0)
@@ -1087,6 +1549,169 @@ namespace OpenSim.Region.Framework.Scenes
1087 } 1549 }
1088 1550
1089 /// <summary> 1551 /// <summary>
1552 /// Add the avatar to this linkset (avatar is sat).
1553 /// </summary>
1554 /// <param name="agentID"></param>
1555 public void AddAvatar(UUID agentID)
1556 {
1557 ScenePresence presence;
1558 if (m_scene.TryGetScenePresence(agentID, out presence))
1559 {
1560 if (!m_linkedAvatars.Contains(presence))
1561 {
1562 m_linkedAvatars.Add(presence);
1563 }
1564 }
1565 }
1566
1567 /// <summary>
1568 /// Delete the avatar from this linkset (avatar is unsat).
1569 /// </summary>
1570 /// <param name="agentID"></param>
1571 public void DeleteAvatar(UUID agentID)
1572 {
1573 ScenePresence presence;
1574 if (m_scene.TryGetScenePresence(agentID, out presence))
1575 {
1576 if (m_linkedAvatars.Contains(presence))
1577 {
1578 m_linkedAvatars.Remove(presence);
1579 }
1580 }
1581 }
1582
1583 /// <summary>
1584 /// Returns the list of linked presences (avatars sat on this group)
1585 /// </summary>
1586 /// <param name="agentID"></param>
1587 public List<ScenePresence> GetLinkedAvatars()
1588 {
1589 return m_linkedAvatars;
1590 }
1591
1592 /// <summary>
1593 /// Attach this scene object to the given avatar.
1594 /// </summary>
1595 /// <param name="agentID"></param>
1596 /// <param name="attachmentpoint"></param>
1597 /// <param name="AttachOffset"></param>
1598 private void AttachToAgent(
1599 ScenePresence avatar, SceneObjectGroup so, uint attachmentpoint, Vector3 attachOffset, bool silent)
1600 {
1601 if (avatar != null)
1602 {
1603 // don't attach attachments to child agents
1604 if (avatar.IsChildAgent) return;
1605
1606 // Remove from database and parcel prim count
1607 m_scene.DeleteFromStorage(so.UUID);
1608 m_scene.EventManager.TriggerParcelPrimCountTainted();
1609
1610 so.AttachedAvatar = avatar.UUID;
1611
1612 if (so.RootPart.PhysActor != null)
1613 {
1614 m_scene.PhysicsScene.RemovePrim(so.RootPart.PhysActor);
1615 so.RootPart.PhysActor = null;
1616 }
1617
1618 so.AbsolutePosition = attachOffset;
1619 so.RootPart.AttachedPos = attachOffset;
1620 so.IsAttachment = true;
1621 so.RootPart.SetParentLocalId(avatar.LocalId);
1622 so.AttachmentPoint = attachmentpoint;
1623
1624 avatar.AddAttachment(this);
1625
1626 if (!silent)
1627 {
1628 // Killing it here will cause the client to deselect it
1629 // It then reappears on the avatar, deselected
1630 // through the full update below
1631 //
1632 if (IsSelected)
1633 {
1634 m_scene.SendKillObject(new List<uint> { m_rootPart.LocalId });
1635 }
1636
1637 IsSelected = false; // fudge....
1638 ScheduleGroupForFullUpdate();
1639 }
1640 }
1641 else
1642 {
1643 m_log.WarnFormat(
1644 "[SOG]: Tried to add attachment {0} to avatar with UUID {1} in region {2} but the avatar is not present",
1645 UUID, avatar.ControllingClient.AgentId, Scene.RegionInfo.RegionName);
1646 }
1647 }
1648
1649 public byte GetAttachmentPoint()
1650 {
1651 return m_rootPart.Shape.State;
1652 }
1653
1654 public void DetachToGround()
1655 {
1656 ScenePresence avatar = m_scene.GetScenePresence(AttachedAvatar);
1657 if (avatar == null)
1658 return;
1659
1660 avatar.RemoveAttachment(this);
1661
1662 Vector3 detachedpos = new Vector3(127f,127f,127f);
1663 if (avatar == null)
1664 return;
1665
1666 detachedpos = avatar.AbsolutePosition;
1667 FromItemID = UUID.Zero;
1668
1669 AbsolutePosition = detachedpos;
1670 AttachedAvatar = UUID.Zero;
1671
1672 //SceneObjectPart[] parts = m_parts.GetArray();
1673 //for (int i = 0; i < parts.Length; i++)
1674 // parts[i].AttachedAvatar = UUID.Zero;
1675
1676 m_rootPart.SetParentLocalId(0);
1677 AttachmentPoint = (byte)0;
1678 // must check if buildind should be true or false here
1679 m_rootPart.ApplyPhysics(m_rootPart.GetEffectiveObjectFlags(), m_rootPart.VolumeDetectActive,false);
1680 HasGroupChanged = true;
1681 RootPart.Rezzed = DateTime.Now;
1682 RootPart.RemFlag(PrimFlags.TemporaryOnRez);
1683 AttachToBackup();
1684 m_scene.EventManager.TriggerParcelPrimCountTainted();
1685 m_rootPart.ScheduleFullUpdate();
1686 m_rootPart.ClearUndoState();
1687 }
1688
1689 public void DetachToInventoryPrep()
1690 {
1691 ScenePresence avatar = m_scene.GetScenePresence(AttachedAvatar);
1692 //Vector3 detachedpos = new Vector3(127f, 127f, 127f);
1693 if (avatar != null)
1694 {
1695 //detachedpos = avatar.AbsolutePosition;
1696 avatar.RemoveAttachment(this);
1697 }
1698
1699 AttachedAvatar = UUID.Zero;
1700
1701 /*SceneObjectPart[] parts = m_parts.GetArray();
1702 for (int i = 0; i < parts.Length; i++)
1703 parts[i].AttachedAvatar = UUID.Zero;*/
1704
1705 m_rootPart.SetParentLocalId(0);
1706 //m_rootPart.SetAttachmentPoint((byte)0);
1707 IsAttachment = false;
1708 AbsolutePosition = m_rootPart.AttachedPos;
1709 //m_rootPart.ApplyPhysics(m_rootPart.GetEffectiveObjectFlags(), m_scene.m_physicalPrim);
1710 //AttachToBackup();
1711 //m_rootPart.ScheduleFullUpdate();
1712 }
1713
1714 /// <summary>
1090 /// 1715 ///
1091 /// </summary> 1716 /// </summary>
1092 /// <param name="part"></param> 1717 /// <param name="part"></param>
@@ -1126,7 +1751,10 @@ namespace OpenSim.Region.Framework.Scenes
1126 public void AddPart(SceneObjectPart part) 1751 public void AddPart(SceneObjectPart part)
1127 { 1752 {
1128 part.SetParent(this); 1753 part.SetParent(this);
1129 part.LinkNum = m_parts.Add(part.UUID, part); 1754 m_parts.Add(part.UUID, part);
1755
1756 part.LinkNum = m_parts.Count;
1757
1130 if (part.LinkNum == 2) 1758 if (part.LinkNum == 2)
1131 RootPart.LinkNum = 1; 1759 RootPart.LinkNum = 1;
1132 } 1760 }
@@ -1152,6 +1780,14 @@ namespace OpenSim.Region.Framework.Scenes
1152 parts[i].UUID = UUID.Random(); 1780 parts[i].UUID = UUID.Random();
1153 } 1781 }
1154 1782
1783 // helper provided for parts.
1784 public int GetSceneMaxUndo()
1785 {
1786 if (m_scene != null)
1787 return m_scene.MaxUndoCount;
1788 return 5;
1789 }
1790
1155 // justincc: I don't believe this hack is needed any longer, especially since the physics 1791 // justincc: I don't believe this hack is needed any longer, especially since the physics
1156 // parts of set AbsolutePosition were already commented out. By changing HasGroupChanged to false 1792 // parts of set AbsolutePosition were already commented out. By changing HasGroupChanged to false
1157 // this method was preventing proper reload of scene objects. 1793 // this method was preventing proper reload of scene objects.
@@ -1209,7 +1845,7 @@ namespace OpenSim.Region.Framework.Scenes
1209// "[SCENE OBJECT GROUP]: Processing OnGrabPart for {0} on {1} {2}, offsetPos {3}", 1845// "[SCENE OBJECT GROUP]: Processing OnGrabPart for {0} on {1} {2}, offsetPos {3}",
1210// remoteClient.Name, part.Name, part.LocalId, offsetPos); 1846// remoteClient.Name, part.Name, part.LocalId, offsetPos);
1211 1847
1212 part.StoreUndoState(); 1848// part.StoreUndoState();
1213 part.OnGrab(offsetPos, remoteClient); 1849 part.OnGrab(offsetPos, remoteClient);
1214 } 1850 }
1215 1851
@@ -1229,6 +1865,11 @@ namespace OpenSim.Region.Framework.Scenes
1229 /// <param name="silent">If true then deletion is not broadcast to clients</param> 1865 /// <param name="silent">If true then deletion is not broadcast to clients</param>
1230 public void DeleteGroupFromScene(bool silent) 1866 public void DeleteGroupFromScene(bool silent)
1231 { 1867 {
1868 // We need to keep track of this state in case this group is still queued for backup.
1869 IsDeleted = true;
1870
1871 DetachFromBackup();
1872
1232 SceneObjectPart[] parts = m_parts.GetArray(); 1873 SceneObjectPart[] parts = m_parts.GetArray();
1233 for (int i = 0; i < parts.Length; i++) 1874 for (int i = 0; i < parts.Length; i++)
1234 { 1875 {
@@ -1252,6 +1893,7 @@ namespace OpenSim.Region.Framework.Scenes
1252 } 1893 }
1253 }); 1894 });
1254 } 1895 }
1896
1255 } 1897 }
1256 1898
1257 public void AddScriptLPS(int count) 1899 public void AddScriptLPS(int count)
@@ -1321,28 +1963,43 @@ namespace OpenSim.Region.Framework.Scenes
1321 /// </summary> 1963 /// </summary>
1322 public void ApplyPhysics() 1964 public void ApplyPhysics()
1323 { 1965 {
1324 // Apply physics to the root prim
1325 m_rootPart.ApplyPhysics(m_rootPart.GetEffectiveObjectFlags(), m_rootPart.VolumeDetectActive);
1326
1327 // Apply physics to child prims
1328 SceneObjectPart[] parts = m_parts.GetArray(); 1966 SceneObjectPart[] parts = m_parts.GetArray();
1329 if (parts.Length > 1) 1967 if (parts.Length > 1)
1330 { 1968 {
1969 ResetChildPrimPhysicsPositions();
1970
1971 // Apply physics to the root prim
1972 m_rootPart.ApplyPhysics(m_rootPart.GetEffectiveObjectFlags(), m_rootPart.VolumeDetectActive, true);
1973
1974
1331 for (int i = 0; i < parts.Length; i++) 1975 for (int i = 0; i < parts.Length; i++)
1332 { 1976 {
1333 SceneObjectPart part = parts[i]; 1977 SceneObjectPart part = parts[i];
1334 if (part.LocalId != m_rootPart.LocalId) 1978 if (part.LocalId != m_rootPart.LocalId)
1335 part.ApplyPhysics(m_rootPart.GetEffectiveObjectFlags(), part.VolumeDetectActive); 1979 part.ApplyPhysics(m_rootPart.GetEffectiveObjectFlags(), part.VolumeDetectActive, true);
1336 } 1980 }
1337
1338 // Hack to get the physics scene geometries in the right spot 1981 // Hack to get the physics scene geometries in the right spot
1339 ResetChildPrimPhysicsPositions(); 1982// ResetChildPrimPhysicsPositions();
1983 if (m_rootPart.PhysActor != null)
1984 {
1985 m_rootPart.PhysActor.Building = false;
1986 }
1987 }
1988 else
1989 {
1990 // Apply physics to the root prim
1991 m_rootPart.ApplyPhysics(m_rootPart.GetEffectiveObjectFlags(), m_rootPart.VolumeDetectActive, false);
1340 } 1992 }
1341 } 1993 }
1342 1994
1343 public void SetOwnerId(UUID userId) 1995 public void SetOwnerId(UUID userId)
1344 { 1996 {
1345 ForEachPart(delegate(SceneObjectPart part) { part.OwnerID = userId; }); 1997 ForEachPart(delegate(SceneObjectPart part)
1998 {
1999
2000 part.OwnerID = userId;
2001
2002 });
1346 } 2003 }
1347 2004
1348 public void ForEachPart(Action<SceneObjectPart> whatToDo) 2005 public void ForEachPart(Action<SceneObjectPart> whatToDo)
@@ -1374,11 +2031,17 @@ namespace OpenSim.Region.Framework.Scenes
1374 return; 2031 return;
1375 } 2032 }
1376 2033
2034 if ((RootPart.Flags & PrimFlags.TemporaryOnRez) != 0)
2035 return;
2036
1377 // Since this is the top of the section of call stack for backing up a particular scene object, don't let 2037 // Since this is the top of the section of call stack for backing up a particular scene object, don't let
1378 // any exception propogate upwards. 2038 // any exception propogate upwards.
1379 try 2039 try
1380 { 2040 {
1381 if (!m_scene.ShuttingDown) // if shutting down then there will be nothing to handle the return so leave till next restart 2041 if (!m_scene.ShuttingDown || // if shutting down then there will be nothing to handle the return so leave till next restart
2042 !m_scene.LoginsEnabled || // We're starting up or doing maintenance, don't mess with things
2043 m_scene.LoadingPrims) // Land may not be valid yet
2044
1382 { 2045 {
1383 ILandObject parcel = m_scene.LandChannel.GetLandObject( 2046 ILandObject parcel = m_scene.LandChannel.GetLandObject(
1384 m_rootPart.GroupPosition.X, m_rootPart.GroupPosition.Y); 2047 m_rootPart.GroupPosition.X, m_rootPart.GroupPosition.Y);
@@ -1405,6 +2068,7 @@ namespace OpenSim.Region.Framework.Scenes
1405 } 2068 }
1406 } 2069 }
1407 } 2070 }
2071
1408 } 2072 }
1409 2073
1410 if (m_scene.UseBackup && HasGroupChanged) 2074 if (m_scene.UseBackup && HasGroupChanged)
@@ -1412,10 +2076,30 @@ namespace OpenSim.Region.Framework.Scenes
1412 // don't backup while it's selected or you're asking for changes mid stream. 2076 // don't backup while it's selected or you're asking for changes mid stream.
1413 if (isTimeToPersist() || forcedBackup) 2077 if (isTimeToPersist() || forcedBackup)
1414 { 2078 {
2079 if (m_rootPart.PhysActor != null &&
2080 (!m_rootPart.PhysActor.IsPhysical))
2081 {
2082 // Possible ghost prim
2083 if (m_rootPart.PhysActor.Position != m_rootPart.GroupPosition)
2084 {
2085 foreach (SceneObjectPart part in m_parts.GetArray())
2086 {
2087 // Re-set physics actor positions and
2088 // orientations
2089 part.GroupPosition = m_rootPart.GroupPosition;
2090 }
2091 }
2092 }
1415// m_log.DebugFormat( 2093// m_log.DebugFormat(
1416// "[SCENE]: Storing {0}, {1} in {2}", 2094// "[SCENE]: Storing {0}, {1} in {2}",
1417// Name, UUID, m_scene.RegionInfo.RegionName); 2095// Name, UUID, m_scene.RegionInfo.RegionName);
1418 2096
2097 if (RootPart.Shape.PCode == 9 && RootPart.Shape.State != 0)
2098 {
2099 RootPart.Shape.State = 0;
2100 ScheduleGroupForFullUpdate();
2101 }
2102
1419 SceneObjectGroup backup_group = Copy(false); 2103 SceneObjectGroup backup_group = Copy(false);
1420 backup_group.RootPart.Velocity = RootPart.Velocity; 2104 backup_group.RootPart.Velocity = RootPart.Velocity;
1421 backup_group.RootPart.Acceleration = RootPart.Acceleration; 2105 backup_group.RootPart.Acceleration = RootPart.Acceleration;
@@ -1425,6 +2109,16 @@ namespace OpenSim.Region.Framework.Scenes
1425 HasGroupChangedDueToDelink = false; 2109 HasGroupChangedDueToDelink = false;
1426 2110
1427 m_scene.EventManager.TriggerOnSceneObjectPreSave(backup_group, this); 2111 m_scene.EventManager.TriggerOnSceneObjectPreSave(backup_group, this);
2112/*
2113 backup_group.ForEachPart(delegate(SceneObjectPart part)
2114 {
2115 if (part.KeyframeMotion != null)
2116 {
2117 part.KeyframeMotion = KeyframeMotion.FromData(backup_group, part.KeyframeMotion.Serialize());
2118// part.KeyframeMotion.UpdateSceneObject(this);
2119 }
2120 });
2121*/
1428 datastore.StoreObject(backup_group, m_scene.RegionInfo.RegionID); 2122 datastore.StoreObject(backup_group, m_scene.RegionInfo.RegionID);
1429 2123
1430 backup_group.ForEachPart(delegate(SceneObjectPart part) 2124 backup_group.ForEachPart(delegate(SceneObjectPart part)
@@ -1481,10 +2175,14 @@ namespace OpenSim.Region.Framework.Scenes
1481 /// <returns></returns> 2175 /// <returns></returns>
1482 public SceneObjectGroup Copy(bool userExposed) 2176 public SceneObjectGroup Copy(bool userExposed)
1483 { 2177 {
2178 m_dupeInProgress = true;
1484 SceneObjectGroup dupe = (SceneObjectGroup)MemberwiseClone(); 2179 SceneObjectGroup dupe = (SceneObjectGroup)MemberwiseClone();
1485 dupe.m_isBackedUp = false; 2180 dupe.m_isBackedUp = false;
1486 dupe.m_parts = new MapAndArray<OpenMetaverse.UUID, SceneObjectPart>(); 2181 dupe.m_parts = new MapAndArray<OpenMetaverse.UUID, SceneObjectPart>();
1487 2182
2183 // new group as no sitting avatars
2184 dupe.m_linkedAvatars = new List<ScenePresence>();
2185
1488 // Warning, The following code related to previousAttachmentStatus is needed so that clones of 2186 // Warning, The following code related to previousAttachmentStatus is needed so that clones of
1489 // attachments do not bordercross while they're being duplicated. This is hacktastic! 2187 // attachments do not bordercross while they're being duplicated. This is hacktastic!
1490 // Normally, setting AbsolutePosition will bordercross a prim if it's outside the region! 2188 // Normally, setting AbsolutePosition will bordercross a prim if it's outside the region!
@@ -1495,7 +2193,7 @@ namespace OpenSim.Region.Framework.Scenes
1495 // This is only necessary when userExposed is false! 2193 // This is only necessary when userExposed is false!
1496 2194
1497 bool previousAttachmentStatus = dupe.IsAttachment; 2195 bool previousAttachmentStatus = dupe.IsAttachment;
1498 2196
1499 if (!userExposed) 2197 if (!userExposed)
1500 dupe.IsAttachment = true; 2198 dupe.IsAttachment = true;
1501 2199
@@ -1508,16 +2206,17 @@ namespace OpenSim.Region.Framework.Scenes
1508 2206
1509 dupe.CopyRootPart(m_rootPart, OwnerID, GroupID, userExposed); 2207 dupe.CopyRootPart(m_rootPart, OwnerID, GroupID, userExposed);
1510 dupe.m_rootPart.LinkNum = m_rootPart.LinkNum; 2208 dupe.m_rootPart.LinkNum = m_rootPart.LinkNum;
2209
1511 2210
1512 if (userExposed) 2211 if (userExposed)
1513 dupe.m_rootPart.TrimPermissions(); 2212 dupe.m_rootPart.TrimPermissions();
1514 2213
1515 List<SceneObjectPart> partList = new List<SceneObjectPart>(m_parts.GetArray()); 2214 List<SceneObjectPart> partList = new List<SceneObjectPart>(m_parts.GetArray());
1516 2215
1517 partList.Sort(delegate(SceneObjectPart p1, SceneObjectPart p2) 2216 partList.Sort(delegate(SceneObjectPart p1, SceneObjectPart p2)
1518 { 2217 {
1519 return p1.LinkNum.CompareTo(p2.LinkNum); 2218 return p1.LinkNum.CompareTo(p2.LinkNum);
1520 } 2219 }
1521 ); 2220 );
1522 2221
1523 foreach (SceneObjectPart part in partList) 2222 foreach (SceneObjectPart part in partList)
@@ -1527,41 +2226,56 @@ namespace OpenSim.Region.Framework.Scenes
1527 { 2226 {
1528 newPart = dupe.CopyPart(part, OwnerID, GroupID, userExposed); 2227 newPart = dupe.CopyPart(part, OwnerID, GroupID, userExposed);
1529 newPart.LinkNum = part.LinkNum; 2228 newPart.LinkNum = part.LinkNum;
1530 } 2229 if (userExposed)
2230 newPart.ParentID = dupe.m_rootPart.LocalId;
2231 }
1531 else 2232 else
1532 { 2233 {
1533 newPart = dupe.m_rootPart; 2234 newPart = dupe.m_rootPart;
1534 } 2235 }
2236/*
2237 bool isphys = ((newPart.Flags & PrimFlags.Physics) != 0);
2238 bool isphan = ((newPart.Flags & PrimFlags.Phantom) != 0);
1535 2239
1536 // Need to duplicate the physics actor as well 2240 // Need to duplicate the physics actor as well
1537 PhysicsActor originalPartPa = part.PhysActor; 2241 if (userExposed && (isphys || !isphan || newPart.VolumeDetectActive))
1538 if (originalPartPa != null && userExposed)
1539 { 2242 {
1540 PrimitiveBaseShape pbs = newPart.Shape; 2243 PrimitiveBaseShape pbs = newPart.Shape;
1541
1542 newPart.PhysActor 2244 newPart.PhysActor
1543 = m_scene.PhysicsScene.AddPrimShape( 2245 = m_scene.PhysicsScene.AddPrimShape(
1544 string.Format("{0}/{1}", newPart.Name, newPart.UUID), 2246 string.Format("{0}/{1}", newPart.Name, newPart.UUID),
1545 pbs, 2247 pbs,
1546 newPart.AbsolutePosition, 2248 newPart.AbsolutePosition,
1547 newPart.Scale, 2249 newPart.Scale,
1548 newPart.RotationOffset, 2250 newPart.GetWorldRotation(),
1549 originalPartPa.IsPhysical, 2251 isphys,
2252 isphan,
1550 newPart.LocalId); 2253 newPart.LocalId);
1551 2254
1552 newPart.DoPhysicsPropertyUpdate(originalPartPa.IsPhysical, true); 2255 newPart.DoPhysicsPropertyUpdate(isphys, true);
1553 } 2256 */
2257 if (userExposed)
2258 newPart.ApplyPhysics((uint)newPart.Flags,newPart.VolumeDetectActive,true);
2259// }
2260 // copy keyframemotion
2261 if (part.KeyframeMotion != null)
2262 newPart.KeyframeMotion = part.KeyframeMotion.Copy(dupe);
1554 } 2263 }
1555 2264
1556 if (userExposed) 2265 if (userExposed)
1557 { 2266 {
1558 dupe.UpdateParentIDs(); 2267// done above dupe.UpdateParentIDs();
2268
2269 if (dupe.m_rootPart.PhysActor != null)
2270 dupe.m_rootPart.PhysActor.Building = false; // tell physics to finish building
2271
1559 dupe.HasGroupChanged = true; 2272 dupe.HasGroupChanged = true;
1560 dupe.AttachToBackup(); 2273 dupe.AttachToBackup();
1561 2274
1562 ScheduleGroupForFullUpdate(); 2275 ScheduleGroupForFullUpdate();
1563 } 2276 }
1564 2277
2278 m_dupeInProgress = false;
1565 return dupe; 2279 return dupe;
1566 } 2280 }
1567 2281
@@ -1573,11 +2287,24 @@ namespace OpenSim.Region.Framework.Scenes
1573 /// <param name="cGroupID"></param> 2287 /// <param name="cGroupID"></param>
1574 public void CopyRootPart(SceneObjectPart part, UUID cAgentID, UUID cGroupID, bool userExposed) 2288 public void CopyRootPart(SceneObjectPart part, UUID cAgentID, UUID cGroupID, bool userExposed)
1575 { 2289 {
1576 SetRootPart(part.Copy(m_scene.AllocateLocalId(), OwnerID, GroupID, 0, userExposed)); 2290 // SetRootPart(part.Copy(m_scene.AllocateLocalId(), OwnerID, GroupID, 0, userExposed));
2291 // give newpart a new local ID lettng old part keep same
2292 SceneObjectPart newpart = part.Copy(part.LocalId, OwnerID, GroupID, 0, userExposed);
2293 newpart.LocalId = m_scene.AllocateLocalId();
2294
2295 SetRootPart(newpart);
2296 if (userExposed)
2297 RootPart.Velocity = Vector3.Zero; // In case source is moving
1577 } 2298 }
1578 2299
1579 public void ScriptSetPhysicsStatus(bool usePhysics) 2300 public void ScriptSetPhysicsStatus(bool usePhysics)
1580 { 2301 {
2302 if (usePhysics)
2303 {
2304 if (RootPart.KeyframeMotion != null)
2305 RootPart.KeyframeMotion.Stop();
2306 RootPart.KeyframeMotion = null;
2307 }
1581 UpdatePrimFlags(RootPart.LocalId, usePhysics, IsTemporary, IsPhantom, IsVolumeDetect); 2308 UpdatePrimFlags(RootPart.LocalId, usePhysics, IsTemporary, IsPhantom, IsVolumeDetect);
1582 } 2309 }
1583 2310
@@ -1625,27 +2352,14 @@ namespace OpenSim.Region.Framework.Scenes
1625 2352
1626 if (pa != null) 2353 if (pa != null)
1627 { 2354 {
1628 pa.AddForce(impulse, true); 2355 // false to be applied as a impulse
1629 m_scene.PhysicsScene.AddPhysicsActorTaint(pa); 2356 pa.AddForce(impulse, false);
1630 }
1631 }
1632 }
1633
1634 public void applyAngularImpulse(Vector3 impulse)
1635 {
1636 PhysicsActor pa = RootPart.PhysActor;
1637
1638 if (pa != null)
1639 {
1640 if (!IsAttachment)
1641 {
1642 pa.AddAngularForce(impulse, true);
1643 m_scene.PhysicsScene.AddPhysicsActorTaint(pa); 2357 m_scene.PhysicsScene.AddPhysicsActorTaint(pa);
1644 } 2358 }
1645 } 2359 }
1646 } 2360 }
1647 2361
1648 public void setAngularImpulse(Vector3 impulse) 2362 public void ApplyAngularImpulse(Vector3 impulse)
1649 { 2363 {
1650 PhysicsActor pa = RootPart.PhysActor; 2364 PhysicsActor pa = RootPart.PhysActor;
1651 2365
@@ -1653,7 +2367,8 @@ namespace OpenSim.Region.Framework.Scenes
1653 { 2367 {
1654 if (!IsAttachment) 2368 if (!IsAttachment)
1655 { 2369 {
1656 pa.Torque = impulse; 2370 // false to be applied as a impulse
2371 pa.AddAngularForce(impulse, false);
1657 m_scene.PhysicsScene.AddPhysicsActorTaint(pa); 2372 m_scene.PhysicsScene.AddPhysicsActorTaint(pa);
1658 } 2373 }
1659 } 2374 }
@@ -1661,20 +2376,10 @@ namespace OpenSim.Region.Framework.Scenes
1661 2376
1662 public Vector3 GetTorque() 2377 public Vector3 GetTorque()
1663 { 2378 {
1664 PhysicsActor pa = RootPart.PhysActor; 2379 return RootPart.Torque;
1665
1666 if (pa != null)
1667 {
1668 if (!IsAttachment)
1669 {
1670 Vector3 torque = pa.Torque;
1671 return torque;
1672 }
1673 }
1674
1675 return Vector3.Zero;
1676 } 2380 }
1677 2381
2382 // This is used by both Double-Click Auto-Pilot and llMoveToTarget() in an attached object
1678 public void moveToTarget(Vector3 target, float tau) 2383 public void moveToTarget(Vector3 target, float tau)
1679 { 2384 {
1680 if (IsAttachment) 2385 if (IsAttachment)
@@ -1704,8 +2409,50 @@ namespace OpenSim.Region.Framework.Scenes
1704 2409
1705 if (pa != null) 2410 if (pa != null)
1706 pa.PIDActive = false; 2411 pa.PIDActive = false;
2412
2413 RootPart.ScheduleTerseUpdate(); // send a stop information
2414 }
2415
2416 public void rotLookAt(Quaternion target, float strength, float damping)
2417 {
2418 SceneObjectPart rootpart = m_rootPart;
2419 if (rootpart != null)
2420 {
2421 if (IsAttachment)
2422 {
2423 /*
2424 ScenePresence avatar = m_scene.GetScenePresence(rootpart.AttachedAvatar);
2425 if (avatar != null)
2426 {
2427 Rotate the Av?
2428 } */
2429 }
2430 else
2431 {
2432 if (rootpart.PhysActor != null)
2433 { // APID must be implemented in your physics system for this to function.
2434 rootpart.PhysActor.APIDTarget = new Quaternion(target.X, target.Y, target.Z, target.W);
2435 rootpart.PhysActor.APIDStrength = strength;
2436 rootpart.PhysActor.APIDDamping = damping;
2437 rootpart.PhysActor.APIDActive = true;
2438 }
2439 }
2440 }
1707 } 2441 }
2442
2443 public void stopLookAt()
2444 {
2445 SceneObjectPart rootpart = m_rootPart;
2446 if (rootpart != null)
2447 {
2448 if (rootpart.PhysActor != null)
2449 { // APID must be implemented in your physics system for this to function.
2450 rootpart.PhysActor.APIDActive = false;
2451 }
2452 }
1708 2453
2454 }
2455
1709 /// <summary> 2456 /// <summary>
1710 /// Uses a PID to attempt to clamp the object on the Z axis at the given height over tau seconds. 2457 /// Uses a PID to attempt to clamp the object on the Z axis at the given height over tau seconds.
1711 /// </summary> 2458 /// </summary>
@@ -1722,7 +2469,7 @@ namespace OpenSim.Region.Framework.Scenes
1722 { 2469 {
1723 pa.PIDHoverHeight = height; 2470 pa.PIDHoverHeight = height;
1724 pa.PIDHoverType = hoverType; 2471 pa.PIDHoverType = hoverType;
1725 pa.PIDTau = tau; 2472 pa.PIDHoverTau = tau;
1726 pa.PIDHoverActive = true; 2473 pa.PIDHoverActive = true;
1727 } 2474 }
1728 else 2475 else
@@ -1762,7 +2509,12 @@ namespace OpenSim.Region.Framework.Scenes
1762 /// <param name="cGroupID"></param> 2509 /// <param name="cGroupID"></param>
1763 public SceneObjectPart CopyPart(SceneObjectPart part, UUID cAgentID, UUID cGroupID, bool userExposed) 2510 public SceneObjectPart CopyPart(SceneObjectPart part, UUID cAgentID, UUID cGroupID, bool userExposed)
1764 { 2511 {
1765 SceneObjectPart newPart = part.Copy(m_scene.AllocateLocalId(), OwnerID, GroupID, m_parts.Count, userExposed); 2512 // give new ID to the new part, letting old keep original
2513 // SceneObjectPart newPart = part.Copy(m_scene.AllocateLocalId(), OwnerID, GroupID, m_parts.Count, userExposed);
2514 SceneObjectPart newPart = part.Copy(part.LocalId, OwnerID, GroupID, m_parts.Count, userExposed);
2515 newPart.LocalId = m_scene.AllocateLocalId();
2516 newPart.SetParent(this);
2517
1766 AddPart(newPart); 2518 AddPart(newPart);
1767 2519
1768 SetPartAsNonRoot(newPart); 2520 SetPartAsNonRoot(newPart);
@@ -1812,6 +2564,7 @@ namespace OpenSim.Region.Framework.Scenes
1812 2564
1813 #endregion 2565 #endregion
1814 2566
2567
1815 public override void Update() 2568 public override void Update()
1816 { 2569 {
1817 // Check that the group was not deleted before the scheduled update 2570 // Check that the group was not deleted before the scheduled update
@@ -1830,19 +2583,8 @@ namespace OpenSim.Region.Framework.Scenes
1830 // check to see if the physical position or rotation warrant an update. 2583 // check to see if the physical position or rotation warrant an update.
1831 if (m_rootPart.UpdateFlag == UpdateRequired.NONE) 2584 if (m_rootPart.UpdateFlag == UpdateRequired.NONE)
1832 { 2585 {
1833 bool UsePhysics = ((RootPart.Flags & PrimFlags.Physics) != 0); 2586 // rootpart SendScheduledUpdates will check if a update is needed
1834 2587 m_rootPart.UpdateFlag = UpdateRequired.TERSE;
1835 if (UsePhysics && !AbsolutePosition.ApproxEquals(lastPhysGroupPos, 0.02f))
1836 {
1837 m_rootPart.UpdateFlag = UpdateRequired.TERSE;
1838 lastPhysGroupPos = AbsolutePosition;
1839 }
1840
1841 if (UsePhysics && !GroupRotation.ApproxEquals(lastPhysGroupRot, 0.1f))
1842 {
1843 m_rootPart.UpdateFlag = UpdateRequired.TERSE;
1844 lastPhysGroupRot = GroupRotation;
1845 }
1846 } 2588 }
1847 2589
1848 SceneObjectPart[] parts = m_parts.GetArray(); 2590 SceneObjectPart[] parts = m_parts.GetArray();
@@ -1901,11 +2643,11 @@ namespace OpenSim.Region.Framework.Scenes
1901 /// Immediately send a full update for this scene object. 2643 /// Immediately send a full update for this scene object.
1902 /// </summary> 2644 /// </summary>
1903 public void SendGroupFullUpdate() 2645 public void SendGroupFullUpdate()
1904 { 2646 {
1905 if (IsDeleted) 2647 if (IsDeleted)
1906 return; 2648 return;
1907 2649
1908// m_log.DebugFormat("[SOG]: Sending immediate full group update for {0} {1}", Name, UUID); 2650// m_log.DebugFormat("[SOG]: Sending immediate full group update for {0} {1}", Name, UUID);
1909 2651
1910 RootPart.SendFullUpdateToAllClients(); 2652 RootPart.SendFullUpdateToAllClients();
1911 2653
@@ -2061,6 +2803,11 @@ namespace OpenSim.Region.Framework.Scenes
2061 // 'linkPart' == the root of the group being linked into this group 2803 // 'linkPart' == the root of the group being linked into this group
2062 SceneObjectPart linkPart = objectGroup.m_rootPart; 2804 SceneObjectPart linkPart = objectGroup.m_rootPart;
2063 2805
2806 if (m_rootPart.PhysActor != null)
2807 m_rootPart.PhysActor.Building = true;
2808 if (linkPart.PhysActor != null)
2809 linkPart.PhysActor.Building = true;
2810
2064 // physics flags from group to be applied to linked parts 2811 // physics flags from group to be applied to linked parts
2065 bool grpusephys = UsesPhysics; 2812 bool grpusephys = UsesPhysics;
2066 bool grptemporary = IsTemporary; 2813 bool grptemporary = IsTemporary;
@@ -2086,12 +2833,12 @@ namespace OpenSim.Region.Framework.Scenes
2086 Vector3 axPos = linkPart.OffsetPosition; 2833 Vector3 axPos = linkPart.OffsetPosition;
2087 // Rotate the linking root SOP's position to be relative to the new root prim 2834 // Rotate the linking root SOP's position to be relative to the new root prim
2088 Quaternion parentRot = m_rootPart.RotationOffset; 2835 Quaternion parentRot = m_rootPart.RotationOffset;
2089 axPos *= Quaternion.Inverse(parentRot); 2836 axPos *= Quaternion.Conjugate(parentRot);
2090 linkPart.OffsetPosition = axPos; 2837 linkPart.OffsetPosition = axPos;
2091 2838
2092 // Make the linking root SOP's rotation relative to the new root prim 2839 // Make the linking root SOP's rotation relative to the new root prim
2093 Quaternion oldRot = linkPart.RotationOffset; 2840 Quaternion oldRot = linkPart.RotationOffset;
2094 Quaternion newRot = Quaternion.Inverse(parentRot) * oldRot; 2841 Quaternion newRot = Quaternion.Conjugate(parentRot) * oldRot;
2095 linkPart.RotationOffset = newRot; 2842 linkPart.RotationOffset = newRot;
2096 2843
2097 // If there is only one SOP in a SOG, the LinkNum is zero. I.e., not a linkset. 2844 // If there is only one SOP in a SOG, the LinkNum is zero. I.e., not a linkset.
@@ -2125,7 +2872,7 @@ namespace OpenSim.Region.Framework.Scenes
2125 linkPart.CreateSelected = true; 2872 linkPart.CreateSelected = true;
2126 2873
2127 // let physics know preserve part volume dtc messy since UpdatePrimFlags doesn't look to parent changes for now 2874 // let physics know preserve part volume dtc messy since UpdatePrimFlags doesn't look to parent changes for now
2128 linkPart.UpdatePrimFlags(grpusephys, grptemporary, (IsPhantom || (linkPart.Flags & PrimFlags.Phantom) != 0), linkPart.VolumeDetectActive); 2875 linkPart.UpdatePrimFlags(grpusephys, grptemporary, (IsPhantom || (linkPart.Flags & PrimFlags.Phantom) != 0), linkPart.VolumeDetectActive, true);
2129 2876
2130 // If the added SOP is physical, also tell the physics engine about the link relationship. 2877 // If the added SOP is physical, also tell the physics engine about the link relationship.
2131 if (linkPart.PhysActor != null && m_rootPart.PhysActor != null && m_rootPart.PhysActor.IsPhysical) 2878 if (linkPart.PhysActor != null && m_rootPart.PhysActor != null && m_rootPart.PhysActor.IsPhysical)
@@ -2135,6 +2882,7 @@ namespace OpenSim.Region.Framework.Scenes
2135 } 2882 }
2136 2883
2137 linkPart.LinkNum = linkNum++; 2884 linkPart.LinkNum = linkNum++;
2885 linkPart.UpdatePrimFlags(UsesPhysics, IsTemporary, IsPhantom, IsVolumeDetect, false);
2138 2886
2139 // Get a list of the SOP's in the old group in order of their linknum's. 2887 // Get a list of the SOP's in the old group in order of their linknum's.
2140 SceneObjectPart[] ogParts = objectGroup.Parts; 2888 SceneObjectPart[] ogParts = objectGroup.Parts;
@@ -2153,7 +2901,7 @@ namespace OpenSim.Region.Framework.Scenes
2153 2901
2154 // Update the physics flags for the newly added SOP 2902 // Update the physics flags for the newly added SOP
2155 // (Is this necessary? LinkNonRootPart() has already called UpdatePrimFlags but with different flags!??) 2903 // (Is this necessary? LinkNonRootPart() has already called UpdatePrimFlags but with different flags!??)
2156 part.UpdatePrimFlags(grpusephys, grptemporary, (IsPhantom || (part.Flags & PrimFlags.Phantom) != 0), part.VolumeDetectActive); 2904 part.UpdatePrimFlags(grpusephys, grptemporary, (IsPhantom || (part.Flags & PrimFlags.Phantom) != 0), part.VolumeDetectActive, true);
2157 2905
2158 // If the added SOP is physical, also tell the physics engine about the link relationship. 2906 // If the added SOP is physical, also tell the physics engine about the link relationship.
2159 if (part.PhysActor != null && m_rootPart.PhysActor != null && m_rootPart.PhysActor.IsPhysical) 2907 if (part.PhysActor != null && m_rootPart.PhysActor != null && m_rootPart.PhysActor.IsPhysical)
@@ -2171,7 +2919,7 @@ namespace OpenSim.Region.Framework.Scenes
2171 objectGroup.IsDeleted = true; 2919 objectGroup.IsDeleted = true;
2172 2920
2173 objectGroup.m_parts.Clear(); 2921 objectGroup.m_parts.Clear();
2174 2922
2175 // Can't do this yet since backup still makes use of the root part without any synchronization 2923 // Can't do this yet since backup still makes use of the root part without any synchronization
2176// objectGroup.m_rootPart = null; 2924// objectGroup.m_rootPart = null;
2177 2925
@@ -2185,6 +2933,9 @@ namespace OpenSim.Region.Framework.Scenes
2185 // unmoved prims! 2933 // unmoved prims!
2186 ResetChildPrimPhysicsPositions(); 2934 ResetChildPrimPhysicsPositions();
2187 2935
2936 if (m_rootPart.PhysActor != null)
2937 m_rootPart.PhysActor.Building = false;
2938
2188 //HasGroupChanged = true; 2939 //HasGroupChanged = true;
2189 //ScheduleGroupForFullUpdate(); 2940 //ScheduleGroupForFullUpdate();
2190 } 2941 }
@@ -2252,7 +3003,10 @@ namespace OpenSim.Region.Framework.Scenes
2252// m_log.DebugFormat( 3003// m_log.DebugFormat(
2253// "[SCENE OBJECT GROUP]: Delinking part {0}, {1} from group with root part {2}, {3}", 3004// "[SCENE OBJECT GROUP]: Delinking part {0}, {1} from group with root part {2}, {3}",
2254// linkPart.Name, linkPart.UUID, RootPart.Name, RootPart.UUID); 3005// linkPart.Name, linkPart.UUID, RootPart.Name, RootPart.UUID);
2255 3006
3007 if (m_rootPart.PhysActor != null)
3008 m_rootPart.PhysActor.Building = true;
3009
2256 linkPart.ClearUndoState(); 3010 linkPart.ClearUndoState();
2257 3011
2258 Vector3 worldPos = linkPart.GetWorldPosition(); 3012 Vector3 worldPos = linkPart.GetWorldPosition();
@@ -2323,6 +3077,14 @@ namespace OpenSim.Region.Framework.Scenes
2323 3077
2324 // When we delete a group, we currently have to force persist to the database if the object id has changed 3078 // When we delete a group, we currently have to force persist to the database if the object id has changed
2325 // (since delete works by deleting all rows which have a given object id) 3079 // (since delete works by deleting all rows which have a given object id)
3080
3081 // this is as it seems to be in sl now
3082 if(linkPart.PhysicsShapeType == (byte)PhysShapeType.none)
3083 linkPart.PhysicsShapeType = linkPart.DefaultPhysicsShapeType(); // root prims can't have type none for now
3084
3085 if (m_rootPart.PhysActor != null)
3086 m_rootPart.PhysActor.Building = false;
3087
2326 objectGroup.HasGroupChangedDueToDelink = true; 3088 objectGroup.HasGroupChangedDueToDelink = true;
2327 3089
2328 return objectGroup; 3090 return objectGroup;
@@ -2334,6 +3096,8 @@ namespace OpenSim.Region.Framework.Scenes
2334 /// <param name="objectGroup"></param> 3096 /// <param name="objectGroup"></param>
2335 public virtual void DetachFromBackup() 3097 public virtual void DetachFromBackup()
2336 { 3098 {
3099 if (m_scene != null)
3100 m_scene.SceneGraph.FireDetachFromBackup(this);
2337 if (m_isBackedUp && Scene != null) 3101 if (m_isBackedUp && Scene != null)
2338 m_scene.EventManager.OnBackup -= ProcessBackup; 3102 m_scene.EventManager.OnBackup -= ProcessBackup;
2339 3103
@@ -2354,7 +3118,8 @@ namespace OpenSim.Region.Framework.Scenes
2354 Vector3 axPos = part.OffsetPosition; 3118 Vector3 axPos = part.OffsetPosition;
2355 axPos *= parentRot; 3119 axPos *= parentRot;
2356 part.OffsetPosition = axPos; 3120 part.OffsetPosition = axPos;
2357 part.GroupPosition = oldGroupPosition + part.OffsetPosition; 3121 Vector3 newPos = oldGroupPosition + part.OffsetPosition;
3122 part.GroupPosition = newPos;
2358 part.OffsetPosition = Vector3.Zero; 3123 part.OffsetPosition = Vector3.Zero;
2359 3124
2360 // Compution our rotation to be not relative to the old parent 3125 // Compution our rotation to be not relative to the old parent
@@ -2369,7 +3134,7 @@ namespace OpenSim.Region.Framework.Scenes
2369 part.LinkNum = linkNum; 3134 part.LinkNum = linkNum;
2370 3135
2371 // Compute the new position of this SOP relative to the group position 3136 // Compute the new position of this SOP relative to the group position
2372 part.OffsetPosition = part.GroupPosition - AbsolutePosition; 3137 part.OffsetPosition = newPos - AbsolutePosition;
2373 3138
2374 // (radams1 20120711: I don't know why part.OffsetPosition is set multiple times. 3139 // (radams1 20120711: I don't know why part.OffsetPosition is set multiple times.
2375 // It would have the affect of setting the physics engine position multiple 3140 // It would have the affect of setting the physics engine position multiple
@@ -2379,18 +3144,19 @@ namespace OpenSim.Region.Framework.Scenes
2379 // Rotate the relative position by the rotation of the group 3144 // Rotate the relative position by the rotation of the group
2380 Quaternion rootRotation = m_rootPart.RotationOffset; 3145 Quaternion rootRotation = m_rootPart.RotationOffset;
2381 Vector3 pos = part.OffsetPosition; 3146 Vector3 pos = part.OffsetPosition;
2382 pos *= Quaternion.Inverse(rootRotation); 3147 pos *= Quaternion.Conjugate(rootRotation);
2383 part.OffsetPosition = pos; 3148 part.OffsetPosition = pos;
2384 3149
2385 // Compute the SOP's rotation relative to the rotation of the group. 3150 // Compute the SOP's rotation relative to the rotation of the group.
2386 parentRot = m_rootPart.RotationOffset; 3151 parentRot = m_rootPart.RotationOffset;
2387 oldRot = part.RotationOffset; 3152 oldRot = part.RotationOffset;
2388 Quaternion newRot = Quaternion.Inverse(parentRot) * oldRot; 3153 Quaternion newRot = Quaternion.Conjugate(parentRot) * worldRot;
2389 part.RotationOffset = newRot; 3154 part.RotationOffset = newRot;
2390 3155
2391 // Since this SOP's state has changed, push those changes into the physics engine 3156 // Since this SOP's state has changed, push those changes into the physics engine
2392 // and the simulator. 3157 // and the simulator.
2393 part.UpdatePrimFlags(UsesPhysics, IsTemporary, IsPhantom, IsVolumeDetect); 3158 // done on caller
3159// part.UpdatePrimFlags(UsesPhysics, IsTemporary, IsPhantom, IsVolumeDetect, false);
2394 } 3160 }
2395 3161
2396 /// <summary> 3162 /// <summary>
@@ -2412,10 +3178,14 @@ namespace OpenSim.Region.Framework.Scenes
2412 { 3178 {
2413 if (!m_rootPart.BlockGrab) 3179 if (!m_rootPart.BlockGrab)
2414 { 3180 {
2415 Vector3 llmoveforce = pos - AbsolutePosition; 3181/* Vector3 llmoveforce = pos - AbsolutePosition;
2416 Vector3 grabforce = llmoveforce; 3182 Vector3 grabforce = llmoveforce;
2417 grabforce = (grabforce / 10) * pa.Mass; 3183 grabforce = (grabforce / 10) * pa.Mass;
2418 pa.AddForce(grabforce, true); 3184 */
3185 // empirically convert distance diference to a impulse
3186 Vector3 grabforce = pos - AbsolutePosition;
3187 grabforce = grabforce * (pa.Mass/ 10.0f);
3188 pa.AddForce(grabforce, false);
2419 m_scene.PhysicsScene.AddPhysicsActorTaint(pa); 3189 m_scene.PhysicsScene.AddPhysicsActorTaint(pa);
2420 } 3190 }
2421 } 3191 }
@@ -2611,6 +3381,8 @@ namespace OpenSim.Region.Framework.Scenes
2611 /// <param name="SetVolumeDetect"></param> 3381 /// <param name="SetVolumeDetect"></param>
2612 public void UpdatePrimFlags(uint localID, bool UsePhysics, bool SetTemporary, bool SetPhantom, bool SetVolumeDetect) 3382 public void UpdatePrimFlags(uint localID, bool UsePhysics, bool SetTemporary, bool SetPhantom, bool SetVolumeDetect)
2613 { 3383 {
3384 HasGroupChanged = true;
3385
2614 SceneObjectPart selectionPart = GetPart(localID); 3386 SceneObjectPart selectionPart = GetPart(localID);
2615 3387
2616 if (SetTemporary && Scene != null) 3388 if (SetTemporary && Scene != null)
@@ -2641,8 +3413,22 @@ namespace OpenSim.Region.Framework.Scenes
2641 } 3413 }
2642 } 3414 }
2643 3415
2644 for (int i = 0; i < parts.Length; i++) 3416 if (parts.Length > 1)
2645 parts[i].UpdatePrimFlags(UsePhysics, SetTemporary, SetPhantom, SetVolumeDetect); 3417 {
3418 m_rootPart.UpdatePrimFlags(UsePhysics, SetTemporary, SetPhantom, SetVolumeDetect, true);
3419
3420 for (int i = 0; i < parts.Length; i++)
3421 {
3422
3423 if (parts[i].UUID != m_rootPart.UUID)
3424 parts[i].UpdatePrimFlags(UsePhysics, SetTemporary, SetPhantom, SetVolumeDetect, true);
3425 }
3426
3427 if (m_rootPart.PhysActor != null)
3428 m_rootPart.PhysActor.Building = false;
3429 }
3430 else
3431 m_rootPart.UpdatePrimFlags(UsePhysics, SetTemporary, SetPhantom, SetVolumeDetect, false);
2646 } 3432 }
2647 } 3433 }
2648 3434
@@ -2655,6 +3441,17 @@ namespace OpenSim.Region.Framework.Scenes
2655 } 3441 }
2656 } 3442 }
2657 3443
3444
3445
3446 /// <summary>
3447 /// Gets the number of parts
3448 /// </summary>
3449 /// <returns></returns>
3450 public int GetPartCount()
3451 {
3452 return Parts.Count();
3453 }
3454
2658 /// <summary> 3455 /// <summary>
2659 /// Update the texture entry for this part 3456 /// Update the texture entry for this part
2660 /// </summary> 3457 /// </summary>
@@ -2692,8 +3489,24 @@ namespace OpenSim.Region.Framework.Scenes
2692 { 3489 {
2693 RootPart.UpdatePermissions(AgentID, field, localID, mask, addRemTF); 3490 RootPart.UpdatePermissions(AgentID, field, localID, mask, addRemTF);
2694 3491
3492 bool god = Scene.Permissions.IsGod(AgentID);
3493
3494 if (field == 1 && god)
3495 {
3496 ForEachPart(part =>
3497 {
3498 part.BaseMask = RootPart.BaseMask;
3499 });
3500 }
3501
2695 AdjustChildPrimPermissions(); 3502 AdjustChildPrimPermissions();
2696 3503
3504 if (field == 1 && god) // Base mask was set. Update all child part inventories
3505 {
3506 foreach (SceneObjectPart part in Parts)
3507 part.Inventory.ApplyGodPermissions(RootPart.BaseMask);
3508 }
3509
2697 HasGroupChanged = true; 3510 HasGroupChanged = true;
2698 3511
2699 // Send the group's properties to all clients once all parts are updated 3512 // Send the group's properties to all clients once all parts are updated
@@ -2739,8 +3552,6 @@ namespace OpenSim.Region.Framework.Scenes
2739 3552
2740 PhysicsActor pa = m_rootPart.PhysActor; 3553 PhysicsActor pa = m_rootPart.PhysActor;
2741 3554
2742 RootPart.StoreUndoState(true);
2743
2744 if (Scene != null) 3555 if (Scene != null)
2745 { 3556 {
2746 scale.X = Math.Max(Scene.m_minNonphys, Math.Min(Scene.m_maxNonphys, scale.X)); 3557 scale.X = Math.Max(Scene.m_minNonphys, Math.Min(Scene.m_maxNonphys, scale.X));
@@ -2768,7 +3579,6 @@ namespace OpenSim.Region.Framework.Scenes
2768 SceneObjectPart obPart = parts[i]; 3579 SceneObjectPart obPart = parts[i];
2769 if (obPart.UUID != m_rootPart.UUID) 3580 if (obPart.UUID != m_rootPart.UUID)
2770 { 3581 {
2771// obPart.IgnoreUndoUpdate = true;
2772 Vector3 oldSize = new Vector3(obPart.Scale); 3582 Vector3 oldSize = new Vector3(obPart.Scale);
2773 3583
2774 float f = 1.0f; 3584 float f = 1.0f;
@@ -2880,8 +3690,6 @@ namespace OpenSim.Region.Framework.Scenes
2880 z *= a; 3690 z *= a;
2881 } 3691 }
2882 } 3692 }
2883
2884// obPart.IgnoreUndoUpdate = false;
2885 } 3693 }
2886 } 3694 }
2887 } 3695 }
@@ -2891,9 +3699,7 @@ namespace OpenSim.Region.Framework.Scenes
2891 prevScale.Y *= y; 3699 prevScale.Y *= y;
2892 prevScale.Z *= z; 3700 prevScale.Z *= z;
2893 3701
2894// RootPart.IgnoreUndoUpdate = true;
2895 RootPart.Resize(prevScale); 3702 RootPart.Resize(prevScale);
2896// RootPart.IgnoreUndoUpdate = false;
2897 3703
2898 for (int i = 0; i < parts.Length; i++) 3704 for (int i = 0; i < parts.Length; i++)
2899 { 3705 {
@@ -2901,8 +3707,6 @@ namespace OpenSim.Region.Framework.Scenes
2901 3707
2902 if (obPart.UUID != m_rootPart.UUID) 3708 if (obPart.UUID != m_rootPart.UUID)
2903 { 3709 {
2904 obPart.IgnoreUndoUpdate = true;
2905
2906 Vector3 currentpos = new Vector3(obPart.OffsetPosition); 3710 Vector3 currentpos = new Vector3(obPart.OffsetPosition);
2907 currentpos.X *= x; 3711 currentpos.X *= x;
2908 currentpos.Y *= y; 3712 currentpos.Y *= y;
@@ -2915,16 +3719,12 @@ namespace OpenSim.Region.Framework.Scenes
2915 3719
2916 obPart.Resize(newSize); 3720 obPart.Resize(newSize);
2917 obPart.UpdateOffSet(currentpos); 3721 obPart.UpdateOffSet(currentpos);
2918
2919 obPart.IgnoreUndoUpdate = false;
2920 } 3722 }
2921 3723
2922// obPart.IgnoreUndoUpdate = false; 3724 HasGroupChanged = true;
2923// obPart.StoreUndoState(); 3725 m_rootPart.TriggerScriptChangedEvent(Changed.SCALE);
3726 ScheduleGroupForTerseUpdate();
2924 } 3727 }
2925
2926// m_log.DebugFormat(
2927// "[SCENE OBJECT GROUP]: Finished group resizing {0} {1} to {2}", Name, LocalId, RootPart.Scale);
2928 } 3728 }
2929 3729
2930 #endregion 3730 #endregion
@@ -2937,14 +3737,6 @@ namespace OpenSim.Region.Framework.Scenes
2937 /// <param name="pos"></param> 3737 /// <param name="pos"></param>
2938 public void UpdateGroupPosition(Vector3 pos) 3738 public void UpdateGroupPosition(Vector3 pos)
2939 { 3739 {
2940// m_log.DebugFormat("[SCENE OBJECT GROUP]: Updating group position on {0} {1} to {2}", Name, LocalId, pos);
2941
2942 RootPart.StoreUndoState(true);
2943
2944// SceneObjectPart[] parts = m_parts.GetArray();
2945// for (int i = 0; i < parts.Length; i++)
2946// parts[i].StoreUndoState();
2947
2948 if (m_scene.EventManager.TriggerGroupMove(UUID, pos)) 3740 if (m_scene.EventManager.TriggerGroupMove(UUID, pos))
2949 { 3741 {
2950 if (IsAttachment) 3742 if (IsAttachment)
@@ -2977,21 +3769,17 @@ namespace OpenSim.Region.Framework.Scenes
2977 /// </summary> 3769 /// </summary>
2978 /// <param name="pos"></param> 3770 /// <param name="pos"></param>
2979 /// <param name="localID"></param> 3771 /// <param name="localID"></param>
3772 ///
3773
2980 public void UpdateSinglePosition(Vector3 pos, uint localID) 3774 public void UpdateSinglePosition(Vector3 pos, uint localID)
2981 { 3775 {
2982 SceneObjectPart part = GetPart(localID); 3776 SceneObjectPart part = GetPart(localID);
2983 3777
2984// SceneObjectPart[] parts = m_parts.GetArray();
2985// for (int i = 0; i < parts.Length; i++)
2986// parts[i].StoreUndoState();
2987
2988 if (part != null) 3778 if (part != null)
2989 { 3779 {
2990// m_log.DebugFormat( 3780// unlock parts position change
2991// "[SCENE OBJECT GROUP]: Updating single position of {0} {1} to {2}", part.Name, part.LocalId, pos); 3781 if (m_rootPart.PhysActor != null)
2992 3782 m_rootPart.PhysActor.Building = true;
2993 part.StoreUndoState(false);
2994 part.IgnoreUndoUpdate = true;
2995 3783
2996 if (part.UUID == m_rootPart.UUID) 3784 if (part.UUID == m_rootPart.UUID)
2997 { 3785 {
@@ -3002,8 +3790,10 @@ namespace OpenSim.Region.Framework.Scenes
3002 part.UpdateOffSet(pos); 3790 part.UpdateOffSet(pos);
3003 } 3791 }
3004 3792
3793 if (m_rootPart.PhysActor != null)
3794 m_rootPart.PhysActor.Building = false;
3795
3005 HasGroupChanged = true; 3796 HasGroupChanged = true;
3006 part.IgnoreUndoUpdate = false;
3007 } 3797 }
3008 } 3798 }
3009 3799
@@ -3013,13 +3803,7 @@ namespace OpenSim.Region.Framework.Scenes
3013 /// <param name="pos"></param> 3803 /// <param name="pos"></param>
3014 public void UpdateRootPosition(Vector3 pos) 3804 public void UpdateRootPosition(Vector3 pos)
3015 { 3805 {
3016// m_log.DebugFormat( 3806 // needs to be called with phys building true
3017// "[SCENE OBJECT GROUP]: Updating root position of {0} {1} to {2}", Name, LocalId, pos);
3018
3019// SceneObjectPart[] parts = m_parts.GetArray();
3020// for (int i = 0; i < parts.Length; i++)
3021// parts[i].StoreUndoState();
3022
3023 Vector3 newPos = new Vector3(pos.X, pos.Y, pos.Z); 3807 Vector3 newPos = new Vector3(pos.X, pos.Y, pos.Z);
3024 Vector3 oldPos = 3808 Vector3 oldPos =
3025 new Vector3(AbsolutePosition.X + m_rootPart.OffsetPosition.X, 3809 new Vector3(AbsolutePosition.X + m_rootPart.OffsetPosition.X,
@@ -3042,7 +3826,14 @@ namespace OpenSim.Region.Framework.Scenes
3042 AbsolutePosition = newPos; 3826 AbsolutePosition = newPos;
3043 3827
3044 HasGroupChanged = true; 3828 HasGroupChanged = true;
3045 ScheduleGroupForTerseUpdate(); 3829 if (m_rootPart.Undoing)
3830 {
3831 ScheduleGroupForFullUpdate();
3832 }
3833 else
3834 {
3835 ScheduleGroupForTerseUpdate();
3836 }
3046 } 3837 }
3047 3838
3048 #endregion 3839 #endregion
@@ -3055,24 +3846,16 @@ namespace OpenSim.Region.Framework.Scenes
3055 /// <param name="rot"></param> 3846 /// <param name="rot"></param>
3056 public void UpdateGroupRotationR(Quaternion rot) 3847 public void UpdateGroupRotationR(Quaternion rot)
3057 { 3848 {
3058// m_log.DebugFormat(
3059// "[SCENE OBJECT GROUP]: Updating group rotation R of {0} {1} to {2}", Name, LocalId, rot);
3060
3061// SceneObjectPart[] parts = m_parts.GetArray();
3062// for (int i = 0; i < parts.Length; i++)
3063// parts[i].StoreUndoState();
3064
3065 m_rootPart.StoreUndoState(true);
3066
3067 m_rootPart.UpdateRotation(rot); 3849 m_rootPart.UpdateRotation(rot);
3068 3850
3851/* this is done by rootpart RotationOffset set called by UpdateRotation
3069 PhysicsActor actor = m_rootPart.PhysActor; 3852 PhysicsActor actor = m_rootPart.PhysActor;
3070 if (actor != null) 3853 if (actor != null)
3071 { 3854 {
3072 actor.Orientation = m_rootPart.RotationOffset; 3855 actor.Orientation = m_rootPart.RotationOffset;
3073 m_scene.PhysicsScene.AddPhysicsActorTaint(actor); 3856 m_scene.PhysicsScene.AddPhysicsActorTaint(actor);
3074 } 3857 }
3075 3858*/
3076 HasGroupChanged = true; 3859 HasGroupChanged = true;
3077 ScheduleGroupForTerseUpdate(); 3860 ScheduleGroupForTerseUpdate();
3078 } 3861 }
@@ -3084,16 +3867,6 @@ namespace OpenSim.Region.Framework.Scenes
3084 /// <param name="rot"></param> 3867 /// <param name="rot"></param>
3085 public void UpdateGroupRotationPR(Vector3 pos, Quaternion rot) 3868 public void UpdateGroupRotationPR(Vector3 pos, Quaternion rot)
3086 { 3869 {
3087// m_log.DebugFormat(
3088// "[SCENE OBJECT GROUP]: Updating group rotation PR of {0} {1} to {2}", Name, LocalId, rot);
3089
3090// SceneObjectPart[] parts = m_parts.GetArray();
3091// for (int i = 0; i < parts.Length; i++)
3092// parts[i].StoreUndoState();
3093
3094 RootPart.StoreUndoState(true);
3095 RootPart.IgnoreUndoUpdate = true;
3096
3097 m_rootPart.UpdateRotation(rot); 3870 m_rootPart.UpdateRotation(rot);
3098 3871
3099 PhysicsActor actor = m_rootPart.PhysActor; 3872 PhysicsActor actor = m_rootPart.PhysActor;
@@ -3112,8 +3885,6 @@ namespace OpenSim.Region.Framework.Scenes
3112 3885
3113 HasGroupChanged = true; 3886 HasGroupChanged = true;
3114 ScheduleGroupForTerseUpdate(); 3887 ScheduleGroupForTerseUpdate();
3115
3116 RootPart.IgnoreUndoUpdate = false;
3117 } 3888 }
3118 3889
3119 /// <summary> 3890 /// <summary>
@@ -3126,13 +3897,11 @@ namespace OpenSim.Region.Framework.Scenes
3126 SceneObjectPart part = GetPart(localID); 3897 SceneObjectPart part = GetPart(localID);
3127 3898
3128 SceneObjectPart[] parts = m_parts.GetArray(); 3899 SceneObjectPart[] parts = m_parts.GetArray();
3129 for (int i = 0; i < parts.Length; i++)
3130 parts[i].StoreUndoState();
3131 3900
3132 if (part != null) 3901 if (part != null)
3133 { 3902 {
3134// m_log.DebugFormat( 3903 if (m_rootPart.PhysActor != null)
3135// "[SCENE OBJECT GROUP]: Updating single rotation of {0} {1} to {2}", part.Name, part.LocalId, rot); 3904 m_rootPart.PhysActor.Building = true;
3136 3905
3137 if (part.UUID == m_rootPart.UUID) 3906 if (part.UUID == m_rootPart.UUID)
3138 { 3907 {
@@ -3142,6 +3911,9 @@ namespace OpenSim.Region.Framework.Scenes
3142 { 3911 {
3143 part.UpdateRotation(rot); 3912 part.UpdateRotation(rot);
3144 } 3913 }
3914
3915 if (m_rootPart.PhysActor != null)
3916 m_rootPart.PhysActor.Building = false;
3145 } 3917 }
3146 } 3918 }
3147 3919
@@ -3155,12 +3927,8 @@ namespace OpenSim.Region.Framework.Scenes
3155 SceneObjectPart part = GetPart(localID); 3927 SceneObjectPart part = GetPart(localID);
3156 if (part != null) 3928 if (part != null)
3157 { 3929 {
3158// m_log.DebugFormat( 3930 if (m_rootPart.PhysActor != null)
3159// "[SCENE OBJECT GROUP]: Updating single position and rotation of {0} {1} to {2}", 3931 m_rootPart.PhysActor.Building = true;
3160// part.Name, part.LocalId, rot);
3161
3162 part.StoreUndoState();
3163 part.IgnoreUndoUpdate = true;
3164 3932
3165 if (part.UUID == m_rootPart.UUID) 3933 if (part.UUID == m_rootPart.UUID)
3166 { 3934 {
@@ -3173,7 +3941,8 @@ namespace OpenSim.Region.Framework.Scenes
3173 part.OffsetPosition = pos; 3941 part.OffsetPosition = pos;
3174 } 3942 }
3175 3943
3176 part.IgnoreUndoUpdate = false; 3944 if (m_rootPart.PhysActor != null)
3945 m_rootPart.PhysActor.Building = false;
3177 } 3946 }
3178 } 3947 }
3179 3948
@@ -3183,15 +3952,12 @@ namespace OpenSim.Region.Framework.Scenes
3183 /// <param name="rot"></param> 3952 /// <param name="rot"></param>
3184 public void UpdateRootRotation(Quaternion rot) 3953 public void UpdateRootRotation(Quaternion rot)
3185 { 3954 {
3186// m_log.DebugFormat( 3955 // needs to be called with phys building true
3187// "[SCENE OBJECT GROUP]: Updating root rotation of {0} {1} to {2}",
3188// Name, LocalId, rot);
3189
3190 Quaternion axRot = rot; 3956 Quaternion axRot = rot;
3191 Quaternion oldParentRot = m_rootPart.RotationOffset; 3957 Quaternion oldParentRot = m_rootPart.RotationOffset;
3192 3958
3193 m_rootPart.StoreUndoState(); 3959 //Don't use UpdateRotation because it schedules an update prematurely
3194 m_rootPart.UpdateRotation(rot); 3960 m_rootPart.RotationOffset = rot;
3195 3961
3196 PhysicsActor pa = m_rootPart.PhysActor; 3962 PhysicsActor pa = m_rootPart.PhysActor;
3197 3963
@@ -3207,35 +3973,145 @@ namespace OpenSim.Region.Framework.Scenes
3207 SceneObjectPart prim = parts[i]; 3973 SceneObjectPart prim = parts[i];
3208 if (prim.UUID != m_rootPart.UUID) 3974 if (prim.UUID != m_rootPart.UUID)
3209 { 3975 {
3210 prim.IgnoreUndoUpdate = true; 3976 Quaternion NewRot = oldParentRot * prim.RotationOffset;
3977 NewRot = Quaternion.Inverse(axRot) * NewRot;
3978 prim.RotationOffset = NewRot;
3979
3211 Vector3 axPos = prim.OffsetPosition; 3980 Vector3 axPos = prim.OffsetPosition;
3981
3212 axPos *= oldParentRot; 3982 axPos *= oldParentRot;
3213 axPos *= Quaternion.Inverse(axRot); 3983 axPos *= Quaternion.Inverse(axRot);
3214 prim.OffsetPosition = axPos; 3984 prim.OffsetPosition = axPos;
3215 Quaternion primsRot = prim.RotationOffset; 3985 }
3216 Quaternion newRot = oldParentRot * primsRot; 3986 }
3217 newRot = Quaternion.Inverse(axRot) * newRot;
3218 prim.RotationOffset = newRot;
3219 prim.ScheduleTerseUpdate();
3220 prim.IgnoreUndoUpdate = false;
3221 }
3222 }
3223
3224// for (int i = 0; i < parts.Length; i++)
3225// {
3226// SceneObjectPart childpart = parts[i];
3227// if (childpart != m_rootPart)
3228// {
3229//// childpart.IgnoreUndoUpdate = false;
3230//// childpart.StoreUndoState();
3231// }
3232// }
3233 3987
3234 m_rootPart.ScheduleTerseUpdate(); 3988 HasGroupChanged = true;
3989 ScheduleGroupForFullUpdate();
3990 }
3235 3991
3236// m_log.DebugFormat( 3992 private enum updatetype :int
3237// "[SCENE OBJECT GROUP]: Updated root rotation of {0} {1} to {2}", 3993 {
3238// Name, LocalId, rot); 3994 none = 0,
3995 partterse = 1,
3996 partfull = 2,
3997 groupterse = 3,
3998 groupfull = 4
3999 }
4000
4001 public void doChangeObject(SceneObjectPart part, ObjectChangeData data)
4002 {
4003 // TODO this still as excessive *.Schedule*Update()s
4004
4005 if (part != null && part.ParentGroup != null)
4006 {
4007 ObjectChangeType change = data.change;
4008 bool togroup = ((change & ObjectChangeType.Group) != 0);
4009 // bool uniform = ((what & ObjectChangeType.UniformScale) != 0); not in use
4010
4011 SceneObjectGroup group = part.ParentGroup;
4012 PhysicsActor pha = group.RootPart.PhysActor;
4013
4014 updatetype updateType = updatetype.none;
4015
4016 if (togroup)
4017 {
4018 // related to group
4019 if ((change & (ObjectChangeType.Rotation | ObjectChangeType.Position)) != 0)
4020 {
4021 if ((change & ObjectChangeType.Rotation) != 0)
4022 {
4023 group.RootPart.UpdateRotation(data.rotation);
4024 updateType = updatetype.none;
4025 }
4026 if ((change & ObjectChangeType.Position) != 0)
4027 {
4028 if (IsAttachment || m_scene.Permissions.CanObjectEntry(group.UUID, false, data.position))
4029 UpdateGroupPosition(data.position);
4030 updateType = updatetype.groupterse;
4031 }
4032 else
4033 // ugly rotation update of all parts
4034 {
4035 group.ResetChildPrimPhysicsPositions();
4036 }
4037
4038 }
4039 if ((change & ObjectChangeType.Scale) != 0)
4040 {
4041 if (pha != null)
4042 pha.Building = true;
4043
4044 group.GroupResize(data.scale);
4045 updateType = updatetype.none;
4046
4047 if (pha != null)
4048 pha.Building = false;
4049 }
4050 }
4051 else
4052 {
4053 // related to single prim in a link-set ( ie group)
4054 if (pha != null)
4055 pha.Building = true;
4056
4057 // root part is special
4058 // parts offset positions or rotations need to change also
4059
4060 if (part == group.RootPart)
4061 {
4062 if ((change & ObjectChangeType.Rotation) != 0)
4063 group.UpdateRootRotation(data.rotation);
4064 if ((change & ObjectChangeType.Position) != 0)
4065 group.UpdateRootPosition(data.position);
4066 if ((change & ObjectChangeType.Scale) != 0)
4067 part.Resize(data.scale);
4068 }
4069 else
4070 {
4071 if ((change & ObjectChangeType.Position) != 0)
4072 {
4073 part.OffsetPosition = data.position;
4074 updateType = updatetype.partterse;
4075 }
4076 if ((change & ObjectChangeType.Rotation) != 0)
4077 {
4078 part.UpdateRotation(data.rotation);
4079 updateType = updatetype.none;
4080 }
4081 if ((change & ObjectChangeType.Scale) != 0)
4082 {
4083 part.Resize(data.scale);
4084 updateType = updatetype.none;
4085 }
4086 }
4087
4088 if (pha != null)
4089 pha.Building = false;
4090 }
4091
4092 if (updateType != updatetype.none)
4093 {
4094 group.HasGroupChanged = true;
4095
4096 switch (updateType)
4097 {
4098 case updatetype.partterse:
4099 part.ScheduleTerseUpdate();
4100 break;
4101 case updatetype.partfull:
4102 part.ScheduleFullUpdate();
4103 break;
4104 case updatetype.groupterse:
4105 group.ScheduleGroupForTerseUpdate();
4106 break;
4107 case updatetype.groupfull:
4108 group.ScheduleGroupForFullUpdate();
4109 break;
4110 default:
4111 break;
4112 }
4113 }
4114 }
3239 } 4115 }
3240 4116
3241 #endregion 4117 #endregion
@@ -3276,6 +4152,8 @@ namespace OpenSim.Region.Framework.Scenes
3276 waypoint.handle = handle; 4152 waypoint.handle = handle;
3277 lock (m_rotTargets) 4153 lock (m_rotTargets)
3278 { 4154 {
4155 if (m_rotTargets.Count >= 8)
4156 m_rotTargets.Remove(m_rotTargets.ElementAt(0).Key);
3279 m_rotTargets.Add(handle, waypoint); 4157 m_rotTargets.Add(handle, waypoint);
3280 } 4158 }
3281 m_scene.AddGroupTarget(this); 4159 m_scene.AddGroupTarget(this);
@@ -3301,6 +4179,8 @@ namespace OpenSim.Region.Framework.Scenes
3301 waypoint.handle = handle; 4179 waypoint.handle = handle;
3302 lock (m_targets) 4180 lock (m_targets)
3303 { 4181 {
4182 if (m_targets.Count >= 8)
4183 m_targets.Remove(m_targets.ElementAt(0).Key);
3304 m_targets.Add(handle, waypoint); 4184 m_targets.Add(handle, waypoint);
3305 } 4185 }
3306 m_scene.AddGroupTarget(this); 4186 m_scene.AddGroupTarget(this);
@@ -3334,10 +4214,11 @@ namespace OpenSim.Region.Framework.Scenes
3334 scriptPosTarget target = m_targets[idx]; 4214 scriptPosTarget target = m_targets[idx];
3335 if (Util.GetDistanceTo(target.targetPos, m_rootPart.GroupPosition) <= target.tolerance) 4215 if (Util.GetDistanceTo(target.targetPos, m_rootPart.GroupPosition) <= target.tolerance)
3336 { 4216 {
4217 at_target = true;
4218
3337 // trigger at_target 4219 // trigger at_target
3338 if (m_scriptListens_atTarget) 4220 if (m_scriptListens_atTarget)
3339 { 4221 {
3340 at_target = true;
3341 scriptPosTarget att = new scriptPosTarget(); 4222 scriptPosTarget att = new scriptPosTarget();
3342 att.targetPos = target.targetPos; 4223 att.targetPos = target.targetPos;
3343 att.tolerance = target.tolerance; 4224 att.tolerance = target.tolerance;
@@ -3455,11 +4336,50 @@ namespace OpenSim.Region.Framework.Scenes
3455 } 4336 }
3456 } 4337 }
3457 } 4338 }
3458 4339
4340 public Vector3 GetGeometricCenter()
4341 {
4342 // this is not real geometric center but a average of positions relative to root prim acording to
4343 // http://wiki.secondlife.com/wiki/llGetGeometricCenter
4344 // ignoring tortured prims details since sl also seems to ignore
4345 // so no real use in doing it on physics
4346
4347 Vector3 gc = Vector3.Zero;
4348
4349 int nparts = m_parts.Count;
4350 if (nparts <= 1)
4351 return gc;
4352
4353 SceneObjectPart[] parts = m_parts.GetArray();
4354 nparts = parts.Length; // just in case it changed
4355 if (nparts <= 1)
4356 return gc;
4357
4358 Quaternion parentRot = RootPart.RotationOffset;
4359 Vector3 pPos;
4360
4361 // average all parts positions
4362 for (int i = 0; i < nparts; i++)
4363 {
4364 // do it directly
4365 // gc += parts[i].GetWorldPosition();
4366 if (parts[i] != RootPart)
4367 {
4368 pPos = parts[i].OffsetPosition;
4369 gc += pPos;
4370 }
4371
4372 }
4373 gc /= nparts;
4374
4375 // relative to root:
4376// gc -= AbsolutePosition;
4377 return gc;
4378 }
4379
3459 public float GetMass() 4380 public float GetMass()
3460 { 4381 {
3461 float retmass = 0f; 4382 float retmass = 0f;
3462
3463 SceneObjectPart[] parts = m_parts.GetArray(); 4383 SceneObjectPart[] parts = m_parts.GetArray();
3464 for (int i = 0; i < parts.Length; i++) 4384 for (int i = 0; i < parts.Length; i++)
3465 retmass += parts[i].GetMass(); 4385 retmass += parts[i].GetMass();
@@ -3467,6 +4387,39 @@ namespace OpenSim.Region.Framework.Scenes
3467 return retmass; 4387 return retmass;
3468 } 4388 }
3469 4389
4390 // center of mass of full object
4391 public Vector3 GetCenterOfMass()
4392 {
4393 PhysicsActor pa = RootPart.PhysActor;
4394
4395 if(((RootPart.Flags & PrimFlags.Physics) !=0) && pa !=null)
4396 {
4397 // physics knows better about center of mass of physical prims
4398 Vector3 tmp = pa.CenterOfMass;
4399 return tmp;
4400 }
4401
4402 Vector3 Ptot = Vector3.Zero;
4403 float totmass = 0f;
4404 float m;
4405
4406 SceneObjectPart[] parts = m_parts.GetArray();
4407 for (int i = 0; i < parts.Length; i++)
4408 {
4409 m = parts[i].GetMass();
4410 Ptot += parts[i].GetPartCenterOfMass() * m;
4411 totmass += m;
4412 }
4413
4414 if (totmass == 0)
4415 totmass = 0;
4416 else
4417 totmass = 1 / totmass;
4418 Ptot *= totmass;
4419
4420 return Ptot;
4421 }
4422
3470 /// <summary> 4423 /// <summary>
3471 /// If the object is a sculpt/mesh, retrieve the mesh data for each part and reinsert it into each shape so that 4424 /// If the object is a sculpt/mesh, retrieve the mesh data for each part and reinsert it into each shape so that
3472 /// the physics engine can use it. 4425 /// the physics engine can use it.
@@ -3646,6 +4599,14 @@ namespace OpenSim.Region.Framework.Scenes
3646 FromItemID = uuid; 4599 FromItemID = uuid;
3647 } 4600 }
3648 4601
4602 public void ResetOwnerChangeFlag()
4603 {
4604 ForEachPart(delegate(SceneObjectPart part)
4605 {
4606 part.ResetOwnerChangeFlag();
4607 });
4608 }
4609
3649 #endregion 4610 #endregion
3650 } 4611 }
3651} 4612}
diff --git a/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs b/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs
index 347a2b5..9e644aa 100644
--- a/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs
+++ b/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs
@@ -64,7 +64,8 @@ namespace OpenSim.Region.Framework.Scenes
64 TELEPORT = 512, 64 TELEPORT = 512,
65 REGION_RESTART = 1024, 65 REGION_RESTART = 1024,
66 MEDIA = 2048, 66 MEDIA = 2048,
67 ANIMATION = 16384 67 ANIMATION = 16384,
68 POSITION = 32768
68 } 69 }
69 70
70 // I don't really know where to put this except here. 71 // I don't really know where to put this except here.
@@ -123,7 +124,18 @@ namespace OpenSim.Region.Framework.Scenes
123 /// Denote all sides of the prim 124 /// Denote all sides of the prim
124 /// </value> 125 /// </value>
125 public const int ALL_SIDES = -1; 126 public const int ALL_SIDES = -1;
126 127
128 private const scriptEvents PhysicsNeededSubsEvents = (
129 scriptEvents.collision | scriptEvents.collision_start | scriptEvents.collision_end |
130 scriptEvents.land_collision | scriptEvents.land_collision_start | scriptEvents.land_collision_end
131 );
132 private const scriptEvents PhyscicsPhantonSubsEvents = (
133 scriptEvents.land_collision | scriptEvents.land_collision_start | scriptEvents.land_collision_end
134 );
135 private const scriptEvents PhyscicsVolumeDtcSubsEvents = (
136 scriptEvents.collision_start | scriptEvents.collision_end
137 );
138
127 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); 139 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
128 140
129 /// <summary> 141 /// <summary>
@@ -160,7 +172,7 @@ namespace OpenSim.Region.Framework.Scenes
160 /// </remarks> 172 /// </remarks>
161 public bool IsRoot 173 public bool IsRoot
162 { 174 {
163 get { return ParentGroup.RootPart == this; } 175 get { return Object.ReferenceEquals(ParentGroup.RootPart, this); }
164 } 176 }
165 177
166 /// <summary> 178 /// <summary>
@@ -219,12 +231,25 @@ namespace OpenSim.Region.Framework.Scenes
219 231
220 public double SoundRadius; 232 public double SoundRadius;
221 233
234
222 public uint TimeStampFull; 235 public uint TimeStampFull;
223 236
224 public uint TimeStampLastActivity; // Will be used for AutoReturn 237 public uint TimeStampLastActivity; // Will be used for AutoReturn
225 238
226 public uint TimeStampTerse; 239 public uint TimeStampTerse;
227 240
241 // The following two are to hold the attachment data
242 // while an object is inworld
243 [XmlIgnore]
244 public byte AttachPoint = 0;
245
246 [XmlIgnore]
247 public Vector3 AttachOffset = Vector3.Zero;
248
249 [XmlIgnore]
250 public Quaternion AttachRotation = Quaternion.Identity;
251
252 [XmlIgnore]
228 public int STATUS_ROTATE_X; 253 public int STATUS_ROTATE_X;
229 254
230 public int STATUS_ROTATE_Y; 255 public int STATUS_ROTATE_Y;
@@ -251,8 +276,7 @@ namespace OpenSim.Region.Framework.Scenes
251 276
252 public Vector3 RotationAxis = Vector3.One; 277 public Vector3 RotationAxis = Vector3.One;
253 278
254 public bool VolumeDetectActive; // XmlIgnore set to avoid problems with persistance until I come to care for this 279 public bool VolumeDetectActive;
255 // Certainly this must be a persistant setting finally
256 280
257 public bool IsWaitingForFirstSpinUpdatePacket; 281 public bool IsWaitingForFirstSpinUpdatePacket;
258 282
@@ -292,10 +316,10 @@ namespace OpenSim.Region.Framework.Scenes
292 private Quaternion m_sitTargetOrientation = Quaternion.Identity; 316 private Quaternion m_sitTargetOrientation = Quaternion.Identity;
293 private Vector3 m_sitTargetPosition; 317 private Vector3 m_sitTargetPosition;
294 private string m_sitAnimation = "SIT"; 318 private string m_sitAnimation = "SIT";
319 private bool m_occupied; // KF if any av is sitting on this prim
295 private string m_text = String.Empty; 320 private string m_text = String.Empty;
296 private string m_touchName = String.Empty; 321 private string m_touchName = String.Empty;
297 private readonly List<UndoState> m_undo = new List<UndoState>(5); 322 private UndoRedoState m_UndoRedo = null;
298 private readonly List<UndoState> m_redo = new List<UndoState>(5);
299 323
300 private bool m_passTouches = false; 324 private bool m_passTouches = false;
301 private bool m_passCollisions = false; 325 private bool m_passCollisions = false;
@@ -323,14 +347,20 @@ namespace OpenSim.Region.Framework.Scenes
323 protected Vector3 m_lastVelocity; 347 protected Vector3 m_lastVelocity;
324 protected Vector3 m_lastAcceleration; 348 protected Vector3 m_lastAcceleration;
325 protected Vector3 m_lastAngularVelocity; 349 protected Vector3 m_lastAngularVelocity;
326 protected int m_lastTerseSent; 350 protected int m_lastUpdateSentTime;
351 protected float m_buoyancy = 0.0f;
352 protected Vector3 m_force;
353 protected Vector3 m_torque;
327 354
328 protected byte m_physicsShapeType = (byte)PhysShapeType.prim; 355 protected byte m_physicsShapeType = (byte)PhysShapeType.prim;
329 protected float m_density = 1000.0f; // in kg/m^3 356 protected float m_density = 1000.0f; // in kg/m^3
330 protected float m_gravitymod = 1.0f; 357 protected float m_gravitymod = 1.0f;
331 protected float m_friction = 0.6f; // wood 358 protected float m_friction = 0.6f; // wood
332 protected float m_bounce = 0.5f; // wood 359 protected float m_bounce = 0.5f; // wood
333 360
361
362 protected bool m_isSelected = false;
363
334 /// <summary> 364 /// <summary>
335 /// Stores media texture data 365 /// Stores media texture data
336 /// </summary> 366 /// </summary>
@@ -342,10 +372,25 @@ namespace OpenSim.Region.Framework.Scenes
342 private Vector3 m_cameraAtOffset; 372 private Vector3 m_cameraAtOffset;
343 private bool m_forceMouselook; 373 private bool m_forceMouselook;
344 374
345 // TODO: Collision sound should have default. 375
376 // 0 for default collision sounds, -1 for script disabled sound 1 for script defined sound
377 private sbyte m_collisionSoundType;
346 private UUID m_collisionSound; 378 private UUID m_collisionSound;
347 private float m_collisionSoundVolume; 379 private float m_collisionSoundVolume;
348 380
381 private int LastColSoundSentTime;
382
383
384 private SOPVehicle m_vehicleParams = null;
385
386 private KeyframeMotion m_keyframeMotion = null;
387
388 public KeyframeMotion KeyframeMotion
389 {
390 get; set;
391 }
392
393
349 #endregion Fields 394 #endregion Fields
350 395
351// ~SceneObjectPart() 396// ~SceneObjectPart()
@@ -375,6 +420,7 @@ namespace OpenSim.Region.Framework.Scenes
375 // this appears to have the same UUID (!) as the prim. If this isn't the case, one can't drag items from 420 // this appears to have the same UUID (!) as the prim. If this isn't the case, one can't drag items from
376 // the prim into an agent inventory (Linden client reports that the "Object not found for drop" in its log 421 // the prim into an agent inventory (Linden client reports that the "Object not found for drop" in its log
377 m_inventory = new SceneObjectPartInventory(this); 422 m_inventory = new SceneObjectPartInventory(this);
423 LastColSoundSentTime = Util.EnvironmentTickCount();
378 } 424 }
379 425
380 /// <summary> 426 /// <summary>
@@ -389,7 +435,7 @@ namespace OpenSim.Region.Framework.Scenes
389 UUID ownerID, PrimitiveBaseShape shape, Vector3 groupPosition, 435 UUID ownerID, PrimitiveBaseShape shape, Vector3 groupPosition,
390 Quaternion rotationOffset, Vector3 offsetPosition) : this() 436 Quaternion rotationOffset, Vector3 offsetPosition) : this()
391 { 437 {
392 m_name = "Primitive"; 438 m_name = "Object";
393 439
394 CreationDate = (int)Utils.DateTimeToUnixTime(Rezzed); 440 CreationDate = (int)Utils.DateTimeToUnixTime(Rezzed);
395 LastOwnerID = CreatorID = OwnerID = ownerID; 441 LastOwnerID = CreatorID = OwnerID = ownerID;
@@ -428,7 +474,7 @@ namespace OpenSim.Region.Framework.Scenes
428 private uint _ownerMask = (uint)(PermissionMask.All | PermissionMask.Export); 474 private uint _ownerMask = (uint)(PermissionMask.All | PermissionMask.Export);
429 private uint _groupMask = (uint)PermissionMask.None; 475 private uint _groupMask = (uint)PermissionMask.None;
430 private uint _everyoneMask = (uint)PermissionMask.None; 476 private uint _everyoneMask = (uint)PermissionMask.None;
431 private uint _nextOwnerMask = (uint)PermissionMask.All; 477 private uint _nextOwnerMask = (uint)(PermissionMask.Move | PermissionMask.Modify | PermissionMask.Transfer);
432 private PrimFlags _flags = PrimFlags.None; 478 private PrimFlags _flags = PrimFlags.None;
433 private DateTime m_expires; 479 private DateTime m_expires;
434 private DateTime m_rezzed; 480 private DateTime m_rezzed;
@@ -522,12 +568,16 @@ namespace OpenSim.Region.Framework.Scenes
522 } 568 }
523 569
524 /// <value> 570 /// <value>
525 /// Access should be via Inventory directly - this property temporarily remains for xml serialization purposes 571 /// Get the inventory list
526 /// </value> 572 /// </value>
527 public TaskInventoryDictionary TaskInventory 573 public TaskInventoryDictionary TaskInventory
528 { 574 {
529 get { return m_inventory.Items; } 575 get {
530 set { m_inventory.Items = value; } 576 return m_inventory.Items;
577 }
578 set {
579 m_inventory.Items = value;
580 }
531 } 581 }
532 582
533 /// <summary> 583 /// <summary>
@@ -577,20 +627,6 @@ namespace OpenSim.Region.Framework.Scenes
577 } 627 }
578 } 628 }
579 629
580 public byte Material
581 {
582 get { return (byte) m_material; }
583 set
584 {
585 m_material = (Material)value;
586
587 PhysicsActor pa = PhysActor;
588
589 if (pa != null)
590 pa.SetMaterial((int)value);
591 }
592 }
593
594 [XmlIgnore] 630 [XmlIgnore]
595 public bool PassTouches 631 public bool PassTouches
596 { 632 {
@@ -616,6 +652,18 @@ namespace OpenSim.Region.Framework.Scenes
616 } 652 }
617 } 653 }
618 654
655 public bool IsSelected
656 {
657 get { return m_isSelected; }
658 set
659 {
660 m_isSelected = value;
661 if (ParentGroup != null)
662 ParentGroup.PartSelectChanged(value);
663 }
664 }
665
666
619 public Dictionary<int, string> CollisionFilter 667 public Dictionary<int, string> CollisionFilter
620 { 668 {
621 get { return m_CollisionFilter; } 669 get { return m_CollisionFilter; }
@@ -684,14 +732,12 @@ namespace OpenSim.Region.Framework.Scenes
684 set { m_LoopSoundSlavePrims = value; } 732 set { m_LoopSoundSlavePrims = value; }
685 } 733 }
686 734
687
688 public Byte[] TextureAnimation 735 public Byte[] TextureAnimation
689 { 736 {
690 get { return m_TextureAnimation; } 737 get { return m_TextureAnimation; }
691 set { m_TextureAnimation = value; } 738 set { m_TextureAnimation = value; }
692 } 739 }
693 740
694
695 public Byte[] ParticleSystem 741 public Byte[] ParticleSystem
696 { 742 {
697 get { return m_particleSystem; } 743 get { return m_particleSystem; }
@@ -728,9 +774,12 @@ namespace OpenSim.Region.Framework.Scenes
728 { 774 {
729 // If this is a linkset, we don't want the physics engine mucking up our group position here. 775 // If this is a linkset, we don't want the physics engine mucking up our group position here.
730 PhysicsActor actor = PhysActor; 776 PhysicsActor actor = PhysActor;
731 // If physical and the root prim of a linkset, the position of the group is what physics thinks. 777 if (ParentID == 0)
732 if (actor != null && ParentID == 0) 778 {
733 m_groupPosition = actor.Position; 779 if (actor != null)
780 m_groupPosition = actor.Position;
781 return m_groupPosition;
782 }
734 783
735 // If I'm an attachment, my position is reported as the position of who I'm attached to 784 // If I'm an attachment, my position is reported as the position of who I'm attached to
736 if (ParentGroup.IsAttachment) 785 if (ParentGroup.IsAttachment)
@@ -740,14 +789,16 @@ namespace OpenSim.Region.Framework.Scenes
740 return sp.AbsolutePosition; 789 return sp.AbsolutePosition;
741 } 790 }
742 791
792 // use root prim's group position. Physics may have updated it
793 if (ParentGroup.RootPart != this)
794 m_groupPosition = ParentGroup.RootPart.GroupPosition;
743 return m_groupPosition; 795 return m_groupPosition;
744 } 796 }
745 set 797 set
746 { 798 {
747 m_groupPosition = value; 799 m_groupPosition = value;
748
749 PhysicsActor actor = PhysActor; 800 PhysicsActor actor = PhysActor;
750 if (actor != null) 801 if (actor != null && ParentGroup.Scene.PhysicsScene != null)
751 { 802 {
752 try 803 try
753 { 804 {
@@ -771,16 +822,6 @@ namespace OpenSim.Region.Framework.Scenes
771 m_log.ErrorFormat("[SCENEOBJECTPART]: GROUP POSITION. {0}", e); 822 m_log.ErrorFormat("[SCENEOBJECTPART]: GROUP POSITION. {0}", e);
772 } 823 }
773 } 824 }
774
775 // TODO if we decide to do sitting in a more SL compatible way (multiple avatars per prim), this has to be fixed, too
776 if (SitTargetAvatar != UUID.Zero)
777 {
778 ScenePresence avatar;
779 if (ParentGroup.Scene.TryGetScenePresence(SitTargetAvatar, out avatar))
780 {
781 avatar.ParentPosition = GetWorldPosition();
782 }
783 }
784 } 825 }
785 } 826 }
786 827
@@ -789,7 +830,7 @@ namespace OpenSim.Region.Framework.Scenes
789 get { return m_offsetPosition; } 830 get { return m_offsetPosition; }
790 set 831 set
791 { 832 {
792// StoreUndoState(); 833 Vector3 oldpos = m_offsetPosition;
793 m_offsetPosition = value; 834 m_offsetPosition = value;
794 835
795 if (ParentGroup != null && !ParentGroup.IsDeleted) 836 if (ParentGroup != null && !ParentGroup.IsDeleted)
@@ -801,10 +842,25 @@ namespace OpenSim.Region.Framework.Scenes
801 actor.Orientation = GetWorldRotation(); 842 actor.Orientation = GetWorldRotation();
802 843
803 // Tell the physics engines that this prim changed. 844 // Tell the physics engines that this prim changed.
804 if (ParentGroup.Scene != null) 845 if (ParentGroup.Scene != null && ParentGroup.Scene.PhysicsScene != null)
805 ParentGroup.Scene.PhysicsScene.AddPhysicsActorTaint(actor); 846 ParentGroup.Scene.PhysicsScene.AddPhysicsActorTaint(actor);
806 } 847 }
848
849 if (!m_parentGroup.m_dupeInProgress)
850 {
851 List<ScenePresence> avs = ParentGroup.GetLinkedAvatars();
852 foreach (ScenePresence av in avs)
853 {
854 if (av.ParentID == m_localId)
855 {
856 Vector3 offset = (m_offsetPosition - oldpos);
857 av.AbsolutePosition += offset;
858 av.SendAvatarDataToAllAgents();
859 }
860 }
861 }
807 } 862 }
863 TriggerScriptChangedEvent(Changed.POSITION);
808 } 864 }
809 } 865 }
810 866
@@ -855,7 +911,7 @@ namespace OpenSim.Region.Framework.Scenes
855 911
856 set 912 set
857 { 913 {
858 StoreUndoState(); 914// StoreUndoState();
859 m_rotationOffset = value; 915 m_rotationOffset = value;
860 916
861 PhysicsActor actor = PhysActor; 917 PhysicsActor actor = PhysActor;
@@ -943,19 +999,36 @@ namespace OpenSim.Region.Framework.Scenes
943 get 999 get
944 { 1000 {
945 PhysicsActor actor = PhysActor; 1001 PhysicsActor actor = PhysActor;
946 if ((actor != null) && actor.IsPhysical) 1002 if ((actor != null) && actor.IsPhysical && ParentGroup.RootPart == this)
947 { 1003 {
948 m_angularVelocity = actor.RotationalVelocity; 1004 m_angularVelocity = actor.RotationalVelocity;
949 } 1005 }
950 return m_angularVelocity; 1006 return m_angularVelocity;
951 } 1007 }
952 set { m_angularVelocity = value; } 1008 set
1009 {
1010 m_angularVelocity = value;
1011 PhysicsActor actor = PhysActor;
1012 if ((actor != null) && actor.IsPhysical && ParentGroup.RootPart == this && VehicleType == (int)Vehicle.TYPE_NONE)
1013 {
1014 actor.RotationalVelocity = m_angularVelocity;
1015 }
1016 }
953 } 1017 }
954 1018
955 /// <summary></summary> 1019 /// <summary></summary>
956 public Vector3 Acceleration 1020 public Vector3 Acceleration
957 { 1021 {
958 get { return m_acceleration; } 1022 get
1023 {
1024 PhysicsActor actor = PhysActor;
1025 if (actor != null)
1026 {
1027 m_acceleration = actor.Acceleration;
1028 }
1029 return m_acceleration;
1030 }
1031
959 set { m_acceleration = value; } 1032 set { m_acceleration = value; }
960 } 1033 }
961 1034
@@ -1023,7 +1096,10 @@ namespace OpenSim.Region.Framework.Scenes
1023 public PrimitiveBaseShape Shape 1096 public PrimitiveBaseShape Shape
1024 { 1097 {
1025 get { return m_shape; } 1098 get { return m_shape; }
1026 set { m_shape = value;} 1099 set
1100 {
1101 m_shape = value;
1102 }
1027 } 1103 }
1028 1104
1029 /// <summary> 1105 /// <summary>
@@ -1036,7 +1112,6 @@ namespace OpenSim.Region.Framework.Scenes
1036 { 1112 {
1037 if (m_shape != null) 1113 if (m_shape != null)
1038 { 1114 {
1039 StoreUndoState();
1040 1115
1041 m_shape.Scale = value; 1116 m_shape.Scale = value;
1042 1117
@@ -1104,10 +1179,7 @@ namespace OpenSim.Region.Framework.Scenes
1104 { 1179 {
1105 get 1180 get
1106 { 1181 {
1107 if (ParentGroup.IsAttachment) 1182 return GroupPosition + (m_offsetPosition * ParentGroup.RootPart.RotationOffset);
1108 return GroupPosition;
1109
1110 return m_offsetPosition + m_groupPosition;
1111 } 1183 }
1112 } 1184 }
1113 1185
@@ -1276,6 +1348,13 @@ namespace OpenSim.Region.Framework.Scenes
1276 _flags = value; 1348 _flags = value;
1277 } 1349 }
1278 } 1350 }
1351
1352 [XmlIgnore]
1353 public bool IsOccupied // KF If an av is sittingon this prim
1354 {
1355 get { return m_occupied; }
1356 set { m_occupied = value; }
1357 }
1279 1358
1280 /// <summary> 1359 /// <summary>
1281 /// 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 1360 /// 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
@@ -1326,12 +1405,41 @@ namespace OpenSim.Region.Framework.Scenes
1326 set { m_sitAnimation = value; } 1405 set { m_sitAnimation = value; }
1327 } 1406 }
1328 1407
1408 public UUID invalidCollisionSoundUUID = new UUID("ffffffff-ffff-ffff-ffff-ffffffffffff");
1409
1410 // 0 for default collision sounds, -1 for script disabled sound 1 for script defined sound
1411 // runtime thing.. do not persist
1412 [XmlIgnore]
1413 public sbyte CollisionSoundType
1414 {
1415 get
1416 {
1417 return m_collisionSoundType;
1418 }
1419 set
1420 {
1421 m_collisionSoundType = value;
1422 if (value == -1)
1423 m_collisionSound = invalidCollisionSoundUUID;
1424 else if (value == 0)
1425 m_collisionSound = UUID.Zero;
1426 }
1427 }
1428
1329 public UUID CollisionSound 1429 public UUID CollisionSound
1330 { 1430 {
1331 get { return m_collisionSound; } 1431 get { return m_collisionSound; }
1332 set 1432 set
1333 { 1433 {
1334 m_collisionSound = value; 1434 m_collisionSound = value;
1435
1436 if (value == invalidCollisionSoundUUID)
1437 m_collisionSoundType = -1;
1438 else if (value == UUID.Zero)
1439 m_collisionSoundType = 0;
1440 else
1441 m_collisionSoundType = 1;
1442
1335 aggregateScriptEvents(); 1443 aggregateScriptEvents();
1336 } 1444 }
1337 } 1445 }
@@ -1342,6 +1450,125 @@ namespace OpenSim.Region.Framework.Scenes
1342 set { m_collisionSoundVolume = value; } 1450 set { m_collisionSoundVolume = value; }
1343 } 1451 }
1344 1452
1453 public float Buoyancy
1454 {
1455 get
1456 {
1457 if (ParentGroup.RootPart == this)
1458 return m_buoyancy;
1459
1460 return ParentGroup.RootPart.Buoyancy;
1461 }
1462 set
1463 {
1464 if (ParentGroup != null && ParentGroup.RootPart != null && ParentGroup.RootPart != this)
1465 {
1466 ParentGroup.RootPart.Buoyancy = value;
1467 return;
1468 }
1469 m_buoyancy = value;
1470 if (PhysActor != null)
1471 PhysActor.Buoyancy = value;
1472 }
1473 }
1474
1475 public Vector3 Force
1476 {
1477 get
1478 {
1479 if (ParentGroup.RootPart == this)
1480 return m_force;
1481
1482 return ParentGroup.RootPart.Force;
1483 }
1484
1485 set
1486 {
1487 if (ParentGroup != null && ParentGroup.RootPart != null && ParentGroup.RootPart != this)
1488 {
1489 ParentGroup.RootPart.Force = value;
1490 return;
1491 }
1492 m_force = value;
1493 if (PhysActor != null)
1494 PhysActor.Force = value;
1495 }
1496 }
1497
1498 public Vector3 Torque
1499 {
1500 get
1501 {
1502 if (ParentGroup.RootPart == this)
1503 return m_torque;
1504
1505 return ParentGroup.RootPart.Torque;
1506 }
1507
1508 set
1509 {
1510 if (ParentGroup != null && ParentGroup.RootPart != null && ParentGroup.RootPart != this)
1511 {
1512 ParentGroup.RootPart.Torque = value;
1513 return;
1514 }
1515 m_torque = value;
1516 if (PhysActor != null)
1517 PhysActor.Torque = value;
1518 }
1519 }
1520
1521 public byte Material
1522 {
1523 get { return (byte)m_material; }
1524 set
1525 {
1526 if (value >= 0 && value <= (byte)SOPMaterialData.MaxMaterial)
1527 {
1528 bool update = false;
1529
1530 if (m_material != (Material)value)
1531 {
1532 update = true;
1533 m_material = (Material)value;
1534 }
1535
1536 if (m_friction != SOPMaterialData.friction(m_material))
1537 {
1538 update = true;
1539 m_friction = SOPMaterialData.friction(m_material);
1540 }
1541
1542 if (m_bounce != SOPMaterialData.bounce(m_material))
1543 {
1544 update = true;
1545 m_bounce = SOPMaterialData.bounce(m_material);
1546 }
1547
1548 if (update)
1549 {
1550 if (PhysActor != null)
1551 {
1552 PhysActor.SetMaterial((int)value);
1553 }
1554 if(ParentGroup != null)
1555 ParentGroup.HasGroupChanged = true;
1556 ScheduleFullUpdateIfNone();
1557 UpdatePhysRequired = true;
1558 }
1559 }
1560 }
1561 }
1562
1563 // not a propriety to move to methods place later
1564 private bool HasMesh()
1565 {
1566 if (Shape != null && (Shape.SculptType == (byte)SculptType.Mesh))
1567 return true;
1568 return false;
1569 }
1570
1571 // not a propriety to move to methods place later
1345 public byte DefaultPhysicsShapeType() 1572 public byte DefaultPhysicsShapeType()
1346 { 1573 {
1347 byte type; 1574 byte type;
@@ -1354,6 +1581,65 @@ namespace OpenSim.Region.Framework.Scenes
1354 return type; 1581 return type;
1355 } 1582 }
1356 1583
1584 [XmlIgnore]
1585 public bool UsesComplexCost
1586 {
1587 get
1588 {
1589 byte pst = PhysicsShapeType;
1590 if(pst == (byte) PhysShapeType.none || pst == (byte) PhysShapeType.convex || HasMesh())
1591 return true;
1592 return false;
1593 }
1594 }
1595
1596 [XmlIgnore]
1597 public float PhysicsCost
1598 {
1599 get
1600 {
1601 if(PhysicsShapeType == (byte)PhysShapeType.none)
1602 return 0;
1603
1604 float cost = 0.1f;
1605 if (PhysActor != null)
1606 cost = PhysActor.PhysicsCost;
1607 else
1608 cost = 0.1f;
1609
1610 if ((Flags & PrimFlags.Physics) != 0)
1611 cost *= (1.0f + 0.01333f * Scale.LengthSquared()); // 0.01333 == 0.04/3
1612 return cost;
1613 }
1614 }
1615
1616 [XmlIgnore]
1617 public float StreamingCost
1618 {
1619 get
1620 {
1621 float cost;
1622 if (PhysActor != null)
1623 cost = PhysActor.StreamCost;
1624 else
1625 cost = 1.0f;
1626 return 1.0f;
1627 }
1628 }
1629
1630 [XmlIgnore]
1631 public float SimulationCost
1632 {
1633 get
1634 {
1635 // ignoring scripts. Don't like considering them for this
1636 if((Flags & PrimFlags.Physics) != 0)
1637 return 1.0f;
1638
1639 return 0.5f;
1640 }
1641 }
1642
1357 public byte PhysicsShapeType 1643 public byte PhysicsShapeType
1358 { 1644 {
1359 get { return m_physicsShapeType; } 1645 get { return m_physicsShapeType; }
@@ -1387,11 +1673,14 @@ namespace OpenSim.Region.Framework.Scenes
1387 } 1673 }
1388 else if (PhysActor == null) 1674 else if (PhysActor == null)
1389 { 1675 {
1390 ApplyPhysics((uint)Flags, VolumeDetectActive); 1676 ApplyPhysics((uint)Flags, VolumeDetectActive, false);
1677 UpdatePhysicsSubscribedEvents();
1391 } 1678 }
1392 else 1679 else
1393 { 1680 {
1394 PhysActor.PhysicsShapeType = m_physicsShapeType; 1681 PhysActor.PhysicsShapeType = m_physicsShapeType;
1682// if (Shape.SculptEntry)
1683// CheckSculptAndLoad();
1395 } 1684 }
1396 1685
1397 if (ParentGroup != null) 1686 if (ParentGroup != null)
@@ -1493,6 +1782,7 @@ namespace OpenSim.Region.Framework.Scenes
1493 } 1782 }
1494 } 1783 }
1495 1784
1785
1496 #endregion Public Properties with only Get 1786 #endregion Public Properties with only Get
1497 1787
1498 private uint ApplyMask(uint val, bool set, uint mask) 1788 private uint ApplyMask(uint val, bool set, uint mask)
@@ -1638,6 +1928,61 @@ namespace OpenSim.Region.Framework.Scenes
1638 } 1928 }
1639 } 1929 }
1640 1930
1931 // SetVelocity for LSL llSetVelocity.. may need revision if having other uses in future
1932 public void SetVelocity(Vector3 pVel, bool localGlobalTF)
1933 {
1934 if (ParentGroup == null || ParentGroup.IsDeleted)
1935 return;
1936
1937 if (ParentGroup.IsAttachment)
1938 return; // don't work on attachments (for now ??)
1939
1940 SceneObjectPart root = ParentGroup.RootPart;
1941
1942 if (root.VehicleType != (int)Vehicle.TYPE_NONE) // don't mess with vehicles
1943 return;
1944
1945 PhysicsActor pa = root.PhysActor;
1946
1947 if (pa == null || !pa.IsPhysical)
1948 return;
1949
1950 if (localGlobalTF)
1951 {
1952 pVel = pVel * GetWorldRotation();
1953 }
1954
1955 ParentGroup.Velocity = pVel;
1956 }
1957
1958 // SetAngularVelocity for LSL llSetAngularVelocity.. may need revision if having other uses in future
1959 public void SetAngularVelocity(Vector3 pAngVel, bool localGlobalTF)
1960 {
1961 if (ParentGroup == null || ParentGroup.IsDeleted)
1962 return;
1963
1964 if (ParentGroup.IsAttachment)
1965 return; // don't work on attachments (for now ??)
1966
1967 SceneObjectPart root = ParentGroup.RootPart;
1968
1969 if (root.VehicleType != (int)Vehicle.TYPE_NONE) // don't mess with vehicles
1970 return;
1971
1972 PhysicsActor pa = root.PhysActor;
1973
1974 if (pa == null || !pa.IsPhysical)
1975 return;
1976
1977 if (localGlobalTF)
1978 {
1979 pAngVel = pAngVel * GetWorldRotation();
1980 }
1981
1982 root.AngularVelocity = pAngVel;
1983 }
1984
1985
1641 /// <summary> 1986 /// <summary>
1642 /// hook to the physics scene to apply angular impulse 1987 /// hook to the physics scene to apply angular impulse
1643 /// This is sent up to the group, which then finds the root prim 1988 /// This is sent up to the group, which then finds the root prim
@@ -1658,7 +2003,7 @@ namespace OpenSim.Region.Framework.Scenes
1658 impulse = newimpulse; 2003 impulse = newimpulse;
1659 } 2004 }
1660 2005
1661 ParentGroup.applyAngularImpulse(impulse); 2006 ParentGroup.ApplyAngularImpulse(impulse);
1662 } 2007 }
1663 2008
1664 /// <summary> 2009 /// <summary>
@@ -1668,20 +2013,24 @@ namespace OpenSim.Region.Framework.Scenes
1668 /// </summary> 2013 /// </summary>
1669 /// <param name="impulsei">Vector force</param> 2014 /// <param name="impulsei">Vector force</param>
1670 /// <param name="localGlobalTF">true for the local frame, false for the global frame</param> 2015 /// <param name="localGlobalTF">true for the local frame, false for the global frame</param>
1671 public void SetAngularImpulse(Vector3 impulsei, bool localGlobalTF) 2016
2017 // this is actualy Set Torque.. keeping naming so not to edit lslapi also
2018 public void SetAngularImpulse(Vector3 torquei, bool localGlobalTF)
1672 { 2019 {
1673 Vector3 impulse = impulsei; 2020 Vector3 torque = torquei;
1674 2021
1675 if (localGlobalTF) 2022 if (localGlobalTF)
1676 { 2023 {
2024/*
1677 Quaternion grot = GetWorldRotation(); 2025 Quaternion grot = GetWorldRotation();
1678 Quaternion AXgrot = grot; 2026 Quaternion AXgrot = grot;
1679 Vector3 AXimpulsei = impulsei; 2027 Vector3 AXimpulsei = impulsei;
1680 Vector3 newimpulse = AXimpulsei * AXgrot; 2028 Vector3 newimpulse = AXimpulsei * AXgrot;
1681 impulse = newimpulse; 2029 */
2030 torque *= GetWorldRotation();
1682 } 2031 }
1683 2032
1684 ParentGroup.setAngularImpulse(impulse); 2033 Torque = torque;
1685 } 2034 }
1686 2035
1687 /// <summary> 2036 /// <summary>
@@ -1689,7 +2038,9 @@ namespace OpenSim.Region.Framework.Scenes
1689 /// </summary> 2038 /// </summary>
1690 /// <param name="rootObjectFlags"></param> 2039 /// <param name="rootObjectFlags"></param>
1691 /// <param name="VolumeDetectActive"></param> 2040 /// <param name="VolumeDetectActive"></param>
1692 public void ApplyPhysics(uint rootObjectFlags, bool _VolumeDetectActive) 2041 /// <param name="building"></param>
2042
2043 public void ApplyPhysics(uint _ObjectFlags, bool _VolumeDetectActive, bool building)
1693 { 2044 {
1694 VolumeDetectActive = _VolumeDetectActive; 2045 VolumeDetectActive = _VolumeDetectActive;
1695 2046
@@ -1699,8 +2050,8 @@ namespace OpenSim.Region.Framework.Scenes
1699 if (PhysicsShapeType == (byte)PhysShapeType.none) 2050 if (PhysicsShapeType == (byte)PhysShapeType.none)
1700 return; 2051 return;
1701 2052
1702 bool isPhysical = (rootObjectFlags & (uint) PrimFlags.Physics) != 0; 2053 bool isPhysical = (_ObjectFlags & (uint) PrimFlags.Physics) != 0;
1703 bool isPhantom = (rootObjectFlags & (uint) PrimFlags.Phantom) != 0; 2054 bool isPhantom = (_ObjectFlags & (uint)PrimFlags.Phantom) != 0;
1704 2055
1705 if (_VolumeDetectActive) 2056 if (_VolumeDetectActive)
1706 isPhantom = true; 2057 isPhantom = true;
@@ -1714,7 +2065,8 @@ namespace OpenSim.Region.Framework.Scenes
1714 if ((!isPhantom || isPhysical || _VolumeDetectActive) && !ParentGroup.IsAttachment 2065 if ((!isPhantom || isPhysical || _VolumeDetectActive) && !ParentGroup.IsAttachment
1715 && !(Shape.PathCurve == (byte)Extrusion.Flexible)) 2066 && !(Shape.PathCurve == (byte)Extrusion.Flexible))
1716 { 2067 {
1717 AddToPhysics(isPhysical, isPhantom, isPhysical); 2068 AddToPhysics(isPhysical, isPhantom, building, isPhysical);
2069 UpdatePhysicsSubscribedEvents(); // not sure if appliable here
1718 } 2070 }
1719 else 2071 else
1720 PhysActor = null; // just to be sure 2072 PhysActor = null; // just to be sure
@@ -1769,6 +2121,12 @@ namespace OpenSim.Region.Framework.Scenes
1769 dupe.Category = Category; 2121 dupe.Category = Category;
1770 dupe.m_rezzed = m_rezzed; 2122 dupe.m_rezzed = m_rezzed;
1771 2123
2124 dupe.m_UndoRedo = null;
2125 dupe.m_isSelected = false;
2126
2127 dupe.IgnoreUndoUpdate = false;
2128 dupe.Undoing = false;
2129
1772 dupe.m_inventory = new SceneObjectPartInventory(dupe); 2130 dupe.m_inventory = new SceneObjectPartInventory(dupe);
1773 dupe.m_inventory.Items = (TaskInventoryDictionary)m_inventory.Items.Clone(); 2131 dupe.m_inventory.Items = (TaskInventoryDictionary)m_inventory.Items.Clone();
1774 2132
@@ -1784,6 +2142,7 @@ namespace OpenSim.Region.Framework.Scenes
1784 2142
1785 // Move afterwards ResetIDs as it clears the localID 2143 // Move afterwards ResetIDs as it clears the localID
1786 dupe.LocalId = localID; 2144 dupe.LocalId = localID;
2145
1787 // This may be wrong... it might have to be applied in SceneObjectGroup to the object that's being duplicated. 2146 // This may be wrong... it might have to be applied in SceneObjectGroup to the object that's being duplicated.
1788 dupe.LastOwnerID = OwnerID; 2147 dupe.LastOwnerID = OwnerID;
1789 2148
@@ -1791,6 +2150,9 @@ namespace OpenSim.Region.Framework.Scenes
1791 Array.Copy(Shape.ExtraParams, extraP, extraP.Length); 2150 Array.Copy(Shape.ExtraParams, extraP, extraP.Length);
1792 dupe.Shape.ExtraParams = extraP; 2151 dupe.Shape.ExtraParams = extraP;
1793 2152
2153 // safeguard actual copy is done in sog.copy
2154 dupe.KeyframeMotion = null;
2155
1794 dupe.DynAttrs.CopyFrom(DynAttrs); 2156 dupe.DynAttrs.CopyFrom(DynAttrs);
1795 2157
1796 if (userExposed) 2158 if (userExposed)
@@ -1804,8 +2166,12 @@ namespace OpenSim.Region.Framework.Scenes
1804*/ 2166*/
1805 bool UsePhysics = ((dupe.Flags & PrimFlags.Physics) != 0); 2167 bool UsePhysics = ((dupe.Flags & PrimFlags.Physics) != 0);
1806 dupe.DoPhysicsPropertyUpdate(UsePhysics, true); 2168 dupe.DoPhysicsPropertyUpdate(UsePhysics, true);
2169// dupe.UpdatePhysicsSubscribedEvents(); // not sure...
1807 } 2170 }
1808 2171
2172 if (dupe.PhysActor != null)
2173 dupe.PhysActor.LocalID = localID;
2174
1809 ParentGroup.Scene.EventManager.TriggerOnSceneObjectPartCopy(dupe, this, userExposed); 2175 ParentGroup.Scene.EventManager.TriggerOnSceneObjectPartCopy(dupe, this, userExposed);
1810 2176
1811// m_log.DebugFormat("[SCENE OBJECT PART]: Clone of {0} {1} finished", Name, UUID); 2177// m_log.DebugFormat("[SCENE OBJECT PART]: Clone of {0} {1} finished", Name, UUID);
@@ -1824,10 +2190,10 @@ namespace OpenSim.Region.Framework.Scenes
1824 { 2190 {
1825 if (asset != null) 2191 if (asset != null)
1826 SculptTextureCallback(asset); 2192 SculptTextureCallback(asset);
1827 else 2193// else
1828 m_log.WarnFormat( 2194// m_log.WarnFormat(
1829 "[SCENE OBJECT PART]: Part {0} {1} requested mesh/sculpt data for asset id {2} from asset service but received no data", 2195// "[SCENE OBJECT PART]: Part {0} {1} requested mesh/sculpt data for asset id {2} from asset service but received no data",
1830 Name, UUID, id); 2196// Name, UUID, id);
1831 } 2197 }
1832*/ 2198*/
1833 /// <summary> 2199 /// <summary>
@@ -1926,6 +2292,7 @@ namespace OpenSim.Region.Framework.Scenes
1926 2292
1927 /// <summary> 2293 /// <summary>
1928 /// Do a physics propery update for this part. 2294 /// Do a physics propery update for this part.
2295 /// now also updates phantom and volume detector
1929 /// </summary> 2296 /// </summary>
1930 /// <param name="UsePhysics"></param> 2297 /// <param name="UsePhysics"></param>
1931 /// <param name="isNew"></param> 2298 /// <param name="isNew"></param>
@@ -1951,61 +2318,69 @@ namespace OpenSim.Region.Framework.Scenes
1951 { 2318 {
1952 if (pa.IsPhysical) // implies UsePhysics==false for this block 2319 if (pa.IsPhysical) // implies UsePhysics==false for this block
1953 { 2320 {
1954 if (!isNew) 2321 if (!isNew) // implies UsePhysics==false for this block
2322 {
1955 ParentGroup.Scene.RemovePhysicalPrim(1); 2323 ParentGroup.Scene.RemovePhysicalPrim(1);
1956 2324
1957 pa.OnRequestTerseUpdate -= PhysicsRequestingTerseUpdate; 2325 Velocity = new Vector3(0, 0, 0);
1958 pa.OnOutOfBounds -= PhysicsOutOfBounds; 2326 Acceleration = new Vector3(0, 0, 0);
1959 pa.delink(); 2327 if (ParentGroup.RootPart == this)
2328 AngularVelocity = new Vector3(0, 0, 0);
1960 2329
1961 if (ParentGroup.Scene.PhysicsScene.SupportsNINJAJoints && (!isNew)) 2330 if (pa.Phantom && !VolumeDetectActive)
1962 { 2331 {
1963 // destroy all joints connected to this now deactivated body 2332 RemoveFromPhysics();
1964 ParentGroup.Scene.PhysicsScene.RemoveAllJointsConnectedToActorThreadLocked(pa); 2333 return;
1965 } 2334 }
1966 2335
1967 // stop client-side interpolation of all joint proxy objects that have just been deleted 2336 pa.IsPhysical = UsePhysics;
1968 // this is done because RemoveAllJointsConnectedToActor invokes the OnJointDeactivated callback, 2337 pa.OnRequestTerseUpdate -= PhysicsRequestingTerseUpdate;
1969 // which stops client-side interpolation of deactivated joint proxy objects. 2338 pa.OnOutOfBounds -= PhysicsOutOfBounds;
2339 pa.delink();
2340 if (ParentGroup.Scene.PhysicsScene.SupportsNINJAJoints)
2341 {
2342 // destroy all joints connected to this now deactivated body
2343 ParentGroup.Scene.PhysicsScene.RemoveAllJointsConnectedToActorThreadLocked(pa);
2344 }
2345 }
1970 } 2346 }
1971 2347
1972 if (!UsePhysics && !isNew) 2348 if (pa.IsPhysical != UsePhysics)
1973 { 2349 pa.IsPhysical = UsePhysics;
1974 // reset velocity to 0 on physics switch-off. Without that, the client thinks the
1975 // prim still has velocity and continues to interpolate its position along the old
1976 // velocity-vector.
1977 Velocity = new Vector3(0, 0, 0);
1978 Acceleration = new Vector3(0, 0, 0);
1979 AngularVelocity = new Vector3(0, 0, 0);
1980 //RotationalVelocity = new Vector3(0, 0, 0);
1981 }
1982 2350
1983 pa.IsPhysical = UsePhysics; 2351 if (UsePhysics)
2352 {
2353 if (ParentGroup.RootPart.KeyframeMotion != null)
2354 ParentGroup.RootPart.KeyframeMotion.Stop();
2355 ParentGroup.RootPart.KeyframeMotion = null;
2356 ParentGroup.Scene.AddPhysicalPrim(1);
1984 2357
1985 // If we're not what we're supposed to be in the physics scene, recreate ourselves. 2358 PhysActor.OnRequestTerseUpdate += PhysicsRequestingTerseUpdate;
1986 //m_parentGroup.Scene.PhysicsScene.RemovePrim(PhysActor); 2359 PhysActor.OnOutOfBounds += PhysicsOutOfBounds;
1987 /// that's not wholesome. Had to make Scene public
1988 //PhysActor = null;
1989 2360
1990 if ((Flags & PrimFlags.Phantom) == 0) 2361 if (ParentID != 0 && ParentID != LocalId)
1991 {
1992 if (UsePhysics)
1993 { 2362 {
1994 ParentGroup.Scene.AddPhysicalPrim(1); 2363 PhysicsActor parentPa = ParentGroup.RootPart.PhysActor;
1995 2364
1996 pa.OnRequestTerseUpdate += PhysicsRequestingTerseUpdate; 2365 if (parentPa != null)
1997 pa.OnOutOfBounds += PhysicsOutOfBounds;
1998 if (ParentID != 0 && ParentID != LocalId)
1999 { 2366 {
2000 PhysicsActor parentPa = ParentGroup.RootPart.PhysActor; 2367 pa.link(parentPa);
2001
2002 if (parentPa != null)
2003 {
2004 pa.link(parentPa);
2005 }
2006 } 2368 }
2007 } 2369 }
2008 } 2370 }
2371 }
2372
2373 bool phan = ((Flags & PrimFlags.Phantom) != 0);
2374 if (pa.Phantom != phan)
2375 pa.Phantom = phan;
2376
2377// some engines dont' have this check still
2378// if (VolumeDetectActive != pa.IsVolumeDtc)
2379 {
2380 if (VolumeDetectActive)
2381 pa.SetVolumeDetect(1);
2382 else
2383 pa.SetVolumeDetect(0);
2009 } 2384 }
2010 2385
2011 // If this part is a sculpt then delay the physics update until we've asynchronously loaded the 2386 // If this part is a sculpt then delay the physics update until we've asynchronously loaded the
@@ -2124,42 +2499,63 @@ namespace OpenSim.Region.Framework.Scenes
2124 2499
2125 public Vector3 GetGeometricCenter() 2500 public Vector3 GetGeometricCenter()
2126 { 2501 {
2502 // this is not real geometric center but a average of positions relative to root prim acording to
2503 // http://wiki.secondlife.com/wiki/llGetGeometricCenter
2504 // ignoring tortured prims details since sl also seems to ignore
2505 // so no real use in doing it on physics
2506 if (ParentGroup.IsDeleted)
2507 return new Vector3(0, 0, 0);
2508
2509 return ParentGroup.GetGeometricCenter();
2510 }
2511
2512 public float GetMass()
2513 {
2127 PhysicsActor pa = PhysActor; 2514 PhysicsActor pa = PhysActor;
2128 2515
2129 if (pa != null) 2516 if (pa != null)
2130 return pa.GeometricCenter; 2517 return pa.Mass;
2131 else 2518 else
2132 return Vector3.Zero; 2519 return 0;
2133 } 2520 }
2134 2521
2135 public Vector3 GetCenterOfMass() 2522 public Vector3 GetCenterOfMass()
2136 { 2523 {
2524 if (ParentGroup.RootPart == this)
2525 {
2526 if (ParentGroup.IsDeleted)
2527 return AbsolutePosition;
2528 return ParentGroup.GetCenterOfMass();
2529 }
2530
2137 PhysicsActor pa = PhysActor; 2531 PhysicsActor pa = PhysActor;
2138 2532
2139 if (pa != null) 2533 if (pa != null)
2140 return pa.CenterOfMass; 2534 {
2535 Vector3 tmp = pa.CenterOfMass;
2536 return tmp;
2537 }
2141 else 2538 else
2142 return Vector3.Zero; 2539 return AbsolutePosition;
2143 } 2540 }
2144 2541
2145 public float GetMass() 2542 public Vector3 GetPartCenterOfMass()
2146 { 2543 {
2147 PhysicsActor pa = PhysActor; 2544 PhysicsActor pa = PhysActor;
2148 2545
2149 if (pa != null) 2546 if (pa != null)
2150 return pa.Mass; 2547 {
2548 Vector3 tmp = pa.CenterOfMass;
2549 return tmp;
2550 }
2151 else 2551 else
2152 return 0; 2552 return AbsolutePosition;
2153 } 2553 }
2154 2554
2555
2155 public Vector3 GetForce() 2556 public Vector3 GetForce()
2156 { 2557 {
2157 PhysicsActor pa = PhysActor; 2558 return Force;
2158
2159 if (pa != null)
2160 return pa.Force;
2161 else
2162 return Vector3.Zero;
2163 } 2559 }
2164 2560
2165 /// <summary> 2561 /// <summary>
@@ -2374,15 +2770,25 @@ namespace OpenSim.Region.Framework.Scenes
2374 2770
2375 private void SendLandCollisionEvent(scriptEvents ev, ScriptCollidingNotification notify) 2771 private void SendLandCollisionEvent(scriptEvents ev, ScriptCollidingNotification notify)
2376 { 2772 {
2377 if ((ParentGroup.RootPart.ScriptEvents & ev) != 0) 2773 bool sendToRoot = true;
2378 {
2379 ColliderArgs LandCollidingMessage = new ColliderArgs();
2380 List<DetectedObject> colliding = new List<DetectedObject>();
2381
2382 colliding.Add(CreateDetObjectForGround());
2383 LandCollidingMessage.Colliders = colliding;
2384 2774
2775 ColliderArgs LandCollidingMessage = new ColliderArgs();
2776 List<DetectedObject> colliding = new List<DetectedObject>();
2777
2778 colliding.Add(CreateDetObjectForGround());
2779 LandCollidingMessage.Colliders = colliding;
2780
2781 if (Inventory.ContainsScripts())
2782 {
2783 if (!PassCollisions)
2784 sendToRoot = false;
2785 }
2786 if ((ScriptEvents & ev) != 0)
2385 notify(LocalId, LandCollidingMessage); 2787 notify(LocalId, LandCollidingMessage);
2788
2789 if ((ParentGroup.RootPart.ScriptEvents & ev) != 0 && sendToRoot)
2790 {
2791 notify(ParentGroup.RootPart.LocalId, LandCollidingMessage);
2386 } 2792 }
2387 } 2793 }
2388 2794
@@ -2398,57 +2804,120 @@ namespace OpenSim.Region.Framework.Scenes
2398 List<uint> endedColliders = new List<uint>(); 2804 List<uint> endedColliders = new List<uint>();
2399 List<uint> startedColliders = new List<uint>(); 2805 List<uint> startedColliders = new List<uint>();
2400 2806
2401 // calculate things that started colliding this time 2807 if (collissionswith.Count == 0)
2402 // and build up list of colliders this time
2403 foreach (uint localid in collissionswith.Keys)
2404 { 2808 {
2405 thisHitColliders.Add(localid); 2809 if (m_lastColliders.Count == 0)
2406 if (!m_lastColliders.Contains(localid)) 2810 return; // nothing to do
2407 startedColliders.Add(localid);
2408 }
2409 2811
2410 // calculate things that ended colliding 2812 foreach (uint localID in m_lastColliders)
2411 foreach (uint localID in m_lastColliders) 2813 {
2412 {
2413 if (!thisHitColliders.Contains(localID))
2414 endedColliders.Add(localID); 2814 endedColliders.Add(localID);
2815 }
2816 m_lastColliders.Clear();
2415 } 2817 }
2416 2818
2417 //add the items that started colliding this time to the last colliders list. 2819 else
2418 foreach (uint localID in startedColliders) 2820 {
2419 m_lastColliders.Add(localID); 2821 List<CollisionForSoundInfo> soundinfolist = new List<CollisionForSoundInfo>();
2822
2823 // calculate things that started colliding this time
2824 // and build up list of colliders this time
2825 if (!VolumeDetectActive && CollisionSoundType >= 0)
2826 {
2827 CollisionForSoundInfo soundinfo;
2828 ContactPoint curcontact;
2420 2829
2421 // remove things that ended colliding from the last colliders list 2830 foreach (uint id in collissionswith.Keys)
2422 foreach (uint localID in endedColliders) 2831 {
2423 m_lastColliders.Remove(localID); 2832 thisHitColliders.Add(id);
2833 if (!m_lastColliders.Contains(id))
2834 {
2835 startedColliders.Add(id);
2424 2836
2425 // play the sound. 2837 curcontact = collissionswith[id];
2426 if (startedColliders.Count > 0 && CollisionSound != UUID.Zero && CollisionSoundVolume > 0.0f) 2838 if (Math.Abs(curcontact.RelativeSpeed) > 0.2)
2427 { 2839 {
2428 ISoundModule soundModule = ParentGroup.Scene.RequestModuleInterface<ISoundModule>(); 2840 soundinfo = new CollisionForSoundInfo();
2429 if (soundModule != null) 2841 soundinfo.colliderID = id;
2842 soundinfo.position = curcontact.Position;
2843 soundinfo.relativeVel = curcontact.RelativeSpeed;
2844 soundinfolist.Add(soundinfo);
2845 }
2846 }
2847 }
2848 }
2849 else
2850 {
2851 foreach (uint id in collissionswith.Keys)
2852 {
2853 thisHitColliders.Add(id);
2854 if (!m_lastColliders.Contains(id))
2855 startedColliders.Add(id);
2856 }
2857 }
2858
2859 // calculate things that ended colliding
2860 foreach (uint localID in m_lastColliders)
2430 { 2861 {
2431 soundModule.SendSound(UUID, CollisionSound, 2862 if (!thisHitColliders.Contains(localID))
2432 CollisionSoundVolume, true, (byte)0, 0, false, 2863 endedColliders.Add(localID);
2433 false);
2434 } 2864 }
2865
2866 //add the items that started colliding this time to the last colliders list.
2867 foreach (uint localID in startedColliders)
2868 m_lastColliders.Add(localID);
2869
2870 // remove things that ended colliding from the last colliders list
2871 foreach (uint localID in endedColliders)
2872 m_lastColliders.Remove(localID);
2873
2874 // play sounds.
2875 if (soundinfolist.Count > 0)
2876 CollisionSounds.PartCollisionSound(this, soundinfolist);
2435 } 2877 }
2436 2878
2437 SendCollisionEvent(scriptEvents.collision_start, startedColliders, ParentGroup.Scene.EventManager.TriggerScriptCollidingStart); 2879 SendCollisionEvent(scriptEvents.collision_start, startedColliders, ParentGroup.Scene.EventManager.TriggerScriptCollidingStart);
2438 SendCollisionEvent(scriptEvents.collision , m_lastColliders , ParentGroup.Scene.EventManager.TriggerScriptColliding); 2880 if (!VolumeDetectActive)
2881 SendCollisionEvent(scriptEvents.collision , m_lastColliders , ParentGroup.Scene.EventManager.TriggerScriptColliding);
2439 SendCollisionEvent(scriptEvents.collision_end , endedColliders , ParentGroup.Scene.EventManager.TriggerScriptCollidingEnd); 2882 SendCollisionEvent(scriptEvents.collision_end , endedColliders , ParentGroup.Scene.EventManager.TriggerScriptCollidingEnd);
2440 2883
2441 if (startedColliders.Contains(0)) 2884 if (startedColliders.Contains(0))
2442 { 2885 SendLandCollisionEvent(scriptEvents.land_collision_start, ParentGroup.Scene.EventManager.TriggerScriptLandCollidingStart);
2443 if (m_lastColliders.Contains(0)) 2886 if (m_lastColliders.Contains(0))
2444 SendLandCollisionEvent(scriptEvents.land_collision, ParentGroup.Scene.EventManager.TriggerScriptLandColliding); 2887 SendLandCollisionEvent(scriptEvents.land_collision, ParentGroup.Scene.EventManager.TriggerScriptLandColliding);
2445 else
2446 SendLandCollisionEvent(scriptEvents.land_collision_start, ParentGroup.Scene.EventManager.TriggerScriptLandCollidingStart);
2447 }
2448 if (endedColliders.Contains(0)) 2888 if (endedColliders.Contains(0))
2449 SendLandCollisionEvent(scriptEvents.land_collision_end, ParentGroup.Scene.EventManager.TriggerScriptLandCollidingEnd); 2889 SendLandCollisionEvent(scriptEvents.land_collision_end, ParentGroup.Scene.EventManager.TriggerScriptLandCollidingEnd);
2450 } 2890 }
2451 2891
2892 // The Collision sounds code calls this
2893 public void SendCollisionSound(UUID soundID, double volume, Vector3 position)
2894 {
2895 if (soundID == UUID.Zero)
2896 return;
2897
2898 ISoundModule soundModule = ParentGroup.Scene.RequestModuleInterface<ISoundModule>();
2899 if (soundModule == null)
2900 return;
2901
2902 if (volume > 1)
2903 volume = 1;
2904 if (volume < 0)
2905 volume = 0;
2906
2907 int now = Util.EnvironmentTickCount();
2908 if(Util.EnvironmentTickCountSubtract(now,LastColSoundSentTime) <200)
2909 return;
2910
2911 LastColSoundSentTime = now;
2912
2913 UUID ownerID = OwnerID;
2914 UUID objectID = ParentGroup.RootPart.UUID;
2915 UUID parentID = ParentGroup.UUID;
2916 ulong regionHandle = ParentGroup.Scene.RegionInfo.RegionHandle;
2917
2918 soundModule.TriggerSound(soundID, ownerID, objectID, parentID, volume, position, regionHandle, 0 );
2919 }
2920
2452 public void PhysicsOutOfBounds(Vector3 pos) 2921 public void PhysicsOutOfBounds(Vector3 pos)
2453 { 2922 {
2454 // Note: This is only being called on the root prim at this time. 2923 // Note: This is only being called on the root prim at this time.
@@ -2470,9 +2939,9 @@ namespace OpenSim.Region.Framework.Scenes
2470 Vector3 newpos = new Vector3(pa.Position.GetBytes(), 0); 2939 Vector3 newpos = new Vector3(pa.Position.GetBytes(), 0);
2471 2940
2472 if (ParentGroup.Scene.TestBorderCross(newpos, Cardinals.N) 2941 if (ParentGroup.Scene.TestBorderCross(newpos, Cardinals.N)
2473 | ParentGroup.Scene.TestBorderCross(newpos, Cardinals.S) 2942 || ParentGroup.Scene.TestBorderCross(newpos, Cardinals.S)
2474 | ParentGroup.Scene.TestBorderCross(newpos, Cardinals.E) 2943 || ParentGroup.Scene.TestBorderCross(newpos, Cardinals.E)
2475 | ParentGroup.Scene.TestBorderCross(newpos, Cardinals.W)) 2944 || ParentGroup.Scene.TestBorderCross(newpos, Cardinals.W))
2476 { 2945 {
2477 ParentGroup.AbsolutePosition = newpos; 2946 ParentGroup.AbsolutePosition = newpos;
2478 return; 2947 return;
@@ -2757,6 +3226,14 @@ namespace OpenSim.Region.Framework.Scenes
2757 if (ParentGroup == null) 3226 if (ParentGroup == null)
2758 return; 3227 return;
2759 3228
3229 // Update the "last" values
3230 m_lastPosition = OffsetPosition;
3231 m_lastRotation = RotationOffset;
3232 m_lastVelocity = Velocity;
3233 m_lastAcceleration = Acceleration;
3234 m_lastAngularVelocity = AngularVelocity;
3235 m_lastUpdateSentTime = Environment.TickCount;
3236
2760 ParentGroup.Scene.ForEachScenePresence(delegate(ScenePresence avatar) 3237 ParentGroup.Scene.ForEachScenePresence(delegate(ScenePresence avatar)
2761 { 3238 {
2762 SendFullUpdate(avatar.ControllingClient); 3239 SendFullUpdate(avatar.ControllingClient);
@@ -2815,8 +3292,8 @@ namespace OpenSim.Region.Framework.Scenes
2815 { 3292 {
2816 const float ROTATION_TOLERANCE = 0.01f; 3293 const float ROTATION_TOLERANCE = 0.01f;
2817 const float VELOCITY_TOLERANCE = 0.001f; 3294 const float VELOCITY_TOLERANCE = 0.001f;
2818 const float POSITION_TOLERANCE = 0.05f; 3295 const float POSITION_TOLERANCE = 0.05f; // I don't like this, but I suppose it's necessary
2819 const int TIME_MS_TOLERANCE = 3000; 3296 const int TIME_MS_TOLERANCE = 200; //llSetPos has a 200ms delay. This should NOT be 3 seconds.
2820 3297
2821 switch (UpdateFlag) 3298 switch (UpdateFlag)
2822 { 3299 {
@@ -2830,17 +3307,10 @@ namespace OpenSim.Region.Framework.Scenes
2830 Velocity.ApproxEquals(Vector3.Zero, VELOCITY_TOLERANCE) || 3307 Velocity.ApproxEquals(Vector3.Zero, VELOCITY_TOLERANCE) ||
2831 !AngularVelocity.ApproxEquals(m_lastAngularVelocity, VELOCITY_TOLERANCE) || 3308 !AngularVelocity.ApproxEquals(m_lastAngularVelocity, VELOCITY_TOLERANCE) ||
2832 !OffsetPosition.ApproxEquals(m_lastPosition, POSITION_TOLERANCE) || 3309 !OffsetPosition.ApproxEquals(m_lastPosition, POSITION_TOLERANCE) ||
2833 Environment.TickCount - m_lastTerseSent > TIME_MS_TOLERANCE) 3310 Environment.TickCount - m_lastUpdateSentTime > TIME_MS_TOLERANCE)
2834 { 3311 {
2835 SendTerseUpdateToAllClients(); 3312 SendTerseUpdateToAllClients();
2836 3313
2837 // Update the "last" values
2838 m_lastPosition = OffsetPosition;
2839 m_lastRotation = RotationOffset;
2840 m_lastVelocity = Velocity;
2841 m_lastAcceleration = Acceleration;
2842 m_lastAngularVelocity = AngularVelocity;
2843 m_lastTerseSent = Environment.TickCount;
2844 } 3314 }
2845 break; 3315 break;
2846 } 3316 }
@@ -2858,6 +3328,17 @@ namespace OpenSim.Region.Framework.Scenes
2858 /// </summary> 3328 /// </summary>
2859 public void SendTerseUpdateToAllClients() 3329 public void SendTerseUpdateToAllClients()
2860 { 3330 {
3331 if (ParentGroup == null || ParentGroup.Scene == null)
3332 return;
3333
3334 // Update the "last" values
3335 m_lastPosition = OffsetPosition;
3336 m_lastRotation = RotationOffset;
3337 m_lastVelocity = Velocity;
3338 m_lastAcceleration = Acceleration;
3339 m_lastAngularVelocity = AngularVelocity;
3340 m_lastUpdateSentTime = Environment.TickCount;
3341
2861 ParentGroup.Scene.ForEachClient(delegate(IClientAPI client) 3342 ParentGroup.Scene.ForEachClient(delegate(IClientAPI client)
2862 { 3343 {
2863 SendTerseUpdateToClient(client); 3344 SendTerseUpdateToClient(client);
@@ -2881,10 +3362,13 @@ namespace OpenSim.Region.Framework.Scenes
2881 3362
2882 public void SetBuoyancy(float fvalue) 3363 public void SetBuoyancy(float fvalue)
2883 { 3364 {
2884 PhysicsActor pa = PhysActor; 3365 Buoyancy = fvalue;
2885 3366/*
2886 if (pa != null) 3367 if (PhysActor != null)
2887 pa.Buoyancy = fvalue; 3368 {
3369 PhysActor.Buoyancy = fvalue;
3370 }
3371 */
2888 } 3372 }
2889 3373
2890 public void SetDieAtEdge(bool p) 3374 public void SetDieAtEdge(bool p)
@@ -2900,47 +3384,111 @@ namespace OpenSim.Region.Framework.Scenes
2900 PhysicsActor pa = PhysActor; 3384 PhysicsActor pa = PhysActor;
2901 3385
2902 if (pa != null) 3386 if (pa != null)
2903 pa.FloatOnWater = floatYN == 1; 3387 pa.FloatOnWater = (floatYN == 1);
2904 } 3388 }
2905 3389
2906 public void SetForce(Vector3 force) 3390 public void SetForce(Vector3 force)
2907 { 3391 {
2908 PhysicsActor pa = PhysActor; 3392 Force = force;
3393 }
2909 3394
2910 if (pa != null) 3395 public SOPVehicle VehicleParams
2911 pa.Force = force; 3396 {
3397 get
3398 {
3399 return m_vehicleParams;
3400 }
3401 set
3402 {
3403 m_vehicleParams = value;
3404 }
3405 }
3406
3407
3408 public int VehicleType
3409 {
3410 get
3411 {
3412 if (m_vehicleParams == null)
3413 return (int)Vehicle.TYPE_NONE;
3414 else
3415 return (int)m_vehicleParams.Type;
3416 }
3417 set
3418 {
3419 SetVehicleType(value);
3420 }
2912 } 3421 }
2913 3422
2914 public void SetVehicleType(int type) 3423 public void SetVehicleType(int type)
2915 { 3424 {
2916 PhysicsActor pa = PhysActor; 3425 m_vehicleParams = null;
3426
3427 if (type == (int)Vehicle.TYPE_NONE)
3428 {
3429 if (_parentID ==0 && PhysActor != null)
3430 PhysActor.VehicleType = (int)Vehicle.TYPE_NONE;
3431 return;
3432 }
3433 m_vehicleParams = new SOPVehicle();
3434 m_vehicleParams.ProcessTypeChange((Vehicle)type);
3435 {
3436 if (_parentID ==0 && PhysActor != null)
3437 PhysActor.VehicleType = type;
3438 return;
3439 }
3440 }
2917 3441
2918 if (pa != null) 3442 public void SetVehicleFlags(int param, bool remove)
2919 pa.VehicleType = type; 3443 {
3444 if (m_vehicleParams == null)
3445 return;
3446
3447 m_vehicleParams.ProcessVehicleFlags(param, remove);
3448
3449 if (_parentID ==0 && PhysActor != null)
3450 {
3451 PhysActor.VehicleFlags(param, remove);
3452 }
2920 } 3453 }
2921 3454
2922 public void SetVehicleFloatParam(int param, float value) 3455 public void SetVehicleFloatParam(int param, float value)
2923 { 3456 {
2924 PhysicsActor pa = PhysActor; 3457 if (m_vehicleParams == null)
3458 return;
2925 3459
2926 if (pa != null) 3460 m_vehicleParams.ProcessFloatVehicleParam((Vehicle)param, value);
2927 pa.VehicleFloatParam(param, value); 3461
3462 if (_parentID == 0 && PhysActor != null)
3463 {
3464 PhysActor.VehicleFloatParam(param, value);
3465 }
2928 } 3466 }
2929 3467
2930 public void SetVehicleVectorParam(int param, Vector3 value) 3468 public void SetVehicleVectorParam(int param, Vector3 value)
2931 { 3469 {
2932 PhysicsActor pa = PhysActor; 3470 if (m_vehicleParams == null)
3471 return;
2933 3472
2934 if (pa != null) 3473 m_vehicleParams.ProcessVectorVehicleParam((Vehicle)param, value);
2935 pa.VehicleVectorParam(param, value); 3474
3475 if (_parentID == 0 && PhysActor != null)
3476 {
3477 PhysActor.VehicleVectorParam(param, value);
3478 }
2936 } 3479 }
2937 3480
2938 public void SetVehicleRotationParam(int param, Quaternion rotation) 3481 public void SetVehicleRotationParam(int param, Quaternion rotation)
2939 { 3482 {
2940 PhysicsActor pa = PhysActor; 3483 if (m_vehicleParams == null)
3484 return;
2941 3485
2942 if (pa != null) 3486 m_vehicleParams.ProcessRotationVehicleParam((Vehicle)param, rotation);
2943 pa.VehicleRotationParam(param, rotation); 3487
3488 if (_parentID == 0 && PhysActor != null)
3489 {
3490 PhysActor.VehicleRotationParam(param, rotation);
3491 }
2944 } 3492 }
2945 3493
2946 /// <summary> 3494 /// <summary>
@@ -3141,14 +3689,6 @@ namespace OpenSim.Region.Framework.Scenes
3141 hasProfileCut = hasDimple; // is it the same thing? 3689 hasProfileCut = hasDimple; // is it the same thing?
3142 } 3690 }
3143 3691
3144 public void SetVehicleFlags(int param, bool remove)
3145 {
3146 PhysicsActor pa = PhysActor;
3147
3148 if (pa != null)
3149 pa.VehicleFlags(param, remove);
3150 }
3151
3152 public void SetGroup(UUID groupID, IClientAPI client) 3692 public void SetGroup(UUID groupID, IClientAPI client)
3153 { 3693 {
3154 // Scene.AddNewPrims() calls with client == null so can't use this. 3694 // Scene.AddNewPrims() calls with client == null so can't use this.
@@ -3252,71 +3792,20 @@ namespace OpenSim.Region.Framework.Scenes
3252 { 3792 {
3253 ParentGroup.stopMoveToTarget(); 3793 ParentGroup.stopMoveToTarget();
3254 3794
3255 ParentGroup.ScheduleGroupForTerseUpdate(); 3795// ParentGroup.ScheduleGroupForTerseUpdate();
3256 //ParentGroup.ScheduleGroupForFullUpdate(); 3796 //ParentGroup.ScheduleGroupForFullUpdate();
3257 } 3797 }
3258 3798
3259 public void StoreUndoState() 3799 public void StoreUndoState(ObjectChangeType change)
3260 { 3800 {
3261 StoreUndoState(false); 3801 if (m_UndoRedo == null)
3262 } 3802 m_UndoRedo = new UndoRedoState(5);
3263 3803
3264 public void StoreUndoState(bool forGroup) 3804 lock (m_UndoRedo)
3265 {
3266 if (ParentGroup == null || ParentGroup.Scene == null)
3267 return;
3268
3269 if (Undoing)
3270 {
3271// m_log.DebugFormat(
3272// "[SCENE OBJECT PART]: Ignoring undo store for {0} {1} since already undoing", Name, LocalId);
3273 return;
3274 }
3275
3276 if (IgnoreUndoUpdate)
3277 {
3278// m_log.DebugFormat("[SCENE OBJECT PART]: Ignoring undo store for {0} {1}", Name, LocalId);
3279 return;
3280 }
3281
3282 lock (m_undo)
3283 { 3805 {
3284 if (m_undo.Count > 0) 3806 if (!Undoing && !IgnoreUndoUpdate && ParentGroup != null) // just to read better - undo is in progress, or suspended
3285 { 3807 {
3286 UndoState last = m_undo[m_undo.Count - 1]; 3808 m_UndoRedo.StoreUndo(this, change);
3287 if (last != null)
3288 {
3289 // TODO: May need to fix for group comparison
3290 if (last.Compare(this))
3291 {
3292// m_log.DebugFormat(
3293// "[SCENE OBJECT PART]: Not storing undo for {0} {1} since current state is same as last undo state, initial stack size {2}",
3294// Name, LocalId, m_undo.Count);
3295
3296 return;
3297 }
3298 }
3299 }
3300
3301// m_log.DebugFormat(
3302// "[SCENE OBJECT PART]: Storing undo state for {0} {1}, forGroup {2}, initial stack size {3}",
3303// Name, LocalId, forGroup, m_undo.Count);
3304
3305 if (ParentGroup.Scene.MaxUndoCount > 0)
3306 {
3307 UndoState nUndo = new UndoState(this, forGroup);
3308
3309 m_undo.Add(nUndo);
3310
3311 if (m_undo.Count > ParentGroup.Scene.MaxUndoCount)
3312 m_undo.RemoveAt(0);
3313
3314 if (m_redo.Count > 0)
3315 m_redo.Clear();
3316
3317// m_log.DebugFormat(
3318// "[SCENE OBJECT PART]: Stored undo state for {0} {1}, forGroup {2}, stack size now {3}",
3319// Name, LocalId, forGroup, m_undo.Count);
3320 } 3809 }
3321 } 3810 }
3322 } 3811 }
@@ -3328,88 +3817,46 @@ namespace OpenSim.Region.Framework.Scenes
3328 { 3817 {
3329 get 3818 get
3330 { 3819 {
3331 lock (m_undo) 3820 if (m_UndoRedo == null)
3332 return m_undo.Count; 3821 return 0;
3822 return m_UndoRedo.Count;
3333 } 3823 }
3334 } 3824 }
3335 3825
3336 public void Undo() 3826 public void Undo()
3337 { 3827 {
3338 lock (m_undo) 3828 if (m_UndoRedo == null || Undoing || ParentGroup == null)
3339 { 3829 return;
3340// m_log.DebugFormat(
3341// "[SCENE OBJECT PART]: Handling undo request for {0} {1}, stack size {2}",
3342// Name, LocalId, m_undo.Count);
3343
3344 if (m_undo.Count > 0)
3345 {
3346 UndoState goback = m_undo[m_undo.Count - 1];
3347 m_undo.RemoveAt(m_undo.Count - 1);
3348
3349 UndoState nUndo = null;
3350
3351 if (ParentGroup.Scene.MaxUndoCount > 0)
3352 {
3353 nUndo = new UndoState(this, goback.ForGroup);
3354 }
3355
3356 goback.PlaybackState(this);
3357
3358 if (nUndo != null)
3359 {
3360 m_redo.Add(nUndo);
3361
3362 if (m_redo.Count > ParentGroup.Scene.MaxUndoCount)
3363 m_redo.RemoveAt(0);
3364 }
3365 }
3366 3830
3367// m_log.DebugFormat( 3831 lock (m_UndoRedo)
3368// "[SCENE OBJECT PART]: Handled undo request for {0} {1}, stack size now {2}", 3832 {
3369// Name, LocalId, m_undo.Count); 3833 Undoing = true;
3834 m_UndoRedo.Undo(this);
3835 Undoing = false;
3370 } 3836 }
3371 } 3837 }
3372 3838
3373 public void Redo() 3839 public void Redo()
3374 { 3840 {
3375 lock (m_undo) 3841 if (m_UndoRedo == null || Undoing || ParentGroup == null)
3376 { 3842 return;
3377// m_log.DebugFormat(
3378// "[SCENE OBJECT PART]: Handling redo request for {0} {1}, stack size {2}",
3379// Name, LocalId, m_redo.Count);
3380
3381 if (m_redo.Count > 0)
3382 {
3383 UndoState gofwd = m_redo[m_redo.Count - 1];
3384 m_redo.RemoveAt(m_redo.Count - 1);
3385
3386 if (ParentGroup.Scene.MaxUndoCount > 0)
3387 {
3388 UndoState nUndo = new UndoState(this, gofwd.ForGroup);
3389
3390 m_undo.Add(nUndo);
3391
3392 if (m_undo.Count > ParentGroup.Scene.MaxUndoCount)
3393 m_undo.RemoveAt(0);
3394 }
3395
3396 gofwd.PlayfwdState(this);
3397 3843
3398// m_log.DebugFormat( 3844 lock (m_UndoRedo)
3399// "[SCENE OBJECT PART]: Handled redo request for {0} {1}, stack size now {2}", 3845 {
3400// Name, LocalId, m_redo.Count); 3846 Undoing = true;
3401 } 3847 m_UndoRedo.Redo(this);
3848 Undoing = false;
3402 } 3849 }
3403 } 3850 }
3404 3851
3405 public void ClearUndoState() 3852 public void ClearUndoState()
3406 { 3853 {
3407// m_log.DebugFormat("[SCENE OBJECT PART]: Clearing undo and redo stacks in {0} {1}", Name, LocalId); 3854 if (m_UndoRedo == null || Undoing)
3855 return;
3408 3856
3409 lock (m_undo) 3857 lock (m_UndoRedo)
3410 { 3858 {
3411 m_undo.Clear(); 3859 m_UndoRedo.Clear();
3412 m_redo.Clear();
3413 } 3860 }
3414 } 3861 }
3415 3862
@@ -3961,7 +4408,7 @@ namespace OpenSim.Region.Framework.Scenes
3961 if (god) 4408 if (god)
3962 { 4409 {
3963 BaseMask = ApplyMask(BaseMask, set, mask); 4410 BaseMask = ApplyMask(BaseMask, set, mask);
3964 Inventory.ApplyGodPermissions(_baseMask); 4411 Inventory.ApplyGodPermissions(BaseMask);
3965 } 4412 }
3966 4413
3967 break; 4414 break;
@@ -3992,7 +4439,7 @@ namespace OpenSim.Region.Framework.Scenes
3992 } 4439 }
3993 NextOwnerMask = ApplyMask(NextOwnerMask, set, mask) & 4440 NextOwnerMask = ApplyMask(NextOwnerMask, set, mask) &
3994 baseMask; 4441 baseMask;
3995 // Prevent the client from creating no mod, no copy 4442 // Prevent the client from creating no copy, no transfer
3996 // objects 4443 // objects
3997 if ((NextOwnerMask & (uint)PermissionMask.Copy) == 0) 4444 if ((NextOwnerMask & (uint)PermissionMask.Copy) == 0)
3998 NextOwnerMask |= (uint)PermissionMask.Transfer; 4445 NextOwnerMask |= (uint)PermissionMask.Transfer;
@@ -4010,20 +4457,20 @@ namespace OpenSim.Region.Framework.Scenes
4010 { 4457 {
4011 bool update = false; 4458 bool update = false;
4012 4459
4013 if (BaseMask != source.BaseMask || 4460 uint prevOwnerMask = OwnerMask;
4014 OwnerMask != source.OwnerMask || 4461 uint prevGroupMask = GroupMask;
4015 GroupMask != source.GroupMask || 4462 uint prevEveryoneMask = EveryoneMask;
4016 EveryoneMask != source.EveryoneMask || 4463 uint prevNextOwnerMask = NextOwnerMask;
4017 NextOwnerMask != source.NextOwnerMask)
4018 update = true;
4019 4464
4020 BaseMask = source.BaseMask; 4465 OwnerMask = source.OwnerMask & BaseMask;
4021 OwnerMask = source.OwnerMask; 4466 GroupMask = source.GroupMask & BaseMask;
4022 GroupMask = source.GroupMask; 4467 EveryoneMask = source.EveryoneMask & BaseMask;
4023 EveryoneMask = source.EveryoneMask; 4468 NextOwnerMask = source.NextOwnerMask & BaseMask;
4024 NextOwnerMask = source.NextOwnerMask;
4025 4469
4026 if (update) 4470 if (OwnerMask != prevOwnerMask ||
4471 GroupMask != prevGroupMask ||
4472 EveryoneMask != prevEveryoneMask ||
4473 NextOwnerMask != prevNextOwnerMask)
4027 SendFullUpdateToAllClients(); 4474 SendFullUpdateToAllClients();
4028 } 4475 }
4029 4476
@@ -4074,6 +4521,7 @@ namespace OpenSim.Region.Framework.Scenes
4074 } 4521 }
4075 } 4522 }
4076 4523
4524
4077 public void UpdateExtraPhysics(ExtraPhysicsData physdata) 4525 public void UpdateExtraPhysics(ExtraPhysicsData physdata)
4078 { 4526 {
4079 if (physdata.PhysShapeType == PhysShapeType.invalid || ParentGroup == null) 4527 if (physdata.PhysShapeType == PhysShapeType.invalid || ParentGroup == null)
@@ -4101,7 +4549,7 @@ namespace OpenSim.Region.Framework.Scenes
4101 /// <param name="SetTemporary"></param> 4549 /// <param name="SetTemporary"></param>
4102 /// <param name="SetPhantom"></param> 4550 /// <param name="SetPhantom"></param>
4103 /// <param name="SetVD"></param> 4551 /// <param name="SetVD"></param>
4104 public void UpdatePrimFlags(bool UsePhysics, bool SetTemporary, bool SetPhantom, bool SetVD) 4552 public void UpdatePrimFlags(bool UsePhysics, bool SetTemporary, bool SetPhantom, bool SetVD, bool building)
4105 { 4553 {
4106 bool wasUsingPhysics = ((Flags & PrimFlags.Physics) != 0); 4554 bool wasUsingPhysics = ((Flags & PrimFlags.Physics) != 0);
4107 bool wasTemporary = ((Flags & PrimFlags.TemporaryOnRez) != 0); 4555 bool wasTemporary = ((Flags & PrimFlags.TemporaryOnRez) != 0);
@@ -4111,116 +4559,98 @@ namespace OpenSim.Region.Framework.Scenes
4111 if ((UsePhysics == wasUsingPhysics) && (wasTemporary == SetTemporary) && (wasPhantom == SetPhantom) && (SetVD == wasVD)) 4559 if ((UsePhysics == wasUsingPhysics) && (wasTemporary == SetTemporary) && (wasPhantom == SetPhantom) && (SetVD == wasVD))
4112 return; 4560 return;
4113 4561
4114 PhysicsActor pa = PhysActor; 4562 VolumeDetectActive = SetVD;
4115
4116 // Special cases for VD. VD can only be called from a script
4117 // and can't be combined with changes to other states. So we can rely
4118 // that...
4119 // ... if VD is changed, all others are not.
4120 // ... if one of the others is changed, VD is not.
4121 if (SetVD) // VD is active, special logic applies
4122 {
4123 // State machine logic for VolumeDetect
4124 // More logic below
4125 bool phanReset = (SetPhantom != wasPhantom) && !SetPhantom;
4126
4127 if (phanReset) // Phantom changes from on to off switch VD off too
4128 {
4129 SetVD = false; // Switch it of for the course of this routine
4130 VolumeDetectActive = false; // and also permanently
4131
4132 if (pa != null)
4133 pa.SetVolumeDetect(0); // Let physics know about it too
4134 }
4135 else
4136 {
4137 // If volumedetect is active we don't want phantom to be applied.
4138 // If this is a new call to VD out of the state "phantom"
4139 // this will also cause the prim to be visible to physics
4140 SetPhantom = false;
4141 }
4142 }
4143 4563
4144 if (UsePhysics && IsJoint()) 4564 // volume detector implies phantom
4145 { 4565 if (VolumeDetectActive)
4146 SetPhantom = true; 4566 SetPhantom = true;
4147 }
4148 4567
4149 if (UsePhysics) 4568 if (UsePhysics)
4150 {
4151 AddFlag(PrimFlags.Physics); 4569 AddFlag(PrimFlags.Physics);
4152 if (!wasUsingPhysics)
4153 {
4154 DoPhysicsPropertyUpdate(UsePhysics, false);
4155 }
4156 }
4157 else 4570 else
4158 {
4159 RemFlag(PrimFlags.Physics); 4571 RemFlag(PrimFlags.Physics);
4160 if (wasUsingPhysics)
4161 {
4162 DoPhysicsPropertyUpdate(UsePhysics, false);
4163 }
4164 }
4165 4572
4166 if (SetPhantom 4573 if (SetPhantom)
4167 || ParentGroup.IsAttachment
4168 || PhysicsShapeType == (byte)PhysShapeType.none
4169 || (Shape.PathCurve == (byte)Extrusion.Flexible)) // note: this may have been changed above in the case of joints
4170 {
4171 AddFlag(PrimFlags.Phantom); 4574 AddFlag(PrimFlags.Phantom);
4575 else
4576 RemFlag(PrimFlags.Phantom);
4172 4577
4173 if (PhysActor != null) 4578 if (SetTemporary)
4579 AddFlag(PrimFlags.TemporaryOnRez);
4580 else
4581 RemFlag(PrimFlags.TemporaryOnRez);
4582
4583
4584 if (ParentGroup.Scene == null)
4585 return;
4586
4587 PhysicsActor pa = PhysActor;
4588
4589 if (pa != null && building && pa.Building != building)
4590 pa.Building = building;
4591
4592 if ((SetPhantom && !UsePhysics && !SetVD) || ParentGroup.IsAttachment || PhysicsShapeType == (byte)PhysShapeType.none
4593 || (Shape.PathCurve == (byte)Extrusion.Flexible))
4594 {
4595 if (pa != null)
4174 { 4596 {
4597 if(wasUsingPhysics)
4598 ParentGroup.Scene.RemovePhysicalPrim(1);
4175 RemoveFromPhysics(); 4599 RemoveFromPhysics();
4176 pa = null;
4177 } 4600 }
4601
4602 Velocity = new Vector3(0, 0, 0);
4603 Acceleration = new Vector3(0, 0, 0);
4604 if (ParentGroup.RootPart == this)
4605 AngularVelocity = new Vector3(0, 0, 0);
4178 } 4606 }
4179 else // Not phantom 4607
4608 else
4180 { 4609 {
4181 RemFlag(PrimFlags.Phantom); 4610 if (ParentGroup.Scene.CollidablePrims)
4182
4183 if (ParentGroup.Scene == null)
4184 return;
4185
4186 if (ParentGroup.Scene.CollidablePrims && pa == null)
4187 { 4611 {
4188 AddToPhysics(UsePhysics, SetPhantom, false); 4612 if (pa == null)
4189 pa = PhysActor;
4190
4191
4192 if (pa != null)
4193 { 4613 {
4194 pa.SetMaterial(Material); 4614 AddToPhysics(UsePhysics, SetPhantom, building, false);
4195 DoPhysicsPropertyUpdate(UsePhysics, true); 4615 pa = PhysActor;
4196 4616/*
4197 if ( 4617 if (pa != null)
4198 ((AggregateScriptEvents & scriptEvents.collision) != 0) ||
4199 ((AggregateScriptEvents & scriptEvents.collision_end) != 0) ||
4200 ((AggregateScriptEvents & scriptEvents.collision_start) != 0) ||
4201 ((AggregateScriptEvents & scriptEvents.land_collision_start) != 0) ||
4202 ((AggregateScriptEvents & scriptEvents.land_collision) != 0) ||
4203 ((AggregateScriptEvents & scriptEvents.land_collision_end) != 0) ||
4204 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.collision) != 0) ||
4205 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.collision_end) != 0) ||
4206 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.collision_start) != 0) ||
4207 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.land_collision_start) != 0) ||
4208 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.land_collision) != 0) ||
4209 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.land_collision_end) != 0) ||
4210 (CollisionSound != UUID.Zero)
4211 )
4212 { 4618 {
4213 pa.OnCollisionUpdate += PhysicsCollision; 4619 if (
4214 pa.SubscribeEvents(1000); 4620// ((AggregateScriptEvents & scriptEvents.collision) != 0) ||
4621// ((AggregateScriptEvents & scriptEvents.collision_end) != 0) ||
4622// ((AggregateScriptEvents & scriptEvents.collision_start) != 0) ||
4623// ((AggregateScriptEvents & scriptEvents.land_collision_start) != 0) ||
4624// ((AggregateScriptEvents & scriptEvents.land_collision) != 0) ||
4625// ((AggregateScriptEvents & scriptEvents.land_collision_end) != 0) ||
4626 ((AggregateScriptEvents & PhysicsNeededSubsEvents) != 0) ||
4627 ((ParentGroup.RootPart.AggregateScriptEvents & PhysicsNeededSubsEvents) != 0) ||
4628 (CollisionSound != UUID.Zero)
4629 )
4630 {
4631 pa.OnCollisionUpdate += PhysicsCollision;
4632 pa.SubscribeEvents(1000);
4633 }
4215 } 4634 }
4635*/
4636 }
4637 else // it already has a physical representation
4638 {
4639 DoPhysicsPropertyUpdate(UsePhysics, false); // Update physical status.
4640/* moved into DoPhysicsPropertyUpdate
4641 if(VolumeDetectActive)
4642 pa.SetVolumeDetect(1);
4643 else
4644 pa.SetVolumeDetect(0);
4645*/
4646
4647 if (pa.Building != building)
4648 pa.Building = building;
4216 } 4649 }
4217 }
4218 else // it already has a physical representation
4219 {
4220 DoPhysicsPropertyUpdate(UsePhysics, false); // Update physical status. If it's phantom this will remove the prim
4221 }
4222 }
4223 4650
4651 UpdatePhysicsSubscribedEvents();
4652 }
4653 }
4224 if (SetVD) 4654 if (SetVD)
4225 { 4655 {
4226 // If the above logic worked (this is urgent candidate to unit tests!) 4656 // If the above logic worked (this is urgent candidate to unit tests!)
@@ -4234,6 +4664,7 @@ namespace OpenSim.Region.Framework.Scenes
4234 AddFlag(PrimFlags.Phantom); // We set this flag also if VD is active 4664 AddFlag(PrimFlags.Phantom); // We set this flag also if VD is active
4235 VolumeDetectActive = true; 4665 VolumeDetectActive = true;
4236 } 4666 }
4667 // m_log.Debug("Update: PHY:" + UsePhysics.ToString() + ", T:" + IsTemporary.ToString() + ", PHA:" + IsPhantom.ToString() + " S:" + CastsShadows.ToString());
4237 } 4668 }
4238 else if (SetVD != wasVD) 4669 else if (SetVD != wasVD)
4239 { 4670 {
@@ -4245,61 +4676,51 @@ namespace OpenSim.Region.Framework.Scenes
4245 RemFlag(PrimFlags.Phantom); 4676 RemFlag(PrimFlags.Phantom);
4246 VolumeDetectActive = false; 4677 VolumeDetectActive = false;
4247 } 4678 }
4248 4679 // and last in case we have a new actor and not building
4249 if (SetTemporary)
4250 {
4251 AddFlag(PrimFlags.TemporaryOnRez);
4252 }
4253 else
4254 {
4255 RemFlag(PrimFlags.TemporaryOnRez);
4256 }
4257
4258 // m_log.Debug("Update: PHY:" + UsePhysics.ToString() + ", T:" + IsTemporary.ToString() + ", PHA:" + IsPhantom.ToString() + " S:" + CastsShadows.ToString());
4259 4680
4260 if (ParentGroup != null) 4681 if (ParentGroup != null)
4261 { 4682 {
4262 ParentGroup.HasGroupChanged = true; 4683 ParentGroup.HasGroupChanged = true;
4263 ScheduleFullUpdate(); 4684 ScheduleFullUpdate();
4264 } 4685 }
4265 4686
4266// m_log.DebugFormat("[SCENE OBJECT PART]: Updated PrimFlags on {0} {1} to {2}", Name, LocalId, Flags); 4687// m_log.DebugFormat("[SCENE OBJECT PART]: Updated PrimFlags on {0} {1} to {2}", Name, LocalId, Flags);
4267 } 4688 }
4268 4689
4269 /// <summary> 4690 /// <summary>
4270 /// Adds this part to the physics scene. 4691 /// Adds this part to the physics scene.
4692 /// and sets the PhysActor property
4271 /// </summary> 4693 /// </summary>
4272 /// <remarks>This method also sets the PhysActor property.</remarks> 4694 /// <param name="isPhysical">Add this prim as physical.</param>
4273 /// <param name="rigidBody">Add this prim with a rigid body.</param> 4695 /// <param name="isPhantom">Add this prim as phantom.</param>
4274 /// <returns> 4696 /// <param name="building">tells physics to delay full construction of object</param>
4275 /// The physics actor. null if there was a failure. 4697 /// <param name="applyDynamics">applies velocities, force and torque</param>
4276 /// </returns> 4698 private void AddToPhysics(bool isPhysical, bool isPhantom, bool building, bool applyDynamics)
4277 private void AddToPhysics(bool isPhysical, bool isPhantom, bool applyDynamics) 4699 {
4278 {
4279 PhysicsActor pa; 4700 PhysicsActor pa;
4280 4701
4281 Vector3 velocity = Velocity; 4702 Vector3 velocity = Velocity;
4282 Vector3 rotationalVelocity = AngularVelocity;; 4703 Vector3 rotationalVelocity = AngularVelocity;;
4283 4704
4284 try 4705 try
4285 { 4706 {
4286 pa = ParentGroup.Scene.PhysicsScene.AddPrimShape( 4707 pa = ParentGroup.Scene.PhysicsScene.AddPrimShape(
4287 string.Format("{0}/{1}", Name, UUID), 4708 string.Format("{0}/{1}", Name, UUID),
4288 Shape, 4709 Shape,
4289 AbsolutePosition, 4710 AbsolutePosition,
4290 Scale, 4711 Scale,
4291 GetWorldRotation(), 4712 GetWorldRotation(),
4292 isPhysical, 4713 isPhysical,
4293 isPhantom, 4714 isPhantom,
4294 PhysicsShapeType, 4715 PhysicsShapeType,
4295 m_localId); 4716 m_localId);
4296 } 4717 }
4297 catch (Exception e) 4718 catch (Exception e)
4298 { 4719 {
4299 m_log.ErrorFormat("[SCENE]: caught exception meshing object {0}. Object set to phantom. e={1}", m_uuid, e); 4720 m_log.ErrorFormat("[SCENE]: caught exception meshing object {0}. Object set to phantom. e={1}", m_uuid, e);
4300 pa = null; 4721 pa = null;
4301 } 4722 }
4302 4723
4303 if (pa != null) 4724 if (pa != null)
4304 { 4725 {
4305 pa.SOPName = this.Name; // save object into the PhysActor so ODE internals know the joint/body info 4726 pa.SOPName = this.Name; // save object into the PhysActor so ODE internals know the joint/body info
@@ -4312,11 +4733,21 @@ namespace OpenSim.Region.Framework.Scenes
4312 4733
4313 if (VolumeDetectActive) // change if not the default only 4734 if (VolumeDetectActive) // change if not the default only
4314 pa.SetVolumeDetect(1); 4735 pa.SetVolumeDetect(1);
4736
4737 if (m_vehicleParams != null && LocalId == ParentGroup.RootPart.LocalId)
4738 m_vehicleParams.SetVehicle(pa);
4739
4315 // we are going to tell rest of code about physics so better have this here 4740 // we are going to tell rest of code about physics so better have this here
4316 PhysActor = pa; 4741 PhysActor = pa;
4317 4742
4743 // DoPhysicsPropertyUpdate(isPhysical, true);
4744 // lets expand it here just with what it really needs to do
4745
4318 if (isPhysical) 4746 if (isPhysical)
4319 { 4747 {
4748 if (ParentGroup.RootPart.KeyframeMotion != null)
4749 ParentGroup.RootPart.KeyframeMotion.Stop();
4750 ParentGroup.RootPart.KeyframeMotion = null;
4320 ParentGroup.Scene.AddPhysicalPrim(1); 4751 ParentGroup.Scene.AddPhysicalPrim(1);
4321 4752
4322 pa.OnRequestTerseUpdate += PhysicsRequestingTerseUpdate; 4753 pa.OnRequestTerseUpdate += PhysicsRequestingTerseUpdate;
@@ -4333,19 +4764,34 @@ namespace OpenSim.Region.Framework.Scenes
4333 } 4764 }
4334 } 4765 }
4335 4766
4336 if (applyDynamics) 4767 if (applyDynamics)
4337 // do independent of isphysical so parameters get setted (at least some) 4768 // do independent of isphysical so parameters get setted (at least some)
4338 { 4769 {
4339 Velocity = velocity; 4770 Velocity = velocity;
4340 AngularVelocity = rotationalVelocity; 4771 AngularVelocity = rotationalVelocity;
4341// pa.Velocity = velocity; 4772// pa.Velocity = velocity;
4342 pa.RotationalVelocity = rotationalVelocity; 4773 pa.RotationalVelocity = rotationalVelocity;
4774
4775 // if not vehicle and root part apply force and torque
4776 if ((m_vehicleParams == null || m_vehicleParams.Type == Vehicle.TYPE_NONE)
4777 && LocalId == ParentGroup.RootPart.LocalId)
4778 {
4779 pa.Force = Force;
4780 pa.Torque = Torque;
4781 }
4343 } 4782 }
4344 4783
4345 ParentGroup.Scene.PhysicsScene.AddPhysicsActorTaint(pa); 4784// if (Shape.SculptEntry)
4785// CheckSculptAndLoad();
4786// else
4787 ParentGroup.Scene.PhysicsScene.AddPhysicsActorTaint(pa);
4788
4789 if (!building)
4790 pa.Building = false;
4346 } 4791 }
4347 4792
4348 PhysActor = pa; 4793 PhysActor = pa;
4794
4349 ParentGroup.Scene.EventManager.TriggerObjectAddedToPhysicalScene(this); 4795 ParentGroup.Scene.EventManager.TriggerObjectAddedToPhysicalScene(this);
4350 } 4796 }
4351 4797
@@ -4354,13 +4800,21 @@ namespace OpenSim.Region.Framework.Scenes
4354 /// </summary> 4800 /// </summary>
4355 /// <remarks> 4801 /// <remarks>
4356 /// This isn't the same as turning off physical, since even without being physical the prim has a physics 4802 /// This isn't the same as turning off physical, since even without being physical the prim has a physics
4357 /// representation for collision detection. Rather, this would be used in situations such as making a prim 4803 /// representation for collision detection.
4358 /// phantom.
4359 /// </remarks> 4804 /// </remarks>
4360 public void RemoveFromPhysics() 4805 public void RemoveFromPhysics()
4361 { 4806 {
4362 ParentGroup.Scene.EventManager.TriggerObjectRemovedFromPhysicalScene(this); 4807 PhysicsActor pa = PhysActor;
4363 ParentGroup.Scene.PhysicsScene.RemovePrim(PhysActor); 4808 if (pa != null)
4809 {
4810 pa.OnCollisionUpdate -= PhysicsCollision;
4811 pa.OnRequestTerseUpdate -= PhysicsRequestingTerseUpdate;
4812 pa.OnOutOfBounds -= PhysicsOutOfBounds;
4813
4814 ParentGroup.Scene.PhysicsScene.RemovePrim(pa);
4815
4816 ParentGroup.Scene.EventManager.TriggerObjectRemovedFromPhysicalScene(this);
4817 }
4364 PhysActor = null; 4818 PhysActor = null;
4365 } 4819 }
4366 4820
@@ -4492,6 +4946,8 @@ namespace OpenSim.Region.Framework.Scenes
4492 { 4946 {
4493// m_log.DebugFormat("Processing CheckSculptAndLoad for {0} {1}", Name, LocalId); 4947// m_log.DebugFormat("Processing CheckSculptAndLoad for {0} {1}", Name, LocalId);
4494 4948
4949 return;
4950
4495 if (ParentGroup.IsDeleted) 4951 if (ParentGroup.IsDeleted)
4496 return; 4952 return;
4497 4953
@@ -4615,6 +5071,44 @@ namespace OpenSim.Region.Framework.Scenes
4615 } 5071 }
4616 } 5072 }
4617 5073
5074
5075 private void UpdatePhysicsSubscribedEvents()
5076 {
5077 PhysicsActor pa = PhysActor;
5078 if (pa == null)
5079 return;
5080
5081 pa.OnCollisionUpdate -= PhysicsCollision;
5082
5083 bool hassound = (!VolumeDetectActive && CollisionSoundType >= 0 && ((Flags & PrimFlags.Physics) != 0));
5084
5085 scriptEvents CombinedEvents = AggregateScriptEvents;
5086
5087 // merge with root part
5088 if (ParentGroup != null && ParentGroup.RootPart != null)
5089 CombinedEvents |= ParentGroup.RootPart.AggregateScriptEvents;
5090
5091 // submit to this part case
5092 if (VolumeDetectActive)
5093 CombinedEvents &= PhyscicsVolumeDtcSubsEvents;
5094 else if ((Flags & PrimFlags.Phantom) != 0)
5095 CombinedEvents &= PhyscicsPhantonSubsEvents;
5096 else
5097 CombinedEvents &= PhysicsNeededSubsEvents;
5098
5099 if (hassound || CombinedEvents != 0)
5100 {
5101 // subscribe to physics updates.
5102 pa.OnCollisionUpdate += PhysicsCollision;
5103 pa.SubscribeEvents(50); // 20 reports per second
5104 }
5105 else
5106 {
5107 pa.UnSubscribeEvents();
5108 }
5109 }
5110
5111
4618 public void aggregateScriptEvents() 5112 public void aggregateScriptEvents()
4619 { 5113 {
4620 if (ParentGroup == null || ParentGroup.RootPart == null) 5114 if (ParentGroup == null || ParentGroup.RootPart == null)
@@ -4651,40 +5145,32 @@ namespace OpenSim.Region.Framework.Scenes
4651 { 5145 {
4652 objectflagupdate |= (uint) PrimFlags.AllowInventoryDrop; 5146 objectflagupdate |= (uint) PrimFlags.AllowInventoryDrop;
4653 } 5147 }
4654 5148/*
4655 PhysicsActor pa = PhysActor; 5149 PhysicsActor pa = PhysActor;
4656 5150 if (pa != null)
4657 if (
4658 ((AggregateScriptEvents & scriptEvents.collision) != 0) ||
4659 ((AggregateScriptEvents & scriptEvents.collision_end) != 0) ||
4660 ((AggregateScriptEvents & scriptEvents.collision_start) != 0) ||
4661 ((AggregateScriptEvents & scriptEvents.land_collision_start) != 0) ||
4662 ((AggregateScriptEvents & scriptEvents.land_collision) != 0) ||
4663 ((AggregateScriptEvents & scriptEvents.land_collision_end) != 0) ||
4664 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.collision) != 0) ||
4665 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.collision_end) != 0) ||
4666 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.collision_start) != 0) ||
4667 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.land_collision_start) != 0) ||
4668 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.land_collision) != 0) ||
4669 ((ParentGroup.RootPart.AggregateScriptEvents & scriptEvents.land_collision_end) != 0) ||
4670 (CollisionSound != UUID.Zero)
4671 )
4672 { 5151 {
4673 // subscribe to physics updates. 5152 if (
4674 if (pa != null) 5153// ((AggregateScriptEvents & scriptEvents.collision) != 0) ||
5154// ((AggregateScriptEvents & scriptEvents.collision_end) != 0) ||
5155// ((AggregateScriptEvents & scriptEvents.collision_start) != 0) ||
5156// ((AggregateScriptEvents & scriptEvents.land_collision_start) != 0) ||
5157// ((AggregateScriptEvents & scriptEvents.land_collision) != 0) ||
5158// ((AggregateScriptEvents & scriptEvents.land_collision_end) != 0) ||
5159 ((AggregateScriptEvents & PhysicsNeededSubsEvents) != 0) || ((ParentGroup.RootPart.AggregateScriptEvents & PhysicsNeededSubsEvents) != 0) || (CollisionSound != UUID.Zero)
5160 )
4675 { 5161 {
5162 // subscribe to physics updates.
4676 pa.OnCollisionUpdate += PhysicsCollision; 5163 pa.OnCollisionUpdate += PhysicsCollision;
4677 pa.SubscribeEvents(1000); 5164 pa.SubscribeEvents(1000);
4678 } 5165 }
4679 } 5166 else
4680 else
4681 {
4682 if (pa != null)
4683 { 5167 {
4684 pa.UnSubscribeEvents(); 5168 pa.UnSubscribeEvents();
4685 pa.OnCollisionUpdate -= PhysicsCollision; 5169 pa.OnCollisionUpdate -= PhysicsCollision;
4686 } 5170 }
4687 } 5171 }
5172 */
5173 UpdatePhysicsSubscribedEvents();
4688 5174
4689 //if ((GetEffectiveObjectFlags() & (uint)PrimFlags.Scripted) != 0) 5175 //if ((GetEffectiveObjectFlags() & (uint)PrimFlags.Scripted) != 0)
4690 //{ 5176 //{
@@ -4818,6 +5304,18 @@ namespace OpenSim.Region.Framework.Scenes
4818 return new Color4(color.R, color.G, color.B, (byte)(0xFF - color.A)); 5304 return new Color4(color.R, color.G, color.B, (byte)(0xFF - color.A));
4819 } 5305 }
4820 5306
5307 public void ResetOwnerChangeFlag()
5308 {
5309 List<UUID> inv = Inventory.GetInventoryList();
5310
5311 foreach (UUID itemID in inv)
5312 {
5313 TaskInventoryItem item = Inventory.GetInventoryItem(itemID);
5314 item.OwnerChanged = false;
5315 Inventory.UpdateInventoryItem(item, false, false);
5316 }
5317 }
5318
4821 /// <summary> 5319 /// <summary>
4822 /// Record an avatar sitting on this part. 5320 /// Record an avatar sitting on this part.
4823 /// </summary> 5321 /// </summary>
diff --git a/OpenSim/Region/Framework/Scenes/SceneObjectPartInventory.cs b/OpenSim/Region/Framework/Scenes/SceneObjectPartInventory.cs
index 7dba7c8..d04d87b 100644
--- a/OpenSim/Region/Framework/Scenes/SceneObjectPartInventory.cs
+++ b/OpenSim/Region/Framework/Scenes/SceneObjectPartInventory.cs
@@ -49,6 +49,9 @@ namespace OpenSim.Region.Framework.Scenes
49 private string m_inventoryFileName = String.Empty; 49 private string m_inventoryFileName = String.Empty;
50 private byte[] m_inventoryFileData = new byte[0]; 50 private byte[] m_inventoryFileData = new byte[0];
51 private uint m_inventoryFileNameSerial = 0; 51 private uint m_inventoryFileNameSerial = 0;
52 private bool m_inventoryPrivileged = false;
53
54 private Dictionary<UUID, ArrayList> m_scriptErrors = new Dictionary<UUID, ArrayList>();
52 55
53 /// <value> 56 /// <value>
54 /// The part to which the inventory belongs. 57 /// The part to which the inventory belongs.
@@ -85,7 +88,9 @@ namespace OpenSim.Region.Framework.Scenes
85 /// </value> 88 /// </value>
86 protected internal TaskInventoryDictionary Items 89 protected internal TaskInventoryDictionary Items
87 { 90 {
88 get { return m_items; } 91 get {
92 return m_items;
93 }
89 set 94 set
90 { 95 {
91 m_items = value; 96 m_items = value;
@@ -134,38 +139,45 @@ namespace OpenSim.Region.Framework.Scenes
134 public void ResetInventoryIDs() 139 public void ResetInventoryIDs()
135 { 140 {
136 if (null == m_part) 141 if (null == m_part)
137 return; 142 m_items.LockItemsForWrite(true);
138 143
139 lock (m_items) 144 if (Items.Count == 0)
140 { 145 {
141 if (0 == m_items.Count) 146 m_items.LockItemsForWrite(false);
142 return; 147 return;
148 }
143 149
144 IList<TaskInventoryItem> items = GetInventoryItems(); 150 IList<TaskInventoryItem> items = new List<TaskInventoryItem>(Items.Values);
145 m_items.Clear(); 151 Items.Clear();
146 152
147 foreach (TaskInventoryItem item in items) 153 foreach (TaskInventoryItem item in items)
148 { 154 {
149 item.ResetIDs(m_part.UUID); 155 item.ResetIDs(m_part.UUID);
150 m_items.Add(item.ItemID, item); 156 Items.Add(item.ItemID, item);
151 }
152 } 157 }
158 m_items.LockItemsForWrite(false);
153 } 159 }
154 160
155 public void ResetObjectID() 161 public void ResetObjectID()
156 { 162 {
157 lock (Items) 163 m_items.LockItemsForWrite(true);
164
165 if (Items.Count == 0)
158 { 166 {
159 IList<TaskInventoryItem> items = new List<TaskInventoryItem>(Items.Values); 167 m_items.LockItemsForWrite(false);
160 Items.Clear(); 168 return;
161
162 foreach (TaskInventoryItem item in items)
163 {
164 item.ParentPartID = m_part.UUID;
165 item.ParentID = m_part.UUID;
166 Items.Add(item.ItemID, item);
167 }
168 } 169 }
170
171 IList<TaskInventoryItem> items = new List<TaskInventoryItem>(Items.Values);
172 Items.Clear();
173
174 foreach (TaskInventoryItem item in items)
175 {
176 item.ParentPartID = m_part.UUID;
177 item.ParentID = m_part.UUID;
178 Items.Add(item.ItemID, item);
179 }
180 m_items.LockItemsForWrite(false);
169 } 181 }
170 182
171 /// <summary> 183 /// <summary>
@@ -174,17 +186,14 @@ namespace OpenSim.Region.Framework.Scenes
174 /// <param name="ownerId"></param> 186 /// <param name="ownerId"></param>
175 public void ChangeInventoryOwner(UUID ownerId) 187 public void ChangeInventoryOwner(UUID ownerId)
176 { 188 {
177 lock (Items) 189 List<TaskInventoryItem> items = GetInventoryItems();
178 { 190
179 if (0 == Items.Count) 191 if (items.Count == 0)
180 { 192 return;
181 return;
182 }
183 }
184 193
194 m_items.LockItemsForWrite(true);
185 HasInventoryChanged = true; 195 HasInventoryChanged = true;
186 m_part.ParentGroup.HasGroupChanged = true; 196 m_part.ParentGroup.HasGroupChanged = true;
187 List<TaskInventoryItem> items = GetInventoryItems();
188 foreach (TaskInventoryItem item in items) 197 foreach (TaskInventoryItem item in items)
189 { 198 {
190 if (ownerId != item.OwnerID) 199 if (ownerId != item.OwnerID)
@@ -195,6 +204,7 @@ namespace OpenSim.Region.Framework.Scenes
195 item.PermsGranter = UUID.Zero; 204 item.PermsGranter = UUID.Zero;
196 item.OwnerChanged = true; 205 item.OwnerChanged = true;
197 } 206 }
207 m_items.LockItemsForWrite(false);
198 } 208 }
199 209
200 /// <summary> 210 /// <summary>
@@ -203,12 +213,11 @@ namespace OpenSim.Region.Framework.Scenes
203 /// <param name="groupID"></param> 213 /// <param name="groupID"></param>
204 public void ChangeInventoryGroup(UUID groupID) 214 public void ChangeInventoryGroup(UUID groupID)
205 { 215 {
206 lock (Items) 216 m_items.LockItemsForWrite(true);
217 if (0 == Items.Count)
207 { 218 {
208 if (0 == Items.Count) 219 m_items.LockItemsForWrite(false);
209 { 220 return;
210 return;
211 }
212 } 221 }
213 222
214 // Don't let this set the HasGroupChanged flag for attachments 223 // Don't let this set the HasGroupChanged flag for attachments
@@ -220,12 +229,15 @@ namespace OpenSim.Region.Framework.Scenes
220 m_part.ParentGroup.HasGroupChanged = true; 229 m_part.ParentGroup.HasGroupChanged = true;
221 } 230 }
222 231
223 List<TaskInventoryItem> items = GetInventoryItems(); 232 IList<TaskInventoryItem> items = new List<TaskInventoryItem>(Items.Values);
224 foreach (TaskInventoryItem item in items) 233 foreach (TaskInventoryItem item in items)
225 { 234 {
226 if (groupID != item.GroupID) 235 if (groupID != item.GroupID)
236 {
227 item.GroupID = groupID; 237 item.GroupID = groupID;
238 }
228 } 239 }
240 m_items.LockItemsForWrite(false);
229 } 241 }
230 242
231 private void QueryScriptStates() 243 private void QueryScriptStates()
@@ -233,15 +245,18 @@ namespace OpenSim.Region.Framework.Scenes
233 if (m_part == null || m_part.ParentGroup == null || m_part.ParentGroup.Scene == null) 245 if (m_part == null || m_part.ParentGroup == null || m_part.ParentGroup.Scene == null)
234 return; 246 return;
235 247
236 lock (Items) 248 Items.LockItemsForRead(true);
249 foreach (TaskInventoryItem item in Items.Values)
237 { 250 {
238 foreach (TaskInventoryItem item in Items.Values) 251 if (item.InvType == (int)InventoryType.LSL)
239 { 252 {
240 bool running; 253 bool running;
241 if (TryGetScriptInstanceRunning(m_part.ParentGroup.Scene, item, out running)) 254 if (TryGetScriptInstanceRunning(m_part.ParentGroup.Scene, item, out running))
242 item.ScriptRunning = running; 255 item.ScriptRunning = running;
243 } 256 }
244 } 257 }
258
259 Items.LockItemsForRead(false);
245 } 260 }
246 261
247 public bool TryGetScriptInstanceRunning(UUID itemId, out bool running) 262 public bool TryGetScriptInstanceRunning(UUID itemId, out bool running)
@@ -318,7 +333,10 @@ namespace OpenSim.Region.Framework.Scenes
318 { 333 {
319 List<TaskInventoryItem> scripts = GetInventoryItems(InventoryType.LSL); 334 List<TaskInventoryItem> scripts = GetInventoryItems(InventoryType.LSL);
320 foreach (TaskInventoryItem item in scripts) 335 foreach (TaskInventoryItem item in scripts)
336 {
321 RemoveScriptInstance(item.ItemID, sceneObjectBeingDeleted); 337 RemoveScriptInstance(item.ItemID, sceneObjectBeingDeleted);
338 m_part.RemoveScriptEvents(item.ItemID);
339 }
322 } 340 }
323 341
324 /// <summary> 342 /// <summary>
@@ -340,7 +358,10 @@ namespace OpenSim.Region.Framework.Scenes
340// item.Name, item.ItemID, m_part.Name, m_part.UUID, m_part.ParentGroup.Scene.RegionInfo.RegionName); 358// item.Name, item.ItemID, m_part.Name, m_part.UUID, m_part.ParentGroup.Scene.RegionInfo.RegionName);
341 359
342 if (!m_part.ParentGroup.Scene.Permissions.CanRunScript(item.ItemID, m_part.UUID, item.OwnerID)) 360 if (!m_part.ParentGroup.Scene.Permissions.CanRunScript(item.ItemID, m_part.UUID, item.OwnerID))
361 {
362 StoreScriptError(item.ItemID, "no permission");
343 return false; 363 return false;
364 }
344 365
345 m_part.AddFlag(PrimFlags.Scripted); 366 m_part.AddFlag(PrimFlags.Scripted);
346 367
@@ -350,14 +371,13 @@ namespace OpenSim.Region.Framework.Scenes
350 if (stateSource == 2 && // Prim crossing 371 if (stateSource == 2 && // Prim crossing
351 m_part.ParentGroup.Scene.m_trustBinaries) 372 m_part.ParentGroup.Scene.m_trustBinaries)
352 { 373 {
353 lock (m_items) 374 m_items.LockItemsForWrite(true);
354 { 375 m_items[item.ItemID].PermsMask = 0;
355 m_items[item.ItemID].PermsMask = 0; 376 m_items[item.ItemID].PermsGranter = UUID.Zero;
356 m_items[item.ItemID].PermsGranter = UUID.Zero; 377 m_items.LockItemsForWrite(false);
357 }
358
359 m_part.ParentGroup.Scene.EventManager.TriggerRezScript( 378 m_part.ParentGroup.Scene.EventManager.TriggerRezScript(
360 m_part.LocalId, item.ItemID, String.Empty, startParam, postOnRez, engine, stateSource); 379 m_part.LocalId, item.ItemID, String.Empty, startParam, postOnRez, engine, stateSource);
380 StoreScriptErrors(item.ItemID, null);
361 m_part.ParentGroup.AddActiveScriptCount(1); 381 m_part.ParentGroup.AddActiveScriptCount(1);
362 m_part.ScheduleFullUpdate(); 382 m_part.ScheduleFullUpdate();
363 return true; 383 return true;
@@ -366,6 +386,8 @@ namespace OpenSim.Region.Framework.Scenes
366 AssetBase asset = m_part.ParentGroup.Scene.AssetService.Get(item.AssetID.ToString()); 386 AssetBase asset = m_part.ParentGroup.Scene.AssetService.Get(item.AssetID.ToString());
367 if (null == asset) 387 if (null == asset)
368 { 388 {
389 string msg = String.Format("asset ID {0} could not be found", item.AssetID);
390 StoreScriptError(item.ItemID, msg);
369 m_log.ErrorFormat( 391 m_log.ErrorFormat(
370 "[PRIM INVENTORY]: Couldn't start script {0}, {1} at {2} in {3} since asset ID {4} could not be found", 392 "[PRIM INVENTORY]: Couldn't start script {0}, {1} at {2} in {3} since asset ID {4} could not be found",
371 item.Name, item.ItemID, m_part.AbsolutePosition, 393 item.Name, item.ItemID, m_part.AbsolutePosition,
@@ -378,16 +400,18 @@ namespace OpenSim.Region.Framework.Scenes
378 if (m_part.ParentGroup.m_savedScriptState != null) 400 if (m_part.ParentGroup.m_savedScriptState != null)
379 item.OldItemID = RestoreSavedScriptState(item.LoadedItemID, item.OldItemID, item.ItemID); 401 item.OldItemID = RestoreSavedScriptState(item.LoadedItemID, item.OldItemID, item.ItemID);
380 402
381 lock (m_items) 403 m_items.LockItemsForWrite(true);
382 { 404
383 m_items[item.ItemID].OldItemID = item.OldItemID; 405 m_items[item.ItemID].OldItemID = item.OldItemID;
384 m_items[item.ItemID].PermsMask = 0; 406 m_items[item.ItemID].PermsMask = 0;
385 m_items[item.ItemID].PermsGranter = UUID.Zero; 407 m_items[item.ItemID].PermsGranter = UUID.Zero;
386 }
387 408
409 m_items.LockItemsForWrite(false);
410
388 string script = Utils.BytesToString(asset.Data); 411 string script = Utils.BytesToString(asset.Data);
389 m_part.ParentGroup.Scene.EventManager.TriggerRezScript( 412 m_part.ParentGroup.Scene.EventManager.TriggerRezScript(
390 m_part.LocalId, item.ItemID, script, startParam, postOnRez, engine, stateSource); 413 m_part.LocalId, item.ItemID, script, startParam, postOnRez, engine, stateSource);
414 StoreScriptErrors(item.ItemID, null);
391 if (!item.ScriptRunning) 415 if (!item.ScriptRunning)
392 m_part.ParentGroup.Scene.EventManager.TriggerStopScript( 416 m_part.ParentGroup.Scene.EventManager.TriggerStopScript(
393 m_part.LocalId, item.ItemID); 417 m_part.LocalId, item.ItemID);
@@ -460,22 +484,149 @@ namespace OpenSim.Region.Framework.Scenes
460 return stateID; 484 return stateID;
461 } 485 }
462 486
487 /// <summary>
488 /// Start a script which is in this prim's inventory.
489 /// Some processing may occur in the background, but this routine returns asap.
490 /// </summary>
491 /// <param name="itemId">
492 /// A <see cref="UUID"/>
493 /// </param>
463 public bool CreateScriptInstance(UUID itemId, int startParam, bool postOnRez, string engine, int stateSource) 494 public bool CreateScriptInstance(UUID itemId, int startParam, bool postOnRez, string engine, int stateSource)
464 { 495 {
465 TaskInventoryItem item = GetInventoryItem(itemId); 496 lock (m_scriptErrors)
466 if (item != null)
467 { 497 {
468 return CreateScriptInstance(item, startParam, postOnRez, engine, stateSource); 498 // Indicate to CreateScriptInstanceInternal() we don't want it to wait for completion
499 m_scriptErrors.Remove(itemId);
500 }
501 CreateScriptInstanceInternal(itemId, startParam, postOnRez, engine, stateSource);
502 return true;
503 }
504
505 private void CreateScriptInstanceInternal(UUID itemId, int startParam, bool postOnRez, string engine, int stateSource)
506 {
507 m_items.LockItemsForRead(true);
508 if (m_items.ContainsKey(itemId))
509 {
510 if (m_items.ContainsKey(itemId))
511 {
512 m_items.LockItemsForRead(false);
513 CreateScriptInstance(m_items[itemId], startParam, postOnRez, engine, stateSource);
514 }
515 else
516 {
517 m_items.LockItemsForRead(false);
518 string msg = String.Format("couldn't be found for prim {0}, {1} at {2} in {3}", m_part.Name, m_part.UUID,
519 m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName);
520 StoreScriptError(itemId, msg);
521 m_log.ErrorFormat(
522 "[PRIM INVENTORY]: " +
523 "Couldn't start script with ID {0} since it {1}", itemId, msg);
524 }
469 } 525 }
470 else 526 else
471 { 527 {
528 m_items.LockItemsForRead(false);
529 string msg = String.Format("couldn't be found for prim {0}, {1}", m_part.Name, m_part.UUID);
530 StoreScriptError(itemId, msg);
472 m_log.ErrorFormat( 531 m_log.ErrorFormat(
473 "[PRIM INVENTORY]: Couldn't start script with ID {0} since it couldn't be found for prim {1}, {2} at {3} in {4}", 532 "[PRIM INVENTORY]: Couldn't start script with ID {0} since it couldn't be found for prim {1}, {2} at {3} in {4}",
474 itemId, m_part.Name, m_part.UUID, 533 itemId, m_part.Name, m_part.UUID,
475 m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName); 534 m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName);
535 }
536
537 }
476 538
477 return false; 539 /// <summary>
540 /// Start a script which is in this prim's inventory and return any compilation error messages.
541 /// </summary>
542 /// <param name="itemId">
543 /// A <see cref="UUID"/>
544 /// </param>
545 public ArrayList CreateScriptInstanceEr(UUID itemId, int startParam, bool postOnRez, string engine, int stateSource)
546 {
547 ArrayList errors;
548
549 // Indicate to CreateScriptInstanceInternal() we want it to
550 // post any compilation/loading error messages
551 lock (m_scriptErrors)
552 {
553 m_scriptErrors[itemId] = null;
554 }
555
556 // Perform compilation/loading
557 CreateScriptInstanceInternal(itemId, startParam, postOnRez, engine, stateSource);
558
559 // Wait for and retrieve any errors
560 lock (m_scriptErrors)
561 {
562 while ((errors = m_scriptErrors[itemId]) == null)
563 {
564 if (!System.Threading.Monitor.Wait(m_scriptErrors, 15000))
565 {
566 m_log.ErrorFormat(
567 "[PRIM INVENTORY]: " +
568 "timedout waiting for script {0} errors", itemId);
569 errors = m_scriptErrors[itemId];
570 if (errors == null)
571 {
572 errors = new ArrayList(1);
573 errors.Add("timedout waiting for errors");
574 }
575 break;
576 }
577 }
578 m_scriptErrors.Remove(itemId);
478 } 579 }
580 return errors;
581 }
582
583 // Signal to CreateScriptInstanceEr() that compilation/loading is complete
584 private void StoreScriptErrors(UUID itemId, ArrayList errors)
585 {
586 lock (m_scriptErrors)
587 {
588 // If compilation/loading initiated via CreateScriptInstance(),
589 // it does not want the errors, so just get out
590 if (!m_scriptErrors.ContainsKey(itemId))
591 {
592 return;
593 }
594
595 // Initiated via CreateScriptInstanceEr(), if we know what the
596 // errors are, save them and wake CreateScriptInstanceEr().
597 if (errors != null)
598 {
599 m_scriptErrors[itemId] = errors;
600 System.Threading.Monitor.PulseAll(m_scriptErrors);
601 return;
602 }
603 }
604
605 // Initiated via CreateScriptInstanceEr() but we don't know what
606 // the errors are yet, so retrieve them from the script engine.
607 // This may involve some waiting internal to GetScriptErrors().
608 errors = GetScriptErrors(itemId);
609
610 // Get a default non-null value to indicate success.
611 if (errors == null)
612 {
613 errors = new ArrayList();
614 }
615
616 // Post to CreateScriptInstanceEr() and wake it up
617 lock (m_scriptErrors)
618 {
619 m_scriptErrors[itemId] = errors;
620 System.Threading.Monitor.PulseAll(m_scriptErrors);
621 }
622 }
623
624 // Like StoreScriptErrors(), but just posts a single string message
625 private void StoreScriptError(UUID itemId, string message)
626 {
627 ArrayList errors = new ArrayList(1);
628 errors.Add(message);
629 StoreScriptErrors(itemId, errors);
479 } 630 }
480 631
481 /// <summary> 632 /// <summary>
@@ -488,15 +639,7 @@ namespace OpenSim.Region.Framework.Scenes
488 /// </param> 639 /// </param>
489 public void RemoveScriptInstance(UUID itemId, bool sceneObjectBeingDeleted) 640 public void RemoveScriptInstance(UUID itemId, bool sceneObjectBeingDeleted)
490 { 641 {
491 bool scriptPresent = false; 642 if (m_items.ContainsKey(itemId))
492
493 lock (m_items)
494 {
495 if (m_items.ContainsKey(itemId))
496 scriptPresent = true;
497 }
498
499 if (scriptPresent)
500 { 643 {
501 if (!sceneObjectBeingDeleted) 644 if (!sceneObjectBeingDeleted)
502 m_part.RemoveScriptEvents(itemId); 645 m_part.RemoveScriptEvents(itemId);
@@ -566,14 +709,16 @@ namespace OpenSim.Region.Framework.Scenes
566 /// <returns></returns> 709 /// <returns></returns>
567 private bool InventoryContainsName(string name) 710 private bool InventoryContainsName(string name)
568 { 711 {
569 lock (m_items) 712 m_items.LockItemsForRead(true);
713 foreach (TaskInventoryItem item in m_items.Values)
570 { 714 {
571 foreach (TaskInventoryItem item in m_items.Values) 715 if (item.Name == name)
572 { 716 {
573 if (item.Name == name) 717 m_items.LockItemsForRead(false);
574 return true; 718 return true;
575 } 719 }
576 } 720 }
721 m_items.LockItemsForRead(false);
577 return false; 722 return false;
578 } 723 }
579 724
@@ -615,8 +760,9 @@ namespace OpenSim.Region.Framework.Scenes
615 /// <param name="item"></param> 760 /// <param name="item"></param>
616 public void AddInventoryItemExclusive(TaskInventoryItem item, bool allowedDrop) 761 public void AddInventoryItemExclusive(TaskInventoryItem item, bool allowedDrop)
617 { 762 {
618 List<TaskInventoryItem> il = GetInventoryItems(); 763 m_items.LockItemsForRead(true);
619 764 List<TaskInventoryItem> il = new List<TaskInventoryItem>(m_items.Values);
765 m_items.LockItemsForRead(false);
620 foreach (TaskInventoryItem i in il) 766 foreach (TaskInventoryItem i in il)
621 { 767 {
622 if (i.Name == item.Name) 768 if (i.Name == item.Name)
@@ -654,14 +800,14 @@ namespace OpenSim.Region.Framework.Scenes
654 item.Name = name; 800 item.Name = name;
655 item.GroupID = m_part.GroupID; 801 item.GroupID = m_part.GroupID;
656 802
657 lock (m_items) 803 m_items.LockItemsForWrite(true);
658 m_items.Add(item.ItemID, item); 804 m_items.Add(item.ItemID, item);
659 805 m_items.LockItemsForWrite(false);
660 if (allowedDrop) 806 if (allowedDrop)
661 m_part.TriggerScriptChangedEvent(Changed.ALLOWED_DROP); 807 m_part.TriggerScriptChangedEvent(Changed.ALLOWED_DROP);
662 else 808 else
663 m_part.TriggerScriptChangedEvent(Changed.INVENTORY); 809 m_part.TriggerScriptChangedEvent(Changed.INVENTORY);
664 810
665 m_inventorySerial++; 811 m_inventorySerial++;
666 //m_inventorySerial += 2; 812 //m_inventorySerial += 2;
667 HasInventoryChanged = true; 813 HasInventoryChanged = true;
@@ -677,15 +823,15 @@ namespace OpenSim.Region.Framework.Scenes
677 /// <param name="items"></param> 823 /// <param name="items"></param>
678 public void RestoreInventoryItems(ICollection<TaskInventoryItem> items) 824 public void RestoreInventoryItems(ICollection<TaskInventoryItem> items)
679 { 825 {
680 lock (m_items) 826 m_items.LockItemsForWrite(true);
827 foreach (TaskInventoryItem item in items)
681 { 828 {
682 foreach (TaskInventoryItem item in items) 829 m_items.Add(item.ItemID, item);
683 { 830// m_part.TriggerScriptChangedEvent(Changed.INVENTORY);
684 m_items.Add(item.ItemID, item);
685// m_part.TriggerScriptChangedEvent(Changed.INVENTORY);
686 }
687 m_inventorySerial++;
688 } 831 }
832 m_items.LockItemsForWrite(false);
833
834 m_inventorySerial++;
689 } 835 }
690 836
691 /// <summary> 837 /// <summary>
@@ -696,23 +842,24 @@ namespace OpenSim.Region.Framework.Scenes
696 public TaskInventoryItem GetInventoryItem(UUID itemId) 842 public TaskInventoryItem GetInventoryItem(UUID itemId)
697 { 843 {
698 TaskInventoryItem item; 844 TaskInventoryItem item;
699 845 m_items.LockItemsForRead(true);
700 lock (m_items) 846 m_items.TryGetValue(itemId, out item);
701 m_items.TryGetValue(itemId, out item); 847 m_items.LockItemsForRead(false);
702
703 return item; 848 return item;
704 } 849 }
705 850
706 public TaskInventoryItem GetInventoryItem(string name) 851 public TaskInventoryItem GetInventoryItem(string name)
707 { 852 {
708 lock (m_items) 853 m_items.LockItemsForRead(true);
854 foreach (TaskInventoryItem item in m_items.Values)
709 { 855 {
710 foreach (TaskInventoryItem item in m_items.Values) 856 if (item.Name == name)
711 { 857 {
712 if (item.Name == name) 858 m_items.LockItemsForRead(false);
713 return item; 859 return item;
714 } 860 }
715 } 861 }
862 m_items.LockItemsForRead(false);
716 863
717 return null; 864 return null;
718 } 865 }
@@ -721,15 +868,16 @@ namespace OpenSim.Region.Framework.Scenes
721 { 868 {
722 List<TaskInventoryItem> items = new List<TaskInventoryItem>(); 869 List<TaskInventoryItem> items = new List<TaskInventoryItem>();
723 870
724 lock (m_items) 871 m_items.LockItemsForRead(true);
872
873 foreach (TaskInventoryItem item in m_items.Values)
725 { 874 {
726 foreach (TaskInventoryItem item in m_items.Values) 875 if (item.Name == name)
727 { 876 items.Add(item);
728 if (item.Name == name)
729 items.Add(item);
730 }
731 } 877 }
732 878
879 m_items.LockItemsForRead(false);
880
733 return items; 881 return items;
734 } 882 }
735 883
@@ -748,6 +896,10 @@ namespace OpenSim.Region.Framework.Scenes
748 string xmlData = Utils.BytesToString(rezAsset.Data); 896 string xmlData = Utils.BytesToString(rezAsset.Data);
749 SceneObjectGroup group = SceneObjectSerializer.FromOriginalXmlFormat(xmlData); 897 SceneObjectGroup group = SceneObjectSerializer.FromOriginalXmlFormat(xmlData);
750 898
899 group.RootPart.AttachPoint = group.RootPart.Shape.State;
900 group.RootPart.AttachOffset = group.AbsolutePosition;
901 group.RootPart.AttachRotation = group.GroupRotation;
902
751 group.ResetIDs(); 903 group.ResetIDs();
752 904
753 SceneObjectPart rootPart = group.GetPart(group.UUID); 905 SceneObjectPart rootPart = group.GetPart(group.UUID);
@@ -822,8 +974,9 @@ namespace OpenSim.Region.Framework.Scenes
822 974
823 public bool UpdateInventoryItem(TaskInventoryItem item, bool fireScriptEvents, bool considerChanged) 975 public bool UpdateInventoryItem(TaskInventoryItem item, bool fireScriptEvents, bool considerChanged)
824 { 976 {
825 TaskInventoryItem it = GetInventoryItem(item.ItemID); 977 m_items.LockItemsForWrite(true);
826 if (it != null) 978
979 if (m_items.ContainsKey(item.ItemID))
827 { 980 {
828// m_log.DebugFormat("[PRIM INVENTORY]: Updating item {0} in {1}", item.Name, m_part.Name); 981// m_log.DebugFormat("[PRIM INVENTORY]: Updating item {0} in {1}", item.Name, m_part.Name);
829 982
@@ -836,14 +989,10 @@ namespace OpenSim.Region.Framework.Scenes
836 item.GroupID = m_part.GroupID; 989 item.GroupID = m_part.GroupID;
837 990
838 if (item.AssetID == UUID.Zero) 991 if (item.AssetID == UUID.Zero)
839 item.AssetID = it.AssetID; 992 item.AssetID = m_items[item.ItemID].AssetID;
840 993
841 lock (m_items) 994 m_items[item.ItemID] = item;
842 { 995 m_inventorySerial++;
843 m_items[item.ItemID] = item;
844 m_inventorySerial++;
845 }
846
847 if (fireScriptEvents) 996 if (fireScriptEvents)
848 m_part.TriggerScriptChangedEvent(Changed.INVENTORY); 997 m_part.TriggerScriptChangedEvent(Changed.INVENTORY);
849 998
@@ -852,7 +1001,7 @@ namespace OpenSim.Region.Framework.Scenes
852 HasInventoryChanged = true; 1001 HasInventoryChanged = true;
853 m_part.ParentGroup.HasGroupChanged = true; 1002 m_part.ParentGroup.HasGroupChanged = true;
854 } 1003 }
855 1004 m_items.LockItemsForWrite(false);
856 return true; 1005 return true;
857 } 1006 }
858 else 1007 else
@@ -863,8 +1012,9 @@ namespace OpenSim.Region.Framework.Scenes
863 item.ItemID, m_part.Name, m_part.UUID, 1012 item.ItemID, m_part.Name, m_part.UUID,
864 m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName); 1013 m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName);
865 } 1014 }
866 return false; 1015 m_items.LockItemsForWrite(false);
867 1016
1017 return false;
868 } 1018 }
869 1019
870 /// <summary> 1020 /// <summary>
@@ -875,43 +1025,59 @@ namespace OpenSim.Region.Framework.Scenes
875 /// in this prim's inventory.</returns> 1025 /// in this prim's inventory.</returns>
876 public int RemoveInventoryItem(UUID itemID) 1026 public int RemoveInventoryItem(UUID itemID)
877 { 1027 {
878 TaskInventoryItem item = GetInventoryItem(itemID); 1028 m_items.LockItemsForRead(true);
879 if (item != null) 1029
1030 if (m_items.ContainsKey(itemID))
880 { 1031 {
881 int type = m_items[itemID].InvType; 1032 int type = m_items[itemID].InvType;
1033 m_items.LockItemsForRead(false);
882 if (type == 10) // Script 1034 if (type == 10) // Script
883 { 1035 {
884 m_part.RemoveScriptEvents(itemID);
885 m_part.ParentGroup.Scene.EventManager.TriggerRemoveScript(m_part.LocalId, itemID); 1036 m_part.ParentGroup.Scene.EventManager.TriggerRemoveScript(m_part.LocalId, itemID);
886 } 1037 }
1038 m_items.LockItemsForWrite(true);
887 m_items.Remove(itemID); 1039 m_items.Remove(itemID);
1040 m_items.LockItemsForWrite(false);
888 m_inventorySerial++; 1041 m_inventorySerial++;
889 m_part.TriggerScriptChangedEvent(Changed.INVENTORY); 1042 m_part.TriggerScriptChangedEvent(Changed.INVENTORY);
890 1043
891 HasInventoryChanged = true; 1044 HasInventoryChanged = true;
892 m_part.ParentGroup.HasGroupChanged = true; 1045 m_part.ParentGroup.HasGroupChanged = true;
893 1046
894 if (!ContainsScripts()) 1047 int scriptcount = 0;
1048 m_items.LockItemsForRead(true);
1049 foreach (TaskInventoryItem item in m_items.Values)
1050 {
1051 if (item.Type == 10)
1052 {
1053 scriptcount++;
1054 }
1055 }
1056 m_items.LockItemsForRead(false);
1057
1058
1059 if (scriptcount <= 0)
1060 {
895 m_part.RemFlag(PrimFlags.Scripted); 1061 m_part.RemFlag(PrimFlags.Scripted);
1062 }
896 1063
897 m_part.ScheduleFullUpdate(); 1064 m_part.ScheduleFullUpdate();
898 1065
899 return type; 1066 return type;
900
901 } 1067 }
902 else 1068 else
903 { 1069 {
1070 m_items.LockItemsForRead(false);
904 m_log.ErrorFormat( 1071 m_log.ErrorFormat(
905 "[PRIM INVENTORY]: " + 1072 "[PRIM INVENTORY]: " +
906 "Tried to remove item ID {0} from prim {1}, {2} at {3} in {4} but the item does not exist in this inventory", 1073 "Tried to remove item ID {0} from prim {1}, {2} but the item does not exist in this inventory",
907 itemID, m_part.Name, m_part.UUID, 1074 itemID, m_part.Name, m_part.UUID);
908 m_part.AbsolutePosition, m_part.ParentGroup.Scene.RegionInfo.RegionName);
909 } 1075 }
910 1076
911 return -1; 1077 return -1;
912 } 1078 }
913 1079
914 private bool CreateInventoryFile() 1080 private bool CreateInventoryFileName()
915 { 1081 {
916// m_log.DebugFormat( 1082// m_log.DebugFormat(
917// "[PRIM INVENTORY]: Creating inventory file for {0} {1} {2}, serial {3}", 1083// "[PRIM INVENTORY]: Creating inventory file for {0} {1} {2}, serial {3}",
@@ -920,70 +1086,12 @@ namespace OpenSim.Region.Framework.Scenes
920 if (m_inventoryFileName == String.Empty || 1086 if (m_inventoryFileName == String.Empty ||
921 m_inventoryFileNameSerial < m_inventorySerial) 1087 m_inventoryFileNameSerial < m_inventorySerial)
922 { 1088 {
923 // Something changed, we need to create a new file
924 m_inventoryFileName = "inventory_" + UUID.Random().ToString() + ".tmp"; 1089 m_inventoryFileName = "inventory_" + UUID.Random().ToString() + ".tmp";
925 m_inventoryFileNameSerial = m_inventorySerial; 1090 m_inventoryFileNameSerial = m_inventorySerial;
926 1091
927 InventoryStringBuilder invString = new InventoryStringBuilder(m_part.UUID, UUID.Zero);
928
929 lock (m_items)
930 {
931 foreach (TaskInventoryItem item in m_items.Values)
932 {
933// m_log.DebugFormat(
934// "[PRIM INVENTORY]: Adding item {0} {1} for serial {2} on prim {3} {4} {5}",
935// item.Name, item.ItemID, m_inventorySerial, m_part.Name, m_part.UUID, m_part.LocalId);
936
937 UUID ownerID = item.OwnerID;
938 uint everyoneMask = 0;
939 uint baseMask = item.BasePermissions;
940 uint ownerMask = item.CurrentPermissions;
941 uint groupMask = item.GroupPermissions;
942
943 invString.AddItemStart();
944 invString.AddNameValueLine("item_id", item.ItemID.ToString());
945 invString.AddNameValueLine("parent_id", m_part.UUID.ToString());
946
947 invString.AddPermissionsStart();
948
949 invString.AddNameValueLine("base_mask", Utils.UIntToHexString(baseMask));
950 invString.AddNameValueLine("owner_mask", Utils.UIntToHexString(ownerMask));
951 invString.AddNameValueLine("group_mask", Utils.UIntToHexString(groupMask));
952 invString.AddNameValueLine("everyone_mask", Utils.UIntToHexString(everyoneMask));
953 invString.AddNameValueLine("next_owner_mask", Utils.UIntToHexString(item.NextPermissions));
954
955 invString.AddNameValueLine("creator_id", item.CreatorID.ToString());
956 invString.AddNameValueLine("owner_id", ownerID.ToString());
957
958 invString.AddNameValueLine("last_owner_id", item.LastOwnerID.ToString());
959
960 invString.AddNameValueLine("group_id", item.GroupID.ToString());
961 invString.AddSectionEnd();
962
963 invString.AddNameValueLine("asset_id", item.AssetID.ToString());
964 invString.AddNameValueLine("type", Utils.AssetTypeToString((AssetType)item.Type));
965 invString.AddNameValueLine("inv_type", Utils.InventoryTypeToString((InventoryType)item.InvType));
966 invString.AddNameValueLine("flags", Utils.UIntToHexString(item.Flags));
967
968 invString.AddSaleStart();
969 invString.AddNameValueLine("sale_type", "not");
970 invString.AddNameValueLine("sale_price", "0");
971 invString.AddSectionEnd();
972
973 invString.AddNameValueLine("name", item.Name + "|");
974 invString.AddNameValueLine("desc", item.Description + "|");
975
976 invString.AddNameValueLine("creation_date", item.CreationDate.ToString());
977 invString.AddSectionEnd();
978 }
979 }
980
981 m_inventoryFileData = Utils.StringToBytes(invString.BuildString);
982
983 return true; 1092 return true;
984 } 1093 }
985 1094
986 // No need to recreate, the existing file is fine
987 return false; 1095 return false;
988 } 1096 }
989 1097
@@ -993,43 +1101,110 @@ namespace OpenSim.Region.Framework.Scenes
993 /// <param name="xferManager"></param> 1101 /// <param name="xferManager"></param>
994 public void RequestInventoryFile(IClientAPI client, IXfer xferManager) 1102 public void RequestInventoryFile(IClientAPI client, IXfer xferManager)
995 { 1103 {
996 lock (m_items) 1104 bool changed = CreateInventoryFileName();
997 {
998 // Don't send a inventory xfer name if there are no items. Doing so causes viewer 3 to crash when rezzing
999 // a new script if any previous deletion has left the prim inventory empty.
1000 if (m_items.Count == 0) // No inventory
1001 {
1002// m_log.DebugFormat(
1003// "[PRIM INVENTORY]: Not sending inventory data for part {0} {1} {2} for {3} since no items",
1004// m_part.Name, m_part.LocalId, m_part.UUID, client.Name);
1005 1105
1006 client.SendTaskInventory(m_part.UUID, 0, new byte[0]); 1106 bool includeAssets = false;
1007 return; 1107 if (m_part.ParentGroup.Scene.Permissions.CanEditObjectInventory(m_part.UUID, client.AgentId))
1008 } 1108 includeAssets = true;
1109
1110 if (m_inventoryPrivileged != includeAssets)
1111 changed = true;
1112
1113 InventoryStringBuilder invString = new InventoryStringBuilder(m_part.UUID, UUID.Zero);
1114
1115 Items.LockItemsForRead(true);
1116
1117 if (m_inventorySerial == 0) // No inventory
1118 {
1119 client.SendTaskInventory(m_part.UUID, 0, new byte[0]);
1120 Items.LockItemsForRead(false);
1121 return;
1122 }
1009 1123
1010 CreateInventoryFile(); 1124 if (m_items.Count == 0) // No inventory
1125 {
1126 client.SendTaskInventory(m_part.UUID, 0, new byte[0]);
1127 Items.LockItemsForRead(false);
1128 return;
1129 }
1011 1130
1012 // In principle, we should only do the rest if the inventory changed; 1131 if (!changed)
1013 // by sending m_inventorySerial to the client, it ought to know 1132 {
1014 // that nothing changed and that it doesn't need to request the file.
1015 // Unfortunately, it doesn't look like the client optimizes this;
1016 // the client seems to always come back and request the Xfer,
1017 // no matter what value m_inventorySerial has.
1018 // FIXME: Could probably be > 0 here rather than > 2
1019 if (m_inventoryFileData.Length > 2) 1133 if (m_inventoryFileData.Length > 2)
1020 { 1134 {
1021 // Add the file for Xfer 1135 xferManager.AddNewFile(m_inventoryFileName,
1022 // m_log.DebugFormat( 1136 m_inventoryFileData);
1023 // "[PRIM INVENTORY]: Adding inventory file {0} (length {1}) for transfer on {2} {3} {4}", 1137 client.SendTaskInventory(m_part.UUID, (short)m_inventorySerial,
1024 // m_inventoryFileName, m_inventoryFileData.Length, m_part.Name, m_part.UUID, m_part.LocalId); 1138 Util.StringToBytes256(m_inventoryFileName));
1025 1139
1026 xferManager.AddNewFile(m_inventoryFileName, m_inventoryFileData); 1140 Items.LockItemsForRead(false);
1141 return;
1027 } 1142 }
1028
1029 // Tell the client we're ready to Xfer the file
1030 client.SendTaskInventory(m_part.UUID, (short)m_inventorySerial,
1031 Util.StringToBytes256(m_inventoryFileName));
1032 } 1143 }
1144
1145 m_inventoryPrivileged = includeAssets;
1146
1147 foreach (TaskInventoryItem item in m_items.Values)
1148 {
1149 UUID ownerID = item.OwnerID;
1150 uint everyoneMask = 0;
1151 uint baseMask = item.BasePermissions;
1152 uint ownerMask = item.CurrentPermissions;
1153 uint groupMask = item.GroupPermissions;
1154
1155 invString.AddItemStart();
1156 invString.AddNameValueLine("item_id", item.ItemID.ToString());
1157 invString.AddNameValueLine("parent_id", m_part.UUID.ToString());
1158
1159 invString.AddPermissionsStart();
1160
1161 invString.AddNameValueLine("base_mask", Utils.UIntToHexString(baseMask));
1162 invString.AddNameValueLine("owner_mask", Utils.UIntToHexString(ownerMask));
1163 invString.AddNameValueLine("group_mask", Utils.UIntToHexString(groupMask));
1164 invString.AddNameValueLine("everyone_mask", Utils.UIntToHexString(everyoneMask));
1165 invString.AddNameValueLine("next_owner_mask", Utils.UIntToHexString(item.NextPermissions));
1166
1167 invString.AddNameValueLine("creator_id", item.CreatorID.ToString());
1168 invString.AddNameValueLine("owner_id", ownerID.ToString());
1169
1170 invString.AddNameValueLine("last_owner_id", item.LastOwnerID.ToString());
1171
1172 invString.AddNameValueLine("group_id", item.GroupID.ToString());
1173 invString.AddSectionEnd();
1174
1175 if (includeAssets)
1176 invString.AddNameValueLine("asset_id", item.AssetID.ToString());
1177 else
1178 invString.AddNameValueLine("asset_id", UUID.Zero.ToString());
1179 invString.AddNameValueLine("type", Utils.AssetTypeToString((AssetType)item.Type));
1180 invString.AddNameValueLine("inv_type", Utils.InventoryTypeToString((InventoryType)item.InvType));
1181 invString.AddNameValueLine("flags", Utils.UIntToHexString(item.Flags));
1182
1183 invString.AddSaleStart();
1184 invString.AddNameValueLine("sale_type", "not");
1185 invString.AddNameValueLine("sale_price", "0");
1186 invString.AddSectionEnd();
1187
1188 invString.AddNameValueLine("name", item.Name + "|");
1189 invString.AddNameValueLine("desc", item.Description + "|");
1190
1191 invString.AddNameValueLine("creation_date", item.CreationDate.ToString());
1192 invString.AddSectionEnd();
1193 }
1194
1195 Items.LockItemsForRead(false);
1196
1197 m_inventoryFileData = Utils.StringToBytes(invString.BuildString);
1198
1199 if (m_inventoryFileData.Length > 2)
1200 {
1201 xferManager.AddNewFile(m_inventoryFileName, m_inventoryFileData);
1202 client.SendTaskInventory(m_part.UUID, (short)m_inventorySerial,
1203 Util.StringToBytes256(m_inventoryFileName));
1204 return;
1205 }
1206
1207 client.SendTaskInventory(m_part.UUID, 0, new byte[0]);
1033 } 1208 }
1034 1209
1035 /// <summary> 1210 /// <summary>
@@ -1038,13 +1213,19 @@ namespace OpenSim.Region.Framework.Scenes
1038 /// <param name="datastore"></param> 1213 /// <param name="datastore"></param>
1039 public void ProcessInventoryBackup(ISimulationDataService datastore) 1214 public void ProcessInventoryBackup(ISimulationDataService datastore)
1040 { 1215 {
1041 if (HasInventoryChanged) 1216// Removed this because linking will cause an immediate delete of the new
1042 { 1217// child prim from the database and the subsequent storing of the prim sees
1043 HasInventoryChanged = false; 1218// the inventory of it as unchanged and doesn't store it at all. The overhead
1044 List<TaskInventoryItem> items = GetInventoryItems(); 1219// of storing prim inventory needlessly is much less than the aggravation
1045 datastore.StorePrimInventory(m_part.UUID, items); 1220// of prim inventory loss.
1221// if (HasInventoryChanged)
1222// {
1223 Items.LockItemsForRead(true);
1224 datastore.StorePrimInventory(m_part.UUID, Items.Values);
1225 Items.LockItemsForRead(false);
1046 1226
1047 } 1227 HasInventoryChanged = false;
1228// }
1048 } 1229 }
1049 1230
1050 public class InventoryStringBuilder 1231 public class InventoryStringBuilder
@@ -1110,87 +1291,63 @@ namespace OpenSim.Region.Framework.Scenes
1110 { 1291 {
1111 uint mask=0x7fffffff; 1292 uint mask=0x7fffffff;
1112 1293
1113 lock (m_items) 1294 foreach (TaskInventoryItem item in m_items.Values)
1114 { 1295 {
1115 foreach (TaskInventoryItem item in m_items.Values) 1296 if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Copy) == 0)
1297 mask &= ~((uint)PermissionMask.Copy >> 13);
1298 if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Transfer) == 0)
1299 mask &= ~((uint)PermissionMask.Transfer >> 13);
1300 if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Modify) == 0)
1301 mask &= ~((uint)PermissionMask.Modify >> 13);
1302
1303 if (item.InvType == (int)InventoryType.Object)
1116 { 1304 {
1117 if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Copy) == 0) 1305 if ((item.CurrentPermissions & ((uint)PermissionMask.Copy >> 13)) == 0)
1118 mask &= ~((uint)PermissionMask.Copy >> 13); 1306 mask &= ~((uint)PermissionMask.Copy >> 13);
1119 if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Transfer) == 0) 1307 if ((item.CurrentPermissions & ((uint)PermissionMask.Transfer >> 13)) == 0)
1120 mask &= ~((uint)PermissionMask.Transfer >> 13); 1308 mask &= ~((uint)PermissionMask.Transfer >> 13);
1121 if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Modify) == 0) 1309 if ((item.CurrentPermissions & ((uint)PermissionMask.Modify >> 13)) == 0)
1122 mask &= ~((uint)PermissionMask.Modify >> 13); 1310 mask &= ~((uint)PermissionMask.Modify >> 13);
1123
1124 if (item.InvType != (int)InventoryType.Object)
1125 {
1126 if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Copy) == 0)
1127 mask &= ~((uint)PermissionMask.Copy >> 13);
1128 if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Transfer) == 0)
1129 mask &= ~((uint)PermissionMask.Transfer >> 13);
1130 if ((item.CurrentPermissions & item.NextPermissions & (uint)PermissionMask.Modify) == 0)
1131 mask &= ~((uint)PermissionMask.Modify >> 13);
1132 }
1133 else
1134 {
1135 if ((item.CurrentPermissions & ((uint)PermissionMask.Copy >> 13)) == 0)
1136 mask &= ~((uint)PermissionMask.Copy >> 13);
1137 if ((item.CurrentPermissions & ((uint)PermissionMask.Transfer >> 13)) == 0)
1138 mask &= ~((uint)PermissionMask.Transfer >> 13);
1139 if ((item.CurrentPermissions & ((uint)PermissionMask.Modify >> 13)) == 0)
1140 mask &= ~((uint)PermissionMask.Modify >> 13);
1141 }
1142
1143 if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0)
1144 mask &= ~(uint)PermissionMask.Copy;
1145 if ((item.CurrentPermissions & (uint)PermissionMask.Transfer) == 0)
1146 mask &= ~(uint)PermissionMask.Transfer;
1147 if ((item.CurrentPermissions & (uint)PermissionMask.Modify) == 0)
1148 mask &= ~(uint)PermissionMask.Modify;
1149 } 1311 }
1312
1313 if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0)
1314 mask &= ~(uint)PermissionMask.Copy;
1315 if ((item.CurrentPermissions & (uint)PermissionMask.Transfer) == 0)
1316 mask &= ~(uint)PermissionMask.Transfer;
1317 if ((item.CurrentPermissions & (uint)PermissionMask.Modify) == 0)
1318 mask &= ~(uint)PermissionMask.Modify;
1150 } 1319 }
1151
1152 return mask; 1320 return mask;
1153 } 1321 }
1154 1322
1155 public void ApplyNextOwnerPermissions() 1323 public void ApplyNextOwnerPermissions()
1156 { 1324 {
1157 lock (m_items) 1325 foreach (TaskInventoryItem item in m_items.Values)
1158 { 1326 {
1159 foreach (TaskInventoryItem item in m_items.Values) 1327 if (item.InvType == (int)InventoryType.Object && (item.CurrentPermissions & 7) != 0)
1160 { 1328 {
1161// m_log.DebugFormat ( 1329 if ((item.CurrentPermissions & ((uint)PermissionMask.Copy >> 13)) == 0)
1162// "[SCENE OBJECT PART INVENTORY]: Applying next permissions {0} to {1} in {2} with current {3}, base {4}, everyone {5}", 1330 item.CurrentPermissions &= ~(uint)PermissionMask.Copy;
1163// item.NextPermissions, item.Name, m_part.Name, item.CurrentPermissions, item.BasePermissions, item.EveryonePermissions); 1331 if ((item.CurrentPermissions & ((uint)PermissionMask.Transfer >> 13)) == 0)
1164 1332 item.CurrentPermissions &= ~(uint)PermissionMask.Transfer;
1165 if (item.InvType == (int)InventoryType.Object && (item.CurrentPermissions & 7) != 0) 1333 if ((item.CurrentPermissions & ((uint)PermissionMask.Modify >> 13)) == 0)
1166 { 1334 item.CurrentPermissions &= ~(uint)PermissionMask.Modify;
1167 if ((item.CurrentPermissions & ((uint)PermissionMask.Copy >> 13)) == 0)
1168 item.CurrentPermissions &= ~(uint)PermissionMask.Copy;
1169 if ((item.CurrentPermissions & ((uint)PermissionMask.Transfer >> 13)) == 0)
1170 item.CurrentPermissions &= ~(uint)PermissionMask.Transfer;
1171 if ((item.CurrentPermissions & ((uint)PermissionMask.Modify >> 13)) == 0)
1172 item.CurrentPermissions &= ~(uint)PermissionMask.Modify;
1173 }
1174
1175 item.CurrentPermissions &= item.NextPermissions;
1176 item.BasePermissions &= item.NextPermissions;
1177 item.EveryonePermissions &= item.NextPermissions;
1178 item.OwnerChanged = true;
1179 item.PermsMask = 0;
1180 item.PermsGranter = UUID.Zero;
1181 } 1335 }
1336 item.CurrentPermissions &= item.NextPermissions;
1337 item.BasePermissions &= item.NextPermissions;
1338 item.EveryonePermissions &= item.NextPermissions;
1339 item.OwnerChanged = true;
1340 item.PermsMask = 0;
1341 item.PermsGranter = UUID.Zero;
1182 } 1342 }
1183 } 1343 }
1184 1344
1185 public void ApplyGodPermissions(uint perms) 1345 public void ApplyGodPermissions(uint perms)
1186 { 1346 {
1187 lock (m_items) 1347 foreach (TaskInventoryItem item in m_items.Values)
1188 { 1348 {
1189 foreach (TaskInventoryItem item in m_items.Values) 1349 item.CurrentPermissions = perms;
1190 { 1350 item.BasePermissions = perms;
1191 item.CurrentPermissions = perms;
1192 item.BasePermissions = perms;
1193 }
1194 } 1351 }
1195 1352
1196 m_inventorySerial++; 1353 m_inventorySerial++;
@@ -1203,14 +1360,11 @@ namespace OpenSim.Region.Framework.Scenes
1203 /// <returns></returns> 1360 /// <returns></returns>
1204 public bool ContainsScripts() 1361 public bool ContainsScripts()
1205 { 1362 {
1206 lock (m_items) 1363 foreach (TaskInventoryItem item in m_items.Values)
1207 { 1364 {
1208 foreach (TaskInventoryItem item in m_items.Values) 1365 if (item.InvType == (int)InventoryType.LSL)
1209 { 1366 {
1210 if (item.InvType == (int)InventoryType.LSL) 1367 return true;
1211 {
1212 return true;
1213 }
1214 } 1368 }
1215 } 1369 }
1216 1370
@@ -1224,17 +1378,15 @@ namespace OpenSim.Region.Framework.Scenes
1224 public int ScriptCount() 1378 public int ScriptCount()
1225 { 1379 {
1226 int count = 0; 1380 int count = 0;
1227 lock (m_items) 1381 Items.LockItemsForRead(true);
1382 foreach (TaskInventoryItem item in m_items.Values)
1228 { 1383 {
1229 foreach (TaskInventoryItem item in m_items.Values) 1384 if (item.InvType == (int)InventoryType.LSL)
1230 { 1385 {
1231 if (item.InvType == (int)InventoryType.LSL) 1386 count++;
1232 {
1233 count++;
1234 }
1235 } 1387 }
1236 } 1388 }
1237 1389 Items.LockItemsForRead(false);
1238 return count; 1390 return count;
1239 } 1391 }
1240 /// <summary> 1392 /// <summary>
@@ -1270,11 +1422,8 @@ namespace OpenSim.Region.Framework.Scenes
1270 { 1422 {
1271 List<UUID> ret = new List<UUID>(); 1423 List<UUID> ret = new List<UUID>();
1272 1424
1273 lock (m_items) 1425 foreach (TaskInventoryItem item in m_items.Values)
1274 { 1426 ret.Add(item.ItemID);
1275 foreach (TaskInventoryItem item in m_items.Values)
1276 ret.Add(item.ItemID);
1277 }
1278 1427
1279 return ret; 1428 return ret;
1280 } 1429 }
@@ -1283,8 +1432,9 @@ namespace OpenSim.Region.Framework.Scenes
1283 { 1432 {
1284 List<TaskInventoryItem> ret = new List<TaskInventoryItem>(); 1433 List<TaskInventoryItem> ret = new List<TaskInventoryItem>();
1285 1434
1286 lock (m_items) 1435 Items.LockItemsForRead(true);
1287 ret = new List<TaskInventoryItem>(m_items.Values); 1436 ret = new List<TaskInventoryItem>(m_items.Values);
1437 Items.LockItemsForRead(false);
1288 1438
1289 return ret; 1439 return ret;
1290 } 1440 }
@@ -1293,18 +1443,24 @@ namespace OpenSim.Region.Framework.Scenes
1293 { 1443 {
1294 List<TaskInventoryItem> ret = new List<TaskInventoryItem>(); 1444 List<TaskInventoryItem> ret = new List<TaskInventoryItem>();
1295 1445
1296 lock (m_items) 1446 Items.LockItemsForRead(true);
1297 { 1447
1298 foreach (TaskInventoryItem item in m_items.Values) 1448 foreach (TaskInventoryItem item in m_items.Values)
1299 if (item.InvType == (int)type) 1449 if (item.InvType == (int)type)
1300 ret.Add(item); 1450 ret.Add(item);
1301 } 1451
1452 Items.LockItemsForRead(false);
1302 1453
1303 return ret; 1454 return ret;
1304 } 1455 }
1305 1456
1306 public Dictionary<UUID, string> GetScriptStates() 1457 public Dictionary<UUID, string> GetScriptStates()
1307 { 1458 {
1459 return GetScriptStates(false);
1460 }
1461
1462 public Dictionary<UUID, string> GetScriptStates(bool oldIDs)
1463 {
1308 Dictionary<UUID, string> ret = new Dictionary<UUID, string>(); 1464 Dictionary<UUID, string> ret = new Dictionary<UUID, string>();
1309 1465
1310 if (m_part.ParentGroup.Scene == null) // Group not in a scene 1466 if (m_part.ParentGroup.Scene == null) // Group not in a scene
@@ -1330,14 +1486,21 @@ namespace OpenSim.Region.Framework.Scenes
1330 string n = e.GetXMLState(item.ItemID); 1486 string n = e.GetXMLState(item.ItemID);
1331 if (n != String.Empty) 1487 if (n != String.Empty)
1332 { 1488 {
1333 if (!ret.ContainsKey(item.ItemID)) 1489 if (oldIDs)
1334 ret[item.ItemID] = n; 1490 {
1491 if (!ret.ContainsKey(item.OldItemID))
1492 ret[item.OldItemID] = n;
1493 }
1494 else
1495 {
1496 if (!ret.ContainsKey(item.ItemID))
1497 ret[item.ItemID] = n;
1498 }
1335 break; 1499 break;
1336 } 1500 }
1337 } 1501 }
1338 } 1502 }
1339 } 1503 }
1340
1341 return ret; 1504 return ret;
1342 } 1505 }
1343 1506
diff --git a/OpenSim/Region/Framework/Scenes/ScenePresence.cs b/OpenSim/Region/Framework/Scenes/ScenePresence.cs
index 215a689..0ab267a 100644
--- a/OpenSim/Region/Framework/Scenes/ScenePresence.cs
+++ b/OpenSim/Region/Framework/Scenes/ScenePresence.cs
@@ -63,6 +63,7 @@ namespace OpenSim.Region.Framework.Scenes
63 63
64 struct ScriptControllers 64 struct ScriptControllers
65 { 65 {
66 public UUID objectID;
66 public UUID itemID; 67 public UUID itemID;
67 public ScriptControlled ignoreControls; 68 public ScriptControlled ignoreControls;
68 public ScriptControlled eventControls; 69 public ScriptControlled eventControls;
@@ -99,7 +100,7 @@ namespace OpenSim.Region.Framework.Scenes
99 /// rotation, prim cut, prim twist, prim taper, and prim shear. See mantis 100 /// rotation, prim cut, prim twist, prim taper, and prim shear. See mantis
100 /// issue #1716 101 /// issue #1716
101 /// </summary> 102 /// </summary>
102 public static readonly Vector3 SIT_TARGET_ADJUSTMENT = new Vector3(0.0f, 0.0f, 0.418f); 103 public static readonly Vector3 SIT_TARGET_ADJUSTMENT = new Vector3(0.0f, 0.0f, 0.4f);
103 104
104 /// <summary> 105 /// <summary>
105 /// Movement updates for agents in neighboring regions are sent directly to clients. 106 /// Movement updates for agents in neighboring regions are sent directly to clients.
@@ -139,6 +140,8 @@ namespace OpenSim.Region.Framework.Scenes
139 private Vector3 m_lastPosition; 140 private Vector3 m_lastPosition;
140 private Quaternion m_lastRotation; 141 private Quaternion m_lastRotation;
141 private Vector3 m_lastVelocity; 142 private Vector3 m_lastVelocity;
143 private Vector3 m_lastSize = new Vector3(0.45f,0.6f,1.9f);
144
142 145
143 private Vector3? m_forceToApply; 146 private Vector3? m_forceToApply;
144 private int m_userFlags; 147 private int m_userFlags;
@@ -171,6 +174,7 @@ namespace OpenSim.Region.Framework.Scenes
171// private int m_lastColCount = -1; //KF: Look for Collision chnages 174// private int m_lastColCount = -1; //KF: Look for Collision chnages
172// private int m_updateCount = 0; //KF: Update Anims for a while 175// private int m_updateCount = 0; //KF: Update Anims for a while
173// private static readonly int UPDATE_COUNT = 10; // how many frames to update for 176// private static readonly int UPDATE_COUNT = 10; // how many frames to update for
177 private List<uint> m_lastColliders = new List<uint>();
174 178
175 private TeleportFlags m_teleportFlags; 179 private TeleportFlags m_teleportFlags;
176 public TeleportFlags TeleportFlags 180 public TeleportFlags TeleportFlags
@@ -226,8 +230,6 @@ namespace OpenSim.Region.Framework.Scenes
226 /// </summary> 230 /// </summary>
227 public bool LandAtTarget { get; private set; } 231 public bool LandAtTarget { get; private set; }
228 232
229 private bool m_followCamAuto;
230
231 private int m_movementUpdateCount; 233 private int m_movementUpdateCount;
232 private const int NumMovementsBetweenRayCast = 5; 234 private const int NumMovementsBetweenRayCast = 5;
233 235
@@ -235,6 +237,13 @@ namespace OpenSim.Region.Framework.Scenes
235 //private int m_moveToPositionStateStatus; 237 //private int m_moveToPositionStateStatus;
236 //***************************************************** 238 //*****************************************************
237 239
240 private bool m_collisionEventFlag = false;
241 private object m_collisionEventLock = new Object();
242
243 private int m_movementAnimationUpdateCounter = 0;
244
245 private Vector3 m_prevSitOffset;
246
238 protected AvatarAppearance m_appearance; 247 protected AvatarAppearance m_appearance;
239 248
240 public AvatarAppearance Appearance 249 public AvatarAppearance Appearance
@@ -349,6 +358,9 @@ namespace OpenSim.Region.Framework.Scenes
349 /// </summary> 358 /// </summary>
350 protected Vector3 m_lastCameraPosition; 359 protected Vector3 m_lastCameraPosition;
351 360
361 private Vector4 m_lastCameraCollisionPlane = new Vector4(0f, 0f, 0f, 1);
362 private bool m_doingCamRayCast = false;
363
352 public Vector3 CameraPosition { get; set; } 364 public Vector3 CameraPosition { get; set; }
353 365
354 public Quaternion CameraRotation 366 public Quaternion CameraRotation
@@ -429,7 +441,9 @@ namespace OpenSim.Region.Framework.Scenes
429 get { return (IClientCore)ControllingClient; } 441 get { return (IClientCore)ControllingClient; }
430 } 442 }
431 443
432 public Vector3 ParentPosition { get; set; } 444 public UUID COF { get; set; }
445
446// public Vector3 ParentPosition { get; set; }
433 447
434 /// <summary> 448 /// <summary>
435 /// Position of this avatar relative to the region the avatar is in 449 /// Position of this avatar relative to the region the avatar is in
@@ -490,7 +504,7 @@ namespace OpenSim.Region.Framework.Scenes
490 if (ParentID == 0) 504 if (ParentID == 0)
491 { 505 {
492 m_pos = value; 506 m_pos = value;
493 ParentPosition = Vector3.Zero; 507// ParentPosition = Vector3.Zero;
494 } 508 }
495 509
496 //m_log.DebugFormat( 510 //m_log.DebugFormat(
@@ -559,7 +573,24 @@ namespace OpenSim.Region.Framework.Scenes
559// Scene.RegionInfo.RegionName, Name, m_velocity); 573// Scene.RegionInfo.RegionName, Name, m_velocity);
560 } 574 }
561 } 575 }
576/*
577 public override Vector3 AngularVelocity
578 {
579 get
580 {
581 if (PhysicsActor != null)
582 {
583 m_rotationalvelocity = PhysicsActor.RotationalVelocity;
562 584
585 // m_log.DebugFormat(
586 // "[SCENE PRESENCE]: Set velocity {0} for {1} in {2} via getting Velocity!",
587 // m_velocity, Name, Scene.RegionInfo.RegionName);
588 }
589
590 return m_rotationalvelocity;
591 }
592 }
593*/
563 private Quaternion m_bodyRot = Quaternion.Identity; 594 private Quaternion m_bodyRot = Quaternion.Identity;
564 595
565 /// <summary> 596 /// <summary>
@@ -582,8 +613,16 @@ namespace OpenSim.Region.Framework.Scenes
582 m_bodyRot = value; 613 m_bodyRot = value;
583 614
584 if (PhysicsActor != null) 615 if (PhysicsActor != null)
585 PhysicsActor.Orientation = m_bodyRot; 616 {
586 617 try
618 {
619 PhysicsActor.Orientation = m_bodyRot;
620 }
621 catch (Exception e)
622 {
623 m_log.Error("[SCENE PRESENCE]: Orientation " + e.Message);
624 }
625 }
587// m_log.DebugFormat("[SCENE PRESENCE]: Body rot for {0} set to {1}", Name, m_bodyRot); 626// m_log.DebugFormat("[SCENE PRESENCE]: Body rot for {0} set to {1}", Name, m_bodyRot);
588 } 627 }
589 } 628 }
@@ -597,12 +636,20 @@ namespace OpenSim.Region.Framework.Scenes
597 } 636 }
598 637
599 public bool IsChildAgent { get; set; } 638 public bool IsChildAgent { get; set; }
639 public bool IsLoggingIn { get; set; }
600 640
601 /// <summary> 641 /// <summary>
602 /// If the avatar is sitting, the local ID of the prim that it's sitting on. If not sitting then zero. 642 /// If the avatar is sitting, the local ID of the prim that it's sitting on. If not sitting then zero.
603 /// </summary> 643 /// </summary>
604 public uint ParentID { get; set; } 644 public uint ParentID { get; set; }
605 645
646 public UUID ParentUUID
647 {
648 get { return m_parentUUID; }
649 set { m_parentUUID = value; }
650 }
651 private UUID m_parentUUID = UUID.Zero;
652
606 /// <summary> 653 /// <summary>
607 /// Are we sitting on an object? 654 /// Are we sitting on an object?
608 /// </summary> 655 /// </summary>
@@ -752,6 +799,7 @@ namespace OpenSim.Region.Framework.Scenes
752 AttachmentsSyncLock = new Object(); 799 AttachmentsSyncLock = new Object();
753 AllowMovement = true; 800 AllowMovement = true;
754 IsChildAgent = true; 801 IsChildAgent = true;
802 IsLoggingIn = false;
755 m_sendCoarseLocationsMethod = SendCoarseLocationsDefault; 803 m_sendCoarseLocationsMethod = SendCoarseLocationsDefault;
756 Animator = new ScenePresenceAnimator(this); 804 Animator = new ScenePresenceAnimator(this);
757 PresenceType = type; 805 PresenceType = type;
@@ -795,6 +843,33 @@ namespace OpenSim.Region.Framework.Scenes
795 Appearance = appearance; 843 Appearance = appearance;
796 } 844 }
797 845
846 private void RegionHeartbeatEnd(Scene scene)
847 {
848 if (IsChildAgent)
849 return;
850
851 m_movementAnimationUpdateCounter ++;
852 if (m_movementAnimationUpdateCounter >= 2)
853 {
854 m_movementAnimationUpdateCounter = 0;
855 if (Animator != null)
856 {
857 // If the parentID == 0 we are not sitting
858 // if !SitGournd then we are not sitting on the ground
859 // Fairly straightforward, now here comes the twist
860 // if ParentUUID is NOT UUID.Zero, we are looking to
861 // be sat on an object that isn't there yet. Should
862 // be treated as if sat.
863 if(ParentID == 0 && !SitGround && ParentUUID == UUID.Zero) // skip it if sitting
864 Animator.UpdateMovementAnimations();
865 }
866 else
867 {
868 m_scene.EventManager.OnRegionHeartbeatEnd -= RegionHeartbeatEnd;
869 }
870 }
871 }
872
798 public void RegisterToEvents() 873 public void RegisterToEvents()
799 { 874 {
800 ControllingClient.OnCompleteMovementToRegion += CompleteMovement; 875 ControllingClient.OnCompleteMovementToRegion += CompleteMovement;
@@ -804,8 +879,10 @@ namespace OpenSim.Region.Framework.Scenes
804 ControllingClient.OnSetAlwaysRun += HandleSetAlwaysRun; 879 ControllingClient.OnSetAlwaysRun += HandleSetAlwaysRun;
805 ControllingClient.OnStartAnim += HandleStartAnim; 880 ControllingClient.OnStartAnim += HandleStartAnim;
806 ControllingClient.OnStopAnim += HandleStopAnim; 881 ControllingClient.OnStopAnim += HandleStopAnim;
882 ControllingClient.OnChangeAnim += avnHandleChangeAnim;
807 ControllingClient.OnForceReleaseControls += HandleForceReleaseControls; 883 ControllingClient.OnForceReleaseControls += HandleForceReleaseControls;
808 ControllingClient.OnAutoPilotGo += MoveToTarget; 884 ControllingClient.OnAutoPilotGo += MoveToTarget;
885 ControllingClient.OnUpdateThrottles += RaiseUpdateThrottles;
809 886
810 // ControllingClient.OnChildAgentStatus += new StatusChange(this.ChildStatusChange); 887 // ControllingClient.OnChildAgentStatus += new StatusChange(this.ChildStatusChange);
811 // ControllingClient.OnStopMovement += new GenericCall2(this.StopMovement); 888 // ControllingClient.OnStopMovement += new GenericCall2(this.StopMovement);
@@ -864,6 +941,38 @@ namespace OpenSim.Region.Framework.Scenes
864 "[SCENE]: Upgrading child to root agent for {0} in {1}", 941 "[SCENE]: Upgrading child to root agent for {0} in {1}",
865 Name, m_scene.RegionInfo.RegionName); 942 Name, m_scene.RegionInfo.RegionName);
866 943
944 if (ParentUUID != UUID.Zero)
945 {
946 m_log.DebugFormat("[SCENE PRESENCE]: Sitting avatar back on prim {0}", ParentUUID);
947 SceneObjectPart part = m_scene.GetSceneObjectPart(ParentUUID);
948 if (part == null)
949 {
950 m_log.ErrorFormat("[SCENE PRESENCE]: Can't find prim {0} to sit on", ParentUUID);
951 }
952 else
953 {
954 part.ParentGroup.AddAvatar(UUID);
955 if (part.SitTargetPosition != Vector3.Zero)
956 part.SitTargetAvatar = UUID;
957// ParentPosition = part.GetWorldPosition();
958 ParentID = part.LocalId;
959 ParentPart = part;
960 m_pos = m_prevSitOffset;
961// pos = ParentPosition;
962 pos = part.GetWorldPosition();
963 }
964 ParentUUID = UUID.Zero;
965
966 IsChildAgent = false;
967
968// Animator.TrySetMovementAnimation("SIT");
969 }
970 else
971 {
972 IsChildAgent = false;
973 IsLoggingIn = false;
974 }
975
867 //m_log.DebugFormat("[SCENE]: known regions in {0}: {1}", Scene.RegionInfo.RegionName, KnownChildRegionHandles.Count); 976 //m_log.DebugFormat("[SCENE]: known regions in {0}: {1}", Scene.RegionInfo.RegionName, KnownChildRegionHandles.Count);
868 977
869 IsChildAgent = false; 978 IsChildAgent = false;
@@ -876,70 +985,106 @@ namespace OpenSim.Region.Framework.Scenes
876 985
877 m_scene.EventManager.TriggerSetRootAgentScene(m_uuid, m_scene); 986 m_scene.EventManager.TriggerSetRootAgentScene(m_uuid, m_scene);
878 987
879 // Moved this from SendInitialData to ensure that Appearance is initialized 988 UUID groupUUID = UUID.Zero;
880 // before the inventory is processed in MakeRootAgent. This fixes a race condition 989 string GroupName = string.Empty;
881 // related to the handling of attachments 990 ulong groupPowers = 0;
882 //m_scene.GetAvatarAppearance(ControllingClient, out Appearance);
883 991
884 if (m_scene.TestBorderCross(pos, Cardinals.E)) 992 // ----------------------------------
993 // Previous Agent Difference - AGNI sends an unsolicited AgentDataUpdate upon root agent status
994 try
885 { 995 {
886 Border crossedBorder = m_scene.GetCrossedBorder(pos, Cardinals.E); 996 if (gm != null)
887 pos.X = crossedBorder.BorderLine.Z - 1; 997 {
998 groupUUID = ControllingClient.ActiveGroupId;
999 GroupRecord record = gm.GetGroupRecord(groupUUID);
1000 if (record != null)
1001 GroupName = record.GroupName;
1002 GroupMembershipData groupMembershipData = gm.GetMembershipData(groupUUID, m_uuid);
1003 if (groupMembershipData != null)
1004 groupPowers = groupMembershipData.GroupPowers;
1005 }
1006 ControllingClient.SendAgentDataUpdate(m_uuid, groupUUID, Firstname, Lastname, groupPowers, GroupName,
1007 Grouptitle);
888 } 1008 }
889 1009 catch (Exception e)
890 if (m_scene.TestBorderCross(pos, Cardinals.N))
891 { 1010 {
892 Border crossedBorder = m_scene.GetCrossedBorder(pos, Cardinals.N); 1011 m_log.Debug("[AGENTUPDATE]: " + e.ToString());
893 pos.Y = crossedBorder.BorderLine.Z - 1;
894 } 1012 }
1013 // ------------------------------------
895 1014
896 CheckAndAdjustLandingPoint(ref pos); 1015 if (ParentID == 0)
897
898 if (pos.X < 0f || pos.Y < 0f || pos.Z < 0f)
899 { 1016 {
900 m_log.WarnFormat( 1017 // Moved this from SendInitialData to ensure that Appearance is initialized
901 "[SCENE PRESENCE]: MakeRootAgent() was given an illegal position of {0} for avatar {1}, {2}. Clamping", 1018 // before the inventory is processed in MakeRootAgent. This fixes a race condition
902 pos, Name, UUID); 1019 // related to the handling of attachments
1020 //m_scene.GetAvatarAppearance(ControllingClient, out Appearance);
1021 if (m_scene.TestBorderCross(pos, Cardinals.E))
1022 {
1023 Border crossedBorder = m_scene.GetCrossedBorder(pos, Cardinals.E);
1024 pos.X = crossedBorder.BorderLine.Z - 1;
1025 }
903 1026
904 if (pos.X < 0f) pos.X = 0f; 1027 if (m_scene.TestBorderCross(pos, Cardinals.N))
905 if (pos.Y < 0f) pos.Y = 0f; 1028 {
906 if (pos.Z < 0f) pos.Z = 0f; 1029 Border crossedBorder = m_scene.GetCrossedBorder(pos, Cardinals.N);
907 } 1030 pos.Y = crossedBorder.BorderLine.Z - 1;
1031 }
908 1032
909 float localAVHeight = 1.56f; 1033 CheckAndAdjustLandingPoint(ref pos);
910 if (Appearance.AvatarHeight > 0)
911 localAVHeight = Appearance.AvatarHeight;
912 1034
913 float posZLimit = 0; 1035 if (pos.X < 0f || pos.Y < 0f || pos.Z < 0f)
1036 {
1037 m_log.WarnFormat(
1038 "[SCENE PRESENCE]: MakeRootAgent() was given an illegal position of {0} for avatar {1}, {2}. Clamping",
1039 pos, Name, UUID);
914 1040
915 if (pos.X < Constants.RegionSize && pos.Y < Constants.RegionSize) 1041 if (pos.X < 0f) pos.X = 0f;
916 posZLimit = (float)m_scene.Heightmap[(int)pos.X, (int)pos.Y]; 1042 if (pos.Y < 0f) pos.Y = 0f;
917 1043 if (pos.Z < 0f) pos.Z = 0f;
918 float newPosZ = posZLimit + localAVHeight / 2; 1044 }
919 if (posZLimit >= (pos.Z - (localAVHeight / 2)) && !(Single.IsInfinity(newPosZ) || Single.IsNaN(newPosZ)))
920 {
921 pos.Z = newPosZ;
922 }
923 AbsolutePosition = pos;
924 1045
925 AddToPhysicalScene(isFlying); 1046 float localAVHeight = 1.56f;
1047 if (Appearance.AvatarHeight > 0)
1048 localAVHeight = Appearance.AvatarHeight;
926 1049
927 // XXX: This is to trigger any secondary teleport needed for a megaregion when the user has teleported to a 1050 float posZLimit = 0;
928 // location outside the 'root region' (the south-west 256x256 corner). This is the earlist we can do it
929 // since it requires a physics actor to be present. If it is left any later, then physics appears to reset
930 // the value to a negative position which does not trigger the border cross.
931 // This may not be the best location for this.
932 CheckForBorderCrossing();
933 1051
934 if (ForceFly) 1052 if (pos.X < Constants.RegionSize && pos.Y < Constants.RegionSize)
935 { 1053 posZLimit = (float)m_scene.Heightmap[(int)pos.X, (int)pos.Y];
936 Flying = true; 1054
937 } 1055 float newPosZ = posZLimit + localAVHeight / 2;
938 else if (FlyDisabled) 1056 if (posZLimit >= (pos.Z - (localAVHeight / 2)) && !(Single.IsInfinity(newPosZ) || Single.IsNaN(newPosZ)))
939 { 1057 {
940 Flying = false; 1058 pos.Z = newPosZ;
941 } 1059 }
1060 AbsolutePosition = pos;
1061
1062 if (m_teleportFlags == TeleportFlags.Default)
1063 {
1064 Vector3 vel = Velocity;
1065 AddToPhysicalScene(isFlying);
1066 if (PhysicsActor != null)
1067 PhysicsActor.SetMomentum(vel);
1068 }
1069 else
1070 AddToPhysicalScene(isFlying);
942 1071
1072 // XXX: This is to trigger any secondary teleport needed for a megaregion when the user has teleported to a
1073 // location outside the 'root region' (the south-west 256x256 corner). This is the earlist we can do it
1074 // since it requires a physics actor to be present. If it is left any later, then physics appears to reset
1075 // the value to a negative position which does not trigger the border cross.
1076 // This may not be the best location for this.
1077 CheckForBorderCrossing();
1078
1079 if (ForceFly)
1080 {
1081 Flying = true;
1082 }
1083 else if (FlyDisabled)
1084 {
1085 Flying = false;
1086 }
1087 }
943 // Don't send an animation pack here, since on a region crossing this will sometimes cause a flying 1088 // Don't send an animation pack here, since on a region crossing this will sometimes cause a flying
944 // avatar to return to the standing position in mid-air. On login it looks like this is being sent 1089 // avatar to return to the standing position in mid-air. On login it looks like this is being sent
945 // elsewhere anyway 1090 // elsewhere anyway
@@ -979,15 +1124,20 @@ namespace OpenSim.Region.Framework.Scenes
979 "[SCENE PRESENCE]: Restarting scripts in attachments for {0} in {1}", Name, Scene.Name); 1124 "[SCENE PRESENCE]: Restarting scripts in attachments for {0} in {1}", Name, Scene.Name);
980 1125
981 // Resume scripts 1126 // Resume scripts
982 foreach (SceneObjectGroup sog in m_attachments) 1127 Util.FireAndForget(delegate(object x) {
983 { 1128 foreach (SceneObjectGroup sog in m_attachments)
984 sog.RootPart.ParentGroup.CreateScriptInstances(0, false, m_scene.DefaultScriptEngine, GetStateSource()); 1129 {
985 sog.ResumeScripts(); 1130 sog.ScheduleGroupForFullUpdate();
986 } 1131 sog.RootPart.ParentGroup.CreateScriptInstances(0, false, m_scene.DefaultScriptEngine, GetStateSource());
1132 sog.ResumeScripts();
1133 }
1134 });
987 } 1135 }
988 } 1136 }
989 } 1137 }
990 1138
1139 SendAvatarDataToAllAgents();
1140
991 // send the animations of the other presences to me 1141 // send the animations of the other presences to me
992 m_scene.ForEachRootScenePresence(delegate(ScenePresence presence) 1142 m_scene.ForEachRootScenePresence(delegate(ScenePresence presence)
993 { 1143 {
@@ -998,9 +1148,12 @@ namespace OpenSim.Region.Framework.Scenes
998 // If we don't reset the movement flag here, an avatar that crosses to a neighbouring sim and returns will 1148 // If we don't reset the movement flag here, an avatar that crosses to a neighbouring sim and returns will
999 // stall on the border crossing since the existing child agent will still have the last movement 1149 // stall on the border crossing since the existing child agent will still have the last movement
1000 // recorded, which stops the input from being processed. 1150 // recorded, which stops the input from being processed.
1151
1001 MovementFlag = 0; 1152 MovementFlag = 0;
1002 1153
1003 m_scene.EventManager.TriggerOnMakeRootAgent(this); 1154 m_scene.EventManager.TriggerOnMakeRootAgent(this);
1155
1156 m_scene.EventManager.OnRegionHeartbeatEnd += RegionHeartbeatEnd;
1004 } 1157 }
1005 1158
1006 public int GetStateSource() 1159 public int GetStateSource()
@@ -1028,12 +1181,16 @@ namespace OpenSim.Region.Framework.Scenes
1028 /// </remarks> 1181 /// </remarks>
1029 public void MakeChildAgent() 1182 public void MakeChildAgent()
1030 { 1183 {
1184 m_scene.EventManager.OnRegionHeartbeatEnd -= RegionHeartbeatEnd;
1185
1031 m_log.DebugFormat("[SCENE PRESENCE]: Making {0} a child agent in {1}", Name, Scene.RegionInfo.RegionName); 1186 m_log.DebugFormat("[SCENE PRESENCE]: Making {0} a child agent in {1}", Name, Scene.RegionInfo.RegionName);
1032 1187
1033 // Reset these so that teleporting in and walking out isn't seen 1188 // Reset these so that teleporting in and walking out isn't seen
1034 // as teleporting back 1189 // as teleporting back
1035 TeleportFlags = TeleportFlags.Default; 1190 TeleportFlags = TeleportFlags.Default;
1036 1191
1192 MovementFlag = 0;
1193
1037 // It looks like Animator is set to null somewhere, and MakeChild 1194 // It looks like Animator is set to null somewhere, and MakeChild
1038 // is called after that. Probably in aborted teleports. 1195 // is called after that. Probably in aborted teleports.
1039 if (Animator == null) 1196 if (Animator == null)
@@ -1041,6 +1198,7 @@ namespace OpenSim.Region.Framework.Scenes
1041 else 1198 else
1042 Animator.ResetAnimations(); 1199 Animator.ResetAnimations();
1043 1200
1201
1044// m_log.DebugFormat( 1202// m_log.DebugFormat(
1045// "[SCENE PRESENCE]: Downgrading root agent {0}, {1} to a child agent in {2}", 1203// "[SCENE PRESENCE]: Downgrading root agent {0}, {1} to a child agent in {2}",
1046// Name, UUID, m_scene.RegionInfo.RegionName); 1204// Name, UUID, m_scene.RegionInfo.RegionName);
@@ -1052,6 +1210,7 @@ namespace OpenSim.Region.Framework.Scenes
1052 IsChildAgent = true; 1210 IsChildAgent = true;
1053 m_scene.SwapRootAgentCount(true); 1211 m_scene.SwapRootAgentCount(true);
1054 RemoveFromPhysicalScene(); 1212 RemoveFromPhysicalScene();
1213 ParentID = 0; // Child agents can't be sitting
1055 1214
1056 // FIXME: Set RegionHandle to the region handle of the scene this agent is moving into 1215 // FIXME: Set RegionHandle to the region handle of the scene this agent is moving into
1057 1216
@@ -1067,9 +1226,9 @@ namespace OpenSim.Region.Framework.Scenes
1067 { 1226 {
1068// PhysicsActor.OnRequestTerseUpdate -= SendTerseUpdateToAllClients; 1227// PhysicsActor.OnRequestTerseUpdate -= SendTerseUpdateToAllClients;
1069 PhysicsActor.OnOutOfBounds -= OutOfBoundsCall; 1228 PhysicsActor.OnOutOfBounds -= OutOfBoundsCall;
1070 m_scene.PhysicsScene.RemoveAvatar(PhysicsActor);
1071 PhysicsActor.UnSubscribeEvents();
1072 PhysicsActor.OnCollisionUpdate -= PhysicsCollisionUpdate; 1229 PhysicsActor.OnCollisionUpdate -= PhysicsCollisionUpdate;
1230 PhysicsActor.UnSubscribeEvents();
1231 m_scene.PhysicsScene.RemoveAvatar(PhysicsActor);
1073 PhysicsActor = null; 1232 PhysicsActor = null;
1074 } 1233 }
1075// else 1234// else
@@ -1086,7 +1245,7 @@ namespace OpenSim.Region.Framework.Scenes
1086 /// <param name="pos"></param> 1245 /// <param name="pos"></param>
1087 public void Teleport(Vector3 pos) 1246 public void Teleport(Vector3 pos)
1088 { 1247 {
1089 TeleportWithMomentum(pos, null); 1248 TeleportWithMomentum(pos, Vector3.Zero);
1090 } 1249 }
1091 1250
1092 public void TeleportWithMomentum(Vector3 pos, Vector3? v) 1251 public void TeleportWithMomentum(Vector3 pos, Vector3? v)
@@ -1110,6 +1269,41 @@ namespace OpenSim.Region.Framework.Scenes
1110 SendTerseUpdateToAllClients(); 1269 SendTerseUpdateToAllClients();
1111 } 1270 }
1112 1271
1272 public void avnLocalTeleport(Vector3 newpos, Vector3? newvel, bool rotateToVelXY)
1273 {
1274 CheckLandingPoint(ref newpos);
1275 AbsolutePosition = newpos;
1276
1277 if (newvel.HasValue)
1278 {
1279 if ((Vector3)newvel == Vector3.Zero)
1280 {
1281 if (PhysicsActor != null)
1282 PhysicsActor.SetMomentum(Vector3.Zero);
1283 m_velocity = Vector3.Zero;
1284 }
1285 else
1286 {
1287 if (PhysicsActor != null)
1288 PhysicsActor.SetMomentum((Vector3)newvel);
1289 m_velocity = (Vector3)newvel;
1290
1291 if (rotateToVelXY)
1292 {
1293 Vector3 lookAt = (Vector3)newvel;
1294 lookAt.Z = 0;
1295 lookAt.Normalize();
1296 ControllingClient.SendLocalTeleport(newpos, lookAt, (uint)TeleportFlags.ViaLocation);
1297 return;
1298 }
1299 }
1300 }
1301
1302 SendTerseUpdateToAllClients();
1303 }
1304
1305
1306
1113 public void StopFlying() 1307 public void StopFlying()
1114 { 1308 {
1115 ControllingClient.StopFlying(this); 1309 ControllingClient.StopFlying(this);
@@ -1279,6 +1473,13 @@ namespace OpenSim.Region.Framework.Scenes
1279 PhysicsActor.Size = new Vector3(0.45f, 0.6f, height); 1473 PhysicsActor.Size = new Vector3(0.45f, 0.6f, height);
1280 } 1474 }
1281 1475
1476 public void SetSize(Vector3 size, float feetoffset)
1477 {
1478 if (PhysicsActor != null && !IsChildAgent)
1479 PhysicsActor.setAvatarSize(size, feetoffset);
1480
1481 }
1482
1282 /// <summary> 1483 /// <summary>
1283 /// Complete Avatar's movement into the region. 1484 /// Complete Avatar's movement into the region.
1284 /// </summary> 1485 /// </summary>
@@ -1298,7 +1499,8 @@ namespace OpenSim.Region.Framework.Scenes
1298 1499
1299 Vector3 look = Velocity; 1500 Vector3 look = Velocity;
1300 1501
1301 if ((look.X == 0) && (look.Y == 0) && (look.Z == 0)) 1502 // if ((look.X == 0) && (look.Y == 0) && (look.Z == 0))
1503 if ((Math.Abs(look.X) < 0.1) && (Math.Abs(look.Y) < 0.1) && (Math.Abs(look.Z) < 0.1))
1302 { 1504 {
1303 look = new Vector3(0.99f, 0.042f, 0); 1505 look = new Vector3(0.99f, 0.042f, 0);
1304 } 1506 }
@@ -1348,13 +1550,15 @@ namespace OpenSim.Region.Framework.Scenes
1348 // Create child agents in neighbouring regions 1550 // Create child agents in neighbouring regions
1349 if (openChildAgents && !IsChildAgent) 1551 if (openChildAgents && !IsChildAgent)
1350 { 1552 {
1553
1351 IEntityTransferModule m_agentTransfer = m_scene.RequestModuleInterface<IEntityTransferModule>(); 1554 IEntityTransferModule m_agentTransfer = m_scene.RequestModuleInterface<IEntityTransferModule>();
1352 if (m_agentTransfer != null) 1555 if (m_agentTransfer != null)
1353 Util.FireAndForget(delegate { m_agentTransfer.EnableChildAgents(this); }); 1556 m_agentTransfer.EnableChildAgents(this);
1354 1557
1355 IFriendsModule friendsModule = m_scene.RequestModuleInterface<IFriendsModule>(); 1558 IFriendsModule friendsModule = m_scene.RequestModuleInterface<IFriendsModule>();
1356 if (friendsModule != null) 1559 if (friendsModule != null)
1357 friendsModule.SendFriendsOnlineIfNeeded(ControllingClient); 1560 friendsModule.SendFriendsOnlineIfNeeded(ControllingClient);
1561
1358 } 1562 }
1359 1563
1360 // XXX: If we force an update here, then multiple attachments do appear correctly on a destination region 1564 // XXX: If we force an update here, then multiple attachments do appear correctly on a destination region
@@ -1379,36 +1583,69 @@ namespace OpenSim.Region.Framework.Scenes
1379 /// <param name="collisionPoint"></param> 1583 /// <param name="collisionPoint"></param>
1380 /// <param name="localid"></param> 1584 /// <param name="localid"></param>
1381 /// <param name="distance"></param> 1585 /// <param name="distance"></param>
1586 ///
1587
1588 private void UpdateCameraCollisionPlane(Vector4 plane)
1589 {
1590 if (m_lastCameraCollisionPlane != plane)
1591 {
1592 m_lastCameraCollisionPlane = plane;
1593 ControllingClient.SendCameraConstraint(plane);
1594 }
1595 }
1596
1382 public void RayCastCameraCallback(bool hitYN, Vector3 collisionPoint, uint localid, float distance, Vector3 pNormal) 1597 public void RayCastCameraCallback(bool hitYN, Vector3 collisionPoint, uint localid, float distance, Vector3 pNormal)
1383 { 1598 {
1384 const float POSITION_TOLERANCE = 0.02f; 1599 const float POSITION_TOLERANCE = 0.02f;
1385 const float VELOCITY_TOLERANCE = 0.02f;
1386 const float ROTATION_TOLERANCE = 0.02f; 1600 const float ROTATION_TOLERANCE = 0.02f;
1387 1601
1388 if (m_followCamAuto) 1602 m_doingCamRayCast = false;
1603 if (hitYN && localid != LocalId)
1389 { 1604 {
1390 if (hitYN) 1605 SceneObjectGroup group = m_scene.GetGroupByPrim(localid);
1606 bool IsPrim = group != null;
1607 if (IsPrim)
1391 { 1608 {
1392 CameraConstraintActive = true; 1609 SceneObjectPart part = group.GetPart(localid);
1393 //m_log.DebugFormat("[RAYCASTRESULT]: {0}, {1}, {2}, {3}", hitYN, collisionPoint, localid, distance); 1610 if (part != null && !part.VolumeDetectActive)
1394 1611 {
1395 Vector3 normal = Vector3.Normalize(new Vector3(0f, 0f, collisionPoint.Z) - collisionPoint); 1612 CameraConstraintActive = true;
1396 ControllingClient.SendCameraConstraint(new Vector4(normal.X, normal.Y, normal.Z, -1 * Vector3.Distance(new Vector3(0,0,collisionPoint.Z),collisionPoint))); 1613 pNormal.X = (float) Math.Round(pNormal.X, 2);
1614 pNormal.Y = (float) Math.Round(pNormal.Y, 2);
1615 pNormal.Z = (float) Math.Round(pNormal.Z, 2);
1616 pNormal.Normalize();
1617 collisionPoint.X = (float) Math.Round(collisionPoint.X, 1);
1618 collisionPoint.Y = (float) Math.Round(collisionPoint.Y, 1);
1619 collisionPoint.Z = (float) Math.Round(collisionPoint.Z, 1);
1620
1621 Vector4 plane = new Vector4(pNormal.X, pNormal.Y, pNormal.Z,
1622 Vector3.Dot(collisionPoint, pNormal));
1623 UpdateCameraCollisionPlane(plane);
1624 }
1397 } 1625 }
1398 else 1626 else
1399 { 1627 {
1400 if (!m_pos.ApproxEquals(m_lastPosition, POSITION_TOLERANCE) || 1628 CameraConstraintActive = true;
1401 !Velocity.ApproxEquals(m_lastVelocity, VELOCITY_TOLERANCE) || 1629 pNormal.X = (float) Math.Round(pNormal.X, 2);
1402 !Rotation.ApproxEquals(m_lastRotation, ROTATION_TOLERANCE)) 1630 pNormal.Y = (float) Math.Round(pNormal.Y, 2);
1403 { 1631 pNormal.Z = (float) Math.Round(pNormal.Z, 2);
1404 if (CameraConstraintActive) 1632 pNormal.Normalize();
1405 { 1633 collisionPoint.X = (float) Math.Round(collisionPoint.X, 1);
1406 ControllingClient.SendCameraConstraint(new Vector4(0f, 0.5f, 0.9f, -3000f)); 1634 collisionPoint.Y = (float) Math.Round(collisionPoint.Y, 1);
1407 CameraConstraintActive = false; 1635 collisionPoint.Z = (float) Math.Round(collisionPoint.Z, 1);
1408 } 1636
1409 } 1637 Vector4 plane = new Vector4(pNormal.X, pNormal.Y, pNormal.Z,
1638 Vector3.Dot(collisionPoint, pNormal));
1639 UpdateCameraCollisionPlane(plane);
1410 } 1640 }
1411 } 1641 }
1642 else if (!m_pos.ApproxEquals(m_lastPosition, POSITION_TOLERANCE) ||
1643 !Rotation.ApproxEquals(m_lastRotation, ROTATION_TOLERANCE))
1644 {
1645 Vector4 plane = new Vector4(0.9f, 0.0f, 0.361f, -9000f); // not right...
1646 UpdateCameraCollisionPlane(plane);
1647 CameraConstraintActive = false;
1648 }
1412 } 1649 }
1413 1650
1414 /// <summary> 1651 /// <summary>
@@ -1482,12 +1719,6 @@ namespace OpenSim.Region.Framework.Scenes
1482 // DrawDistance = agentData.Far; 1719 // DrawDistance = agentData.Far;
1483 DrawDistance = Scene.DefaultDrawDistance; 1720 DrawDistance = Scene.DefaultDrawDistance;
1484 1721
1485 // Check if Client has camera in 'follow cam' or 'build' mode.
1486 Vector3 camdif = (Vector3.One * Rotation - Vector3.One * CameraRotation);
1487
1488 m_followCamAuto = ((CameraUpAxis.Z > 0.959f && CameraUpAxis.Z < 0.98f)
1489 && (Math.Abs(camdif.X) < 0.4f && Math.Abs(camdif.Y) < 0.4f)) ? true : false;
1490
1491 m_mouseLook = (flags & AgentManager.ControlFlags.AGENT_CONTROL_MOUSELOOK) != 0; 1722 m_mouseLook = (flags & AgentManager.ControlFlags.AGENT_CONTROL_MOUSELOOK) != 0;
1492 m_leftButtonDown = (flags & AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_DOWN) != 0; 1723 m_leftButtonDown = (flags & AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_DOWN) != 0;
1493 1724
@@ -1507,14 +1738,38 @@ namespace OpenSim.Region.Framework.Scenes
1507 StandUp(); 1738 StandUp();
1508 } 1739 }
1509 1740
1510 //m_log.DebugFormat("[FollowCam]: {0}", m_followCamAuto);
1511 // Raycast from the avatar's head to the camera to see if there's anything blocking the view 1741 // Raycast from the avatar's head to the camera to see if there's anything blocking the view
1512 if ((m_movementUpdateCount % NumMovementsBetweenRayCast) == 0 && m_scene.PhysicsScene.SupportsRayCast()) 1742 // this exclude checks may not be complete
1743
1744 if (m_movementUpdateCount % NumMovementsBetweenRayCast == 0 && m_scene.PhysicsScene.SupportsRayCast())
1513 { 1745 {
1514 if (m_followCamAuto) 1746 if (!m_doingCamRayCast && !m_mouseLook && ParentID == 0)
1747 {
1748 Vector3 posAdjusted = AbsolutePosition;
1749// posAdjusted.Z += 0.5f * Appearance.AvatarSize.Z - 0.5f;
1750 posAdjusted.Z += 1.0f; // viewer current camera focus point
1751 Vector3 tocam = CameraPosition - posAdjusted;
1752 tocam.X = (float)Math.Round(tocam.X, 1);
1753 tocam.Y = (float)Math.Round(tocam.Y, 1);
1754 tocam.Z = (float)Math.Round(tocam.Z, 1);
1755
1756 float distTocamlen = tocam.Length();
1757 if (distTocamlen > 0.3f)
1758 {
1759 tocam *= (1.0f / distTocamlen);
1760 posAdjusted.X = (float)Math.Round(posAdjusted.X, 1);
1761 posAdjusted.Y = (float)Math.Round(posAdjusted.Y, 1);
1762 posAdjusted.Z = (float)Math.Round(posAdjusted.Z, 1);
1763
1764 m_doingCamRayCast = true;
1765 m_scene.PhysicsScene.RaycastWorld(posAdjusted, tocam, distTocamlen + 1.0f, RayCastCameraCallback);
1766 }
1767 }
1768 else if (CameraConstraintActive && (m_mouseLook || ParentID != 0))
1515 { 1769 {
1516 Vector3 posAdjusted = m_pos + HEAD_ADJUSTMENT; 1770 Vector4 plane = new Vector4(0.9f, 0.0f, 0.361f, -10000f); // not right...
1517 m_scene.PhysicsScene.RaycastWorld(m_pos, Vector3.Normalize(CameraPosition - posAdjusted), Vector3.Distance(CameraPosition, posAdjusted) + 0.3f, RayCastCameraCallback); 1771 UpdateCameraCollisionPlane(plane);
1772 CameraConstraintActive = false;
1518 } 1773 }
1519 } 1774 }
1520 1775
@@ -1979,7 +2234,8 @@ namespace OpenSim.Region.Framework.Scenes
1979// m_log.DebugFormat("[SCENE PRESENCE]: Resetting move to target for {0}", Name); 2234// m_log.DebugFormat("[SCENE PRESENCE]: Resetting move to target for {0}", Name);
1980 2235
1981 MovingToTarget = false; 2236 MovingToTarget = false;
1982 MoveToPositionTarget = Vector3.Zero; 2237// MoveToPositionTarget = Vector3.Zero;
2238 m_forceToApply = null; // cancel possible last action
1983 2239
1984 // We need to reset the control flag as the ScenePresenceAnimator uses this to determine the correct 2240 // We need to reset the control flag as the ScenePresenceAnimator uses this to determine the correct
1985 // resting animation (e.g. hover or stand). NPCs don't have a client that will quickly reset this flag. 2241 // resting animation (e.g. hover or stand). NPCs don't have a client that will quickly reset this flag.
@@ -1997,12 +2253,17 @@ namespace OpenSim.Region.Framework.Scenes
1997// m_log.DebugFormat("[SCENE PRESENCE]: StandUp() for {0}", Name); 2253// m_log.DebugFormat("[SCENE PRESENCE]: StandUp() for {0}", Name);
1998 2254
1999 SitGround = false; 2255 SitGround = false;
2256
2257/* move this down so avatar gets physical in the new position and not where it is siting
2000 if (PhysicsActor == null) 2258 if (PhysicsActor == null)
2001 AddToPhysicalScene(false); 2259 AddToPhysicalScene(false);
2260 */
2002 2261
2003 if (ParentID != 0) 2262 if (ParentID != 0)
2004 { 2263 {
2005 SceneObjectPart part = ParentPart; 2264 SceneObjectPart part = ParentPart;
2265 UnRegisterSeatControls(part.ParentGroup.UUID);
2266
2006 TaskInventoryDictionary taskIDict = part.TaskInventory; 2267 TaskInventoryDictionary taskIDict = part.TaskInventory;
2007 if (taskIDict != null) 2268 if (taskIDict != null)
2008 { 2269 {
@@ -2018,14 +2279,22 @@ namespace OpenSim.Region.Framework.Scenes
2018 } 2279 }
2019 } 2280 }
2020 2281
2021 ParentPosition = part.GetWorldPosition(); 2282 part.ParentGroup.DeleteAvatar(UUID);
2283// ParentPosition = part.GetWorldPosition();
2022 ControllingClient.SendClearFollowCamProperties(part.ParentUUID); 2284 ControllingClient.SendClearFollowCamProperties(part.ParentUUID);
2023 2285
2024 m_pos += ParentPosition + new Vector3(0.0f, 0.0f, 2.0f * m_sitAvatarHeight); 2286// m_pos += ParentPosition + new Vector3(0.0f, 0.0f, 2.0f * m_sitAvatarHeight);
2025 ParentPosition = Vector3.Zero; 2287// ParentPosition = Vector3.Zero;
2288 m_pos = part.AbsolutePosition + (m_pos * part.GetWorldRotation()) + new Vector3(0.0f, 0.0f, 2.0f * m_sitAvatarHeight);
2289 if (part.SitTargetAvatar == UUID)
2290 m_bodyRot = part.GetWorldRotation() * part.SitTargetOrientation;
2026 2291
2027 ParentID = 0; 2292 ParentID = 0;
2028 ParentPart = null; 2293 ParentPart = null;
2294
2295 if (PhysicsActor == null)
2296 AddToPhysicalScene(false);
2297
2029 SendAvatarDataToAllAgents(); 2298 SendAvatarDataToAllAgents();
2030 m_requestedSitTargetID = 0; 2299 m_requestedSitTargetID = 0;
2031 2300
@@ -2035,6 +2304,9 @@ namespace OpenSim.Region.Framework.Scenes
2035 part.ParentGroup.TriggerScriptChangedEvent(Changed.LINK); 2304 part.ParentGroup.TriggerScriptChangedEvent(Changed.LINK);
2036 } 2305 }
2037 2306
2307 else if (PhysicsActor == null)
2308 AddToPhysicalScene(false);
2309
2038 Animator.TrySetMovementAnimation("STAND"); 2310 Animator.TrySetMovementAnimation("STAND");
2039 } 2311 }
2040 2312
@@ -2082,11 +2354,8 @@ namespace OpenSim.Region.Framework.Scenes
2082 if (part == null) 2354 if (part == null)
2083 return; 2355 return;
2084 2356
2085 // TODO: determine position to sit at based on scene geometry; don't trust offset from client
2086 // see http://wiki.secondlife.com/wiki/User:Andrew_Linden/Office_Hours/2007_11_06 for details on how LL does it
2087
2088 if (PhysicsActor != null) 2357 if (PhysicsActor != null)
2089 m_sitAvatarHeight = PhysicsActor.Size.Z; 2358 m_sitAvatarHeight = PhysicsActor.Size.Z * 0.5f;
2090 2359
2091 bool canSit = false; 2360 bool canSit = false;
2092 Vector3 pos = part.AbsolutePosition + offset; 2361 Vector3 pos = part.AbsolutePosition + offset;
@@ -2103,31 +2372,31 @@ namespace OpenSim.Region.Framework.Scenes
2103 } 2372 }
2104 else 2373 else
2105 { 2374 {
2375 if (PhysicsSit(part,offset)) // physics engine
2376 return;
2377
2106 if (Util.GetDistanceTo(AbsolutePosition, pos) <= 10) 2378 if (Util.GetDistanceTo(AbsolutePosition, pos) <= 10)
2107 { 2379 {
2108// m_log.DebugFormat(
2109// "[SCENE PRESENCE]: Sitting {0} on {1} {2} because sit target is unset and within 10m",
2110// Name, part.Name, part.LocalId);
2111 2380
2112 AbsolutePosition = pos + new Vector3(0.0f, 0.0f, m_sitAvatarHeight); 2381 AbsolutePosition = pos + new Vector3(0.0f, 0.0f, m_sitAvatarHeight);
2113 canSit = true; 2382 canSit = true;
2114 } 2383 }
2115// else
2116// {
2117// m_log.DebugFormat(
2118// "[SCENE PRESENCE]: Ignoring sit request of {0} on {1} {2} because sit target is unset and outside 10m",
2119// Name, part.Name, part.LocalId);
2120// }
2121 } 2384 }
2122 2385
2123 if (canSit) 2386 if (canSit)
2124 { 2387 {
2388
2125 if (PhysicsActor != null) 2389 if (PhysicsActor != null)
2126 { 2390 {
2127 // We can remove the physicsActor until they stand up. 2391 // We can remove the physicsActor until they stand up.
2128 RemoveFromPhysicalScene(); 2392 RemoveFromPhysicalScene();
2129 } 2393 }
2130 2394
2395 if (MovingToTarget)
2396 ResetMoveToTarget();
2397
2398 Velocity = Vector3.Zero;
2399
2131 part.AddSittingAvatar(UUID); 2400 part.AddSittingAvatar(UUID);
2132 2401
2133 cameraAtOffset = part.GetCameraAtOffset(); 2402 cameraAtOffset = part.GetCameraAtOffset();
@@ -2135,7 +2404,7 @@ namespace OpenSim.Region.Framework.Scenes
2135 forceMouselook = part.GetForceMouselook(); 2404 forceMouselook = part.GetForceMouselook();
2136 2405
2137 ControllingClient.SendSitResponse( 2406 ControllingClient.SendSitResponse(
2138 targetID, offset, sitOrientation, false, cameraAtOffset, cameraEyeOffset, forceMouselook); 2407 part.UUID, offset, sitOrientation, false, cameraAtOffset, cameraEyeOffset, forceMouselook);
2139 2408
2140 m_requestedSitTargetUUID = targetID; 2409 m_requestedSitTargetUUID = targetID;
2141 2410
@@ -2149,6 +2418,9 @@ namespace OpenSim.Region.Framework.Scenes
2149 2418
2150 public void HandleAgentRequestSit(IClientAPI remoteClient, UUID agentID, UUID targetID, Vector3 offset) 2419 public void HandleAgentRequestSit(IClientAPI remoteClient, UUID agentID, UUID targetID, Vector3 offset)
2151 { 2420 {
2421 if (IsChildAgent)
2422 return;
2423
2152 if (ParentID != 0) 2424 if (ParentID != 0)
2153 { 2425 {
2154 if (ParentPart.UUID == targetID) 2426 if (ParentPart.UUID == targetID)
@@ -2164,14 +2436,6 @@ namespace OpenSim.Region.Framework.Scenes
2164 m_requestedSitTargetID = part.LocalId; 2436 m_requestedSitTargetID = part.LocalId;
2165 m_requestedSitTargetUUID = targetID; 2437 m_requestedSitTargetUUID = targetID;
2166 2438
2167// m_log.DebugFormat("[SIT]: Client requested Sit Position: {0}", offset);
2168
2169 if (m_scene.PhysicsScene.SupportsRayCast())
2170 {
2171 //m_scene.PhysicsScene.RaycastWorld(Vector3.Zero,Vector3.Zero, 0.01f,new RaycastCallback());
2172 //SitRayCastAvatarPosition(part);
2173 //return;
2174 }
2175 } 2439 }
2176 else 2440 else
2177 { 2441 {
@@ -2181,197 +2445,111 @@ namespace OpenSim.Region.Framework.Scenes
2181 SendSitResponse(targetID, offset, Quaternion.Identity); 2445 SendSitResponse(targetID, offset, Quaternion.Identity);
2182 } 2446 }
2183 2447
2184 /* 2448 // returns false if does not suport so older sit can be tried
2185 public void SitRayCastAvatarPosition(SceneObjectPart part) 2449 public bool PhysicsSit(SceneObjectPart part, Vector3 offset)
2186 { 2450 {
2187 Vector3 EndRayCastPosition = part.AbsolutePosition + m_requestedSitOffset; 2451 if (part == null || part.ParentGroup.IsAttachment)
2188 Vector3 StartRayCastPosition = AbsolutePosition;
2189 Vector3 direction = Vector3.Normalize(EndRayCastPosition - StartRayCastPosition);
2190 float distance = Vector3.Distance(EndRayCastPosition, StartRayCastPosition);
2191 m_scene.PhysicsScene.RaycastWorld(StartRayCastPosition, direction, distance, SitRayCastAvatarPositionResponse);
2192 }
2193
2194 public void SitRayCastAvatarPositionResponse(bool hitYN, Vector3 collisionPoint, uint localid, float pdistance, Vector3 normal)
2195 {
2196 SceneObjectPart part = FindNextAvailableSitTarget(m_requestedSitTargetUUID);
2197 if (part != null)
2198 {
2199 if (hitYN)
2200 {
2201 if (collisionPoint.ApproxEquals(m_requestedSitOffset + part.AbsolutePosition, 0.2f))
2202 {
2203 SitRaycastFindEdge(collisionPoint, normal);
2204 m_log.DebugFormat("[SIT]: Raycast Avatar Position succeeded at point: {0}, normal:{1}", collisionPoint, normal);
2205 }
2206 else
2207 {
2208 SitRayCastAvatarPositionCameraZ(part);
2209 }
2210 }
2211 else
2212 {
2213 SitRayCastAvatarPositionCameraZ(part);
2214 }
2215 }
2216 else
2217 { 2452 {
2218 ControllingClient.SendAlertMessage("Sit position no longer exists"); 2453 return true;
2219 m_requestedSitTargetUUID = UUID.Zero;
2220 m_requestedSitTargetID = 0;
2221 m_requestedSitOffset = Vector3.Zero;
2222 } 2454 }
2223 2455
2224 } 2456 if ( m_scene.PhysicsScene == null)
2457 return false;
2225 2458
2226 public void SitRayCastAvatarPositionCameraZ(SceneObjectPart part) 2459 if (part.PhysActor == null)
2227 {
2228 // Next, try to raycast from the camera Z position
2229 Vector3 EndRayCastPosition = part.AbsolutePosition + m_requestedSitOffset;
2230 Vector3 StartRayCastPosition = AbsolutePosition; StartRayCastPosition.Z = CameraPosition.Z;
2231 Vector3 direction = Vector3.Normalize(EndRayCastPosition - StartRayCastPosition);
2232 float distance = Vector3.Distance(EndRayCastPosition, StartRayCastPosition);
2233 m_scene.PhysicsScene.RaycastWorld(StartRayCastPosition, direction, distance, SitRayCastAvatarPositionCameraZResponse);
2234 }
2235
2236 public void SitRayCastAvatarPositionCameraZResponse(bool hitYN, Vector3 collisionPoint, uint localid, float pdistance, Vector3 normal)
2237 {
2238 SceneObjectPart part = FindNextAvailableSitTarget(m_requestedSitTargetUUID);
2239 if (part != null)
2240 { 2460 {
2241 if (hitYN) 2461 // none physcis shape
2242 { 2462 if (part.PhysicsShapeType == (byte)PhysicsShapeType.None)
2243 if (collisionPoint.ApproxEquals(m_requestedSitOffset + part.AbsolutePosition, 0.2f)) 2463 ControllingClient.SendAlertMessage(" There is no suitable surface to sit on, try another spot.");
2244 {
2245 SitRaycastFindEdge(collisionPoint, normal);
2246 m_log.DebugFormat("[SIT]: Raycast Avatar Position + CameraZ succeeded at point: {0}, normal:{1}", collisionPoint, normal);
2247 }
2248 else
2249 {
2250 SitRayCastCameraPosition(part);
2251 }
2252 }
2253 else 2464 else
2254 { 2465 { // non physical phantom TODO
2255 SitRayCastCameraPosition(part); 2466 ControllingClient.SendAlertMessage(" There is no suitable surface to sit on, try another spot.");
2467 return false;
2256 } 2468 }
2257 } 2469 return true;
2258 else
2259 {
2260 ControllingClient.SendAlertMessage("Sit position no longer exists");
2261 m_requestedSitTargetUUID = UUID.Zero;
2262 m_requestedSitTargetID = 0;
2263 m_requestedSitOffset = Vector3.Zero;
2264 } 2470 }
2265 2471
2266 }
2267 2472
2268 public void SitRayCastCameraPosition(SceneObjectPart part) 2473 // not doing autopilot
2269 { 2474 m_requestedSitTargetID = 0;
2270 // Next, try to raycast from the camera position
2271 Vector3 EndRayCastPosition = part.AbsolutePosition + m_requestedSitOffset;
2272 Vector3 StartRayCastPosition = CameraPosition;
2273 Vector3 direction = Vector3.Normalize(EndRayCastPosition - StartRayCastPosition);
2274 float distance = Vector3.Distance(EndRayCastPosition, StartRayCastPosition);
2275 m_scene.PhysicsScene.RaycastWorld(StartRayCastPosition, direction, distance, SitRayCastCameraPositionResponse);
2276 }
2277 2475
2278 public void SitRayCastCameraPositionResponse(bool hitYN, Vector3 collisionPoint, uint localid, float pdistance, Vector3 normal) 2476 if (m_scene.PhysicsScene.SitAvatar(part.PhysActor, AbsolutePosition, CameraPosition, offset, new Vector3(0.35f, 0, 0.65f), PhysicsSitResponse) != 0)
2279 { 2477 return true;
2280 SceneObjectPart part = FindNextAvailableSitTarget(m_requestedSitTargetUUID);
2281 if (part != null)
2282 {
2283 if (hitYN)
2284 {
2285 if (collisionPoint.ApproxEquals(m_requestedSitOffset + part.AbsolutePosition, 0.2f))
2286 {
2287 SitRaycastFindEdge(collisionPoint, normal);
2288 m_log.DebugFormat("[SIT]: Raycast Camera Position succeeded at point: {0}, normal:{1}", collisionPoint, normal);
2289 }
2290 else
2291 {
2292 SitRayHorizontal(part);
2293 }
2294 }
2295 else
2296 {
2297 SitRayHorizontal(part);
2298 }
2299 }
2300 else
2301 {
2302 ControllingClient.SendAlertMessage("Sit position no longer exists");
2303 m_requestedSitTargetUUID = UUID.Zero;
2304 m_requestedSitTargetID = 0;
2305 m_requestedSitOffset = Vector3.Zero;
2306 }
2307 2478
2479 return false;
2308 } 2480 }
2309 2481
2310 public void SitRayHorizontal(SceneObjectPart part) 2482
2483 private bool CanEnterLandPosition(Vector3 testPos)
2311 { 2484 {
2312 // Next, try to raycast from the avatar position to fwd 2485 ILandObject land = m_scene.LandChannel.GetLandObject(testPos.X, testPos.Y);
2313 Vector3 EndRayCastPosition = part.AbsolutePosition + m_requestedSitOffset; 2486
2314 Vector3 StartRayCastPosition = CameraPosition; 2487 if (land == null || land.LandData.Name == "NO_LAND")
2315 Vector3 direction = Vector3.Normalize(EndRayCastPosition - StartRayCastPosition); 2488 return true;
2316 float distance = Vector3.Distance(EndRayCastPosition, StartRayCastPosition); 2489
2317 m_scene.PhysicsScene.RaycastWorld(StartRayCastPosition, direction, distance, SitRayCastHorizontalResponse); 2490 return land.CanBeOnThisLand(UUID,testPos.Z);
2318 } 2491 }
2319 2492
2320 public void SitRayCastHorizontalResponse(bool hitYN, Vector3 collisionPoint, uint localid, float pdistance, Vector3 normal) 2493 // status
2494 // < 0 ignore
2495 // 0 bad sit spot
2496 public void PhysicsSitResponse(int status, uint partID, Vector3 offset, Quaternion Orientation)
2321 { 2497 {
2322 SceneObjectPart part = FindNextAvailableSitTarget(m_requestedSitTargetUUID); 2498 if (status < 0)
2323 if (part != null) 2499 return;
2500
2501 if (status == 0)
2324 { 2502 {
2325 if (hitYN) 2503 ControllingClient.SendAlertMessage(" There is no suitable surface to sit on, try another spot.");
2326 { 2504 return;
2327 if (collisionPoint.ApproxEquals(m_requestedSitOffset + part.AbsolutePosition, 0.2f))
2328 {
2329 SitRaycastFindEdge(collisionPoint, normal);
2330 m_log.DebugFormat("[SIT]: Raycast Horizontal Position succeeded at point: {0}, normal:{1}", collisionPoint, normal);
2331 // Next, try to raycast from the camera position
2332 Vector3 EndRayCastPosition = part.AbsolutePosition + m_requestedSitOffset;
2333 Vector3 StartRayCastPosition = CameraPosition;
2334 Vector3 direction = Vector3.Normalize(EndRayCastPosition - StartRayCastPosition);
2335 float distance = Vector3.Distance(EndRayCastPosition, StartRayCastPosition);
2336 //m_scene.PhysicsScene.RaycastWorld(StartRayCastPosition, direction, distance, SitRayCastResponseAvatarPosition);
2337 }
2338 else
2339 {
2340 ControllingClient.SendAlertMessage("Sit position not accessable.");
2341 m_requestedSitTargetUUID = UUID.Zero;
2342 m_requestedSitTargetID = 0;
2343 m_requestedSitOffset = Vector3.Zero;
2344 }
2345 }
2346 else
2347 {
2348 ControllingClient.SendAlertMessage("Sit position not accessable.");
2349 m_requestedSitTargetUUID = UUID.Zero;
2350 m_requestedSitTargetID = 0;
2351 m_requestedSitOffset = Vector3.Zero;
2352 }
2353 } 2505 }
2354 else 2506
2507 SceneObjectPart part = m_scene.GetSceneObjectPart(partID);
2508 if (part == null)
2509 return;
2510
2511 Vector3 targetPos = part.GetWorldPosition() + offset * part.GetWorldRotation();
2512 if(!CanEnterLandPosition(targetPos))
2355 { 2513 {
2356 ControllingClient.SendAlertMessage("Sit position no longer exists"); 2514 ControllingClient.SendAlertMessage(" Sit position on restricted land, try another spot");
2357 m_requestedSitTargetUUID = UUID.Zero; 2515 return;
2358 m_requestedSitTargetID = 0;
2359 m_requestedSitOffset = Vector3.Zero;
2360 } 2516 }
2361 2517
2362 } 2518 RemoveFromPhysicalScene();
2363 2519
2364 private void SitRaycastFindEdge(Vector3 collisionPoint, Vector3 collisionNormal) 2520 if (MovingToTarget)
2365 { 2521 ResetMoveToTarget();
2366 int i = 0; 2522
2367 //throw new NotImplementedException(); 2523 Velocity = Vector3.Zero;
2368 //m_requestedSitTargetUUID = UUID.Zero; 2524
2369 //m_requestedSitTargetID = 0; 2525 part.AddSittingAvatar(UUID);
2370 //m_requestedSitOffset = Vector3.Zero;
2371 2526
2372 SendSitResponse(ControllingClient, m_requestedSitTargetUUID, collisionPoint - m_requestedSitOffset, Quaternion.Identity); 2527 Vector3 cameraAtOffset = part.GetCameraAtOffset();
2528 Vector3 cameraEyeOffset = part.GetCameraEyeOffset();
2529 bool forceMouselook = part.GetForceMouselook();
2530
2531 ControllingClient.SendSitResponse(
2532 part.UUID, offset, Orientation, false, cameraAtOffset, cameraEyeOffset, forceMouselook);
2533
2534 // not using autopilot
2535
2536 Rotation = Orientation;
2537 m_pos = offset;
2538
2539 m_requestedSitTargetID = 0;
2540 part.ParentGroup.AddAvatar(UUID);
2541
2542 ParentPart = part;
2543 ParentID = part.LocalId;
2544 if(status == 3)
2545 Animator.TrySetMovementAnimation("SIT_GROUND");
2546 else
2547 Animator.TrySetMovementAnimation("SIT");
2548 SendAvatarDataToAllAgents();
2549
2550 part.ParentGroup.TriggerScriptChangedEvent(Changed.LINK);
2373 } 2551 }
2374 */ 2552
2375 2553
2376 public void HandleAgentSit(IClientAPI remoteClient, UUID agentID) 2554 public void HandleAgentSit(IClientAPI remoteClient, UUID agentID)
2377 { 2555 {
@@ -2388,6 +2566,7 @@ namespace OpenSim.Region.Framework.Scenes
2388 return; 2566 return;
2389 } 2567 }
2390 2568
2569
2391 if (part.SitTargetAvatar == UUID) 2570 if (part.SitTargetAvatar == UUID)
2392 { 2571 {
2393 Vector3 sitTargetPos = part.SitTargetPosition; 2572 Vector3 sitTargetPos = part.SitTargetPosition;
@@ -2402,14 +2581,39 @@ namespace OpenSim.Region.Framework.Scenes
2402 2581
2403 //Quaternion result = (sitTargetOrient * vq) * nq; 2582 //Quaternion result = (sitTargetOrient * vq) * nq;
2404 2583
2405 m_pos = sitTargetPos + SIT_TARGET_ADJUSTMENT; 2584 double x, y, z, m;
2585
2586 Quaternion r = sitTargetOrient;
2587 m = r.X * r.X + r.Y * r.Y + r.Z * r.Z + r.W * r.W;
2588
2589 if (Math.Abs(1.0 - m) > 0.000001)
2590 {
2591 m = 1.0 / Math.Sqrt(m);
2592 r.X *= (float)m;
2593 r.Y *= (float)m;
2594 r.Z *= (float)m;
2595 r.W *= (float)m;
2596 }
2597
2598 x = 2 * (r.X * r.Z + r.Y * r.W);
2599 y = 2 * (-r.X * r.W + r.Y * r.Z);
2600 z = -r.X * r.X - r.Y * r.Y + r.Z * r.Z + r.W * r.W;
2601
2602 Vector3 up = new Vector3((float)x, (float)y, (float)z);
2603 Vector3 sitOffset = up * Appearance.AvatarHeight * 0.02638f;
2604
2605 m_pos = sitTargetPos + sitOffset + SIT_TARGET_ADJUSTMENT;
2606
2607// m_pos = sitTargetPos + SIT_TARGET_ADJUSTMENT - sitOffset;
2406 Rotation = sitTargetOrient; 2608 Rotation = sitTargetOrient;
2407 ParentPosition = part.AbsolutePosition; 2609// ParentPosition = part.AbsolutePosition;
2610 part.ParentGroup.AddAvatar(UUID);
2408 } 2611 }
2409 else 2612 else
2410 { 2613 {
2411 m_pos -= part.AbsolutePosition; 2614 m_pos -= part.AbsolutePosition;
2412 ParentPosition = part.AbsolutePosition; 2615// ParentPosition = part.AbsolutePosition;
2616 part.ParentGroup.AddAvatar(UUID);
2413 2617
2414// m_log.DebugFormat( 2618// m_log.DebugFormat(
2415// "[SCENE PRESENCE]: Sitting {0} at position {1} ({2} + {3}) on part {4} {5} without sit target", 2619// "[SCENE PRESENCE]: Sitting {0} at position {1} ({2} + {3}) on part {4} {5} without sit target",
@@ -2460,6 +2664,13 @@ namespace OpenSim.Region.Framework.Scenes
2460 Animator.RemoveAnimation(animID, false); 2664 Animator.RemoveAnimation(animID, false);
2461 } 2665 }
2462 2666
2667 public void avnHandleChangeAnim(UUID animID, bool addRemove,bool sendPack)
2668 {
2669 Animator.avnChangeAnim(animID, addRemove, sendPack);
2670 }
2671
2672
2673
2463 /// <summary> 2674 /// <summary>
2464 /// Rotate the avatar to the given rotation and apply a movement in the given relative vector 2675 /// Rotate the avatar to the given rotation and apply a movement in the given relative vector
2465 /// </summary> 2676 /// </summary>
@@ -2516,8 +2727,8 @@ namespace OpenSim.Region.Framework.Scenes
2516 direc.Z *= 2.6f; 2727 direc.Z *= 2.6f;
2517 2728
2518 // TODO: PreJump and jump happen too quickly. Many times prejump gets ignored. 2729 // TODO: PreJump and jump happen too quickly. Many times prejump gets ignored.
2519 Animator.TrySetMovementAnimation("PREJUMP"); 2730// Animator.TrySetMovementAnimation("PREJUMP");
2520 Animator.TrySetMovementAnimation("JUMP"); 2731// Animator.TrySetMovementAnimation("JUMP");
2521 } 2732 }
2522 } 2733 }
2523 } 2734 }
@@ -2526,6 +2737,7 @@ namespace OpenSim.Region.Framework.Scenes
2526 2737
2527 // TODO: Add the force instead of only setting it to support multiple forces per frame? 2738 // TODO: Add the force instead of only setting it to support multiple forces per frame?
2528 m_forceToApply = direc; 2739 m_forceToApply = direc;
2740 Animator.UpdateMovementAnimations();
2529 } 2741 }
2530 2742
2531 #endregion 2743 #endregion
@@ -2543,16 +2755,12 @@ namespace OpenSim.Region.Framework.Scenes
2543 // NOTE: Velocity is not the same as m_velocity. Velocity will attempt to 2755 // NOTE: Velocity is not the same as m_velocity. Velocity will attempt to
2544 // grab the latest PhysicsActor velocity, whereas m_velocity is often 2756 // grab the latest PhysicsActor velocity, whereas m_velocity is often
2545 // storing a requested force instead of an actual traveling velocity 2757 // storing a requested force instead of an actual traveling velocity
2758 if (Appearance.AvatarSize != m_lastSize && !IsLoggingIn)
2759 SendAvatarDataToAllAgents();
2546 2760
2547 // Throw away duplicate or insignificant updates 2761 if (!Rotation.ApproxEquals(m_lastRotation, ROTATION_TOLERANCE) ||
2548 if ( 2762 !Velocity.ApproxEquals(m_lastVelocity, VELOCITY_TOLERANCE) ||
2549 // If the velocity has become zero, send it no matter what. 2763 !m_pos.ApproxEquals(m_lastPosition, POSITION_TOLERANCE))
2550 (Velocity != m_lastVelocity && Velocity == Vector3.Zero)
2551 // otherwise, if things have changed reasonably, send the update
2552 || (!Rotation.ApproxEquals(m_lastRotation, ROTATION_TOLERANCE)
2553 || !Velocity.ApproxEquals(m_lastVelocity, VELOCITY_TOLERANCE)
2554 || !m_pos.ApproxEquals(m_lastPosition, POSITION_TOLERANCE)))
2555
2556 { 2764 {
2557 SendTerseUpdateToAllClients(); 2765 SendTerseUpdateToAllClients();
2558 2766
@@ -2741,6 +2949,8 @@ namespace OpenSim.Region.Framework.Scenes
2741 return; 2949 return;
2742 } 2950 }
2743 2951
2952 m_lastSize = Appearance.AvatarSize;
2953
2744 int count = 0; 2954 int count = 0;
2745 m_scene.ForEachScenePresence(delegate(ScenePresence scenePresence) 2955 m_scene.ForEachScenePresence(delegate(ScenePresence scenePresence)
2746 { 2956 {
@@ -2848,6 +3058,8 @@ namespace OpenSim.Region.Framework.Scenes
2848 3058
2849 avatar.ControllingClient.SendAppearance( 3059 avatar.ControllingClient.SendAppearance(
2850 UUID, Appearance.VisualParams, Appearance.Texture.GetBytes()); 3060 UUID, Appearance.VisualParams, Appearance.Texture.GetBytes());
3061
3062
2851 } 3063 }
2852 3064
2853 #endregion 3065 #endregion
@@ -2922,8 +3134,9 @@ namespace OpenSim.Region.Framework.Scenes
2922 3134
2923 // If we don't have a PhysActor, we can't cross anyway 3135 // If we don't have a PhysActor, we can't cross anyway
2924 // Also don't do this while sat, sitting avatars cross with the 3136 // Also don't do this while sat, sitting avatars cross with the
2925 // object they sit on. 3137 // object they sit on. ParentUUID denoted a pending sit, don't
2926 if (ParentID != 0 || PhysicsActor == null) 3138 // interfere with it.
3139 if (ParentID != 0 || PhysicsActor == null || ParentUUID != UUID.Zero)
2927 return; 3140 return;
2928 3141
2929 if (!IsInTransit) 3142 if (!IsInTransit)
@@ -3188,6 +3401,10 @@ namespace OpenSim.Region.Framework.Scenes
3188 } 3401 }
3189 3402
3190 private static Vector3 marker = new Vector3(-1f, -1f, -1f); 3403 private static Vector3 marker = new Vector3(-1f, -1f, -1f);
3404 private void RaiseUpdateThrottles()
3405 {
3406 m_scene.EventManager.TriggerThrottleUpdate(this);
3407 }
3191 /// <summary> 3408 /// <summary>
3192 /// This updates important decision making data about a child agent 3409 /// This updates important decision making data about a child agent
3193 /// The main purpose is to figure out what objects to send to a child agent that's in a neighboring region 3410 /// The main purpose is to figure out what objects to send to a child agent that's in a neighboring region
@@ -3268,6 +3485,9 @@ namespace OpenSim.Region.Framework.Scenes
3268 cAgent.AlwaysRun = SetAlwaysRun; 3485 cAgent.AlwaysRun = SetAlwaysRun;
3269 3486
3270 cAgent.Appearance = new AvatarAppearance(Appearance); 3487 cAgent.Appearance = new AvatarAppearance(Appearance);
3488
3489 cAgent.ParentPart = ParentUUID;
3490 cAgent.SitOffset = m_pos;
3271 3491
3272 lock (scriptedcontrols) 3492 lock (scriptedcontrols)
3273 { 3493 {
@@ -3276,7 +3496,7 @@ namespace OpenSim.Region.Framework.Scenes
3276 3496
3277 foreach (ScriptControllers c in scriptedcontrols.Values) 3497 foreach (ScriptControllers c in scriptedcontrols.Values)
3278 { 3498 {
3279 controls[i++] = new ControllerData(c.itemID, (uint)c.ignoreControls, (uint)c.eventControls); 3499 controls[i++] = new ControllerData(c.objectID, c.itemID, (uint)c.ignoreControls, (uint)c.eventControls);
3280 } 3500 }
3281 cAgent.Controllers = controls; 3501 cAgent.Controllers = controls;
3282 } 3502 }
@@ -3309,6 +3529,8 @@ namespace OpenSim.Region.Framework.Scenes
3309 CameraAtAxis = cAgent.AtAxis; 3529 CameraAtAxis = cAgent.AtAxis;
3310 CameraLeftAxis = cAgent.LeftAxis; 3530 CameraLeftAxis = cAgent.LeftAxis;
3311 CameraUpAxis = cAgent.UpAxis; 3531 CameraUpAxis = cAgent.UpAxis;
3532 ParentUUID = cAgent.ParentPart;
3533 m_prevSitOffset = cAgent.SitOffset;
3312 3534
3313 // When we get to the point of re-computing neighbors everytime this 3535 // When we get to the point of re-computing neighbors everytime this
3314 // changes, then start using the agent's drawdistance rather than the 3536 // changes, then start using the agent's drawdistance rather than the
@@ -3346,6 +3568,7 @@ namespace OpenSim.Region.Framework.Scenes
3346 foreach (ControllerData c in cAgent.Controllers) 3568 foreach (ControllerData c in cAgent.Controllers)
3347 { 3569 {
3348 ScriptControllers sc = new ScriptControllers(); 3570 ScriptControllers sc = new ScriptControllers();
3571 sc.objectID = c.ObjectID;
3349 sc.itemID = c.ItemID; 3572 sc.itemID = c.ItemID;
3350 sc.ignoreControls = (ScriptControlled)c.IgnoreControls; 3573 sc.ignoreControls = (ScriptControlled)c.IgnoreControls;
3351 sc.eventControls = (ScriptControlled)c.EventControls; 3574 sc.eventControls = (ScriptControlled)c.EventControls;
@@ -3413,20 +3636,27 @@ namespace OpenSim.Region.Framework.Scenes
3413 } 3636 }
3414 3637
3415 if (Appearance.AvatarHeight == 0) 3638 if (Appearance.AvatarHeight == 0)
3416 Appearance.SetHeight(); 3639// Appearance.SetHeight();
3640 Appearance.SetSize(new Vector3(0.45f,0.6f,1.9f));
3417 3641
3418 PhysicsScene scene = m_scene.PhysicsScene; 3642 PhysicsScene scene = m_scene.PhysicsScene;
3419 3643
3420 Vector3 pVec = AbsolutePosition; 3644 Vector3 pVec = AbsolutePosition;
3421 3645
3646/*
3422 PhysicsActor = scene.AddAvatar( 3647 PhysicsActor = scene.AddAvatar(
3423 LocalId, Firstname + "." + Lastname, pVec, 3648 LocalId, Firstname + "." + Lastname, pVec,
3424 new Vector3(0f, 0f, Appearance.AvatarHeight), isFlying); 3649 new Vector3(0.45f, 0.6f, Appearance.AvatarHeight), isFlying);
3650*/
3651
3652 PhysicsActor = scene.AddAvatar(
3653 LocalId, Firstname + "." + Lastname, pVec,
3654 Appearance.AvatarBoxSize,Appearance.AvatarFeetOffset, isFlying);
3425 3655
3426 //PhysicsActor.OnRequestTerseUpdate += SendTerseUpdateToAllClients; 3656 //PhysicsActor.OnRequestTerseUpdate += SendTerseUpdateToAllClients;
3427 PhysicsActor.OnCollisionUpdate += PhysicsCollisionUpdate; 3657 PhysicsActor.OnCollisionUpdate += PhysicsCollisionUpdate;
3428 PhysicsActor.OnOutOfBounds += OutOfBoundsCall; // Called for PhysicsActors when there's something wrong 3658 PhysicsActor.OnOutOfBounds += OutOfBoundsCall; // Called for PhysicsActors when there's something wrong
3429 PhysicsActor.SubscribeEvents(500); 3659 PhysicsActor.SubscribeEvents(100);
3430 PhysicsActor.LocalID = LocalId; 3660 PhysicsActor.LocalID = LocalId;
3431 } 3661 }
3432 3662
@@ -3440,6 +3670,7 @@ namespace OpenSim.Region.Framework.Scenes
3440 ControllingClient.SendAgentAlertMessage("Physics is having a problem with your avatar. You may not be able to move until you relog.", true); 3670 ControllingClient.SendAgentAlertMessage("Physics is having a problem with your avatar. You may not be able to move until you relog.", true);
3441 } 3671 }
3442 3672
3673
3443 /// <summary> 3674 /// <summary>
3444 /// Event called by the physics plugin to tell the avatar about a collision. 3675 /// Event called by the physics plugin to tell the avatar about a collision.
3445 /// </summary> 3676 /// </summary>
@@ -3453,7 +3684,7 @@ namespace OpenSim.Region.Framework.Scenes
3453 /// <param name="e"></param> 3684 /// <param name="e"></param>
3454 public void PhysicsCollisionUpdate(EventArgs e) 3685 public void PhysicsCollisionUpdate(EventArgs e)
3455 { 3686 {
3456 if (IsChildAgent) 3687 if (IsChildAgent || Animator == null)
3457 return; 3688 return;
3458 3689
3459 //if ((Math.Abs(Velocity.X) > 0.1e-9f) || (Math.Abs(Velocity.Y) > 0.1e-9f)) 3690 //if ((Math.Abs(Velocity.X) > 0.1e-9f) || (Math.Abs(Velocity.Y) > 0.1e-9f))
@@ -3469,7 +3700,6 @@ namespace OpenSim.Region.Framework.Scenes
3469 CollisionEventUpdate collisionData = (CollisionEventUpdate)e; 3700 CollisionEventUpdate collisionData = (CollisionEventUpdate)e;
3470 Dictionary<uint, ContactPoint> coldata = collisionData.m_objCollisionList; 3701 Dictionary<uint, ContactPoint> coldata = collisionData.m_objCollisionList;
3471 3702
3472 CollisionPlane = Vector4.UnitW;
3473 3703
3474// // No collisions at all means we may be flying. Update always 3704// // No collisions at all means we may be flying. Update always
3475// // to make falling work 3705// // to make falling work
@@ -3481,6 +3711,7 @@ namespace OpenSim.Region.Framework.Scenes
3481 3711
3482 if (coldata.Count != 0) 3712 if (coldata.Count != 0)
3483 { 3713 {
3714/*
3484 switch (Animator.CurrentMovementAnimation) 3715 switch (Animator.CurrentMovementAnimation)
3485 { 3716 {
3486 case "STAND": 3717 case "STAND":
@@ -3489,24 +3720,38 @@ namespace OpenSim.Region.Framework.Scenes
3489 case "CROUCH": 3720 case "CROUCH":
3490 case "CROUCHWALK": 3721 case "CROUCHWALK":
3491 { 3722 {
3723 */
3492 ContactPoint lowest; 3724 ContactPoint lowest;
3493 lowest.SurfaceNormal = Vector3.Zero; 3725 lowest.SurfaceNormal = Vector3.Zero;
3494 lowest.Position = Vector3.Zero; 3726 lowest.Position = Vector3.Zero;
3495 lowest.Position.Z = Single.NaN; 3727 lowest.Position.Z = float.MaxValue;
3496 3728
3497 foreach (ContactPoint contact in coldata.Values) 3729 foreach (ContactPoint contact in coldata.Values)
3498 { 3730 {
3499 if (Single.IsNaN(lowest.Position.Z) || contact.Position.Z < lowest.Position.Z) 3731
3732 if (contact.CharacterFeet && contact.Position.Z < lowest.Position.Z)
3500 { 3733 {
3501 lowest = contact; 3734 lowest = contact;
3502 } 3735 }
3503 } 3736 }
3504 3737
3505 CollisionPlane = new Vector4(-lowest.SurfaceNormal, -Vector3.Dot(lowest.Position, lowest.SurfaceNormal)); 3738 if (lowest.Position.Z != float.MaxValue)
3739 {
3740 lowest.SurfaceNormal = -lowest.SurfaceNormal;
3741 CollisionPlane = new Vector4(lowest.SurfaceNormal, Vector3.Dot(lowest.Position, lowest.SurfaceNormal));
3742 }
3743 else
3744 CollisionPlane = Vector4.UnitW;
3745/*
3506 } 3746 }
3507 break; 3747 break;
3508 } 3748 }
3749*/
3509 } 3750 }
3751 else
3752 CollisionPlane = Vector4.UnitW;
3753
3754 RaiseCollisionScriptEvents(coldata);
3510 3755
3511 // Gods do not take damage and Invulnerable is set depending on parcel/region flags 3756 // Gods do not take damage and Invulnerable is set depending on parcel/region flags
3512 if (Invulnerable || GodLevel > 0) 3757 if (Invulnerable || GodLevel > 0)
@@ -3605,6 +3850,13 @@ namespace OpenSim.Region.Framework.Scenes
3605 // m_reprioritizationTimer.Dispose(); 3850 // m_reprioritizationTimer.Dispose();
3606 3851
3607 RemoveFromPhysicalScene(); 3852 RemoveFromPhysicalScene();
3853
3854 m_scene.EventManager.OnRegionHeartbeatEnd -= RegionHeartbeatEnd;
3855
3856// if (Animator != null)
3857// Animator.Close();
3858 Animator = null;
3859
3608 } 3860 }
3609 3861
3610 public void AddAttachment(SceneObjectGroup gobj) 3862 public void AddAttachment(SceneObjectGroup gobj)
@@ -3838,10 +4090,18 @@ namespace OpenSim.Region.Framework.Scenes
3838 4090
3839 public void RegisterControlEventsToScript(int controls, int accept, int pass_on, uint Obj_localID, UUID Script_item_UUID) 4091 public void RegisterControlEventsToScript(int controls, int accept, int pass_on, uint Obj_localID, UUID Script_item_UUID)
3840 { 4092 {
4093 SceneObjectPart p = m_scene.GetSceneObjectPart(Obj_localID);
4094 if (p == null)
4095 return;
4096
4097 ControllingClient.SendTakeControls(controls, false, false);
4098 ControllingClient.SendTakeControls(controls, true, false);
4099
3841 ScriptControllers obj = new ScriptControllers(); 4100 ScriptControllers obj = new ScriptControllers();
3842 obj.ignoreControls = ScriptControlled.CONTROL_ZERO; 4101 obj.ignoreControls = ScriptControlled.CONTROL_ZERO;
3843 obj.eventControls = ScriptControlled.CONTROL_ZERO; 4102 obj.eventControls = ScriptControlled.CONTROL_ZERO;
3844 4103
4104 obj.objectID = p.ParentGroup.UUID;
3845 obj.itemID = Script_item_UUID; 4105 obj.itemID = Script_item_UUID;
3846 if (pass_on == 0 && accept == 0) 4106 if (pass_on == 0 && accept == 0)
3847 { 4107 {
@@ -3890,6 +4150,21 @@ namespace OpenSim.Region.Framework.Scenes
3890 ControllingClient.SendTakeControls(int.MaxValue, false, false); 4150 ControllingClient.SendTakeControls(int.MaxValue, false, false);
3891 } 4151 }
3892 4152
4153 private void UnRegisterSeatControls(UUID obj)
4154 {
4155 List<UUID> takers = new List<UUID>();
4156
4157 foreach (ScriptControllers c in scriptedcontrols.Values)
4158 {
4159 if (c.objectID == obj)
4160 takers.Add(c.itemID);
4161 }
4162 foreach (UUID t in takers)
4163 {
4164 UnRegisterControlEventsToScript(0, t);
4165 }
4166 }
4167
3893 public void UnRegisterControlEventsToScript(uint Obj_localID, UUID Script_item_UUID) 4168 public void UnRegisterControlEventsToScript(uint Obj_localID, UUID Script_item_UUID)
3894 { 4169 {
3895 ScriptControllers takecontrols; 4170 ScriptControllers takecontrols;
@@ -4219,6 +4494,12 @@ namespace OpenSim.Region.Framework.Scenes
4219 4494
4220 private void CheckAndAdjustLandingPoint(ref Vector3 pos) 4495 private void CheckAndAdjustLandingPoint(ref Vector3 pos)
4221 { 4496 {
4497 string reason;
4498
4499 // Honor bans
4500 if (!m_scene.TestLandRestrictions(UUID, out reason, ref pos.X, ref pos.Y))
4501 return;
4502
4222 SceneObjectGroup telehub = null; 4503 SceneObjectGroup telehub = null;
4223 if (m_scene.RegionInfo.RegionSettings.TelehubObject != UUID.Zero && (telehub = m_scene.GetSceneObjectGroup(m_scene.RegionInfo.RegionSettings.TelehubObject)) != null) 4504 if (m_scene.RegionInfo.RegionSettings.TelehubObject != UUID.Zero && (telehub = m_scene.GetSceneObjectGroup(m_scene.RegionInfo.RegionSettings.TelehubObject)) != null)
4224 { 4505 {
@@ -4258,11 +4539,206 @@ namespace OpenSim.Region.Framework.Scenes
4258 pos = land.LandData.UserLocation; 4539 pos = land.LandData.UserLocation;
4259 } 4540 }
4260 } 4541 }
4261 4542
4262 land.SendLandUpdateToClient(ControllingClient); 4543 land.SendLandUpdateToClient(ControllingClient);
4263 } 4544 }
4264 } 4545 }
4265 4546
4547 private DetectedObject CreateDetObject(SceneObjectPart obj)
4548 {
4549 DetectedObject detobj = new DetectedObject();
4550 detobj.keyUUID = obj.UUID;
4551 detobj.nameStr = obj.Name;
4552 detobj.ownerUUID = obj.OwnerID;
4553 detobj.posVector = obj.AbsolutePosition;
4554 detobj.rotQuat = obj.GetWorldRotation();
4555 detobj.velVector = obj.Velocity;
4556 detobj.colliderType = 0;
4557 detobj.groupUUID = obj.GroupID;
4558
4559 return detobj;
4560 }
4561
4562 private DetectedObject CreateDetObject(ScenePresence av)
4563 {
4564 DetectedObject detobj = new DetectedObject();
4565 detobj.keyUUID = av.UUID;
4566 detobj.nameStr = av.ControllingClient.Name;
4567 detobj.ownerUUID = av.UUID;
4568 detobj.posVector = av.AbsolutePosition;
4569 detobj.rotQuat = av.Rotation;
4570 detobj.velVector = av.Velocity;
4571 detobj.colliderType = 0;
4572 detobj.groupUUID = av.ControllingClient.ActiveGroupId;
4573
4574 return detobj;
4575 }
4576
4577 private DetectedObject CreateDetObjectForGround()
4578 {
4579 DetectedObject detobj = new DetectedObject();
4580 detobj.keyUUID = UUID.Zero;
4581 detobj.nameStr = "";
4582 detobj.ownerUUID = UUID.Zero;
4583 detobj.posVector = AbsolutePosition;
4584 detobj.rotQuat = Quaternion.Identity;
4585 detobj.velVector = Vector3.Zero;
4586 detobj.colliderType = 0;
4587 detobj.groupUUID = UUID.Zero;
4588
4589 return detobj;
4590 }
4591
4592 private ColliderArgs CreateColliderArgs(SceneObjectPart dest, List<uint> colliders)
4593 {
4594 ColliderArgs colliderArgs = new ColliderArgs();
4595 List<DetectedObject> colliding = new List<DetectedObject>();
4596 foreach (uint localId in colliders)
4597 {
4598 if (localId == 0)
4599 continue;
4600
4601 SceneObjectPart obj = m_scene.GetSceneObjectPart(localId);
4602 if (obj != null)
4603 {
4604 if (!dest.CollisionFilteredOut(obj.UUID, obj.Name))
4605 colliding.Add(CreateDetObject(obj));
4606 }
4607 else
4608 {
4609 ScenePresence av = m_scene.GetScenePresence(localId);
4610 if (av != null && (!av.IsChildAgent))
4611 {
4612 if (!dest.CollisionFilteredOut(av.UUID, av.Name))
4613 colliding.Add(CreateDetObject(av));
4614 }
4615 }
4616 }
4617
4618 colliderArgs.Colliders = colliding;
4619
4620 return colliderArgs;
4621 }
4622
4623 private delegate void ScriptCollidingNotification(uint localID, ColliderArgs message);
4624
4625 private void SendCollisionEvent(SceneObjectGroup dest, scriptEvents ev, List<uint> colliders, ScriptCollidingNotification notify)
4626 {
4627 ColliderArgs CollidingMessage;
4628
4629 if (colliders.Count > 0)
4630 {
4631 if ((dest.RootPart.ScriptEvents & ev) != 0)
4632 {
4633 CollidingMessage = CreateColliderArgs(dest.RootPart, colliders);
4634
4635 if (CollidingMessage.Colliders.Count > 0)
4636 notify(dest.RootPart.LocalId, CollidingMessage);
4637 }
4638 }
4639 }
4640
4641 private void SendLandCollisionEvent(SceneObjectGroup dest, scriptEvents ev, ScriptCollidingNotification notify)
4642 {
4643 if ((dest.RootPart.ScriptEvents & ev) != 0)
4644 {
4645 ColliderArgs LandCollidingMessage = new ColliderArgs();
4646 List<DetectedObject> colliding = new List<DetectedObject>();
4647
4648 colliding.Add(CreateDetObjectForGround());
4649 LandCollidingMessage.Colliders = colliding;
4650
4651 notify(dest.RootPart.LocalId, LandCollidingMessage);
4652 }
4653 }
4654
4655 private void RaiseCollisionScriptEvents(Dictionary<uint, ContactPoint> coldata)
4656 {
4657 try
4658 {
4659 List<uint> thisHitColliders = new List<uint>();
4660 List<uint> endedColliders = new List<uint>();
4661 List<uint> startedColliders = new List<uint>();
4662 List<CollisionForSoundInfo> soundinfolist = new List<CollisionForSoundInfo>();
4663 CollisionForSoundInfo soundinfo;
4664 ContactPoint curcontact;
4665
4666 if (coldata.Count == 0)
4667 {
4668 if (m_lastColliders.Count == 0)
4669 return; // nothing to do
4670
4671 foreach (uint localID in m_lastColliders)
4672 {
4673 endedColliders.Add(localID);
4674 }
4675 m_lastColliders.Clear();
4676 }
4677
4678 else
4679 {
4680 foreach (uint id in coldata.Keys)
4681 {
4682 thisHitColliders.Add(id);
4683 if (!m_lastColliders.Contains(id))
4684 {
4685 startedColliders.Add(id);
4686 curcontact = coldata[id];
4687 if (Math.Abs(curcontact.RelativeSpeed) > 0.2)
4688 {
4689 soundinfo = new CollisionForSoundInfo();
4690 soundinfo.colliderID = id;
4691 soundinfo.position = curcontact.Position;
4692 soundinfo.relativeVel = curcontact.RelativeSpeed;
4693 soundinfolist.Add(soundinfo);
4694 }
4695 }
4696 //m_log.Debug("[SCENE PRESENCE]: Collided with:" + localid.ToString() + " at depth of: " + collissionswith[localid].ToString());
4697 }
4698
4699 // calculate things that ended colliding
4700 foreach (uint localID in m_lastColliders)
4701 {
4702 if (!thisHitColliders.Contains(localID))
4703 {
4704 endedColliders.Add(localID);
4705 }
4706 }
4707 //add the items that started colliding this time to the last colliders list.
4708 foreach (uint localID in startedColliders)
4709 {
4710 m_lastColliders.Add(localID);
4711 }
4712 // remove things that ended colliding from the last colliders list
4713 foreach (uint localID in endedColliders)
4714 {
4715 m_lastColliders.Remove(localID);
4716 }
4717
4718 if (soundinfolist.Count > 0)
4719 CollisionSounds.AvatarCollisionSound(this, soundinfolist);
4720 }
4721
4722 foreach (SceneObjectGroup att in GetAttachments())
4723 {
4724 SendCollisionEvent(att, scriptEvents.collision_start, startedColliders, m_scene.EventManager.TriggerScriptCollidingStart);
4725 SendCollisionEvent(att, scriptEvents.collision , m_lastColliders , m_scene.EventManager.TriggerScriptColliding);
4726 SendCollisionEvent(att, scriptEvents.collision_end , endedColliders , m_scene.EventManager.TriggerScriptCollidingEnd);
4727
4728 if (startedColliders.Contains(0))
4729 SendLandCollisionEvent(att, scriptEvents.land_collision_start, m_scene.EventManager.TriggerScriptLandCollidingStart);
4730 if (m_lastColliders.Contains(0))
4731 SendLandCollisionEvent(att, scriptEvents.land_collision, m_scene.EventManager.TriggerScriptLandColliding);
4732 if (endedColliders.Contains(0))
4733 SendLandCollisionEvent(att, scriptEvents.land_collision_end, m_scene.EventManager.TriggerScriptLandCollidingEnd);
4734 }
4735 }
4736 finally
4737 {
4738 m_collisionEventFlag = false;
4739 }
4740 }
4741
4266 private void TeleportFlagsDebug() { 4742 private void TeleportFlagsDebug() {
4267 4743
4268 // Some temporary debugging help to show all the TeleportFlags we have... 4744 // Some temporary debugging help to show all the TeleportFlags we have...
@@ -4287,6 +4763,5 @@ namespace OpenSim.Region.Framework.Scenes
4287 m_log.InfoFormat("[SCENE PRESENCE]: TELEPORT ******************"); 4763 m_log.InfoFormat("[SCENE PRESENCE]: TELEPORT ******************");
4288 4764
4289 } 4765 }
4290
4291 } 4766 }
4292} 4767}
diff --git a/OpenSim/Region/Framework/Scenes/Serialization/SceneObjectSerializer.cs b/OpenSim/Region/Framework/Scenes/Serialization/SceneObjectSerializer.cs
index 39420a6..ce4fb40 100644
--- a/OpenSim/Region/Framework/Scenes/Serialization/SceneObjectSerializer.cs
+++ b/OpenSim/Region/Framework/Scenes/Serialization/SceneObjectSerializer.cs
@@ -262,6 +262,12 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
262 sr.Close(); 262 sr.Close();
263 } 263 }
264 264
265 XmlNodeList keymotion = doc.GetElementsByTagName("KeyframeMotion");
266 if (keymotion.Count > 0)
267 sceneObject.RootPart.KeyframeMotion = KeyframeMotion.FromData(sceneObject, Convert.FromBase64String(keymotion[0].InnerText));
268 else
269 sceneObject.RootPart.KeyframeMotion = null;
270
265 // Script state may, or may not, exist. Not having any, is NOT 271 // Script state may, or may not, exist. Not having any, is NOT
266 // ever a problem. 272 // ever a problem.
267 sceneObject.LoadScriptState(doc); 273 sceneObject.LoadScriptState(doc);
@@ -368,11 +374,21 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
368 m_SOPXmlProcessors.Add("PayPrice3", ProcessPayPrice3); 374 m_SOPXmlProcessors.Add("PayPrice3", ProcessPayPrice3);
369 m_SOPXmlProcessors.Add("PayPrice4", ProcessPayPrice4); 375 m_SOPXmlProcessors.Add("PayPrice4", ProcessPayPrice4);
370 376
377 m_SOPXmlProcessors.Add("Buoyancy", ProcessBuoyancy);
378 m_SOPXmlProcessors.Add("Force", ProcessForce);
379 m_SOPXmlProcessors.Add("Torque", ProcessTorque);
380 m_SOPXmlProcessors.Add("VolumeDetectActive", ProcessVolumeDetectActive);
381
382
383 m_SOPXmlProcessors.Add("Vehicle", ProcessVehicle);
384
371 m_SOPXmlProcessors.Add("PhysicsShapeType", ProcessPhysicsShapeType); 385 m_SOPXmlProcessors.Add("PhysicsShapeType", ProcessPhysicsShapeType);
372 m_SOPXmlProcessors.Add("Density", ProcessDensity); 386 m_SOPXmlProcessors.Add("Density", ProcessDensity);
373 m_SOPXmlProcessors.Add("Friction", ProcessFriction); 387 m_SOPXmlProcessors.Add("Friction", ProcessFriction);
374 m_SOPXmlProcessors.Add("Bounce", ProcessBounce); 388 m_SOPXmlProcessors.Add("Bounce", ProcessBounce);
375 m_SOPXmlProcessors.Add("GravityModifier", ProcessGravityModifier); 389 m_SOPXmlProcessors.Add("GravityModifier", ProcessGravityModifier);
390 m_SOPXmlProcessors.Add("CameraEyeOffset", ProcessCameraEyeOffset);
391 m_SOPXmlProcessors.Add("CameraAtOffset", ProcessCameraAtOffset);
376 392
377 #endregion 393 #endregion
378 394
@@ -401,7 +417,7 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
401 m_TaskInventoryXmlProcessors.Add("PermsMask", ProcessTIPermsMask); 417 m_TaskInventoryXmlProcessors.Add("PermsMask", ProcessTIPermsMask);
402 m_TaskInventoryXmlProcessors.Add("Type", ProcessTIType); 418 m_TaskInventoryXmlProcessors.Add("Type", ProcessTIType);
403 m_TaskInventoryXmlProcessors.Add("OwnerChanged", ProcessTIOwnerChanged); 419 m_TaskInventoryXmlProcessors.Add("OwnerChanged", ProcessTIOwnerChanged);
404 420
405 #endregion 421 #endregion
406 422
407 #region ShapeXmlProcessors initialization 423 #region ShapeXmlProcessors initialization
@@ -626,6 +642,33 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
626 obj.GravityModifier = reader.ReadElementContentAsFloat("GravityModifier", String.Empty); 642 obj.GravityModifier = reader.ReadElementContentAsFloat("GravityModifier", String.Empty);
627 } 643 }
628 644
645 private static void ProcessCameraEyeOffset(SceneObjectPart obj, XmlTextReader reader)
646 {
647 obj.SetCameraEyeOffset(Util.ReadVector(reader, "CameraEyeOffset"));
648 }
649
650 private static void ProcessCameraAtOffset(SceneObjectPart obj, XmlTextReader reader)
651 {
652 obj.SetCameraAtOffset(Util.ReadVector(reader, "CameraAtOffset"));
653 }
654
655 private static void ProcessVehicle(SceneObjectPart obj, XmlTextReader reader)
656 {
657 SOPVehicle vehicle = SOPVehicle.FromXml2(reader);
658
659 if (vehicle == null)
660 {
661 obj.VehicleParams = null;
662 m_log.DebugFormat(
663 "[SceneObjectSerializer]: Parsing Vehicle for object part {0} {1} encountered errors. Please see earlier log entries.",
664 obj.Name, obj.UUID);
665 }
666 else
667 {
668 obj.VehicleParams = vehicle;
669 }
670 }
671
629 private static void ProcessShape(SceneObjectPart obj, XmlTextReader reader) 672 private static void ProcessShape(SceneObjectPart obj, XmlTextReader reader)
630 { 673 {
631 List<string> errorNodeNames; 674 List<string> errorNodeNames;
@@ -795,6 +838,25 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
795 obj.PayPrice[4] = (int)reader.ReadElementContentAsInt("PayPrice4", String.Empty); 838 obj.PayPrice[4] = (int)reader.ReadElementContentAsInt("PayPrice4", String.Empty);
796 } 839 }
797 840
841 private static void ProcessBuoyancy(SceneObjectPart obj, XmlTextReader reader)
842 {
843 obj.Buoyancy = (float)reader.ReadElementContentAsFloat("Buoyancy", String.Empty);
844 }
845
846 private static void ProcessForce(SceneObjectPart obj, XmlTextReader reader)
847 {
848 obj.Force = Util.ReadVector(reader, "Force");
849 }
850 private static void ProcessTorque(SceneObjectPart obj, XmlTextReader reader)
851 {
852 obj.Torque = Util.ReadVector(reader, "Torque");
853 }
854
855 private static void ProcessVolumeDetectActive(SceneObjectPart obj, XmlTextReader reader)
856 {
857 obj.VolumeDetectActive = Util.ReadBoolean(reader);
858 }
859
798 #endregion 860 #endregion
799 861
800 #region TaskInventoryXmlProcessors 862 #region TaskInventoryXmlProcessors
@@ -1182,6 +1244,16 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
1182 }); 1244 });
1183 1245
1184 writer.WriteEndElement(); 1246 writer.WriteEndElement();
1247
1248 if (sog.RootPart.KeyframeMotion != null)
1249 {
1250 Byte[] data = sog.RootPart.KeyframeMotion.Serialize();
1251
1252 writer.WriteStartElement(String.Empty, "KeyframeMotion", String.Empty);
1253 writer.WriteBase64(data, 0, data.Length);
1254 writer.WriteEndElement();
1255 }
1256
1185 writer.WriteEndElement(); 1257 writer.WriteEndElement();
1186 } 1258 }
1187 1259
@@ -1289,6 +1361,16 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
1289 writer.WriteElementString("PayPrice3", sop.PayPrice[3].ToString()); 1361 writer.WriteElementString("PayPrice3", sop.PayPrice[3].ToString());
1290 writer.WriteElementString("PayPrice4", sop.PayPrice[4].ToString()); 1362 writer.WriteElementString("PayPrice4", sop.PayPrice[4].ToString());
1291 1363
1364 writer.WriteElementString("Buoyancy", sop.Buoyancy.ToString());
1365
1366 WriteVector(writer, "Force", sop.Force);
1367 WriteVector(writer, "Torque", sop.Torque);
1368
1369 writer.WriteElementString("VolumeDetectActive", sop.VolumeDetectActive.ToString().ToLower());
1370
1371 if (sop.VehicleParams != null)
1372 sop.VehicleParams.ToXml2(writer);
1373
1292 if(sop.PhysicsShapeType != sop.DefaultPhysicsShapeType()) 1374 if(sop.PhysicsShapeType != sop.DefaultPhysicsShapeType())
1293 writer.WriteElementString("PhysicsShapeType", sop.PhysicsShapeType.ToString().ToLower()); 1375 writer.WriteElementString("PhysicsShapeType", sop.PhysicsShapeType.ToString().ToLower());
1294 if (sop.Density != 1000.0f) 1376 if (sop.Density != 1000.0f)
@@ -1299,6 +1381,8 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
1299 writer.WriteElementString("Bounce", sop.Restitution.ToString().ToLower()); 1381 writer.WriteElementString("Bounce", sop.Restitution.ToString().ToLower());
1300 if (sop.GravityModifier != 1.0f) 1382 if (sop.GravityModifier != 1.0f)
1301 writer.WriteElementString("GravityModifier", sop.GravityModifier.ToString().ToLower()); 1383 writer.WriteElementString("GravityModifier", sop.GravityModifier.ToString().ToLower());
1384 WriteVector(writer, "CameraEyeOffset", sop.GetCameraEyeOffset());
1385 WriteVector(writer, "CameraAtOffset", sop.GetCameraAtOffset());
1302 1386
1303 writer.WriteEndElement(); 1387 writer.WriteEndElement();
1304 } 1388 }
@@ -1524,12 +1608,6 @@ namespace OpenSim.Region.Framework.Scenes.Serialization
1524 { 1608 {
1525 TaskInventoryDictionary tinv = new TaskInventoryDictionary(); 1609 TaskInventoryDictionary tinv = new TaskInventoryDictionary();
1526 1610
1527 if (reader.IsEmptyElement)
1528 {
1529 reader.Read();
1530 return tinv;
1531 }
1532
1533 reader.ReadStartElement(name, String.Empty); 1611 reader.ReadStartElement(name, String.Empty);
1534 1612
1535 while (reader.Name == "TaskInventoryItem") 1613 while (reader.Name == "TaskInventoryItem")
diff --git a/OpenSim/Region/Framework/Scenes/SimStatsReporter.cs b/OpenSim/Region/Framework/Scenes/SimStatsReporter.cs
index b9d615e..5398ab9 100644
--- a/OpenSim/Region/Framework/Scenes/SimStatsReporter.cs
+++ b/OpenSim/Region/Framework/Scenes/SimStatsReporter.cs
@@ -175,7 +175,7 @@ namespace OpenSim.Region.Framework.Scenes
175 175
176 // saved last reported value so there is something available for llGetRegionFPS 176 // saved last reported value so there is something available for llGetRegionFPS
177 private float lastReportedSimFPS; 177 private float lastReportedSimFPS;
178 private float[] lastReportedSimStats = new float[22]; 178 private float[] lastReportedSimStats = new float[23];
179 private float m_pfps; 179 private float m_pfps;
180 180
181 /// <summary> 181 /// <summary>
@@ -189,12 +189,13 @@ namespace OpenSim.Region.Framework.Scenes
189 private int m_objectUpdates; 189 private int m_objectUpdates;
190 190
191 private int m_frameMS; 191 private int m_frameMS;
192 private int m_spareMS; 192
193 private int m_netMS; 193 private int m_netMS;
194 private int m_agentMS; 194 private int m_agentMS;
195 private int m_physicsMS; 195 private int m_physicsMS;
196 private int m_imageMS; 196 private int m_imageMS;
197 private int m_otherMS; 197 private int m_otherMS;
198 private int m_sleeptimeMS;
198 199
199//Ckrinke: (3-21-08) Comment out to remove a compiler warning. Bring back into play when needed. 200//Ckrinke: (3-21-08) Comment out to remove a compiler warning. Bring back into play when needed.
200//Ckrinke private int m_scriptMS = 0; 201//Ckrinke private int m_scriptMS = 0;
@@ -289,7 +290,7 @@ namespace OpenSim.Region.Framework.Scenes
289 290
290 private void statsHeartBeat(object sender, EventArgs e) 291 private void statsHeartBeat(object sender, EventArgs e)
291 { 292 {
292 SimStatsPacket.StatBlock[] sb = new SimStatsPacket.StatBlock[22]; 293 SimStatsPacket.StatBlock[] sb = new SimStatsPacket.StatBlock[23];
293 SimStatsPacket.RegionBlock rb = new SimStatsPacket.RegionBlock(); 294 SimStatsPacket.RegionBlock rb = new SimStatsPacket.RegionBlock();
294 295
295 // Know what's not thread safe in Mono... modifying timers. 296 // Know what's not thread safe in Mono... modifying timers.
@@ -327,6 +328,35 @@ namespace OpenSim.Region.Framework.Scenes
327 physfps = 0; 328 physfps = 0;
328 329
329#endregion 330#endregion
331 float factor = 1 / m_statsUpdateFactor;
332
333 if (reportedFPS <= 0)
334 reportedFPS = 1;
335
336 float perframe = 1.0f / (float)reportedFPS;
337
338 float TotalFrameTime = m_frameMS * perframe;
339
340 float targetframetime = 1100.0f / (float)m_nominalReportedFps;
341
342 float sparetime;
343 float sleeptime;
344
345 if (TotalFrameTime > targetframetime)
346 {
347 sparetime = 0;
348 sleeptime = 0;
349 }
350 else
351 {
352 sparetime = m_frameMS - m_physicsMS - m_agentMS;
353 sparetime *= perframe;
354 if (sparetime < 0)
355 sparetime = 0;
356 else if (sparetime > TotalFrameTime)
357 sparetime = TotalFrameTime;
358 sleeptime = m_sleeptimeMS * perframe;
359 }
330 360
331 m_rootAgents = m_scene.SceneGraph.GetRootAgentCount(); 361 m_rootAgents = m_scene.SceneGraph.GetRootAgentCount();
332 m_childAgents = m_scene.SceneGraph.GetChildAgentCount(); 362 m_childAgents = m_scene.SceneGraph.GetChildAgentCount();
@@ -338,25 +368,15 @@ namespace OpenSim.Region.Framework.Scenes
338 // so that stat numbers are always consistent. 368 // so that stat numbers are always consistent.
339 CheckStatSanity(); 369 CheckStatSanity();
340 370
341 //Our time dilation is 0.91 when we're running a full speed, 371 // other MS is actually simulation time
342 // therefore to make sure we get an appropriate range, 372 // m_otherMS = m_frameMS - m_physicsMS - m_imageMS - m_netMS - m_agentMS;
343 // we have to factor in our error. (0.10f * statsUpdateFactor) 373 // m_imageMS m_netMS are not included in m_frameMS
344 // multiplies the fix for the error times the amount of times it'll occur a second
345 // / 10 divides the value by the number of times the sim heartbeat runs (10fps)
346 // Then we divide the whole amount by the amount of seconds pass in between stats updates.
347
348 // 'statsUpdateFactor' is how often stats packets are sent in seconds. Used below to change
349 // values to X-per-second values.
350 374
351 uint thisFrame = m_scene.Frame; 375 m_otherMS = m_frameMS - m_physicsMS - m_agentMS - m_sleeptimeMS;
352 float framesUpdated = (float)(thisFrame - m_lastUpdateFrame) * m_reportedFpsCorrectionFactor; 376 if (m_otherMS < 0)
353 m_lastUpdateFrame = thisFrame; 377 m_otherMS = 0;
354 378
355 // Avoid div-by-zero if somehow we've not updated any frames. 379 for (int i = 0; i < 23; i++)
356 if (framesUpdated == 0)
357 framesUpdated = 1;
358
359 for (int i = 0; i < 22; i++)
360 { 380 {
361 sb[i] = new SimStatsPacket.StatBlock(); 381 sb[i] = new SimStatsPacket.StatBlock();
362 } 382 }
@@ -386,19 +406,19 @@ namespace OpenSim.Region.Framework.Scenes
386 sb[7].StatValue = m_activePrim; 406 sb[7].StatValue = m_activePrim;
387 407
388 sb[8].StatID = (uint)Stats.FrameMS; 408 sb[8].StatID = (uint)Stats.FrameMS;
389 sb[8].StatValue = m_frameMS / framesUpdated; 409 sb[8].StatValue = TotalFrameTime;
390 410
391 sb[9].StatID = (uint)Stats.NetMS; 411 sb[9].StatID = (uint)Stats.NetMS;
392 sb[9].StatValue = m_netMS / framesUpdated; 412 sb[9].StatValue = m_netMS * perframe;
393 413
394 sb[10].StatID = (uint)Stats.PhysicsMS; 414 sb[10].StatID = (uint)Stats.PhysicsMS;
395 sb[10].StatValue = m_physicsMS / framesUpdated; 415 sb[10].StatValue = m_physicsMS * perframe;
396 416
397 sb[11].StatID = (uint)Stats.ImageMS ; 417 sb[11].StatID = (uint)Stats.ImageMS ;
398 sb[11].StatValue = m_imageMS / framesUpdated; 418 sb[11].StatValue = m_imageMS * perframe;
399 419
400 sb[12].StatID = (uint)Stats.OtherMS; 420 sb[12].StatID = (uint)Stats.OtherMS;
401 sb[12].StatValue = m_otherMS / framesUpdated; 421 sb[12].StatValue = m_otherMS * perframe;
402 422
403 sb[13].StatID = (uint)Stats.InPacketsPerSecond; 423 sb[13].StatID = (uint)Stats.InPacketsPerSecond;
404 sb[13].StatValue = (m_inPacketsPerSecond / m_statsUpdateFactor); 424 sb[13].StatValue = (m_inPacketsPerSecond / m_statsUpdateFactor);
@@ -410,7 +430,7 @@ namespace OpenSim.Region.Framework.Scenes
410 sb[15].StatValue = m_unAckedBytes; 430 sb[15].StatValue = m_unAckedBytes;
411 431
412 sb[16].StatID = (uint)Stats.AgentMS; 432 sb[16].StatID = (uint)Stats.AgentMS;
413 sb[16].StatValue = m_agentMS / framesUpdated; 433 sb[16].StatValue = m_agentMS * perframe;
414 434
415 sb[17].StatID = (uint)Stats.PendingDownloads; 435 sb[17].StatID = (uint)Stats.PendingDownloads;
416 sb[17].StatValue = m_pendingDownloads; 436 sb[17].StatValue = m_pendingDownloads;
@@ -425,7 +445,10 @@ namespace OpenSim.Region.Framework.Scenes
425 sb[20].StatValue = m_scriptLinesPerSecond / m_statsUpdateFactor; 445 sb[20].StatValue = m_scriptLinesPerSecond / m_statsUpdateFactor;
426 446
427 sb[21].StatID = (uint)Stats.SimSpareMs; 447 sb[21].StatID = (uint)Stats.SimSpareMs;
428 sb[21].StatValue = m_spareMS / framesUpdated; 448 sb[21].StatValue = sparetime;
449
450 sb[22].StatID = (uint)Stats.SimSleepMs;
451 sb[22].StatValue = sleeptime;
429 452
430 for (int i = 0; i < 22; i++) 453 for (int i = 0; i < 22; i++)
431 { 454 {
@@ -444,28 +467,32 @@ namespace OpenSim.Region.Framework.Scenes
444 } 467 }
445 468
446 // Extra statistics that aren't currently sent to clients 469 // Extra statistics that aren't currently sent to clients
447 lock (m_lastReportedExtraSimStats) 470 if (m_scene.PhysicsScene != null)
448 { 471 {
449 m_lastReportedExtraSimStats[LastReportedObjectUpdateStatName] = m_objectUpdates / m_statsUpdateFactor; 472 lock (m_lastReportedExtraSimStats)
450 m_lastReportedExtraSimStats[SlowFramesStat.ShortName] = (float)SlowFramesStat.Value;
451
452 Dictionary<string, float> physicsStats = m_scene.PhysicsScene.GetStats();
453
454 if (physicsStats != null)
455 { 473 {
456 foreach (KeyValuePair<string, float> tuple in physicsStats) 474 m_lastReportedExtraSimStats[LastReportedObjectUpdateStatName] = m_objectUpdates / m_statsUpdateFactor;
475 m_lastReportedExtraSimStats[SlowFramesStat.ShortName] = (float)SlowFramesStat.Value;
476
477 Dictionary<string, float> physicsStats = m_scene.PhysicsScene.GetStats();
478
479 if (physicsStats != null)
457 { 480 {
458 // FIXME: An extremely dirty hack to divide MS stats per frame rather than per second 481 foreach (KeyValuePair<string, float> tuple in physicsStats)
459 // Need to change things so that stats source can indicate whether they are per second or 482 {
460 // per frame. 483 // FIXME: An extremely dirty hack to divide MS stats per frame rather than per second
461 if (tuple.Key.EndsWith("MS")) 484 // Need to change things so that stats source can indicate whether they are per second or
462 m_lastReportedExtraSimStats[tuple.Key] = tuple.Value / framesUpdated; 485 // per frame.
463 else 486 if (tuple.Key.EndsWith("MS"))
464 m_lastReportedExtraSimStats[tuple.Key] = tuple.Value / m_statsUpdateFactor; 487 m_lastReportedExtraSimStats[tuple.Key] = tuple.Value * perframe;
488 else
489 m_lastReportedExtraSimStats[tuple.Key] = tuple.Value / m_statsUpdateFactor;
490 }
465 } 491 }
466 } 492 }
467 } 493 }
468 494
495// LastReportedObjectUpdates = m_objectUpdates / m_statsUpdateFactor;
469 ResetValues(); 496 ResetValues();
470 } 497 }
471 } 498 }
@@ -488,7 +515,8 @@ namespace OpenSim.Region.Framework.Scenes
488 m_physicsMS = 0; 515 m_physicsMS = 0;
489 m_imageMS = 0; 516 m_imageMS = 0;
490 m_otherMS = 0; 517 m_otherMS = 0;
491 m_spareMS = 0; 518// m_spareMS = 0;
519 m_sleeptimeMS = 0;
492 520
493//Ckrinke This variable is not used, so comment to remove compiler warning until it is used. 521//Ckrinke This variable is not used, so comment to remove compiler warning until it is used.
494//Ckrinke m_scriptMS = 0; 522//Ckrinke m_scriptMS = 0;
@@ -572,11 +600,6 @@ namespace OpenSim.Region.Framework.Scenes
572 SlowFramesStat.Value++; 600 SlowFramesStat.Value++;
573 } 601 }
574 602
575 public void AddSpareMS(int ms)
576 {
577 m_spareMS += ms;
578 }
579
580 public void addNetMS(int ms) 603 public void addNetMS(int ms)
581 { 604 {
582 m_netMS += ms; 605 m_netMS += ms;
@@ -602,6 +625,11 @@ namespace OpenSim.Region.Framework.Scenes
602 m_otherMS += ms; 625 m_otherMS += ms;
603 } 626 }
604 627
628 public void addSleepMS(int ms)
629 {
630 m_sleeptimeMS += ms;
631 }
632
605 public void AddPendingDownloads(int count) 633 public void AddPendingDownloads(int count)
606 { 634 {
607 m_pendingDownloads += count; 635 m_pendingDownloads += count;
diff --git a/OpenSim/Region/Framework/Scenes/Tests/SceneObjectResizeTests.cs b/OpenSim/Region/Framework/Scenes/Tests/SceneObjectResizeTests.cs
index c264433..1182c96 100644
--- a/OpenSim/Region/Framework/Scenes/Tests/SceneObjectResizeTests.cs
+++ b/OpenSim/Region/Framework/Scenes/Tests/SceneObjectResizeTests.cs
@@ -62,6 +62,8 @@ namespace OpenSim.Region.Framework.Scenes.Tests
62 Assert.That(g1Post.RootPart.Scale.X, Is.EqualTo(2)); 62 Assert.That(g1Post.RootPart.Scale.X, Is.EqualTo(2));
63 Assert.That(g1Post.RootPart.Scale.Y, Is.EqualTo(3)); 63 Assert.That(g1Post.RootPart.Scale.Y, Is.EqualTo(3));
64 Assert.That(g1Post.RootPart.Scale.Z, Is.EqualTo(4)); 64 Assert.That(g1Post.RootPart.Scale.Z, Is.EqualTo(4));
65
66 Assert.That(g1Post.RootPart.UndoCount, Is.EqualTo(1));
65 } 67 }
66 68
67 /// <summary> 69 /// <summary>
diff --git a/OpenSim/Region/Framework/Scenes/Tests/SceneObjectUndoRedoTests.cs b/OpenSim/Region/Framework/Scenes/Tests/SceneObjectUndoRedoTests.cs
deleted file mode 100644
index 4883ae7..0000000
--- a/OpenSim/Region/Framework/Scenes/Tests/SceneObjectUndoRedoTests.cs
+++ /dev/null
@@ -1,184 +0,0 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Reflection;
30using NUnit.Framework;
31using OpenMetaverse;
32using OpenSim.Framework;
33using OpenSim.Framework.Communications;
34using OpenSim.Region.Framework.Scenes;
35using OpenSim.Tests.Common;
36using OpenSim.Tests.Common.Mock;
37
38namespace OpenSim.Region.Framework.Scenes.Tests
39{
40 /// <summary>
41 /// Tests for undo/redo
42 /// </summary>
43 public class SceneObjectUndoRedoTests : OpenSimTestCase
44 {
45 [Test]
46 public void TestUndoRedoResizeSceneObject()
47 {
48 TestHelpers.InMethod();
49// TestHelpers.EnableLogging();
50
51 Vector3 firstSize = new Vector3(2, 3, 4);
52 Vector3 secondSize = new Vector3(5, 6, 7);
53
54 Scene scene = new SceneHelpers().SetupScene();
55 scene.MaxUndoCount = 20;
56 SceneObjectGroup g1 = SceneHelpers.AddSceneObject(scene);
57
58 // TODO: It happens to be the case that we are not storing undo states for SOPs which are not yet in a SOG,
59 // which is the way that AddSceneObject() sets up the object (i.e. it creates the SOP first). However,
60 // this is somewhat by chance. Really, we shouldn't be storing undo states at all if the object is not
61 // in a scene.
62 Assert.That(g1.RootPart.UndoCount, Is.EqualTo(0));
63
64 g1.GroupResize(firstSize);
65 Assert.That(g1.RootPart.UndoCount, Is.EqualTo(1));
66
67 g1.GroupResize(secondSize);
68 Assert.That(g1.RootPart.UndoCount, Is.EqualTo(2));
69
70 g1.RootPart.Undo();
71 Assert.That(g1.RootPart.UndoCount, Is.EqualTo(1));
72 Assert.That(g1.GroupScale, Is.EqualTo(firstSize));
73
74 g1.RootPart.Redo();
75 Assert.That(g1.RootPart.UndoCount, Is.EqualTo(2));
76 Assert.That(g1.GroupScale, Is.EqualTo(secondSize));
77 }
78
79 [Test]
80 public void TestUndoLimit()
81 {
82 TestHelpers.InMethod();
83
84 Vector3 firstSize = new Vector3(2, 3, 4);
85 Vector3 secondSize = new Vector3(5, 6, 7);
86 Vector3 thirdSize = new Vector3(8, 9, 10);
87 Vector3 fourthSize = new Vector3(11, 12, 13);
88
89 Scene scene = new SceneHelpers().SetupScene();
90 scene.MaxUndoCount = 2;
91 SceneObjectGroup g1 = SceneHelpers.AddSceneObject(scene);
92
93 g1.GroupResize(firstSize);
94 g1.GroupResize(secondSize);
95 g1.GroupResize(thirdSize);
96 g1.GroupResize(fourthSize);
97
98 g1.RootPart.Undo();
99 g1.RootPart.Undo();
100 g1.RootPart.Undo();
101
102 Assert.That(g1.RootPart.UndoCount, Is.EqualTo(0));
103 Assert.That(g1.GroupScale, Is.EqualTo(secondSize));
104 }
105
106 [Test]
107 public void TestNoUndoOnObjectsNotInScene()
108 {
109 TestHelpers.InMethod();
110
111 Vector3 firstSize = new Vector3(2, 3, 4);
112 Vector3 secondSize = new Vector3(5, 6, 7);
113// Vector3 thirdSize = new Vector3(8, 9, 10);
114// Vector3 fourthSize = new Vector3(11, 12, 13);
115
116 Scene scene = new SceneHelpers().SetupScene();
117 scene.MaxUndoCount = 20;
118 SceneObjectGroup g1 = SceneHelpers.CreateSceneObject(1, TestHelpers.ParseTail(0x1));
119
120 g1.GroupResize(firstSize);
121 g1.GroupResize(secondSize);
122
123 Assert.That(g1.RootPart.UndoCount, Is.EqualTo(0));
124
125 g1.RootPart.Undo();
126
127 Assert.That(g1.GroupScale, Is.EqualTo(secondSize));
128 }
129
130 [Test]
131 public void TestUndoBeyondAvailable()
132 {
133 TestHelpers.InMethod();
134
135 Vector3 newSize = new Vector3(2, 3, 4);
136
137 Scene scene = new SceneHelpers().SetupScene();
138 scene.MaxUndoCount = 20;
139 SceneObjectGroup g1 = SceneHelpers.AddSceneObject(scene);
140 Vector3 originalSize = g1.GroupScale;
141
142 g1.RootPart.Undo();
143
144 Assert.That(g1.RootPart.UndoCount, Is.EqualTo(0));
145 Assert.That(g1.GroupScale, Is.EqualTo(originalSize));
146
147 g1.GroupResize(newSize);
148 Assert.That(g1.RootPart.UndoCount, Is.EqualTo(1));
149 Assert.That(g1.GroupScale, Is.EqualTo(newSize));
150
151 g1.RootPart.Undo();
152 g1.RootPart.Undo();
153
154 Assert.That(g1.RootPart.UndoCount, Is.EqualTo(0));
155 Assert.That(g1.GroupScale, Is.EqualTo(originalSize));
156 }
157
158 [Test]
159 public void TestRedoBeyondAvailable()
160 {
161 TestHelpers.InMethod();
162
163 Vector3 newSize = new Vector3(2, 3, 4);
164
165 Scene scene = new SceneHelpers().SetupScene();
166 scene.MaxUndoCount = 20;
167 SceneObjectGroup g1 = SceneHelpers.AddSceneObject(scene);
168 Vector3 originalSize = g1.GroupScale;
169
170 g1.RootPart.Redo();
171
172 Assert.That(g1.RootPart.UndoCount, Is.EqualTo(0));
173 Assert.That(g1.GroupScale, Is.EqualTo(originalSize));
174
175 g1.GroupResize(newSize);
176 g1.RootPart.Undo();
177 g1.RootPart.Redo();
178 g1.RootPart.Redo();
179
180 Assert.That(g1.RootPart.UndoCount, Is.EqualTo(1));
181 Assert.That(g1.GroupScale, Is.EqualTo(newSize));
182 }
183 }
184} \ No newline at end of file
diff --git a/OpenSim/Region/Framework/Scenes/Tests/SceneObjectUserGroupTests.cs b/OpenSim/Region/Framework/Scenes/Tests/SceneObjectUserGroupTests.cs
index 2b79271..c7eaff9 100644
--- a/OpenSim/Region/Framework/Scenes/Tests/SceneObjectUserGroupTests.cs
+++ b/OpenSim/Region/Framework/Scenes/Tests/SceneObjectUserGroupTests.cs
@@ -44,7 +44,7 @@ using OpenSim.Tests.Common.Mock;
44namespace OpenSim.Region.Framework.Scenes.Tests 44namespace OpenSim.Region.Framework.Scenes.Tests
45{ 45{
46 [TestFixture] 46 [TestFixture]
47 public class SceneObjectUserGroupTests : OpenSimTestCase 47 public class SceneObjectUserGroupTests
48 { 48 {
49 /// <summary> 49 /// <summary>
50 /// Test share with group object functionality 50 /// Test share with group object functionality
@@ -54,6 +54,7 @@ namespace OpenSim.Region.Framework.Scenes.Tests
54 public void TestShareWithGroup() 54 public void TestShareWithGroup()
55 { 55 {
56 TestHelpers.InMethod(); 56 TestHelpers.InMethod();
57// log4net.Config.XmlConfigurator.Configure();
57 58
58 UUID userId = UUID.Parse("10000000-0000-0000-0000-000000000001"); 59 UUID userId = UUID.Parse("10000000-0000-0000-0000-000000000001");
59 60
diff --git a/OpenSim/Region/Framework/Scenes/UndoState.cs b/OpenSim/Region/Framework/Scenes/UndoState.cs
index 860172c..7bbf1bd 100644
--- a/OpenSim/Region/Framework/Scenes/UndoState.cs
+++ b/OpenSim/Region/Framework/Scenes/UndoState.cs
@@ -27,202 +27,307 @@
27 27
28using System; 28using System;
29using System.Reflection; 29using System.Reflection;
30using System.Collections.Generic;
30using log4net; 31using log4net;
31using OpenMetaverse; 32using OpenMetaverse;
33using OpenSim.Framework;
32using OpenSim.Region.Framework.Interfaces; 34using OpenSim.Region.Framework.Interfaces;
33 35
34namespace OpenSim.Region.Framework.Scenes 36namespace OpenSim.Region.Framework.Scenes
35{ 37{
36 public class UndoState 38 public class UndoState
37 { 39 {
38// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); 40 const int UNDOEXPIRESECONDS = 300; // undo expire time (nice to have it came from a ini later)
39
40 public Vector3 Position = Vector3.Zero;
41 public Vector3 Scale = Vector3.Zero;
42 public Quaternion Rotation = Quaternion.Identity;
43
44 /// <summary>
45 /// Is this undo state for an entire group?
46 /// </summary>
47 public bool ForGroup;
48 41
42 public ObjectChangeData data;
43 public DateTime creationtime;
49 /// <summary> 44 /// <summary>
50 /// Constructor. 45 /// Constructor.
51 /// </summary> 46 /// </summary>
52 /// <param name="part"></param> 47 /// <param name="part"></param>
53 /// <param name="forGroup">True if the undo is for an entire group</param> 48 /// <param name="change">bit field with what is changed</param>
54 public UndoState(SceneObjectPart part, bool forGroup) 49 ///
50 public UndoState(SceneObjectPart part, ObjectChangeType change)
55 { 51 {
56 if (part.ParentID == 0) 52 data = new ObjectChangeData();
57 { 53 data.change = change;
58 ForGroup = forGroup; 54 creationtime = DateTime.UtcNow;
59
60// if (ForGroup)
61 Position = part.ParentGroup.AbsolutePosition;
62// else
63// Position = part.OffsetPosition;
64
65// m_log.DebugFormat(
66// "[UNDO STATE]: Storing undo position {0} for root part", Position);
67 55
68 Rotation = part.RotationOffset; 56 if (part.ParentGroup.RootPart == part)
69 57 {
70// m_log.DebugFormat( 58 if ((change & ObjectChangeType.Position) != 0)
71// "[UNDO STATE]: Storing undo rotation {0} for root part", Rotation); 59 data.position = part.ParentGroup.AbsolutePosition;
72 60 if ((change & ObjectChangeType.Rotation) != 0)
73 Scale = part.Shape.Scale; 61 data.rotation = part.RotationOffset;
74 62 if ((change & ObjectChangeType.Scale) != 0)
75// m_log.DebugFormat( 63 data.scale = part.Shape.Scale;
76// "[UNDO STATE]: Storing undo scale {0} for root part", Scale);
77 } 64 }
78 else 65 else
79 { 66 {
80 Position = part.OffsetPosition; 67 if ((change & ObjectChangeType.Position) != 0)
81// m_log.DebugFormat( 68 data.position = part.OffsetPosition;
82// "[UNDO STATE]: Storing undo position {0} for child part", Position); 69 if ((change & ObjectChangeType.Rotation) != 0)
70 data.rotation = part.RotationOffset;
71 if ((change & ObjectChangeType.Scale) != 0)
72 data.scale = part.Shape.Scale;
73 }
74 }
75 /// <summary>
76 /// check if undo or redo is too old
77 /// </summary>
83 78
84 Rotation = part.RotationOffset; 79 public bool checkExpire()
85// m_log.DebugFormat( 80 {
86// "[UNDO STATE]: Storing undo rotation {0} for child part", Rotation); 81 TimeSpan t = DateTime.UtcNow - creationtime;
82 if (t.Seconds > UNDOEXPIRESECONDS)
83 return true;
84 return false;
85 }
87 86
88 Scale = part.Shape.Scale; 87 /// <summary>
89// m_log.DebugFormat( 88 /// updates undo or redo creation time to now
90// "[UNDO STATE]: Storing undo scale {0} for child part", Scale); 89 /// </summary>
91 } 90 public void updateExpire()
91 {
92 creationtime = DateTime.UtcNow;
92 } 93 }
93 94
94 /// <summary> 95 /// <summary>
95 /// Compare the relevant state in the given part to this state. 96 /// Compare the relevant state in the given part to this state.
96 /// </summary> 97 /// </summary>
97 /// <param name="part"></param> 98 /// <param name="part"></param>
98 /// <returns>true if both the part's position, rotation and scale match those in this undo state. False otherwise.</returns> 99 /// <returns>true what fiels and related data are equal, False otherwise.</returns>
99 public bool Compare(SceneObjectPart part) 100 ///
101 public bool Compare(SceneObjectPart part, ObjectChangeType change)
100 { 102 {
103 if (data.change != change) // if diferent targets, then they are diferent
104 return false;
105
101 if (part != null) 106 if (part != null)
102 { 107 {
103 if (part.ParentID == 0) 108 if (part.ParentID == 0)
104 return 109 {
105 Position == part.ParentGroup.AbsolutePosition 110 if ((change & ObjectChangeType.Position) != 0 && data.position != part.ParentGroup.AbsolutePosition)
106 && Rotation == part.RotationOffset 111 return false;
107 && Scale == part.Shape.Scale; 112 }
108 else 113 else
109 return 114 {
110 Position == part.OffsetPosition 115 if ((change & ObjectChangeType.Position) != 0 && data.position != part.OffsetPosition)
111 && Rotation == part.RotationOffset 116 return false;
112 && Scale == part.Shape.Scale; 117 }
113 } 118
119 if ((change & ObjectChangeType.Rotation) != 0 && data.rotation != part.RotationOffset)
120 return false;
121 if ((change & ObjectChangeType.Rotation) != 0 && data.scale == part.Shape.Scale)
122 return false;
123 return true;
114 124
125 }
115 return false; 126 return false;
116 } 127 }
117 128
118 public void PlaybackState(SceneObjectPart part) 129 /// <summary>
130 /// executes the undo or redo to a part or its group
131 /// </summary>
132 /// <param name="part"></param>
133 ///
134
135 public void PlayState(SceneObjectPart part)
119 { 136 {
120 part.Undoing = true; 137 part.Undoing = true;
121 138
122 if (part.ParentID == 0) 139 SceneObjectGroup grp = part.ParentGroup;
123 {
124// m_log.DebugFormat(
125// "[UNDO STATE]: Undoing position to {0} for root part {1} {2}",
126// Position, part.Name, part.LocalId);
127 140
128 if (Position != Vector3.Zero) 141 if (grp != null)
129 { 142 {
130 if (ForGroup) 143 grp.doChangeObject(part, data);
131 part.ParentGroup.AbsolutePosition = Position; 144 }
132 else 145 part.Undoing = false;
133 part.ParentGroup.UpdateRootPosition(Position); 146 }
134 } 147 }
135 148
136// m_log.DebugFormat( 149 public class UndoRedoState
137// "[UNDO STATE]: Undoing rotation {0} to {1} for root part {2} {3}", 150 {
138// part.RotationOffset, Rotation, part.Name, part.LocalId); 151 int size;
152 public LinkedList<UndoState> m_redo = new LinkedList<UndoState>();
153 public LinkedList<UndoState> m_undo = new LinkedList<UndoState>();
139 154
140 if (ForGroup) 155 /// <summary>
141 part.UpdateRotation(Rotation); 156 /// creates a new UndoRedoState with default states memory size
142 else 157 /// </summary>
143 part.ParentGroup.UpdateRootRotation(Rotation);
144 158
145 if (Scale != Vector3.Zero) 159 public UndoRedoState()
146 { 160 {
147// m_log.DebugFormat( 161 size = 5;
148// "[UNDO STATE]: Undoing scale {0} to {1} for root part {2} {3}", 162 }
149// part.Shape.Scale, Scale, part.Name, part.LocalId);
150 163
151 if (ForGroup) 164 /// <summary>
152 part.ParentGroup.GroupResize(Scale); 165 /// creates a new UndoRedoState with states memory having indicated size
153 else 166 /// </summary>
154 part.Resize(Scale); 167 /// <param name="size"></param>
155 }
156 168
157 part.ParentGroup.ScheduleGroupForTerseUpdate(); 169 public UndoRedoState(int _size)
158 } 170 {
171 if (_size < 3)
172 size = 3;
159 else 173 else
160 { 174 size = _size;
161 // Note: Updating these properties on sop automatically schedules an update if needed 175 }
162 if (Position != Vector3.Zero)
163 {
164// m_log.DebugFormat(
165// "[UNDO STATE]: Undoing position {0} to {1} for child part {2} {3}",
166// part.OffsetPosition, Position, part.Name, part.LocalId);
167 176
168 part.OffsetPosition = Position; 177 /// <summary>
169 } 178 /// returns number of undo entries in memory
179 /// </summary>
170 180
171// m_log.DebugFormat( 181 public int Count
172// "[UNDO STATE]: Undoing rotation {0} to {1} for child part {2} {3}", 182 {
173// part.RotationOffset, Rotation, part.Name, part.LocalId); 183 get { return m_undo.Count; }
184 }
174 185
175 part.UpdateRotation(Rotation); 186 /// <summary>
187 /// clears all undo and redo entries
188 /// </summary>
176 189
177 if (Scale != Vector3.Zero) 190 public void Clear()
191 {
192 m_undo.Clear();
193 m_redo.Clear();
194 }
195
196 /// <summary>
197 /// adds a new state undo to part or its group, with changes indicated by what bits
198 /// </summary>
199 /// <param name="part"></param>
200 /// <param name="change">bit field with what is changed</param>
201
202 public void StoreUndo(SceneObjectPart part, ObjectChangeType change)
203 {
204 lock (m_undo)
205 {
206 UndoState last;
207
208 if (m_redo.Count > 0) // last code seems to clear redo on every new undo
178 { 209 {
179// m_log.DebugFormat( 210 m_redo.Clear();
180// "[UNDO STATE]: Undoing scale {0} to {1} for child part {2} {3}", 211 }
181// part.Shape.Scale, Scale, part.Name, part.LocalId);
182 212
183 part.Resize(Scale); 213 if (m_undo.Count > 0)
214 {
215 // check expired entry
216 last = m_undo.First.Value;
217 if (last != null && last.checkExpire())
218 m_undo.Clear();
219 else
220 {
221 // see if we actually have a change
222 if (last != null)
223 {
224 if (last.Compare(part, change))
225 return;
226 }
227 }
184 } 228 }
185 }
186 229
187 part.Undoing = false; 230 // limite size
231 while (m_undo.Count >= size)
232 m_undo.RemoveLast();
233
234 UndoState nUndo = new UndoState(part, change);
235 m_undo.AddFirst(nUndo);
236 }
188 } 237 }
189 238
190 public void PlayfwdState(SceneObjectPart part) 239 /// <summary>
191 { 240 /// executes last state undo to part or its group
192 part.Undoing = true; 241 /// current state is pushed into redo
242 /// </summary>
243 /// <param name="part"></param>
193 244
194 if (part.ParentID == 0) 245 public void Undo(SceneObjectPart part)
246 {
247 lock (m_undo)
195 { 248 {
196 if (Position != Vector3.Zero) 249 UndoState nUndo;
197 part.ParentGroup.AbsolutePosition = Position;
198
199 if (Rotation != Quaternion.Identity)
200 part.UpdateRotation(Rotation);
201 250
202 if (Scale != Vector3.Zero) 251 // expire redo
252 if (m_redo.Count > 0)
203 { 253 {
204 if (ForGroup) 254 nUndo = m_redo.First.Value;
205 part.ParentGroup.GroupResize(Scale); 255 if (nUndo != null && nUndo.checkExpire())
206 else 256 m_redo.Clear();
207 part.Resize(Scale);
208 } 257 }
209 258
210 part.ParentGroup.ScheduleGroupForTerseUpdate(); 259 if (m_undo.Count > 0)
260 {
261 UndoState goback = m_undo.First.Value;
262 // check expired
263 if (goback != null && goback.checkExpire())
264 {
265 m_undo.Clear();
266 return;
267 }
268
269 if (goback != null)
270 {
271 m_undo.RemoveFirst();
272
273 // redo limite size
274 while (m_redo.Count >= size)
275 m_redo.RemoveLast();
276
277 nUndo = new UndoState(part, goback.data.change); // new value in part should it be full goback copy?
278 m_redo.AddFirst(nUndo);
279
280 goback.PlayState(part);
281 }
282 }
211 } 283 }
212 else 284 }
285
286 /// <summary>
287 /// executes last state redo to part or its group
288 /// current state is pushed into undo
289 /// </summary>
290 /// <param name="part"></param>
291
292 public void Redo(SceneObjectPart part)
293 {
294 lock (m_undo)
213 { 295 {
214 // Note: Updating these properties on sop automatically schedules an update if needed 296 UndoState nUndo;
215 if (Position != Vector3.Zero)
216 part.OffsetPosition = Position;
217 297
218 if (Rotation != Quaternion.Identity) 298 // expire undo
219 part.UpdateRotation(Rotation); 299 if (m_undo.Count > 0)
300 {
301 nUndo = m_undo.First.Value;
302 if (nUndo != null && nUndo.checkExpire())
303 m_undo.Clear();
304 }
220 305
221 if (Scale != Vector3.Zero) 306 if (m_redo.Count > 0)
222 part.Resize(Scale); 307 {
308 UndoState gofwd = m_redo.First.Value;
309 // check expired
310 if (gofwd != null && gofwd.checkExpire())
311 {
312 m_redo.Clear();
313 return;
314 }
315
316 if (gofwd != null)
317 {
318 m_redo.RemoveFirst();
319
320 // limite undo size
321 while (m_undo.Count >= size)
322 m_undo.RemoveLast();
323
324 nUndo = new UndoState(part, gofwd.data.change); // new value in part should it be full gofwd copy?
325 m_undo.AddFirst(nUndo);
326
327 gofwd.PlayState(part);
328 }
329 }
223 } 330 }
224
225 part.Undoing = false;
226 } 331 }
227 } 332 }
228 333
@@ -247,4 +352,4 @@ namespace OpenSim.Region.Framework.Scenes
247 m_terrainModule.UndoTerrain(m_terrainChannel); 352 m_terrainModule.UndoTerrain(m_terrainChannel);
248 } 353 }
249 } 354 }
250} \ No newline at end of file 355}
diff --git a/OpenSim/Region/Framework/Scenes/UuidGatherer.cs b/OpenSim/Region/Framework/Scenes/UuidGatherer.cs
index ad33607..b09ae39 100644
--- a/OpenSim/Region/Framework/Scenes/UuidGatherer.cs
+++ b/OpenSim/Region/Framework/Scenes/UuidGatherer.cs
@@ -84,10 +84,6 @@ namespace OpenSim.Region.Framework.Scenes
84 /// <param name="assetUuids">The assets gathered</param> 84 /// <param name="assetUuids">The assets gathered</param>
85 public void GatherAssetUuids(UUID assetUuid, AssetType assetType, IDictionary<UUID, AssetType> assetUuids) 85 public void GatherAssetUuids(UUID assetUuid, AssetType assetType, IDictionary<UUID, AssetType> assetUuids)
86 { 86 {
87 // avoid infinite loops
88 if (assetUuids.ContainsKey(assetUuid))
89 return;
90
91 try 87 try
92 { 88 {
93 assetUuids[assetUuid] = assetType; 89 assetUuids[assetUuid] = assetType;