BSActorAvatarMove.cs 22 KB

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