OpenSim
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Events Macros
BSActorAvatarMove.cs
Go to the documentation of this file.
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 copyrightD
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 
28 using System;
29 using System.Collections.Generic;
30 using System.Linq;
31 using System.Text;
32 
33 using OpenSim.Framework;
34 using OpenSim.Region.PhysicsModules.SharedBase;
35 
36 using OMV = OpenMetaverse;
37 
38 namespace OpenSim.Region.PhysicsModule.BulletS
39 {
40 public class BSActorAvatarMove : BSActor
41 {
42  BSVMotor m_velocityMotor;
43 
44  // Set to true if we think we're going up stairs.
45  // This state is remembered because collisions will turn on and off as we go up stairs.
46  int m_walkingUpStairs;
47  // The amount the step up is applying. Used to smooth stair walking.
48  float m_lastStepUp;
49 
50  // There are times the velocity is set but we don't want to inforce stationary until the
51  // real velocity drops.
52  bool m_waitingForLowVelocityForStationary = false;
53 
54  public BSActorAvatarMove(BSScene physicsScene, BSPhysObject pObj, string actorName)
55  : base(physicsScene, pObj, actorName)
56  {
57  m_velocityMotor = null;
58  m_walkingUpStairs = 0;
59  m_physicsScene.DetailLog("{0},BSActorAvatarMove,constructor", m_controllingPrim.LocalID);
60  }
61 
62  // BSActor.isActive
63  public override bool isActive
64  {
65  get { return Enabled && m_controllingPrim.IsPhysicallyActive; }
66  }
67 
68  // Release any connections and resources used by the actor.
69  // BSActor.Dispose()
70  public override void Dispose()
71  {
72  base.SetEnabled(false);
73  DeactivateAvatarMove();
74  }
75 
76  // Called when physical parameters (properties set in Bullet) need to be re-applied.
77  // Called at taint-time.
78  // BSActor.Refresh()
79  public override void Refresh()
80  {
81  m_physicsScene.DetailLog("{0},BSActorAvatarMove,refresh", m_controllingPrim.LocalID);
82 
83  // If the object is physically active, add the hoverer prestep action
84  if (isActive)
85  {
86  ActivateAvatarMove();
87  }
88  else
89  {
90  DeactivateAvatarMove();
91  }
92  }
93 
94  // The object's physical representation is being rebuilt so pick up any physical dependencies (constraints, ...).
95  // Register a prestep action to restore physical requirements before the next simulation step.
96  // Called at taint-time.
97  // BSActor.RemoveDependencies()
98  public override void RemoveDependencies()
99  {
100  // Nothing to do for the hoverer since it is all software at pre-step action time.
101  }
102 
103  // Usually called when target velocity changes to set the current velocity and the target
104  // into the movement motor.
105  public void SetVelocityAndTarget(OMV.Vector3 vel, OMV.Vector3 targ, bool inTaintTime)
106  {
107  m_physicsScene.TaintedObject(inTaintTime, m_controllingPrim.LocalID, "BSActorAvatarMove.setVelocityAndTarget", delegate()
108  {
109  if (m_velocityMotor != null)
110  {
111 // if (targ == OMV.Vector3.Zero)
112 // Util.PrintCallStack();
113 //
114 // Console.WriteLine("SetVelocityAndTarget, {0} {1}", vel, targ);
115  m_velocityMotor.Reset();
116  m_velocityMotor.SetTarget(targ);
117  m_velocityMotor.SetCurrent(vel);
118  m_velocityMotor.Enabled = true;
119  m_physicsScene.DetailLog("{0},BSCharacter.MoveMotor,SetVelocityAndTarget,vel={1}, targ={2}",
120  m_controllingPrim.LocalID, vel, targ);
121  m_waitingForLowVelocityForStationary = false;
122  }
123  });
124  }
125 
127  {
128  m_waitingForLowVelocityForStationary = true;
129  }
130 
131  // If a movement motor has not been created, create one and start the hovering.
132  private void ActivateAvatarMove()
133  {
134  if (m_velocityMotor == null)
135  {
136  // Infinite decay and timescale values so motor only changes current to target values.
137  m_velocityMotor = new BSVMotor("BSCharacter.Velocity",
138  0.2f, // time scale
139  BSMotor.Infinite, // decay time scale
140  1f // efficiency
141  );
142  m_velocityMotor.ErrorZeroThreshold = BSParam.AvatarStopZeroThreshold;
143  // m_velocityMotor.PhysicsScene = m_controllingPrim.PhysScene; // DEBUG DEBUG so motor will output detail log messages.
144  SetVelocityAndTarget(m_controllingPrim.RawVelocity, m_controllingPrim.TargetVelocity, true /* inTaintTime */);
145 
146  m_physicsScene.BeforeStep += Mover;
147  m_controllingPrim.OnPreUpdateProperty += Process_OnPreUpdateProperty;
148 
149  m_walkingUpStairs = 0;
150  m_waitingForLowVelocityForStationary = false;
151  }
152  }
153 
154  private void DeactivateAvatarMove()
155  {
156  if (m_velocityMotor != null)
157  {
158  m_controllingPrim.OnPreUpdateProperty -= Process_OnPreUpdateProperty;
159  m_physicsScene.BeforeStep -= Mover;
160  m_velocityMotor = null;
161  }
162  }
163 
164  // Called just before the simulation step. Update the vertical position for hoverness.
165  private void Mover(float timeStep)
166  {
167  // Don't do movement while the object is selected.
168  if (!isActive)
169  return;
170 
171  // TODO: Decide if the step parameters should be changed depending on the avatar's
172  // state (flying, colliding, ...). There is code in ODE to do this.
173 
174  // COMMENTARY: when the user is making the avatar walk, except for falling, the velocity
175  // specified for the avatar is the one that should be used. For falling, if the avatar
176  // is not flying and is not colliding then it is presumed to be falling and the Z
177  // component is not fooled with (thus allowing gravity to do its thing).
178  // When the avatar is standing, though, the user has specified a velocity of zero and
179  // the avatar should be standing. But if the avatar is pushed by something in the world
180  // (raising elevator platform, moving vehicle, ...) the avatar should be allowed to
181  // move. Thus, the velocity cannot be forced to zero. The problem is that small velocity
182  // errors can creap in and the avatar will slowly float off in some direction.
183  // So, the problem is that, when an avatar is standing, we cannot tell creaping error
184  // from real pushing.
185  // The code below uses whether the collider is static or moving to decide whether to zero motion.
186 
187  m_velocityMotor.Step(timeStep);
188  m_controllingPrim.IsStationary = false;
189 
190  // If we're not supposed to be moving, make sure things are zero.
191  if (m_velocityMotor.ErrorIsZero() && m_velocityMotor.TargetValue == OMV.Vector3.Zero)
192  {
193  // The avatar shouldn't be moving
194  m_velocityMotor.Zero();
195 
196  if (m_controllingPrim.IsColliding)
197  {
198  // if colliding with something stationary and we're not doing volume detect .
199  if (!m_controllingPrim.ColliderIsMoving && !m_controllingPrim.ColliderIsVolumeDetect)
200  {
201  if (m_waitingForLowVelocityForStationary)
202  {
203  // if waiting for velocity to drop and it has finally dropped, we can be stationary
204  if (m_controllingPrim.RawVelocity.LengthSquared() < BSParam.AvatarStopZeroThresholdSquared)
205  {
206  m_waitingForLowVelocityForStationary = false;
207  }
208  }
209  if (!m_waitingForLowVelocityForStationary)
210  {
211  m_physicsScene.DetailLog("{0},BSCharacter.MoveMotor,collidingWithStationary,zeroingMotion", m_controllingPrim.LocalID);
212  m_controllingPrim.IsStationary = true;
213  m_controllingPrim.ZeroMotion(true /* inTaintTime */);
214  }
215  else
216  {
217  m_physicsScene.DetailLog("{0},BSCharacter.MoveMotor,waitingForLowVel,rawvel={1}",
218  m_controllingPrim.LocalID, m_controllingPrim.RawVelocity.Length());
219  }
220  }
221 
222  // Standing has more friction on the ground
223  if (m_controllingPrim.Friction != BSParam.AvatarStandingFriction)
224  {
225  m_controllingPrim.Friction = BSParam.AvatarStandingFriction;
226  m_physicsScene.PE.SetFriction(m_controllingPrim.PhysBody, m_controllingPrim.Friction);
227  }
228  }
229  else
230  {
231  if (m_controllingPrim.Flying)
232  {
233  // Flying and not colliding and velocity nearly zero.
234  m_controllingPrim.ZeroMotion(true /* inTaintTime */);
235  }
236  else
237  {
238  //We are falling but are not touching any keys make sure not falling too fast
239  if (m_controllingPrim.RawVelocity.Z < BSParam.AvatarTerminalVelocity)
240  {
241 
242  OMV.Vector3 slowingForce = new OMV.Vector3(0f, 0f, BSParam.AvatarTerminalVelocity - m_controllingPrim.RawVelocity.Z) * m_controllingPrim.Mass;
243  m_physicsScene.PE.ApplyCentralImpulse(m_controllingPrim.PhysBody, slowingForce);
244  }
245 
246  }
247  }
248 
249  m_physicsScene.DetailLog("{0},BSCharacter.MoveMotor,taint,stopping,target={1},colliding={2},isStationary={3}",
250  m_controllingPrim.LocalID, m_velocityMotor.TargetValue, m_controllingPrim.IsColliding,m_controllingPrim.IsStationary);
251  }
252  else
253  {
254  // Supposed to be moving.
255  OMV.Vector3 stepVelocity = m_velocityMotor.CurrentValue;
256 
257  if (m_controllingPrim.Friction != BSParam.AvatarFriction)
258  {
259  // Probably starting to walk. Set friction to moving friction.
260  m_controllingPrim.Friction = BSParam.AvatarFriction;
261  m_physicsScene.PE.SetFriction(m_controllingPrim.PhysBody, m_controllingPrim.Friction);
262  }
263 
264  // 'm_velocityMotor is used for walking, flying, and jumping and will thus have the correct values
265  // for Z. But in come cases it must be over-ridden. Like when falling or jumping.
266 
267  float realVelocityZ = m_controllingPrim.RawVelocity.Z;
268 
269  // If not flying and falling, we over-ride the stepping motor so we can fall to the ground
270  if (!m_controllingPrim.Flying && realVelocityZ < 0)
271  {
272  // Can't fall faster than this
273  if (realVelocityZ < BSParam.AvatarTerminalVelocity)
274  {
275  realVelocityZ = BSParam.AvatarTerminalVelocity;
276  }
277 
278  stepVelocity.Z = realVelocityZ;
279  }
280  // m_physicsScene.DetailLog("{0},BSCharacter.MoveMotor,DEBUG,motorCurrent={1},realZ={2},flying={3},collid={4},jFrames={5}",
281  // m_controllingPrim.LocalID, m_velocityMotor.CurrentValue, realVelocityZ, m_controllingPrim.Flying, m_controllingPrim.IsColliding, m_jumpFrames);
282 
283  //Alicia: Maintain minimum height when flying.
284  // SL has a flying effect that keeps the avatar flying above the ground by some margin
285  if (m_controllingPrim.Flying)
286  {
287  float hover_height = m_physicsScene.TerrainManager.GetTerrainHeightAtXYZ(m_controllingPrim.RawPosition)
288  + BSParam.AvatarFlyingGroundMargin;
289 
290  if( m_controllingPrim.Position.Z < hover_height)
291  {
292  m_physicsScene.DetailLog("{0},BSCharacter.MoveMotor,addingUpforceForGroundMargin,height={1},hoverHeight={2}",
293  m_controllingPrim.LocalID, m_controllingPrim.Position.Z, hover_height);
294  stepVelocity.Z += BSParam.AvatarFlyingGroundUpForce;
295  }
296  }
297 
298  // 'stepVelocity' is now the speed we'd like the avatar to move in. Turn that into an instantanous force.
299  OMV.Vector3 moveForce = (stepVelocity - m_controllingPrim.RawVelocity) * m_controllingPrim.Mass;
300 
301  // Add special movement force to allow avatars to walk up stepped surfaces.
302  moveForce += WalkUpStairs();
303 
304  m_physicsScene.DetailLog("{0},BSCharacter.MoveMotor,move,stepVel={1},vel={2},mass={3},moveForce={4}",
305  m_controllingPrim.LocalID, stepVelocity, m_controllingPrim.RawVelocity, m_controllingPrim.Mass, moveForce);
306  m_physicsScene.PE.ApplyCentralImpulse(m_controllingPrim.PhysBody, moveForce);
307  }
308  }
309 
310  // Called just as the property update is received from the physics engine.
311  // Do any mode necessary for avatar movement.
312  private void Process_OnPreUpdateProperty(ref EntityProperties entprop)
313  {
314  // Don't change position if standing on a stationary object.
315  if (m_controllingPrim.IsStationary)
316  {
317  entprop.Position = m_controllingPrim.RawPosition;
318  entprop.Velocity = OMV.Vector3.Zero;
319  m_physicsScene.PE.SetTranslation(m_controllingPrim.PhysBody, entprop.Position, entprop.Rotation);
320  }
321 
322  }
323 
324  // Decide if the character is colliding with a low object and compute a force to pop the
325  // avatar up so it can walk up and over the low objects.
326  private OMV.Vector3 WalkUpStairs()
327  {
328  OMV.Vector3 ret = OMV.Vector3.Zero;
329 
330  m_physicsScene.DetailLog("{0},BSCharacter.WalkUpStairs,IsColliding={1},flying={2},targSpeed={3},collisions={4},avHeight={5}",
331  m_controllingPrim.LocalID, m_controllingPrim.IsColliding, m_controllingPrim.Flying,
332  m_controllingPrim.TargetVelocitySpeed, m_controllingPrim.CollisionsLastTick.Count, m_controllingPrim.Size.Z);
333 
334  // Check for stairs climbing if colliding, not flying and moving forward
335  if ( m_controllingPrim.IsColliding
336  && !m_controllingPrim.Flying
337  && m_controllingPrim.TargetVelocitySpeed > 0.1f )
338  {
339  // The range near the character's feet where we will consider stairs
340  // float nearFeetHeightMin = m_controllingPrim.RawPosition.Z - (m_controllingPrim.Size.Z / 2f) + 0.05f;
341  // Note: there is a problem with the computation of the capsule height. Thus RawPosition is off
342  // from the height. Revisit size and this computation when height is scaled properly.
343  float nearFeetHeightMin = m_controllingPrim.RawPosition.Z - (m_controllingPrim.Size.Z / 2f) - BSParam.AvatarStepGroundFudge;
344  float nearFeetHeightMax = nearFeetHeightMin + BSParam.AvatarStepHeight;
345 
346  // Look for a collision point that is near the character's feet and is oriented the same as the charactor is.
347  // Find the highest 'good' collision.
348  OMV.Vector3 highestTouchPosition = OMV.Vector3.Zero;
349  foreach (KeyValuePair<uint, ContactPoint> kvp in m_controllingPrim.CollisionsLastTick.m_objCollisionList)
350  {
351  // Don't care about collisions with the terrain
352  if (kvp.Key > m_physicsScene.TerrainManager.HighestTerrainID)
353  {
354  BSPhysObject collisionObject;
355  if (m_physicsScene.PhysObjects.TryGetValue(kvp.Key, out collisionObject))
356  {
357  if (!collisionObject.IsVolumeDetect)
358  {
359  OMV.Vector3 touchPosition = kvp.Value.Position;
360  m_physicsScene.DetailLog("{0},BSCharacter.WalkUpStairs,min={1},max={2},touch={3}",
361  m_controllingPrim.LocalID, nearFeetHeightMin, nearFeetHeightMax, touchPosition);
362  if (touchPosition.Z >= nearFeetHeightMin && touchPosition.Z <= nearFeetHeightMax)
363  {
364  // This contact is within the 'near the feet' range.
365  // The step is presumed to be more or less vertical. Thus the Z component should
366  // be nearly horizontal.
367  OMV.Vector3 directionFacing = OMV.Vector3.UnitX * m_controllingPrim.RawOrientation;
368  OMV.Vector3 touchNormal = OMV.Vector3.Normalize(kvp.Value.SurfaceNormal);
369  const float PIOver2 = 1.571f; // Used to make unit vector axis into approx radian angles
370  // m_physicsScene.DetailLog("{0},BSCharacter.WalkUpStairs,avNormal={1},colNormal={2},diff={3}",
371  // m_controllingPrim.LocalID, directionFacing, touchNormal,
372  // Math.Abs(OMV.Vector3.Distance(directionFacing, touchNormal)) );
373  if ((Math.Abs(directionFacing.Z) * PIOver2) < BSParam.AvatarStepAngle
374  && (Math.Abs(touchNormal.Z) * PIOver2) < BSParam.AvatarStepAngle)
375  {
376  // The normal should be our contact point to the object so it is pointing away
377  // thus the difference between our facing orientation and the normal should be small.
378  float diff = Math.Abs(OMV.Vector3.Distance(directionFacing, touchNormal));
379  if (diff < BSParam.AvatarStepApproachFactor)
380  {
381  if (highestTouchPosition.Z < touchPosition.Z)
382  highestTouchPosition = touchPosition;
383  }
384  }
385  }
386  }
387  }
388  }
389  }
390  m_walkingUpStairs = 0;
391  // If there is a good step sensing, move the avatar over the step.
392  if (highestTouchPosition != OMV.Vector3.Zero)
393  {
394  // Remember that we are going up stairs. This is needed because collisions
395  // will stop when we move up so this smoothes out that effect.
396  m_walkingUpStairs = BSParam.AvatarStepSmoothingSteps;
397 
398  m_lastStepUp = highestTouchPosition.Z - nearFeetHeightMin;
399  ret = ComputeStairCorrection(m_lastStepUp);
400  m_physicsScene.DetailLog("{0},BSCharacter.WalkUpStairs,touchPos={1},nearFeetMin={2},ret={3}",
401  m_controllingPrim.LocalID, highestTouchPosition, nearFeetHeightMin, ret);
402  }
403  }
404  else
405  {
406  // If we used to be going up stairs but are not now, smooth the case where collision goes away while
407  // we are bouncing up the stairs.
408  if (m_walkingUpStairs > 0)
409  {
410  m_walkingUpStairs--;
411  ret = ComputeStairCorrection(m_lastStepUp);
412  }
413  }
414 
415  return ret;
416  }
417 
418  private OMV.Vector3 ComputeStairCorrection(float stepUp)
419  {
420  OMV.Vector3 ret = OMV.Vector3.Zero;
421  OMV.Vector3 displacement = OMV.Vector3.Zero;
422 
423  if (stepUp > 0f)
424  {
425  // Found the stairs contact point. Push up a little to raise the character.
426  if (BSParam.AvatarStepForceFactor > 0f)
427  {
428  float upForce = stepUp * m_controllingPrim.Mass * BSParam.AvatarStepForceFactor;
429  ret = new OMV.Vector3(0f, 0f, upForce);
430  }
431 
432  // Also move the avatar up for the new height
433  if (BSParam.AvatarStepUpCorrectionFactor > 0f)
434  {
435  // Move the avatar up related to the height of the collision
436  displacement = new OMV.Vector3(0f, 0f, stepUp * BSParam.AvatarStepUpCorrectionFactor);
437  m_controllingPrim.ForcePosition = m_controllingPrim.RawPosition + displacement;
438  }
439  else
440  {
441  if (BSParam.AvatarStepUpCorrectionFactor < 0f)
442  {
443  // Move the avatar up about the specified step height
444  displacement = new OMV.Vector3(0f, 0f, BSParam.AvatarStepHeight);
445  m_controllingPrim.ForcePosition = m_controllingPrim.RawPosition + displacement;
446  }
447  }
448  m_physicsScene.DetailLog("{0},BSCharacter.WalkUpStairs.ComputeStairCorrection,stepUp={1},isp={2},force={3}",
449  m_controllingPrim.LocalID, stepUp, displacement, ret);
450 
451  }
452  return ret;
453  }
454 }
455 }
456 
457 
OpenMetaverse OMV
Each physical object can have 'actors' who are pushing the object around. This can be used for hover...
Definition: BSActors.cs:118
void SetVelocityAndTarget(OMV.Vector3 vel, OMV.Vector3 targ, bool inTaintTime)
BSActorAvatarMove(BSScene physicsScene, BSPhysObject pObj, string actorName)
Interactive OpenSim region server
Definition: OpenSim.cs:55