aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs
diff options
context:
space:
mode:
Diffstat (limited to 'OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs')
-rw-r--r--OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs526
1 files changed, 374 insertions, 152 deletions
diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs
index 4c195e1..7603254 100644
--- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs
+++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs
@@ -56,19 +56,19 @@ public sealed class BSCharacter : BSPhysObject
56 private int _physicsActorType; 56 private int _physicsActorType;
57 private bool _isPhysical; 57 private bool _isPhysical;
58 private bool _flying; 58 private bool _flying;
59 private bool _wasWalking; // 'true' if the avatar was walking/moving last frame
59 private bool _setAlwaysRun; 60 private bool _setAlwaysRun;
60 private bool _throttleUpdates; 61 private bool _throttleUpdates;
61 private bool _isColliding;
62 private bool _collidingObj;
63 private bool _floatOnWater; 62 private bool _floatOnWater;
64 private OMV.Vector3 _rotationalVelocity; 63 private OMV.Vector3 _rotationalVelocity;
65 private bool _kinematic; 64 private bool _kinematic;
66 private float _buoyancy; 65 private float _buoyancy;
67 66
68 // The friction and velocity of the avatar is modified depending on whether walking or not. 67 // The friction and velocity of the avatar is modified depending on whether walking or not.
69 private OMV.Vector3 _appliedVelocity; // the last velocity applied to the avatar
70 private float _currentFriction; // the friction currently being used (changed by setVelocity). 68 private float _currentFriction; // the friction currently being used (changed by setVelocity).
71 69
70 private BSVMotor _velocityMotor;
71
72 private OMV.Vector3 _PIDTarget; 72 private OMV.Vector3 _PIDTarget;
73 private bool _usePID; 73 private bool _usePID;
74 private float _PIDTau; 74 private float _PIDTau;
@@ -83,34 +83,37 @@ public sealed class BSCharacter : BSPhysObject
83 _physicsActorType = (int)ActorTypes.Agent; 83 _physicsActorType = (int)ActorTypes.Agent;
84 _position = pos; 84 _position = pos;
85 85
86 // Old versions of ScenePresence passed only the height. If width and/or depth are zero,
87 // replace with the default values.
88 _size = size;
89 if (_size.X == 0f) _size.X = PhysicsScene.Params.avatarCapsuleDepth;
90 if (_size.Y == 0f) _size.Y = PhysicsScene.Params.avatarCapsuleWidth;
91
92 _flying = isFlying; 86 _flying = isFlying;
87 _wasWalking = true; // causes first step to initialize standing
93 _orientation = OMV.Quaternion.Identity; 88 _orientation = OMV.Quaternion.Identity;
94 _velocity = OMV.Vector3.Zero; 89 _velocity = OMV.Vector3.Zero;
95 _appliedVelocity = OMV.Vector3.Zero;
96 _buoyancy = ComputeBuoyancyFromFlying(isFlying); 90 _buoyancy = ComputeBuoyancyFromFlying(isFlying);
97 _currentFriction = PhysicsScene.Params.avatarStandingFriction; 91 _currentFriction = BSParam.AvatarStandingFriction;
98 _avatarDensity = PhysicsScene.Params.avatarDensity; 92 _avatarDensity = BSParam.AvatarDensity;
93
94 // Old versions of ScenePresence passed only the height. If width and/or depth are zero,
95 // replace with the default values.
96 _size = size;
97 if (_size.X == 0f) _size.X = BSParam.AvatarCapsuleDepth;
98 if (_size.Y == 0f) _size.Y = BSParam.AvatarCapsuleWidth;
99 99
100 // The dimensions of the avatar capsule are kept in the scale. 100 // The dimensions of the physical capsule are kept in the scale.
101 // Physics creates a unit capsule which is scaled by the physics engine. 101 // Physics creates a unit capsule which is scaled by the physics engine.
102 ComputeAvatarScale(_size); 102 Scale = ComputeAvatarScale(_size);
103 // set _avatarVolume and _mass based on capsule size, _density and Scale 103 // set _avatarVolume and _mass based on capsule size, _density and Scale
104 ComputeAvatarVolumeAndMass(); 104 ComputeAvatarVolumeAndMass();
105
106 SetupMovementMotor();
107
105 DetailLog("{0},BSCharacter.create,call,size={1},scale={2},density={3},volume={4},mass={5}", 108 DetailLog("{0},BSCharacter.create,call,size={1},scale={2},density={3},volume={4},mass={5}",
106 LocalID, _size, Scale, _avatarDensity, _avatarVolume, RawMass); 109 LocalID, _size, Scale, _avatarDensity, _avatarVolume, RawMass);
107 110
108 // do actual create at taint time 111 // do actual creation in taint time
109 PhysicsScene.TaintedObject("BSCharacter.create", delegate() 112 PhysicsScene.TaintedObject("BSCharacter.create", delegate()
110 { 113 {
111 DetailLog("{0},BSCharacter.create,taint", LocalID); 114 DetailLog("{0},BSCharacter.create,taint", LocalID);
112 // New body and shape into PhysBody and PhysShape 115 // New body and shape into PhysBody and PhysShape
113 PhysicsScene.Shapes.GetBodyAndShape(true, PhysicsScene.World, this, null, null); 116 PhysicsScene.Shapes.GetBodyAndShape(true, PhysicsScene.World, this);
114 117
115 SetPhysicalProperties(); 118 SetPhysicalProperties();
116 }); 119 });
@@ -120,54 +123,198 @@ public sealed class BSCharacter : BSPhysObject
120 // called when this character is being destroyed and the resources should be released 123 // called when this character is being destroyed and the resources should be released
121 public override void Destroy() 124 public override void Destroy()
122 { 125 {
126 base.Destroy();
127
123 DetailLog("{0},BSCharacter.Destroy", LocalID); 128 DetailLog("{0},BSCharacter.Destroy", LocalID);
124 PhysicsScene.TaintedObject("BSCharacter.destroy", delegate() 129 PhysicsScene.TaintedObject("BSCharacter.destroy", delegate()
125 { 130 {
126 PhysicsScene.Shapes.DereferenceBody(PhysBody, true, null); 131 PhysicsScene.Shapes.DereferenceBody(PhysBody, true /* inTaintTime */, null /* bodyCallback */);
127 PhysicsScene.Shapes.DereferenceShape(PhysShape, true, null); 132 PhysBody.Clear();
133 PhysicsScene.Shapes.DereferenceShape(PhysShape, true /* inTaintTime */, null /* bodyCallback */);
134 PhysShape.Clear();
128 }); 135 });
129 } 136 }
130 137
131 private void SetPhysicalProperties() 138 private void SetPhysicalProperties()
132 { 139 {
133 BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.ptr, PhysBody.ptr); 140 PhysicsScene.PE.RemoveObjectFromWorld(PhysicsScene.World, PhysBody);
134 141
135 ZeroMotion(true); 142 ZeroMotion(true);
136 ForcePosition = _position; 143 ForcePosition = _position;
144
137 // Set the velocity and compute the proper friction 145 // Set the velocity and compute the proper friction
146 _velocityMotor.Reset();
147 _velocityMotor.SetTarget(_velocity);
148 _velocityMotor.SetCurrent(_velocity);
138 ForceVelocity = _velocity; 149 ForceVelocity = _velocity;
139 150
140 // This will enable or disable the flying buoyancy of the avatar. 151 // This will enable or disable the flying buoyancy of the avatar.
141 // Needs to be reset especially when an avatar is recreated after crossing a region boundry. 152 // Needs to be reset especially when an avatar is recreated after crossing a region boundry.
142 Flying = _flying; 153 Flying = _flying;
143 154
144 BulletSimAPI.SetRestitution2(PhysBody.ptr, PhysicsScene.Params.avatarRestitution); 155 PhysicsScene.PE.SetRestitution(PhysBody, BSParam.AvatarRestitution);
145 BulletSimAPI.SetMargin2(PhysShape.ptr, PhysicsScene.Params.collisionMargin); 156 PhysicsScene.PE.SetMargin(PhysShape, PhysicsScene.Params.collisionMargin);
146 BulletSimAPI.SetLocalScaling2(PhysShape.ptr, Scale); 157 PhysicsScene.PE.SetLocalScaling(PhysShape, Scale);
147 BulletSimAPI.SetContactProcessingThreshold2(PhysBody.ptr, PhysicsScene.Params.contactProcessingThreshold); 158 PhysicsScene.PE.SetContactProcessingThreshold(PhysBody, BSParam.ContactProcessingThreshold);
148 if (PhysicsScene.Params.ccdMotionThreshold > 0f) 159 if (BSParam.CcdMotionThreshold > 0f)
149 { 160 {
150 BulletSimAPI.SetCcdMotionThreshold2(PhysBody.ptr, PhysicsScene.Params.ccdMotionThreshold); 161 PhysicsScene.PE.SetCcdMotionThreshold(PhysBody, BSParam.CcdMotionThreshold);
151 BulletSimAPI.SetCcdSweptSphereRadius2(PhysBody.ptr, PhysicsScene.Params.ccdSweptSphereRadius); 162 PhysicsScene.PE.SetCcdSweptSphereRadius(PhysBody, BSParam.CcdSweptSphereRadius);
152 } 163 }
153 164
154 UpdatePhysicalMassProperties(RawMass); 165 UpdatePhysicalMassProperties(RawMass, false);
155 166
156 // Make so capsule does not fall over 167 // Make so capsule does not fall over
157 BulletSimAPI.SetAngularFactorV2(PhysBody.ptr, OMV.Vector3.Zero); 168 PhysicsScene.PE.SetAngularFactorV(PhysBody, OMV.Vector3.Zero);
158 169
159 BulletSimAPI.AddToCollisionFlags2(PhysBody.ptr, CollisionFlags.CF_CHARACTER_OBJECT); 170 PhysicsScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.CF_CHARACTER_OBJECT);
160 171
161 BulletSimAPI.AddObjectToWorld2(PhysicsScene.World.ptr, PhysBody.ptr); 172 PhysicsScene.PE.AddObjectToWorld(PhysicsScene.World, PhysBody);
162 173
163 // BulletSimAPI.ForceActivationState2(BSBody.ptr, ActivationState.ACTIVE_TAG); 174 // PhysicsScene.PE.ForceActivationState(PhysBody, ActivationState.ACTIVE_TAG);
164 BulletSimAPI.ForceActivationState2(PhysBody.ptr, ActivationState.DISABLE_DEACTIVATION); 175 PhysicsScene.PE.ForceActivationState(PhysBody, ActivationState.DISABLE_DEACTIVATION);
165 BulletSimAPI.UpdateSingleAabb2(PhysicsScene.World.ptr, PhysBody.ptr); 176 PhysicsScene.PE.UpdateSingleAabb(PhysicsScene.World, PhysBody);
166 177
167 // Do this after the object has been added to the world 178 // Do this after the object has been added to the world
168 BulletSimAPI.SetCollisionFilterMask2(PhysBody.ptr, 179 PhysBody.collisionType = CollisionType.Avatar;
169 (uint)CollisionFilterGroups.AvatarFilter, 180 PhysBody.ApplyCollisionMask(PhysicsScene);
170 (uint)CollisionFilterGroups.AvatarMask); 181 }
182
183 // The avatar's movement is controlled by this motor that speeds up and slows down
184 // the avatar seeking to reach the motor's target speed.
185 // This motor runs as a prestep action for the avatar so it will keep the avatar
186 // standing as well as moving. Destruction of the avatar will destroy the pre-step action.
187 private void SetupMovementMotor()
188 {
189 // Infinite decay and timescale values so motor only changes current to target values.
190 _velocityMotor = new BSVMotor("BSCharacter.Velocity",
191 0.2f, // time scale
192 BSMotor.Infinite, // decay time scale
193 BSMotor.InfiniteVector, // friction timescale
194 1f // efficiency
195 );
196 // _velocityMotor.PhysicsScene = PhysicsScene; // DEBUG DEBUG so motor will output detail log messages.
197
198 RegisterPreStepAction("BSCharactor.Movement", LocalID, delegate(float timeStep)
199 {
200 // TODO: Decide if the step parameters should be changed depending on the avatar's
201 // state (flying, colliding, ...). There is code in ODE to do this.
202
203 // COMMENTARY: when the user is making the avatar walk, except for falling, the velocity
204 // specified for the avatar is the one that should be used. For falling, if the avatar
205 // is not flying and is not colliding then it is presumed to be falling and the Z
206 // component is not fooled with (thus allowing gravity to do its thing).
207 // When the avatar is standing, though, the user has specified a velocity of zero and
208 // the avatar should be standing. But if the avatar is pushed by something in the world
209 // (raising elevator platform, moving vehicle, ...) the avatar should be allowed to
210 // move. Thus, the velocity cannot be forced to zero. The problem is that small velocity
211 // errors can creap in and the avatar will slowly float off in some direction.
212 // So, the problem is that, when an avatar is standing, we cannot tell creaping error
213 // from real pushing.OMV.Vector3.Zero;
214 // The code below keeps setting the velocity to zero hoping the world will keep pushing.
215
216 _velocityMotor.Step(timeStep);
217
218 // If we're not supposed to be moving, make sure things are zero.
219 if (_velocityMotor.ErrorIsZero() && _velocityMotor.TargetValue == OMV.Vector3.Zero && IsColliding)
220 {
221 // The avatar shouldn't be moving
222 _velocityMotor.Zero();
223 ZeroMotion(true /* inTaintTime */);
224
225 // Standing has more friction on the ground
226 if (_currentFriction != BSParam.AvatarStandingFriction)
227 {
228 _currentFriction = BSParam.AvatarStandingFriction;
229 PhysicsScene.PE.SetFriction(PhysBody, _currentFriction);
230 }
231 DetailLog("{0},BSCharacter.MoveMotor,taint,stopping,target={1}", LocalID, _velocityMotor.TargetValue);
232
233 _wasWalking = false;
234 }
235 else
236 {
237 OMV.Vector3 stepVelocity = _velocityMotor.CurrentValue;
238
239 if (_currentFriction != BSParam.AvatarFriction)
240 {
241 // Probably starting up walking. Set friction to moving friction.
242 _currentFriction = BSParam.AvatarFriction;
243 PhysicsScene.PE.SetFriction(PhysBody, _currentFriction);
244 }
245
246 // If falling, we keep the world's downward vector no matter what the other axis specify.
247 if (!Flying && !IsColliding)
248 {
249 stepVelocity.Z = _velocity.Z;
250 // DetailLog("{0},BSCharacter.MoveMotor,taint,overrideStepZWithWorldZ,stepVel={1}", LocalID, stepVelocity);
251 }
252
253 // 'stepVelocity' is now the speed we'd like the avatar to move in. Turn that into an instantanous force.
254 OMV.Vector3 moveForce = (stepVelocity - _velocity) * Mass;
255
256 // Should we check for move force being small and forcing velocity to zero?
257
258 // Add special movement force to allow avatars to walk up stepped surfaces.
259 moveForce += WalkUpStairs();
260
261 DetailLog("{0},BSCharacter.MoveMotor,move,stepVel={1},vel={2},mass={3},moveForce={4}", LocalID, stepVelocity, _velocity, Mass, moveForce);
262 PhysicsScene.PE.ApplyCentralImpulse(PhysBody, moveForce);
263 _wasWalking = true;
264 }
265 });
266 }
267
268 // Decide of the character is colliding with a low object and compute a force to pop the
269 // avatar up so it has a chance of walking up and over the low object.
270 private OMV.Vector3 WalkUpStairs()
271 {
272 OMV.Vector3 ret = OMV.Vector3.Zero;
273
274 // This test is done if moving forward, not flying and is colliding with something.
275 // DetailLog("{0},BSCharacter.WalkUpStairs,IsColliding={1},flying={2},targSpeed={3},collisions={4}",
276 // LocalID, IsColliding, Flying, TargetSpeed, CollisionsLastTick.Count);
277 if (IsColliding && !Flying && TargetSpeed > 0.1f /* && ForwardSpeed < 0.1f */)
278 {
279 // The range near the character's feet where we will consider stairs
280 float nearFeetHeightMin = RawPosition.Z - (Size.Z / 2f) + 0.05f;
281 float nearFeetHeightMax = nearFeetHeightMin + BSParam.AvatarStepHeight;
282
283 // Look for a collision point that is near the character's feet and is oriented the same as the charactor is
284 foreach (KeyValuePair<uint, ContactPoint> kvp in CollisionsLastTick.m_objCollisionList)
285 {
286 // Don't care about collisions with the terrain
287 if (kvp.Key > PhysicsScene.TerrainManager.HighestTerrainID)
288 {
289 OMV.Vector3 touchPosition = kvp.Value.Position;
290 // DetailLog("{0},BSCharacter.WalkUpStairs,min={1},max={2},touch={3}",
291 // LocalID, nearFeetHeightMin, nearFeetHeightMax, touchPosition);
292 if (touchPosition.Z >= nearFeetHeightMin && touchPosition.Z <= nearFeetHeightMax)
293 {
294 // This contact is within the 'near the feet' range.
295 // The normal should be our contact point to the object so it is pointing away
296 // thus the difference between our facing orientation and the normal should be small.
297 OMV.Vector3 directionFacing = OMV.Vector3.UnitX * RawOrientation;
298 OMV.Vector3 touchNormal = OMV.Vector3.Normalize(kvp.Value.SurfaceNormal);
299 float diff = Math.Abs(OMV.Vector3.Distance(directionFacing, touchNormal));
300 if (diff < BSParam.AvatarStepApproachFactor)
301 {
302 // Found the stairs contact point. Push up a little to raise the character.
303 float upForce = (touchPosition.Z - nearFeetHeightMin) * Mass * BSParam.AvatarStepForceFactor;
304 ret = new OMV.Vector3(0f, 0f, upForce);
305
306 // Also move the avatar up for the new height
307 OMV.Vector3 displacement = new OMV.Vector3(0f, 0f, BSParam.AvatarStepHeight / 2f);
308 ForcePosition = RawPosition + displacement;
309 }
310 DetailLog("{0},BSCharacter.WalkUpStairs,touchPos={1},nearFeetMin={2},faceDir={3},norm={4},diff={5},ret={6}",
311 LocalID, touchPosition, nearFeetHeightMin, directionFacing, touchNormal, diff, ret);
312 }
313 }
314 }
315 }
316
317 return ret;
171 } 318 }
172 319
173 public override void RequestPhysicsterseUpdate() 320 public override void RequestPhysicsterseUpdate()
@@ -185,24 +332,31 @@ public sealed class BSCharacter : BSPhysObject
185 } 332 }
186 333
187 set { 334 set {
188 // When an avatar's size is set, only the height is changed.
189 _size = value; 335 _size = value;
190 ComputeAvatarScale(_size); 336 // Old versions of ScenePresence passed only the height. If width and/or depth are zero,
337 // replace with the default values.
338 if (_size.X == 0f) _size.X = BSParam.AvatarCapsuleDepth;
339 if (_size.Y == 0f) _size.Y = BSParam.AvatarCapsuleWidth;
340
341 Scale = ComputeAvatarScale(_size);
191 ComputeAvatarVolumeAndMass(); 342 ComputeAvatarVolumeAndMass();
192 DetailLog("{0},BSCharacter.setSize,call,size={1},scale={2},density={3},volume={4},mass={5}", 343 DetailLog("{0},BSCharacter.setSize,call,size={1},scale={2},density={3},volume={4},mass={5}",
193 LocalID, _size, Scale, _avatarDensity, _avatarVolume, RawMass); 344 LocalID, _size, Scale, _avatarDensity, _avatarVolume, RawMass);
194 345
195 PhysicsScene.TaintedObject("BSCharacter.setSize", delegate() 346 PhysicsScene.TaintedObject("BSCharacter.setSize", delegate()
196 { 347 {
197 BulletSimAPI.SetLocalScaling2(PhysShape.ptr, Scale); 348 if (PhysBody.HasPhysicalBody && PhysShape.HasPhysicalShape)
198 UpdatePhysicalMassProperties(RawMass); 349 {
350 PhysicsScene.PE.SetLocalScaling(PhysShape, Scale);
351 UpdatePhysicalMassProperties(RawMass, true);
352 // Make sure this change appears as a property update event
353 PhysicsScene.PE.PushUpdate(PhysBody);
354 }
199 }); 355 });
200 356
201 } 357 }
202 } 358 }
203 359
204 public override OMV.Vector3 Scale { get; set; }
205
206 public override PrimitiveBaseShape Shape 360 public override PrimitiveBaseShape Shape
207 { 361 {
208 set { BaseShape = value; } 362 set { BaseShape = value; }
@@ -219,6 +373,10 @@ public sealed class BSCharacter : BSPhysObject
219 public override bool Selected { 373 public override bool Selected {
220 set { _selected = value; } 374 set { _selected = value; }
221 } 375 }
376 public override bool IsSelected
377 {
378 get { return _selected; }
379 }
222 public override void CrossingFailure() { return; } 380 public override void CrossingFailure() { return; }
223 public override void link(PhysicsActor obj) { return; } 381 public override void link(PhysicsActor obj) { return; }
224 public override void delink() { return; } 382 public override void delink() { return; }
@@ -236,7 +394,8 @@ public sealed class BSCharacter : BSPhysObject
236 // Zero some other properties directly into the physics engine 394 // Zero some other properties directly into the physics engine
237 PhysicsScene.TaintedObject(inTaintTime, "BSCharacter.ZeroMotion", delegate() 395 PhysicsScene.TaintedObject(inTaintTime, "BSCharacter.ZeroMotion", delegate()
238 { 396 {
239 BulletSimAPI.ClearAllForces2(PhysBody.ptr); 397 if (PhysBody.HasPhysicalBody)
398 PhysicsScene.PE.ClearAllForces(PhysBody);
240 }); 399 });
241 } 400 }
242 public override void ZeroAngularMotion(bool inTaintTime) 401 public override void ZeroAngularMotion(bool inTaintTime)
@@ -245,10 +404,13 @@ public sealed class BSCharacter : BSPhysObject
245 404
246 PhysicsScene.TaintedObject(inTaintTime, "BSCharacter.ZeroMotion", delegate() 405 PhysicsScene.TaintedObject(inTaintTime, "BSCharacter.ZeroMotion", delegate()
247 { 406 {
248 BulletSimAPI.SetInterpolationAngularVelocity2(PhysBody.ptr, OMV.Vector3.Zero); 407 if (PhysBody.HasPhysicalBody)
249 BulletSimAPI.SetAngularVelocity2(PhysBody.ptr, OMV.Vector3.Zero); 408 {
250 // The next also get rid of applied linear force but the linear velocity is untouched. 409 PhysicsScene.PE.SetInterpolationAngularVelocity(PhysBody, OMV.Vector3.Zero);
251 BulletSimAPI.ClearForces2(PhysBody.ptr); 410 PhysicsScene.PE.SetAngularVelocity(PhysBody, OMV.Vector3.Zero);
411 // The next also get rid of applied linear force but the linear velocity is untouched.
412 PhysicsScene.PE.ClearForces(PhysBody);
413 }
252 }); 414 });
253 } 415 }
254 416
@@ -263,29 +425,31 @@ public sealed class BSCharacter : BSPhysObject
263 public override OMV.Vector3 Position { 425 public override OMV.Vector3 Position {
264 get { 426 get {
265 // Don't refetch the position because this function is called a zillion times 427 // Don't refetch the position because this function is called a zillion times
266 // _position = BulletSimAPI.GetObjectPosition2(Scene.World.ptr, LocalID); 428 // _position = PhysicsScene.PE.GetObjectPosition(Scene.World, LocalID);
267 return _position; 429 return _position;
268 } 430 }
269 set { 431 set {
270 _position = value; 432 _position = value;
271 PositionSanityCheck();
272 433
273 PhysicsScene.TaintedObject("BSCharacter.setPosition", delegate() 434 PhysicsScene.TaintedObject("BSCharacter.setPosition", delegate()
274 { 435 {
275 DetailLog("{0},BSCharacter.SetPosition,taint,pos={1},orient={2}", LocalID, _position, _orientation); 436 DetailLog("{0},BSCharacter.SetPosition,taint,pos={1},orient={2}", LocalID, _position, _orientation);
276 BulletSimAPI.SetTranslation2(PhysBody.ptr, _position, _orientation); 437 ForcePosition = _position;
277 }); 438 });
278 } 439 }
279 } 440 }
280 public override OMV.Vector3 ForcePosition { 441 public override OMV.Vector3 ForcePosition {
281 get { 442 get {
282 _position = BulletSimAPI.GetPosition2(PhysBody.ptr); 443 _position = PhysicsScene.PE.GetPosition(PhysBody);
283 return _position; 444 return _position;
284 } 445 }
285 set { 446 set {
286 _position = value; 447 _position = value;
287 PositionSanityCheck(); 448 if (PhysBody.HasPhysicalBody)
288 BulletSimAPI.SetTranslation2(PhysBody.ptr, _position, _orientation); 449 {
450 PositionSanityCheck();
451 PhysicsScene.PE.SetTranslation(PhysBody, _position, _orientation);
452 }
289 } 453 }
290 } 454 }
291 455
@@ -297,8 +461,17 @@ public sealed class BSCharacter : BSPhysObject
297 { 461 {
298 bool ret = false; 462 bool ret = false;
299 463
464 // TODO: check for out of bounds
465 if (!PhysicsScene.TerrainManager.IsWithinKnownTerrain(RawPosition))
466 {
467 // The character is out of the known/simulated area.
468 // Upper levels of code will handle the transition to other areas so, for
469 // the time, we just ignore the position.
470 return ret;
471 }
472
300 // If below the ground, move the avatar up 473 // If below the ground, move the avatar up
301 float terrainHeight = PhysicsScene.TerrainManager.GetTerrainHeightAtXYZ(_position); 474 float terrainHeight = PhysicsScene.TerrainManager.GetTerrainHeightAtXYZ(RawPosition);
302 if (Position.Z < terrainHeight) 475 if (Position.Z < terrainHeight)
303 { 476 {
304 DetailLog("{0},BSCharacter.PositionAdjustUnderGround,call,pos={1},terrain={2}", LocalID, _position, terrainHeight); 477 DetailLog("{0},BSCharacter.PositionAdjustUnderGround,call,pos={1},terrain={2}", LocalID, _position, terrainHeight);
@@ -307,7 +480,7 @@ public sealed class BSCharacter : BSPhysObject
307 } 480 }
308 if ((CurrentCollisionFlags & CollisionFlags.BS_FLOATS_ON_WATER) != 0) 481 if ((CurrentCollisionFlags & CollisionFlags.BS_FLOATS_ON_WATER) != 0)
309 { 482 {
310 float waterHeight = PhysicsScene.GetWaterLevelAtXYZ(_position); 483 float waterHeight = PhysicsScene.TerrainManager.GetWaterLevelAtXYZ(_position);
311 if (Position.Z < waterHeight) 484 if (Position.Z < waterHeight)
312 { 485 {
313 _position.Z = waterHeight; 486 _position.Z = waterHeight;
@@ -315,7 +488,6 @@ public sealed class BSCharacter : BSPhysObject
315 } 488 }
316 } 489 }
317 490
318 // TODO: check for out of bounds
319 return ret; 491 return ret;
320 } 492 }
321 493
@@ -332,7 +504,8 @@ public sealed class BSCharacter : BSPhysObject
332 PhysicsScene.TaintedObject(inTaintTime, "BSCharacter.PositionSanityCheck", delegate() 504 PhysicsScene.TaintedObject(inTaintTime, "BSCharacter.PositionSanityCheck", delegate()
333 { 505 {
334 DetailLog("{0},BSCharacter.PositionSanityCheck,taint,pos={1},orient={2}", LocalID, _position, _orientation); 506 DetailLog("{0},BSCharacter.PositionSanityCheck,taint,pos={1},orient={2}", LocalID, _position, _orientation);
335 BulletSimAPI.SetTranslation2(PhysBody.ptr, _position, _orientation); 507 if (PhysBody.HasPhysicalBody)
508 PhysicsScene.PE.SetTranslation(PhysBody, _position, _orientation);
336 }); 509 });
337 ret = true; 510 ret = true;
338 } 511 }
@@ -345,10 +518,10 @@ public sealed class BSCharacter : BSPhysObject
345 public override float RawMass { 518 public override float RawMass {
346 get {return _mass; } 519 get {return _mass; }
347 } 520 }
348 public override void UpdatePhysicalMassProperties(float physMass) 521 public override void UpdatePhysicalMassProperties(float physMass, bool inWorld)
349 { 522 {
350 OMV.Vector3 localInertia = BulletSimAPI.CalculateLocalInertia2(PhysShape.ptr, physMass); 523 OMV.Vector3 localInertia = PhysicsScene.PE.CalculateLocalInertia(PhysShape, physMass);
351 BulletSimAPI.SetMassProps2(PhysBody.ptr, physMass, localInertia); 524 PhysicsScene.PE.SetMassProps(PhysBody, physMass, localInertia);
352 } 525 }
353 526
354 public override OMV.Vector3 Force { 527 public override OMV.Vector3 Force {
@@ -359,7 +532,8 @@ public sealed class BSCharacter : BSPhysObject
359 PhysicsScene.TaintedObject("BSCharacter.SetForce", delegate() 532 PhysicsScene.TaintedObject("BSCharacter.SetForce", delegate()
360 { 533 {
361 DetailLog("{0},BSCharacter.setForce,taint,force={1}", LocalID, _force); 534 DetailLog("{0},BSCharacter.setForce,taint,force={1}", LocalID, _force);
362 BulletSimAPI.SetObjectForce2(PhysBody.ptr, _force); 535 if (PhysBody.HasPhysicalBody)
536 PhysicsScene.PE.SetObjectForce(PhysBody, _force);
363 }); 537 });
364 } 538 }
365 } 539 }
@@ -376,6 +550,36 @@ public sealed class BSCharacter : BSPhysObject
376 550
377 public override OMV.Vector3 GeometricCenter { get { return OMV.Vector3.Zero; } } 551 public override OMV.Vector3 GeometricCenter { get { return OMV.Vector3.Zero; } }
378 public override OMV.Vector3 CenterOfMass { get { return OMV.Vector3.Zero; } } 552 public override OMV.Vector3 CenterOfMass { get { return OMV.Vector3.Zero; } }
553
554 // Sets the target in the motor. This starts the changing of the avatar's velocity.
555 public override OMV.Vector3 TargetVelocity
556 {
557 get
558 {
559 return _velocityMotor.TargetValue;
560 }
561 set
562 {
563 DetailLog("{0},BSCharacter.setTargetVelocity,call,vel={1}", LocalID, value);
564 OMV.Vector3 targetVel = value;
565 if (_setAlwaysRun)
566 targetVel *= BSParam.AvatarAlwaysRunFactor;
567
568 PhysicsScene.TaintedObject("BSCharacter.setTargetVelocity", delegate()
569 {
570 _velocityMotor.Reset();
571 _velocityMotor.SetTarget(targetVel);
572 _velocityMotor.SetCurrent(_velocity);
573 _velocityMotor.Enabled = true;
574 });
575 }
576 }
577 public override OMV.Vector3 RawVelocity
578 {
579 get { return _velocity; }
580 set { _velocity = value; }
581 }
582 // Directly setting velocity means this is what the user really wants now.
379 public override OMV.Vector3 Velocity { 583 public override OMV.Vector3 Velocity {
380 get { return _velocity; } 584 get { return _velocity; }
381 set { 585 set {
@@ -383,6 +587,12 @@ public sealed class BSCharacter : BSPhysObject
383 // m_log.DebugFormat("{0}: set velocity = {1}", LogHeader, _velocity); 587 // m_log.DebugFormat("{0}: set velocity = {1}", LogHeader, _velocity);
384 PhysicsScene.TaintedObject("BSCharacter.setVelocity", delegate() 588 PhysicsScene.TaintedObject("BSCharacter.setVelocity", delegate()
385 { 589 {
590 _velocityMotor.Reset();
591 _velocityMotor.SetCurrent(_velocity);
592 _velocityMotor.SetTarget(_velocity);
593 // Even though the motor is initialized, it's not used and the velocity goes straight into the avatar.
594 _velocityMotor.Enabled = false;
595
386 DetailLog("{0},BSCharacter.setVelocity,taint,vel={1}", LocalID, _velocity); 596 DetailLog("{0},BSCharacter.setVelocity,taint,vel={1}", LocalID, _velocity);
387 ForceVelocity = _velocity; 597 ForceVelocity = _velocity;
388 }); 598 });
@@ -391,30 +601,11 @@ public sealed class BSCharacter : BSPhysObject
391 public override OMV.Vector3 ForceVelocity { 601 public override OMV.Vector3 ForceVelocity {
392 get { return _velocity; } 602 get { return _velocity; }
393 set { 603 set {
394 // Depending on whether the avatar is moving or not, change the friction 604 PhysicsScene.AssertInTaintTime("BSCharacter.ForceVelocity");
395 // to keep the avatar from slipping around
396 if (_velocity.Length() == 0)
397 {
398 if (_currentFriction != PhysicsScene.Params.avatarStandingFriction)
399 {
400 _currentFriction = PhysicsScene.Params.avatarStandingFriction;
401 BulletSimAPI.SetFriction2(PhysBody.ptr, _currentFriction);
402 }
403 }
404 else
405 {
406 if (_currentFriction != PhysicsScene.Params.avatarFriction)
407 {
408 _currentFriction = PhysicsScene.Params.avatarFriction;
409 BulletSimAPI.SetFriction2(PhysBody.ptr, _currentFriction);
410 }
411 }
412 _velocity = value;
413 // Remember the set velocity so we can suppress the reduction by friction, ...
414 _appliedVelocity = value;
415 605
416 BulletSimAPI.SetLinearVelocity2(PhysBody.ptr, _velocity); 606 _velocity = value;
417 BulletSimAPI.Activate2(PhysBody.ptr, true); 607 PhysicsScene.PE.SetLinearVelocity(PhysBody, _velocity);
608 PhysicsScene.PE.Activate(PhysBody, true);
418 } 609 }
419 } 610 }
420 public override OMV.Vector3 Torque { 611 public override OMV.Vector3 Torque {
@@ -439,13 +630,16 @@ public sealed class BSCharacter : BSPhysObject
439 public override OMV.Quaternion Orientation { 630 public override OMV.Quaternion Orientation {
440 get { return _orientation; } 631 get { return _orientation; }
441 set { 632 set {
442 _orientation = value; 633 // Orientation is set zillions of times when an avatar is walking. It's like
443 // m_log.DebugFormat("{0}: set orientation to {1}", LogHeader, _orientation); 634 // the viewer doesn't trust us.
444 PhysicsScene.TaintedObject("BSCharacter.setOrientation", delegate() 635 if (_orientation != value)
445 { 636 {
446 // _position = BulletSimAPI.GetPosition2(BSBody.ptr); 637 _orientation = value;
447 BulletSimAPI.SetTranslation2(PhysBody.ptr, _position, _orientation); 638 PhysicsScene.TaintedObject("BSCharacter.setOrientation", delegate()
448 }); 639 {
640 ForceOrientation = _orientation;
641 });
642 }
449 } 643 }
450 } 644 }
451 // Go directly to Bullet to get/set the value. 645 // Go directly to Bullet to get/set the value.
@@ -453,13 +647,17 @@ public sealed class BSCharacter : BSPhysObject
453 { 647 {
454 get 648 get
455 { 649 {
456 _orientation = BulletSimAPI.GetOrientation2(PhysBody.ptr); 650 _orientation = PhysicsScene.PE.GetOrientation(PhysBody);
457 return _orientation; 651 return _orientation;
458 } 652 }
459 set 653 set
460 { 654 {
461 _orientation = value; 655 _orientation = value;
462 BulletSimAPI.SetTranslation2(PhysBody.ptr, _position, _orientation); 656 if (PhysBody.HasPhysicalBody)
657 {
658 // _position = PhysicsScene.PE.GetPosition(BSBody);
659 PhysicsScene.PE.SetTranslation(PhysBody, _position, _orientation);
660 }
463 } 661 }
464 } 662 }
465 public override int PhysicsActorType { 663 public override int PhysicsActorType {
@@ -478,10 +676,14 @@ public sealed class BSCharacter : BSPhysObject
478 public override bool IsStatic { 676 public override bool IsStatic {
479 get { return false; } 677 get { return false; }
480 } 678 }
679 public override bool IsPhysicallyActive {
680 get { return true; }
681 }
481 public override bool Flying { 682 public override bool Flying {
482 get { return _flying; } 683 get { return _flying; }
483 set { 684 set {
484 _flying = value; 685 _flying = value;
686
485 // simulate flying by changing the effect of gravity 687 // simulate flying by changing the effect of gravity
486 Buoyancy = ComputeBuoyancyFromFlying(_flying); 688 Buoyancy = ComputeBuoyancyFromFlying(_flying);
487 } 689 }
@@ -500,27 +702,18 @@ public sealed class BSCharacter : BSPhysObject
500 get { return _throttleUpdates; } 702 get { return _throttleUpdates; }
501 set { _throttleUpdates = value; } 703 set { _throttleUpdates = value; }
502 } 704 }
503 public override bool IsColliding {
504 get { return (CollidingStep == PhysicsScene.SimulationStep); }
505 set { _isColliding = value; }
506 }
507 public override bool CollidingGround {
508 get { return (CollidingGroundStep == PhysicsScene.SimulationStep); }
509 set { CollidingGround = value; }
510 }
511 public override bool CollidingObj {
512 get { return _collidingObj; }
513 set { _collidingObj = value; }
514 }
515 public override bool FloatOnWater { 705 public override bool FloatOnWater {
516 set { 706 set {
517 _floatOnWater = value; 707 _floatOnWater = value;
518 PhysicsScene.TaintedObject("BSCharacter.setFloatOnWater", delegate() 708 PhysicsScene.TaintedObject("BSCharacter.setFloatOnWater", delegate()
519 { 709 {
520 if (_floatOnWater) 710 if (PhysBody.HasPhysicalBody)
521 CurrentCollisionFlags = BulletSimAPI.AddToCollisionFlags2(PhysBody.ptr, CollisionFlags.BS_FLOATS_ON_WATER); 711 {
522 else 712 if (_floatOnWater)
523 CurrentCollisionFlags = BulletSimAPI.RemoveFromCollisionFlags2(PhysBody.ptr, CollisionFlags.BS_FLOATS_ON_WATER); 713 CurrentCollisionFlags = PhysicsScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.BS_FLOATS_ON_WATER);
714 else
715 CurrentCollisionFlags = PhysicsScene.PE.RemoveFromCollisionFlags(PhysBody, CollisionFlags.BS_FLOATS_ON_WATER);
716 }
524 }); 717 });
525 } 718 }
526 } 719 }
@@ -549,11 +742,15 @@ public sealed class BSCharacter : BSPhysObject
549 } 742 }
550 public override float ForceBuoyancy { 743 public override float ForceBuoyancy {
551 get { return _buoyancy; } 744 get { return _buoyancy; }
552 set { _buoyancy = value; 745 set {
746 PhysicsScene.AssertInTaintTime("BSCharacter.ForceBuoyancy");
747
748 _buoyancy = value;
553 DetailLog("{0},BSCharacter.setForceBuoyancy,taint,buoy={1}", LocalID, _buoyancy); 749 DetailLog("{0},BSCharacter.setForceBuoyancy,taint,buoy={1}", LocalID, _buoyancy);
554 // Buoyancy is faked by changing the gravity applied to the object 750 // Buoyancy is faked by changing the gravity applied to the object
555 float grav = PhysicsScene.Params.gravity * (1f - _buoyancy); 751 float grav = PhysicsScene.Params.gravity * (1f - _buoyancy);
556 BulletSimAPI.SetGravity2(PhysBody.ptr, new OMV.Vector3(0f, 0f, grav)); 752 if (PhysBody.HasPhysicalBody)
753 PhysicsScene.PE.SetGravity(PhysBody, new OMV.Vector3(0f, 0f, grav));
557 } 754 }
558 } 755 }
559 756
@@ -589,24 +786,40 @@ public sealed class BSCharacter : BSPhysObject
589 public override float APIDStrength { set { return; } } 786 public override float APIDStrength { set { return; } }
590 public override float APIDDamping { set { return; } } 787 public override float APIDDamping { set { return; } }
591 788
592 public override void AddForce(OMV.Vector3 force, bool pushforce) { 789 public override void AddForce(OMV.Vector3 force, bool pushforce)
790 {
791 // Since this force is being applied in only one step, make this a force per second.
792 OMV.Vector3 addForce = force / PhysicsScene.LastTimeStep;
793 AddForce(addForce, pushforce, false);
794 }
795 private void AddForce(OMV.Vector3 force, bool pushforce, bool inTaintTime) {
593 if (force.IsFinite()) 796 if (force.IsFinite())
594 { 797 {
595 _force.X += force.X; 798 float magnitude = force.Length();
596 _force.Y += force.Y; 799 if (magnitude > BSParam.MaxAddForceMagnitude)
597 _force.Z += force.Z;
598 // m_log.DebugFormat("{0}: AddForce. adding={1}, newForce={2}", LogHeader, force, _force);
599 PhysicsScene.TaintedObject("BSCharacter.AddForce", delegate()
600 { 800 {
601 DetailLog("{0},BSCharacter.setAddForce,taint,addedForce={1}", LocalID, _force); 801 // Force has a limit
602 BulletSimAPI.SetObjectForce2(PhysBody.ptr, _force); 802 force = force / magnitude * BSParam.MaxAddForceMagnitude;
803 }
804
805 OMV.Vector3 addForce = force;
806 // DetailLog("{0},BSCharacter.addForce,call,force={1}", LocalID, addForce);
807
808 PhysicsScene.TaintedObject(inTaintTime, "BSCharacter.AddForce", delegate()
809 {
810 // Bullet adds this central force to the total force for this tick
811 // DetailLog("{0},BSCharacter.addForce,taint,force={1}", LocalID, addForce);
812 if (PhysBody.HasPhysicalBody)
813 {
814 PhysicsScene.PE.ApplyCentralForce(PhysBody, addForce);
815 }
603 }); 816 });
604 } 817 }
605 else 818 else
606 { 819 {
607 m_log.ErrorFormat("{0}: Got a NaN force applied to a Character", LogHeader); 820 m_log.WarnFormat("{0}: Got a NaN force applied to a character. LocalID={1}", LogHeader, LocalID);
821 return;
608 } 822 }
609 //m_lastUpdateSent = false;
610 } 823 }
611 824
612 public override void AddAngularForce(OMV.Vector3 force, bool pushforce) { 825 public override void AddAngularForce(OMV.Vector3 force, bool pushforce) {
@@ -614,24 +827,31 @@ public sealed class BSCharacter : BSPhysObject
614 public override void SetMomentum(OMV.Vector3 momentum) { 827 public override void SetMomentum(OMV.Vector3 momentum) {
615 } 828 }
616 829
617 private void ComputeAvatarScale(OMV.Vector3 size) 830 private OMV.Vector3 ComputeAvatarScale(OMV.Vector3 size)
618 { 831 {
619 // The 'size' given by the simulator is the mid-point of the avatar 832 OMV.Vector3 newScale;
620 // and X and Y are unspecified. 833
621 834 // Bullet's capsule total height is the "passed height + radius * 2";
622 OMV.Vector3 newScale = size; 835 // The base capsule is 1 diameter and 2 height (passed radius=0.5, passed height = 1)
623 // newScale.X = PhysicsScene.Params.avatarCapsuleWidth; 836 // The number we pass in for 'scaling' is the multiplier to get that base
624 // newScale.Y = PhysicsScene.Params.avatarCapsuleDepth; 837 // shape to be the size desired.
625 838 // So, when creating the scale for the avatar height, we take the passed height
626 // From the total height, remove the capsule half spheres that are at each end 839 // (size.Z) and remove the caps.
627 // The 1.15f came from ODE. Not sure what this factors in. 840 // Another oddity of the Bullet capsule implementation is that it presumes the Y
628 // newScale.Z = (size.Z * 1.15f) - (newScale.X + newScale.Y); 841 // dimension is the radius of the capsule. Even though some of the code allows
842 // for a asymmetrical capsule, other parts of the code presume it is cylindrical.
843
844 // Scale is multiplier of radius with one of "0.5"
845 newScale.X = size.X / 2f;
846 newScale.Y = size.Y / 2f;
629 847
630 // The total scale height is the central cylindar plus the caps on the two ends. 848 // The total scale height is the central cylindar plus the caps on the two ends.
631 newScale.Z = size.Z + (Math.Min(size.X, size.Y) * 2f); 849 newScale.Z = (size.Z + (Math.Min(size.X, size.Y) * 2)) / 2f;
850 // If smaller than the endcaps, just fake like we're almost that small
851 if (newScale.Z < 0)
852 newScale.Z = 0.1f;
632 853
633 // Convert diameters to radii and height to half height -- the way Bullet expects it. 854 return newScale;
634 Scale = newScale / 2f;
635 } 855 }
636 856
637 // set _avatarVolume and _mass based on capsule size, _density and Scale 857 // set _avatarVolume and _mass based on capsule size, _density and Scale
@@ -639,14 +859,14 @@ public sealed class BSCharacter : BSPhysObject
639 { 859 {
640 _avatarVolume = (float)( 860 _avatarVolume = (float)(
641 Math.PI 861 Math.PI
642 * Scale.X 862 * Size.X / 2f
643 * Scale.Y // the area of capsule cylinder 863 * Size.Y / 2f // the area of capsule cylinder
644 * Scale.Z // times height of capsule cylinder 864 * Size.Z // times height of capsule cylinder
645 + 1.33333333f 865 + 1.33333333f
646 * Math.PI 866 * Math.PI
647 * Scale.X 867 * Size.X / 2f
648 * Math.Min(Scale.X, Scale.Y) 868 * Math.Min(Size.X, Size.Y) / 2
649 * Scale.Y // plus the volume of the capsule end caps 869 * Size.Y / 2f // plus the volume of the capsule end caps
650 ); 870 );
651 _mass = _avatarDensity * _avatarVolume; 871 _mass = _avatarDensity * _avatarVolume;
652 } 872 }
@@ -657,27 +877,29 @@ public sealed class BSCharacter : BSPhysObject
657 { 877 {
658 _position = entprop.Position; 878 _position = entprop.Position;
659 _orientation = entprop.Rotation; 879 _orientation = entprop.Rotation;
660 _velocity = entprop.Velocity; 880
881 // Smooth velocity. OpenSimulator is VERY sensitive to changes in velocity of the avatar
882 // and will send agent updates to the clients if velocity changes by more than
883 // 0.001m/s. Bullet introduces a lot of jitter in the velocity which causes many
884 // extra updates.
885 if (!entprop.Velocity.ApproxEquals(_velocity, 0.1f))
886 _velocity = entprop.Velocity;
887
661 _acceleration = entprop.Acceleration; 888 _acceleration = entprop.Acceleration;
662 _rotationalVelocity = entprop.RotationalVelocity; 889 _rotationalVelocity = entprop.RotationalVelocity;
890
663 // Do some sanity checking for the avatar. Make sure it's above ground and inbounds. 891 // Do some sanity checking for the avatar. Make sure it's above ground and inbounds.
664 PositionSanityCheck(true); 892 if (PositionSanityCheck(true))
893 {
894 entprop.Position = _position;
895 }
665 896
666 // remember the current and last set values 897 // remember the current and last set values
667 LastEntityProperties = CurrentEntityProperties; 898 LastEntityProperties = CurrentEntityProperties;
668 CurrentEntityProperties = entprop; 899 CurrentEntityProperties = entprop;
669 900
670 if (entprop.Velocity != LastEntityProperties.Velocity)
671 {
672 // Changes in the velocity are suppressed in avatars.
673 // That's just the way they are defined.
674 OMV.Vector3 avVel = new OMV.Vector3(_appliedVelocity.X, _appliedVelocity.Y, entprop.Velocity.Z);
675 _velocity = avVel;
676 BulletSimAPI.SetLinearVelocity2(PhysBody.ptr, avVel);
677 }
678
679 // Tell the linkset about value changes 901 // Tell the linkset about value changes
680 Linkset.UpdateProperties(this); 902 Linkset.UpdateProperties(UpdatedProperties.EntPropUpdates, this);
681 903
682 // Avatars don't report their changes the usual way. Changes are checked for in the heartbeat loop. 904 // Avatars don't report their changes the usual way. Changes are checked for in the heartbeat loop.
683 // base.RequestPhysicsterseUpdate(); 905 // base.RequestPhysicsterseUpdate();