From fe16dc09da3f2736fad5a9e792f5f81098b5f9a1 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Sun, 7 Apr 2013 08:27:49 -0700 Subject: BulletSim: complete movement of physical object action code out of the physical object and into actors for setForce, setTorque, hover, lock axis and avatar move. --- .../Physics/BulletSPlugin/BSActorAvatarMove.cs | 287 +++++++++++++++++++ .../Region/Physics/BulletSPlugin/BSActorHover.cs | 176 ++++++++++++ .../Physics/BulletSPlugin/BSActorLockAxis.cs | 4 +- .../Physics/BulletSPlugin/BSActorMoveToTarget.cs | 156 +++++++++++ .../Physics/BulletSPlugin/BSActorSetForce.cs | 137 +++++++++ .../Physics/BulletSPlugin/BSActorSetTorque.cs | 138 +++++++++ OpenSim/Region/Physics/BulletSPlugin/BSActors.cs | 12 +- .../Region/Physics/BulletSPlugin/BSCharacter.cs | 268 +++--------------- .../Region/Physics/BulletSPlugin/BSPhysObject.cs | 226 ++++++--------- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 307 ++++----------------- .../Region/Physics/BulletSPlugin/BulletSimTODO.txt | 3 +- 11 files changed, 1078 insertions(+), 636 deletions(-) create mode 100755 OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs create mode 100755 OpenSim/Region/Physics/BulletSPlugin/BSActorHover.cs create mode 100755 OpenSim/Region/Physics/BulletSPlugin/BSActorMoveToTarget.cs create mode 100755 OpenSim/Region/Physics/BulletSPlugin/BSActorSetForce.cs create mode 100755 OpenSim/Region/Physics/BulletSPlugin/BSActorSetTorque.cs (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs b/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs new file mode 100755 index 0000000..634a898 --- /dev/null +++ b/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs @@ -0,0 +1,287 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyrightD + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +using OpenSim.Region.Physics.Manager; + +using OMV = OpenMetaverse; + +namespace OpenSim.Region.Physics.BulletSPlugin +{ +public class BSActorAvatarMove : BSActor +{ + BSVMotor m_velocityMotor; + + public BSActorAvatarMove(BSScene physicsScene, BSPhysObject pObj, string actorName) + : base(physicsScene, pObj, actorName) + { + m_velocityMotor = null; + m_physicsScene.DetailLog("{0},BSActorAvatarMove,constructor", m_controllingPrim.LocalID); + } + + // BSActor.isActive + public override bool isActive + { + get { return Enabled && m_controllingPrim.IsPhysicallyActive; } + } + + // Release any connections and resources used by the actor. + // BSActor.Dispose() + public override void Dispose() + { + Enabled = false; + } + + // Called when physical parameters (properties set in Bullet) need to be re-applied. + // Called at taint-time. + // BSActor.Refresh() + public override void Refresh() + { + m_physicsScene.DetailLog("{0},BSActorAvatarMove,refresh", m_controllingPrim.LocalID); + + // If not active any more, get rid of me (shouldn't ever happen, but just to be safe) + if (m_controllingPrim.RawForce == OMV.Vector3.Zero) + { + m_physicsScene.DetailLog("{0},BSActorAvatarMove,refresh,notAvatarMove,removing={1}", m_controllingPrim.LocalID, ActorName); + m_controllingPrim.PhysicalActors.RemoveAndRelease(ActorName); + return; + } + + // If the object is physically active, add the hoverer prestep action + if (isActive) + { + ActivateAvatarMove(); + } + else + { + DeactivateAvatarMove(); + } + } + + // The object's physical representation is being rebuilt so pick up any physical dependencies (constraints, ...). + // Register a prestep action to restore physical requirements before the next simulation step. + // Called at taint-time. + // BSActor.RemoveBodyDependencies() + public override void RemoveBodyDependencies() + { + // Nothing to do for the hoverer since it is all software at pre-step action time. + } + + public void SetVelocityAndTarget(OMV.Vector3 vel, OMV.Vector3 targ, bool inTaintTime) + { + m_physicsScene.TaintedObject(inTaintTime, "BSActorAvatarMove.setVelocityAndTarget", delegate() + { + m_velocityMotor.Reset(); + m_velocityMotor.SetTarget(targ); + m_velocityMotor.SetCurrent(vel); + m_velocityMotor.Enabled = true; + }); + } + + // If a hover motor has not been created, create one and start the hovering. + private void ActivateAvatarMove() + { + if (m_velocityMotor == null) + { + // Infinite decay and timescale values so motor only changes current to target values. + m_velocityMotor = new BSVMotor("BSCharacter.Velocity", + 0.2f, // time scale + BSMotor.Infinite, // decay time scale + BSMotor.InfiniteVector, // friction timescale + 1f // efficiency + ); + // _velocityMotor.PhysicsScene = PhysicsScene; // DEBUG DEBUG so motor will output detail log messages. + + m_physicsScene.BeforeStep += Mover; + } + } + + private void DeactivateAvatarMove() + { + if (m_velocityMotor != null) + { + m_physicsScene.BeforeStep -= Mover; + m_velocityMotor = null; + } + } + + // Called just before the simulation step. Update the vertical position for hoverness. + private void Mover(float timeStep) + { + // Don't do movement while the object is selected. + if (!isActive) + return; + + // TODO: Decide if the step parameters should be changed depending on the avatar's + // state (flying, colliding, ...). There is code in ODE to do this. + + // COMMENTARY: when the user is making the avatar walk, except for falling, the velocity + // specified for the avatar is the one that should be used. For falling, if the avatar + // is not flying and is not colliding then it is presumed to be falling and the Z + // component is not fooled with (thus allowing gravity to do its thing). + // When the avatar is standing, though, the user has specified a velocity of zero and + // the avatar should be standing. But if the avatar is pushed by something in the world + // (raising elevator platform, moving vehicle, ...) the avatar should be allowed to + // move. Thus, the velocity cannot be forced to zero. The problem is that small velocity + // errors can creap in and the avatar will slowly float off in some direction. + // So, the problem is that, when an avatar is standing, we cannot tell creaping error + // from real pushing. + // The code below uses whether the collider is static or moving to decide whether to zero motion. + + m_velocityMotor.Step(timeStep); + m_controllingPrim.IsStationary = false; + + // If we're not supposed to be moving, make sure things are zero. + if (m_velocityMotor.ErrorIsZero() && m_velocityMotor.TargetValue == OMV.Vector3.Zero) + { + // The avatar shouldn't be moving + m_velocityMotor.Zero(); + + if (m_controllingPrim.IsColliding) + { + // If we are colliding with a stationary object, presume we're standing and don't move around + if (!m_controllingPrim.ColliderIsMoving) + { + m_physicsScene.DetailLog("{0},BSCharacter.MoveMotor,collidingWithStationary,zeroingMotion", m_controllingPrim.LocalID); + m_controllingPrim.IsStationary = true; + m_controllingPrim.ZeroMotion(true /* inTaintTime */); + } + + // Standing has more friction on the ground + if (m_controllingPrim.Friction != BSParam.AvatarStandingFriction) + { + m_controllingPrim.Friction = BSParam.AvatarStandingFriction; + m_physicsScene.PE.SetFriction(m_controllingPrim.PhysBody, m_controllingPrim.Friction); + } + } + else + { + if (m_controllingPrim.Flying) + { + // Flying and not collising and velocity nearly zero. + m_controllingPrim.ZeroMotion(true /* inTaintTime */); + } + } + + m_physicsScene.DetailLog("{0},BSCharacter.MoveMotor,taint,stopping,target={1},colliding={2}", + m_controllingPrim.LocalID, m_velocityMotor.TargetValue, m_controllingPrim.IsColliding); + } + else + { + // Supposed to be moving. + OMV.Vector3 stepVelocity = m_velocityMotor.CurrentValue; + + if (m_controllingPrim.Friction != BSParam.AvatarFriction) + { + // Probably starting up walking. Set friction to moving friction. + m_controllingPrim.Friction = BSParam.AvatarFriction; + m_physicsScene.PE.SetFriction(m_controllingPrim.PhysBody, m_controllingPrim.Friction); + } + + // If falling, we keep the world's downward vector no matter what the other axis specify. + // The check for RawVelocity.Z < 0 makes jumping work (temporary upward force). + if (!m_controllingPrim.Flying && !m_controllingPrim.IsColliding) + { + if (m_controllingPrim.RawVelocity.Z < 0) + stepVelocity.Z = m_controllingPrim.RawVelocity.Z; + // DetailLog("{0},BSCharacter.MoveMotor,taint,overrideStepZWithWorldZ,stepVel={1}", LocalID, stepVelocity); + } + + // 'stepVelocity' is now the speed we'd like the avatar to move in. Turn that into an instantanous force. + OMV.Vector3 moveForce = (stepVelocity - m_controllingPrim.RawVelocity) * m_controllingPrim.Mass; + + // Should we check for move force being small and forcing velocity to zero? + + // Add special movement force to allow avatars to walk up stepped surfaces. + moveForce += WalkUpStairs(); + + m_physicsScene.DetailLog("{0},BSCharacter.MoveMotor,move,stepVel={1},vel={2},mass={3},moveForce={4}", + m_controllingPrim.LocalID, stepVelocity, m_controllingPrim.RawVelocity, m_controllingPrim.Mass, moveForce); + m_physicsScene.PE.ApplyCentralImpulse(m_controllingPrim.PhysBody, moveForce); + } + } + + // Decide if the character is colliding with a low object and compute a force to pop the + // avatar up so it can walk up and over the low objects. + private OMV.Vector3 WalkUpStairs() + { + OMV.Vector3 ret = OMV.Vector3.Zero; + + // This test is done if moving forward, not flying and is colliding with something. + // DetailLog("{0},BSCharacter.WalkUpStairs,IsColliding={1},flying={2},targSpeed={3},collisions={4}", + // LocalID, IsColliding, Flying, TargetSpeed, CollisionsLastTick.Count); + if (m_controllingPrim.IsColliding && !m_controllingPrim.Flying && m_controllingPrim.TargetVelocitySpeed > 0.1f /* && ForwardSpeed < 0.1f */) + { + // The range near the character's feet where we will consider stairs + float nearFeetHeightMin = m_controllingPrim.RawPosition.Z - (m_controllingPrim.Size.Z / 2f) + 0.05f; + float nearFeetHeightMax = nearFeetHeightMin + BSParam.AvatarStepHeight; + + // Look for a collision point that is near the character's feet and is oriented the same as the charactor is + foreach (KeyValuePair kvp in m_controllingPrim.CollisionsLastTick.m_objCollisionList) + { + // Don't care about collisions with the terrain + if (kvp.Key > m_physicsScene.TerrainManager.HighestTerrainID) + { + OMV.Vector3 touchPosition = kvp.Value.Position; + // DetailLog("{0},BSCharacter.WalkUpStairs,min={1},max={2},touch={3}", + // LocalID, nearFeetHeightMin, nearFeetHeightMax, touchPosition); + if (touchPosition.Z >= nearFeetHeightMin && touchPosition.Z <= nearFeetHeightMax) + { + // This contact is within the 'near the feet' range. + // The normal should be our contact point to the object so it is pointing away + // thus the difference between our facing orientation and the normal should be small. + OMV.Vector3 directionFacing = OMV.Vector3.UnitX * m_controllingPrim.RawOrientation; + OMV.Vector3 touchNormal = OMV.Vector3.Normalize(kvp.Value.SurfaceNormal); + float diff = Math.Abs(OMV.Vector3.Distance(directionFacing, touchNormal)); + if (diff < BSParam.AvatarStepApproachFactor) + { + // Found the stairs contact point. Push up a little to raise the character. + float upForce = (touchPosition.Z - nearFeetHeightMin) * m_controllingPrim.Mass * BSParam.AvatarStepForceFactor; + ret = new OMV.Vector3(0f, 0f, upForce); + + // Also move the avatar up for the new height + OMV.Vector3 displacement = new OMV.Vector3(0f, 0f, BSParam.AvatarStepHeight / 2f); + m_controllingPrim.ForcePosition = m_controllingPrim.RawPosition + displacement; + } + m_physicsScene.DetailLog("{0},BSCharacter.WalkUpStairs,touchPos={1},nearFeetMin={2},faceDir={3},norm={4},diff={5},ret={6}", + m_controllingPrim.LocalID, touchPosition, nearFeetHeightMin, directionFacing, touchNormal, diff, ret); + } + } + } + } + + return ret; + } + +} +} + + diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSActorHover.cs b/OpenSim/Region/Physics/BulletSPlugin/BSActorHover.cs new file mode 100755 index 0000000..8dd3700 --- /dev/null +++ b/OpenSim/Region/Physics/BulletSPlugin/BSActorHover.cs @@ -0,0 +1,176 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyrightD + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +using OpenSim.Region.Physics.Manager; + +using OMV = OpenMetaverse; + +namespace OpenSim.Region.Physics.BulletSPlugin +{ +public class BSActorHover : BSActor +{ + private BSFMotor m_hoverMotor; + + public BSActorHover(BSScene physicsScene, BSPhysObject pObj, string actorName) + : base(physicsScene, pObj, actorName) + { + m_hoverMotor = null; + m_physicsScene.DetailLog("{0},BSActorHover,constructor", m_controllingPrim.LocalID); + } + + // BSActor.isActive + public override bool isActive + { + get { return Enabled && m_controllingPrim.IsPhysicallyActive; } + } + + // Release any connections and resources used by the actor. + // BSActor.Dispose() + public override void Dispose() + { + Enabled = false; + } + + // Called when physical parameters (properties set in Bullet) need to be re-applied. + // Called at taint-time. + // BSActor.Refresh() + public override void Refresh() + { + m_physicsScene.DetailLog("{0},BSActorHover,refresh", m_controllingPrim.LocalID); + + // If not active any more, get rid of me (shouldn't ever happen, but just to be safe) + if (!m_controllingPrim.HoverActive) + { + m_physicsScene.DetailLog("{0},BSActorHover,refresh,notHovering,removing={1}", m_controllingPrim.LocalID, ActorName); + m_controllingPrim.PhysicalActors.RemoveAndRelease(ActorName); + return; + } + + // If the object is physically active, add the hoverer prestep action + if (isActive) + { + ActivateHover(); + } + else + { + DeactivateHover(); + } + } + + // The object's physical representation is being rebuilt so pick up any physical dependencies (constraints, ...). + // Register a prestep action to restore physical requirements before the next simulation step. + // Called at taint-time. + // BSActor.RemoveBodyDependencies() + public override void RemoveBodyDependencies() + { + // Nothing to do for the hoverer since it is all software at pre-step action time. + } + + // If a hover motor has not been created, create one and start the hovering. + private void ActivateHover() + { + if (m_hoverMotor == null) + { + // Turning the target on + m_hoverMotor = new BSFMotor("BSActorHover", + m_controllingPrim.HoverTau, // timeScale + BSMotor.Infinite, // decay time scale + BSMotor.Infinite, // friction timescale + 1f // efficiency + ); + m_hoverMotor.SetTarget(ComputeCurrentHoverHeight()); + m_hoverMotor.SetCurrent(m_controllingPrim.RawPosition.Z); + m_hoverMotor.PhysicsScene = m_physicsScene; // DEBUG DEBUG so motor will output detail log messages. + + m_physicsScene.BeforeStep += Hoverer; + } + } + + private void DeactivateHover() + { + if (m_hoverMotor != null) + { + m_physicsScene.BeforeStep -= Hoverer; + m_hoverMotor = null; + } + } + + // Called just before the simulation step. Update the vertical position for hoverness. + private void Hoverer(float timeStep) + { + // Don't do hovering while the object is selected. + if (!isActive) + return; + + m_hoverMotor.SetCurrent(m_controllingPrim.RawPosition.Z); + m_hoverMotor.SetTarget(ComputeCurrentHoverHeight()); + float targetHeight = m_hoverMotor.Step(timeStep); + + // 'targetHeight' is where we'd like the Z of the prim to be at this moment. + // Compute the amount of force to push us there. + float moveForce = (targetHeight - m_controllingPrim.RawPosition.Z) * m_controllingPrim.RawMass; + // Undo anything the object thinks it's doing at the moment + moveForce = -m_controllingPrim.RawVelocity.Z * m_controllingPrim.Mass; + + m_physicsScene.PE.ApplyCentralImpulse(m_controllingPrim.PhysBody, new OMV.Vector3(0f, 0f, moveForce)); + m_physicsScene.DetailLog("{0},BSPrim.Hover,move,targHt={1},moveForce={2},mass={3}", + m_controllingPrim.LocalID, targetHeight, moveForce, m_controllingPrim.RawMass); + } + + // Based on current position, determine what we should be hovering at now. + // Must recompute often. What if we walked offa cliff> + private float ComputeCurrentHoverHeight() + { + float ret = m_controllingPrim.HoverHeight; + float groundHeight = m_physicsScene.TerrainManager.GetTerrainHeightAtXYZ(m_controllingPrim.RawPosition); + + switch (m_controllingPrim.HoverType) + { + case PIDHoverType.Ground: + ret = groundHeight + m_controllingPrim.HoverHeight; + break; + case PIDHoverType.GroundAndWater: + float waterHeight = m_physicsScene.TerrainManager.GetWaterLevelAtXYZ(m_controllingPrim.RawPosition); + if (groundHeight > waterHeight) + { + ret = groundHeight + m_controllingPrim.HoverHeight; + } + else + { + ret = waterHeight + m_controllingPrim.HoverHeight; + } + break; + } + return ret; + } +} +} diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSActorLockAxis.cs b/OpenSim/Region/Physics/BulletSPlugin/BSActorLockAxis.cs index 7219617..c40a499 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSActorLockAxis.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSActorLockAxis.cs @@ -40,7 +40,7 @@ public class BSActorLockAxis : BSActor BSConstraint LockAxisConstraint = null; public BSActorLockAxis(BSScene physicsScene, BSPhysObject pObj, string actorName) - : base(physicsScene, pObj,actorName) + : base(physicsScene, pObj, actorName) { m_physicsScene.DetailLog("{0},BSActorLockAxis,constructor", m_controllingPrim.LocalID); LockAxisConstraint = null; @@ -99,7 +99,7 @@ public class BSActorLockAxis : BSActor // If a constraint is set up, remove it from the physical scene RemoveAxisLockConstraint(); // Schedule a call before the next simulation step to restore the constraint. - m_physicsScene.PostTaintObject(m_controllingPrim.LockedAxisActorName, m_controllingPrim.LocalID, delegate() + m_physicsScene.PostTaintObject("BSActorLockAxis:" + ActorName, m_controllingPrim.LocalID, delegate() { Refresh(); }); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSActorMoveToTarget.cs b/OpenSim/Region/Physics/BulletSPlugin/BSActorMoveToTarget.cs new file mode 100755 index 0000000..3517ef2 --- /dev/null +++ b/OpenSim/Region/Physics/BulletSPlugin/BSActorMoveToTarget.cs @@ -0,0 +1,156 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyrightD + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +using OpenSim.Region.Physics.Manager; + +using OMV = OpenMetaverse; + +namespace OpenSim.Region.Physics.BulletSPlugin +{ +public class BSActorMoveToTarget : BSActor +{ + private BSVMotor m_targetMotor; + + public BSActorMoveToTarget(BSScene physicsScene, BSPhysObject pObj, string actorName) + : base(physicsScene, pObj, actorName) + { + m_targetMotor = null; + m_physicsScene.DetailLog("{0},BSActorMoveToTarget,constructor", m_controllingPrim.LocalID); + } + + // BSActor.isActive + public override bool isActive + { + get { return Enabled && m_controllingPrim.IsPhysicallyActive; } + } + + // Release any connections and resources used by the actor. + // BSActor.Dispose() + public override void Dispose() + { + Enabled = false; + } + + // Called when physical parameters (properties set in Bullet) need to be re-applied. + // Called at taint-time. + // BSActor.Refresh() + public override void Refresh() + { + m_physicsScene.DetailLog("{0},BSActorMoveToTarget,refresh", m_controllingPrim.LocalID); + + // If not active any more, get rid of me (shouldn't ever happen, but just to be safe) + if (!m_controllingPrim.HoverActive) + { + m_physicsScene.DetailLog("{0},BSActorMoveToTarget,refresh,notMoveToTarget,removing={1}", m_controllingPrim.LocalID, ActorName); + m_controllingPrim.PhysicalActors.RemoveAndRelease(ActorName); + return; + } + + // If the object is physically active, add the hoverer prestep action + if (isActive) + { + ActivateMoveToTarget(); + } + else + { + DeactivateMoveToTarget(); + } + } + + // The object's physical representation is being rebuilt so pick up any physical dependencies (constraints, ...). + // Register a prestep action to restore physical requirements before the next simulation step. + // Called at taint-time. + // BSActor.RemoveBodyDependencies() + public override void RemoveBodyDependencies() + { + // Nothing to do for the hoverer since it is all software at pre-step action time. + } + + // If a hover motor has not been created, create one and start the hovering. + private void ActivateMoveToTarget() + { + if (m_targetMotor == null) + { + // We're taking over after this. + m_controllingPrim.ZeroMotion(true); + + m_targetMotor = new BSVMotor("BSPrim.PIDTarget", + m_controllingPrim.MoveToTargetTau, // timeScale + BSMotor.Infinite, // decay time scale + BSMotor.InfiniteVector, // friction timescale + 1f // efficiency + ); + m_targetMotor.PhysicsScene = m_physicsScene; // DEBUG DEBUG so motor will output detail log messages. + m_targetMotor.SetTarget(m_controllingPrim.MoveToTargetTarget); + m_targetMotor.SetCurrent(m_controllingPrim.RawPosition); + + m_physicsScene.BeforeStep += Mover; + } + } + + private void DeactivateMoveToTarget() + { + if (m_targetMotor != null) + { + m_physicsScene.BeforeStep -= Mover; + m_targetMotor = null; + } + } + + // Called just before the simulation step. Update the vertical position for hoverness. + private void Mover(float timeStep) + { + // Don't do hovering while the object is selected. + if (!isActive) + return; + + OMV.Vector3 origPosition = m_controllingPrim.RawPosition; // DEBUG DEBUG (for printout below) + + // 'movePosition' is where we'd like the prim to be at this moment. + OMV.Vector3 movePosition = m_controllingPrim.RawPosition + m_targetMotor.Step(timeStep); + + // If we are very close to our target, turn off the movement motor. + if (m_targetMotor.ErrorIsZero()) + { + m_physicsScene.DetailLog("{0},BSPrim.PIDTarget,zeroMovement,movePos={1},pos={2},mass={3}", + m_controllingPrim.LocalID, movePosition, m_controllingPrim.RawPosition, m_controllingPrim.Mass); + m_controllingPrim.ForcePosition = m_targetMotor.TargetValue; + m_targetMotor.Enabled = false; + } + else + { + m_controllingPrim.ForcePosition = movePosition; + } + m_physicsScene.DetailLog("{0},BSPrim.PIDTarget,move,fromPos={1},movePos={2}", m_controllingPrim.LocalID, origPosition, movePosition); + } +} +} diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSActorSetForce.cs b/OpenSim/Region/Physics/BulletSPlugin/BSActorSetForce.cs new file mode 100755 index 0000000..d942490 --- /dev/null +++ b/OpenSim/Region/Physics/BulletSPlugin/BSActorSetForce.cs @@ -0,0 +1,137 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyrightD + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +using OpenSim.Region.Physics.Manager; + +using OMV = OpenMetaverse; + +namespace OpenSim.Region.Physics.BulletSPlugin +{ +public class BSActorSetForce : BSActor +{ + BSFMotor m_forceMotor; + + public BSActorSetForce(BSScene physicsScene, BSPhysObject pObj, string actorName) + : base(physicsScene, pObj, actorName) + { + m_forceMotor = null; + m_physicsScene.DetailLog("{0},BSActorSetForce,constructor", m_controllingPrim.LocalID); + } + + // BSActor.isActive + public override bool isActive + { + get { return Enabled && m_controllingPrim.IsPhysicallyActive; } + } + + // Release any connections and resources used by the actor. + // BSActor.Dispose() + public override void Dispose() + { + Enabled = false; + } + + // Called when physical parameters (properties set in Bullet) need to be re-applied. + // Called at taint-time. + // BSActor.Refresh() + public override void Refresh() + { + m_physicsScene.DetailLog("{0},BSActorSetForce,refresh", m_controllingPrim.LocalID); + + // If not active any more, get rid of me (shouldn't ever happen, but just to be safe) + if (m_controllingPrim.RawForce == OMV.Vector3.Zero) + { + m_physicsScene.DetailLog("{0},BSActorSetForce,refresh,notSetForce,removing={1}", m_controllingPrim.LocalID, ActorName); + m_controllingPrim.PhysicalActors.RemoveAndRelease(ActorName); + return; + } + + // If the object is physically active, add the hoverer prestep action + if (isActive) + { + ActivateSetForce(); + } + else + { + DeactivateSetForce(); + } + } + + // The object's physical representation is being rebuilt so pick up any physical dependencies (constraints, ...). + // Register a prestep action to restore physical requirements before the next simulation step. + // Called at taint-time. + // BSActor.RemoveBodyDependencies() + public override void RemoveBodyDependencies() + { + // Nothing to do for the hoverer since it is all software at pre-step action time. + } + + // If a hover motor has not been created, create one and start the hovering. + private void ActivateSetForce() + { + if (m_forceMotor == null) + { + // A fake motor that might be used someday + m_forceMotor = new BSFMotor("setForce", 1f, 1f, 1f, 1f); + + m_physicsScene.BeforeStep += Mover; + } + } + + private void DeactivateSetForce() + { + if (m_forceMotor != null) + { + m_physicsScene.BeforeStep -= Mover; + m_forceMotor = null; + } + } + + // Called just before the simulation step. Update the vertical position for hoverness. + private void Mover(float timeStep) + { + // Don't do force while the object is selected. + if (!isActive) + return; + + m_physicsScene.DetailLog("{0},BSActorSetForce,preStep,force={1}", m_controllingPrim.LocalID, m_controllingPrim.RawForce); + if (m_controllingPrim.PhysBody.HasPhysicalBody) + { + m_physicsScene.PE.ApplyCentralForce(m_controllingPrim.PhysBody, m_controllingPrim.RawForce); + m_controllingPrim.ActivateIfPhysical(false); + } + + // TODO: + } +} +} + diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSActorSetTorque.cs b/OpenSim/Region/Physics/BulletSPlugin/BSActorSetTorque.cs new file mode 100755 index 0000000..e0f719f --- /dev/null +++ b/OpenSim/Region/Physics/BulletSPlugin/BSActorSetTorque.cs @@ -0,0 +1,138 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyrightD + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +using OpenSim.Region.Physics.Manager; + +using OMV = OpenMetaverse; + +namespace OpenSim.Region.Physics.BulletSPlugin +{ +public class BSActorSetTorque : BSActor +{ + BSFMotor m_torqueMotor; + + public BSActorSetTorque(BSScene physicsScene, BSPhysObject pObj, string actorName) + : base(physicsScene, pObj, actorName) + { + m_torqueMotor = null; + m_physicsScene.DetailLog("{0},BSActorSetTorque,constructor", m_controllingPrim.LocalID); + } + + // BSActor.isActive + public override bool isActive + { + get { return Enabled && m_controllingPrim.IsPhysicallyActive; } + } + + // Release any connections and resources used by the actor. + // BSActor.Dispose() + public override void Dispose() + { + Enabled = false; + } + + // Called when physical parameters (properties set in Bullet) need to be re-applied. + // Called at taint-time. + // BSActor.Refresh() + public override void Refresh() + { + m_physicsScene.DetailLog("{0},BSActorSetTorque,refresh", m_controllingPrim.LocalID); + + // If not active any more, get rid of me (shouldn't ever happen, but just to be safe) + if (m_controllingPrim.RawTorque == OMV.Vector3.Zero) + { + m_physicsScene.DetailLog("{0},BSActorSetTorque,refresh,notSetTorque,removing={1}", m_controllingPrim.LocalID, ActorName); + m_controllingPrim.PhysicalActors.RemoveAndRelease(ActorName); + return; + } + + // If the object is physically active, add the hoverer prestep action + if (isActive) + { + ActivateSetTorque(); + } + else + { + DeactivateSetTorque(); + } + } + + // The object's physical representation is being rebuilt so pick up any physical dependencies (constraints, ...). + // Register a prestep action to restore physical requirements before the next simulation step. + // Called at taint-time. + // BSActor.RemoveBodyDependencies() + public override void RemoveBodyDependencies() + { + // Nothing to do for the hoverer since it is all software at pre-step action time. + } + + // If a hover motor has not been created, create one and start the hovering. + private void ActivateSetTorque() + { + if (m_torqueMotor == null) + { + // A fake motor that might be used someday + m_torqueMotor = new BSFMotor("setTorque", 1f, 1f, 1f, 1f); + + m_physicsScene.BeforeStep += Mover; + } + } + + private void DeactivateSetTorque() + { + if (m_torqueMotor != null) + { + m_physicsScene.BeforeStep -= Mover; + m_torqueMotor = null; + } + } + + // Called just before the simulation step. Update the vertical position for hoverness. + private void Mover(float timeStep) + { + // Don't do force while the object is selected. + if (!isActive) + return; + + m_physicsScene.DetailLog("{0},BSActorSetTorque,preStep,force={1}", m_controllingPrim.LocalID, m_controllingPrim.RawTorque); + if (m_controllingPrim.PhysBody.HasPhysicalBody) + { + m_controllingPrim.AddAngularForce(m_controllingPrim.RawTorque, false, true); + m_controllingPrim.ActivateIfPhysical(false); + } + + // TODO: + } +} +} + + diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSActors.cs b/OpenSim/Region/Physics/BulletSPlugin/BSActors.cs index 5a19ba4..fb4d452 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSActors.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSActors.cs @@ -32,12 +32,12 @@ namespace OpenSim.Region.Physics.BulletSPlugin { public class BSActorCollection { - private BSScene PhysicsScene { get; set; } + private BSScene m_physicsScene { get; set; } private Dictionary m_actors; public BSActorCollection(BSScene physicsScene) { - PhysicsScene = physicsScene; + m_physicsScene = physicsScene; m_actors = new Dictionary(); } public void Add(string name, BSActor actor) @@ -61,6 +61,10 @@ public class BSActorCollection Release(); m_actors.Clear(); } + public void Dispose() + { + Clear(); + } public bool HasActor(string name) { return m_actors.ContainsKey(name); @@ -71,6 +75,10 @@ public class BSActorCollection act(kvp.Value); } + public void Enable(bool enabl) + { + ForEachActor(a => a.Enable(enabl)); + } public void Release() { ForEachActor(a => a.Dispose()); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index 25be416..09c9b16 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -46,9 +46,6 @@ public sealed class BSCharacter : BSPhysObject private OMV.Vector3 _position; private float _mass; private float _avatarVolume; - private OMV.Vector3 _force; - private OMV.Vector3 _velocity; - private OMV.Vector3 _torque; private float _collisionScore; private OMV.Vector3 _acceleration; private OMV.Quaternion _orientation; @@ -61,17 +58,13 @@ public sealed class BSCharacter : BSPhysObject private OMV.Vector3 _rotationalVelocity; private bool _kinematic; private float _buoyancy; - private bool _isStationaryStanding; // true is standing on a stationary object - private BSVMotor _velocityMotor; + private BSActorAvatarMove m_moveActor; + private const string AvatarMoveActorName = "BSCharacter.AvatarMove"; private OMV.Vector3 _PIDTarget; private bool _usePID; private float _PIDTau; - private bool _useHoverPID; - private float _PIDHoverHeight; - private PIDHoverType _PIDHoverType; - private float _PIDHoverTao; public BSCharacter(uint localID, String avName, BSScene parent_scene, OMV.Vector3 pos, OMV.Vector3 size, bool isFlying) : base(parent_scene, localID, avName, "BSCharacter") @@ -81,11 +74,10 @@ public sealed class BSCharacter : BSPhysObject _flying = isFlying; _orientation = OMV.Quaternion.Identity; - _velocity = OMV.Vector3.Zero; + RawVelocity = OMV.Vector3.Zero; _buoyancy = ComputeBuoyancyFromFlying(isFlying); Friction = BSParam.AvatarStandingFriction; Density = BSParam.AvatarDensity / BSParam.DensityScaleFactor; - _isStationaryStanding = false; // Old versions of ScenePresence passed only the height. If width and/or depth are zero, // replace with the default values. @@ -99,7 +91,12 @@ public sealed class BSCharacter : BSPhysObject // set _avatarVolume and _mass based on capsule size, _density and Scale ComputeAvatarVolumeAndMass(); - SetupMovementMotor(); + // The avatar's movement is controlled by this motor that speeds up and slows down + // the avatar seeking to reach the motor's target speed. + // This motor runs as a prestep action for the avatar so it will keep the avatar + // standing as well as moving. Destruction of the avatar will destroy the pre-step action. + m_moveActor = new BSActorAvatarMove(PhysicsScene, this, AvatarMoveActorName); + PhysicalActors.Add(AvatarMoveActorName, m_moveActor); DetailLog("{0},BSCharacter.create,call,size={1},scale={2},density={3},volume={4},mass={5}", LocalID, _size, Scale, Density, _avatarVolume, RawMass); @@ -139,10 +136,10 @@ public sealed class BSCharacter : BSPhysObject ForcePosition = _position; // Set the velocity - _velocityMotor.Reset(); - _velocityMotor.SetTarget(_velocity); - _velocityMotor.SetCurrent(_velocity); - ForceVelocity = _velocity; + if (m_moveActor != null) + m_moveActor.SetVelocityAndTarget(RawVelocity, RawVelocity, false); + + ForceVelocity = RawVelocity; // This will enable or disable the flying buoyancy of the avatar. // Needs to be reset especially when an avatar is recreated after crossing a region boundry. @@ -176,162 +173,6 @@ public sealed class BSCharacter : BSPhysObject PhysBody.ApplyCollisionMask(PhysicsScene); } - // The avatar's movement is controlled by this motor that speeds up and slows down - // the avatar seeking to reach the motor's target speed. - // This motor runs as a prestep action for the avatar so it will keep the avatar - // standing as well as moving. Destruction of the avatar will destroy the pre-step action. - private void SetupMovementMotor() - { - // Infinite decay and timescale values so motor only changes current to target values. - _velocityMotor = new BSVMotor("BSCharacter.Velocity", - 0.2f, // time scale - BSMotor.Infinite, // decay time scale - BSMotor.InfiniteVector, // friction timescale - 1f // efficiency - ); - // _velocityMotor.PhysicsScene = PhysicsScene; // DEBUG DEBUG so motor will output detail log messages. - - RegisterPreStepAction("BSCharactor.Movement", LocalID, delegate(float timeStep) - { - // TODO: Decide if the step parameters should be changed depending on the avatar's - // state (flying, colliding, ...). There is code in ODE to do this. - - // COMMENTARY: when the user is making the avatar walk, except for falling, the velocity - // specified for the avatar is the one that should be used. For falling, if the avatar - // is not flying and is not colliding then it is presumed to be falling and the Z - // component is not fooled with (thus allowing gravity to do its thing). - // When the avatar is standing, though, the user has specified a velocity of zero and - // the avatar should be standing. But if the avatar is pushed by something in the world - // (raising elevator platform, moving vehicle, ...) the avatar should be allowed to - // move. Thus, the velocity cannot be forced to zero. The problem is that small velocity - // errors can creap in and the avatar will slowly float off in some direction. - // So, the problem is that, when an avatar is standing, we cannot tell creaping error - // from real pushing. - // The code below uses whether the collider is static or moving to decide whether to zero motion. - - _velocityMotor.Step(timeStep); - _isStationaryStanding = false; - - // If we're not supposed to be moving, make sure things are zero. - if (_velocityMotor.ErrorIsZero() && _velocityMotor.TargetValue == OMV.Vector3.Zero) - { - // The avatar shouldn't be moving - _velocityMotor.Zero(); - - if (IsColliding) - { - // If we are colliding with a stationary object, presume we're standing and don't move around - if (!ColliderIsMoving) - { - DetailLog("{0},BSCharacter.MoveMotor,collidingWithStationary,zeroingMotion", LocalID); - _isStationaryStanding = true; - ZeroMotion(true /* inTaintTime */); - } - - // Standing has more friction on the ground - if (Friction != BSParam.AvatarStandingFriction) - { - Friction = BSParam.AvatarStandingFriction; - PhysicsScene.PE.SetFriction(PhysBody, Friction); - } - } - else - { - if (Flying) - { - // Flying and not collising and velocity nearly zero. - ZeroMotion(true /* inTaintTime */); - } - } - - DetailLog("{0},BSCharacter.MoveMotor,taint,stopping,target={1},colliding={2}", LocalID, _velocityMotor.TargetValue, IsColliding); - } - else - { - // Supposed to be moving. - OMV.Vector3 stepVelocity = _velocityMotor.CurrentValue; - - if (Friction != BSParam.AvatarFriction) - { - // Probably starting up walking. Set friction to moving friction. - Friction = BSParam.AvatarFriction; - PhysicsScene.PE.SetFriction(PhysBody, Friction); - } - - // If falling, we keep the world's downward vector no matter what the other axis specify. - // The check for _velocity.Z < 0 makes jumping work (temporary upward force). - if (!Flying && !IsColliding) - { - if (_velocity.Z < 0) - stepVelocity.Z = _velocity.Z; - // DetailLog("{0},BSCharacter.MoveMotor,taint,overrideStepZWithWorldZ,stepVel={1}", LocalID, stepVelocity); - } - - // 'stepVelocity' is now the speed we'd like the avatar to move in. Turn that into an instantanous force. - OMV.Vector3 moveForce = (stepVelocity - _velocity) * Mass; - - // Should we check for move force being small and forcing velocity to zero? - - // Add special movement force to allow avatars to walk up stepped surfaces. - moveForce += WalkUpStairs(); - - DetailLog("{0},BSCharacter.MoveMotor,move,stepVel={1},vel={2},mass={3},moveForce={4}", LocalID, stepVelocity, _velocity, Mass, moveForce); - PhysicsScene.PE.ApplyCentralImpulse(PhysBody, moveForce); - } - }); - } - - // Decide if the character is colliding with a low object and compute a force to pop the - // avatar up so it can walk up and over the low objects. - private OMV.Vector3 WalkUpStairs() - { - OMV.Vector3 ret = OMV.Vector3.Zero; - - // This test is done if moving forward, not flying and is colliding with something. - // DetailLog("{0},BSCharacter.WalkUpStairs,IsColliding={1},flying={2},targSpeed={3},collisions={4}", - // LocalID, IsColliding, Flying, TargetSpeed, CollisionsLastTick.Count); - if (IsColliding && !Flying && TargetVelocitySpeed > 0.1f /* && ForwardSpeed < 0.1f */) - { - // The range near the character's feet where we will consider stairs - float nearFeetHeightMin = RawPosition.Z - (Size.Z / 2f) + 0.05f; - float nearFeetHeightMax = nearFeetHeightMin + BSParam.AvatarStepHeight; - - // Look for a collision point that is near the character's feet and is oriented the same as the charactor is - foreach (KeyValuePair kvp in CollisionsLastTick.m_objCollisionList) - { - // Don't care about collisions with the terrain - if (kvp.Key > PhysicsScene.TerrainManager.HighestTerrainID) - { - OMV.Vector3 touchPosition = kvp.Value.Position; - // DetailLog("{0},BSCharacter.WalkUpStairs,min={1},max={2},touch={3}", - // LocalID, nearFeetHeightMin, nearFeetHeightMax, touchPosition); - if (touchPosition.Z >= nearFeetHeightMin && touchPosition.Z <= nearFeetHeightMax) - { - // This contact is within the 'near the feet' range. - // The normal should be our contact point to the object so it is pointing away - // thus the difference between our facing orientation and the normal should be small. - OMV.Vector3 directionFacing = OMV.Vector3.UnitX * RawOrientation; - OMV.Vector3 touchNormal = OMV.Vector3.Normalize(kvp.Value.SurfaceNormal); - float diff = Math.Abs(OMV.Vector3.Distance(directionFacing, touchNormal)); - if (diff < BSParam.AvatarStepApproachFactor) - { - // Found the stairs contact point. Push up a little to raise the character. - float upForce = (touchPosition.Z - nearFeetHeightMin) * Mass * BSParam.AvatarStepForceFactor; - ret = new OMV.Vector3(0f, 0f, upForce); - - // Also move the avatar up for the new height - OMV.Vector3 displacement = new OMV.Vector3(0f, 0f, BSParam.AvatarStepHeight / 2f); - ForcePosition = RawPosition + displacement; - } - DetailLog("{0},BSCharacter.WalkUpStairs,touchPos={1},nearFeetMin={2},faceDir={3},norm={4},diff={5},ret={6}", - LocalID, touchPosition, nearFeetHeightMin, directionFacing, touchNormal, diff, ret); - } - } - } - } - - return ret; - } public override void RequestPhysicsterseUpdate() { @@ -403,7 +244,7 @@ public sealed class BSCharacter : BSPhysObject // Called at taint time! public override void ZeroMotion(bool inTaintTime) { - _velocity = OMV.Vector3.Zero; + RawVelocity = OMV.Vector3.Zero; _acceleration = OMV.Vector3.Zero; _rotationalVelocity = OMV.Vector3.Zero; @@ -542,15 +383,15 @@ public sealed class BSCharacter : BSPhysObject } public override OMV.Vector3 Force { - get { return _force; } + get { return RawForce; } set { - _force = value; + RawForce = value; // m_log.DebugFormat("{0}: Force = {1}", LogHeader, _force); PhysicsScene.TaintedObject("BSCharacter.SetForce", delegate() { - DetailLog("{0},BSCharacter.setForce,taint,force={1}", LocalID, _force); + DetailLog("{0},BSCharacter.setForce,taint,force={1}", LocalID, RawForce); if (PhysBody.HasPhysicalBody) - PhysicsScene.PE.SetObjectForce(PhysBody, _force); + PhysicsScene.PE.SetObjectForce(PhysBody, RawForce); }); } } @@ -573,7 +414,7 @@ public sealed class BSCharacter : BSPhysObject { get { - return m_targetVelocity; + return base.m_targetVelocity; } set { @@ -583,51 +424,39 @@ public sealed class BSCharacter : BSPhysObject if (_setAlwaysRun) targetVel *= new OMV.Vector3(BSParam.AvatarAlwaysRunFactor, BSParam.AvatarAlwaysRunFactor, 0f); - PhysicsScene.TaintedObject("BSCharacter.setTargetVelocity", delegate() - { - _velocityMotor.Reset(); - _velocityMotor.SetTarget(targetVel); - _velocityMotor.SetCurrent(_velocity); - _velocityMotor.Enabled = true; - }); + if (m_moveActor != null) + m_moveActor.SetVelocityAndTarget(RawVelocity, targetVel, false /* inTaintTime */); } } - public override OMV.Vector3 RawVelocity - { - get { return _velocity; } - set { _velocity = value; } - } // Directly setting velocity means this is what the user really wants now. public override OMV.Vector3 Velocity { - get { return _velocity; } + get { return RawVelocity; } set { - _velocity = value; - // m_log.DebugFormat("{0}: set velocity = {1}", LogHeader, _velocity); + RawVelocity = value; + // m_log.DebugFormat("{0}: set velocity = {1}", LogHeader, RawVelocity); PhysicsScene.TaintedObject("BSCharacter.setVelocity", delegate() { - _velocityMotor.Reset(); - _velocityMotor.SetCurrent(_velocity); - _velocityMotor.SetTarget(_velocity); - _velocityMotor.Enabled = false; + if (m_moveActor != null) + m_moveActor.SetVelocityAndTarget(RawVelocity, RawVelocity, true /* inTaintTime */); - DetailLog("{0},BSCharacter.setVelocity,taint,vel={1}", LocalID, _velocity); - ForceVelocity = _velocity; + DetailLog("{0},BSCharacter.setVelocity,taint,vel={1}", LocalID, RawVelocity); + ForceVelocity = RawVelocity; }); } } public override OMV.Vector3 ForceVelocity { - get { return _velocity; } + get { return RawVelocity; } set { PhysicsScene.AssertInTaintTime("BSCharacter.ForceVelocity"); - _velocity = value; - PhysicsScene.PE.SetLinearVelocity(PhysBody, _velocity); + RawVelocity = value; + PhysicsScene.PE.SetLinearVelocity(PhysBody, RawVelocity); PhysicsScene.PE.Activate(PhysBody, true); } } public override OMV.Vector3 Torque { - get { return _torque; } - set { _torque = value; + get { return RawTorque; } + set { RawTorque = value; } } public override float CollisionScore { @@ -783,27 +612,6 @@ public sealed class BSCharacter : BSPhysObject set { _PIDTau = value; } } - // Used for llSetHoverHeight and maybe vehicle height - // Hover Height will override MoveTo target's Z - public override bool PIDHoverActive { - set { _useHoverPID = value; } - } - public override float PIDHoverHeight { - set { _PIDHoverHeight = value; } - } - public override PIDHoverType PIDHoverType { - set { _PIDHoverType = value; } - } - public override float PIDHoverTau { - set { _PIDHoverTao = value; } - } - - // For RotLookAt - public override OMV.Quaternion APIDTarget { set { return; } } - public override bool APIDActive { set { return; } } - public override float APIDStrength { set { return; } } - public override float APIDDamping { set { return; } } - public override void AddForce(OMV.Vector3 force, bool pushforce) { // Since this force is being applied in only one step, make this a force per second. @@ -833,7 +641,7 @@ public sealed class BSCharacter : BSPhysObject } } - public override void AddAngularForce(OMV.Vector3 force, bool pushforce) { + public override void AddAngularForce(OMV.Vector3 force, bool pushforce, bool inTaintTime) { } public override void SetMomentum(OMV.Vector3 momentum) { } @@ -887,7 +695,7 @@ public sealed class BSCharacter : BSPhysObject public override void UpdateProperties(EntityProperties entprop) { // Don't change position if standing on a stationary object. - if (!_isStationaryStanding) + if (!IsStationary) _position = entprop.Position; _orientation = entprop.Rotation; @@ -896,8 +704,8 @@ public sealed class BSCharacter : BSPhysObject // and will send agent updates to the clients if velocity changes by more than // 0.001m/s. Bullet introduces a lot of jitter in the velocity which causes many // extra updates. - if (!entprop.Velocity.ApproxEquals(_velocity, 0.1f)) - _velocity = entprop.Velocity; + if (!entprop.Velocity.ApproxEquals(RawVelocity, 0.1f)) + RawVelocity = entprop.Velocity; _acceleration = entprop.Acceleration; _rotationalVelocity = entprop.RotationalVelocity; @@ -920,7 +728,7 @@ public sealed class BSCharacter : BSPhysObject // base.RequestPhysicsterseUpdate(); DetailLog("{0},BSCharacter.UpdateProperties,call,pos={1},orient={2},vel={3},accel={4},rotVel={5}", - LocalID, _position, _orientation, _velocity, _acceleration, _rotationalVelocity); + LocalID, _position, _orientation, RawVelocity, _acceleration, _rotationalVelocity); } } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index 98ea833..644bc7e 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -43,7 +43,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin * VariableName: used by the simulator and performs taint operations, etc * RawVariableName: direct reference to the BulletSim storage for the variable value * ForceVariableName: direct reference (store and fetch) to the value in the physics engine. - * The last two (and certainly the last one) should be referenced only in taint-time. + * The last one should only be referenced in taint-time. */ /* @@ -84,6 +84,7 @@ public abstract class BSPhysObject : PhysicsActor // Initialize variables kept in base. GravModifier = 1.0f; Gravity = new OMV.Vector3(0f, 0f, BSParam.Gravity); + HoverActive = false; // We don't have any physical representation yet. PhysBody = new BulletBody(localID); @@ -110,11 +111,10 @@ public abstract class BSPhysObject : PhysicsActor // Tell the object to clean up. public virtual void Destroy() { - UnRegisterAllPreStepActions(); - UnRegisterAllPostStepActions(); + PhysicalActors.Enable(false); PhysicsScene.TaintedObject("BSPhysObject.Destroy", delegate() { - PhysicalActors.Release(); + PhysicalActors.Dispose(); }); } @@ -203,15 +203,48 @@ public abstract class BSPhysObject : PhysicsActor public abstract OMV.Quaternion RawOrientation { get; set; } public abstract OMV.Quaternion ForceOrientation { get; set; } - public abstract OMV.Vector3 RawVelocity { get; set; } + public OMV.Vector3 RawVelocity { get; set; } public abstract OMV.Vector3 ForceVelocity { get; set; } + public OMV.Vector3 RawForce { get; set; } + public OMV.Vector3 RawTorque { get; set; } + public override void AddAngularForce(OMV.Vector3 force, bool pushforce) + { + AddAngularForce(force, pushforce, false); + } + public abstract void AddAngularForce(OMV.Vector3 force, bool pushforce, bool inTaintTime); + public abstract OMV.Vector3 ForceRotationalVelocity { get; set; } public abstract float ForceBuoyancy { get; set; } public virtual bool ForceBodyShapeRebuild(bool inTaintTime) { return false; } + public override bool PIDActive { set { MoveToTargetActive = value; } } + public override OMV.Vector3 PIDTarget { set { MoveToTargetTarget = value; } } + public override float PIDTau { set { MoveToTargetTau = value; } } + + public bool MoveToTargetActive { get; set; } + public OMV.Vector3 MoveToTargetTarget { get; set; } + public float MoveToTargetTau { get; set; } + + // Used for llSetHoverHeight and maybe vehicle height. Hover Height will override MoveTo target's Z + public override bool PIDHoverActive { set { HoverActive = value; } } + public override float PIDHoverHeight { set { HoverHeight = value; } } + public override PIDHoverType PIDHoverType { set { HoverType = value; } } + public override float PIDHoverTau { set { HoverTau = value; } } + + public bool HoverActive { get; set; } + public float HoverHeight { get; set; } + public PIDHoverType HoverType { get; set; } + public float HoverTau { get; set; } + + // For RotLookAt + public override OMV.Quaternion APIDTarget { set { return; } } + public override bool APIDActive { set { return; } } + public override float APIDStrength { set { return; } } + public override float APIDDamping { set { return; } } + // The current velocity forward public virtual float ForwardSpeed { @@ -237,7 +270,44 @@ public abstract class BSPhysObject : PhysicsActor public OMV.Vector3 LockedAxis { get; set; } // zero means locked. one means free. public readonly OMV.Vector3 LockedAxisFree = new OMV.Vector3(1f, 1f, 1f); // All axis are free - public readonly String LockedAxisActorName = "BSPrim.LockedAxis"; + + // Enable physical actions. Bullet will keep sleeping non-moving physical objects so + // they need waking up when parameters are changed. + // Called in taint-time!! + public void ActivateIfPhysical(bool forceIt) + { + if (IsPhysical && PhysBody.HasPhysicalBody) + PhysicsScene.PE.Activate(PhysBody, forceIt); + } + + // 'actors' act on the physical object to change or constrain its motion. These can range from + // hovering to complex vehicle motion. + public delegate BSActor CreateActor(); + public void CreateRemoveActor(bool createRemove, string actorName, bool inTaintTime, CreateActor creator) + { + if (createRemove) + { + PhysicsScene.TaintedObject(inTaintTime, "BSPrim.CreateRemoveActor:" + actorName, delegate() + { + if (!PhysicalActors.HasActor(actorName)) + { + DetailLog("{0},BSPrim.CreateRemoveActor,taint,registerActor,a={1}", LocalID, actorName); + PhysicalActors.Add(actorName, creator()); + } + }); + } + else + { + PhysicsScene.TaintedObject(inTaintTime, "BSPrim.CreateRemoveActor:" + actorName, delegate() + { + if (PhysicalActors.HasActor(actorName)) + { + DetailLog("{0},BSPrim.CreateRemoveActor,taint,unregisterActor,a={1}", LocalID, actorName); + PhysicalActors.RemoveAndRelease(actorName); + } + }); + } + } #region Collisions @@ -255,7 +325,9 @@ public abstract class BSPhysObject : PhysicsActor protected CollisionFlags CurrentCollisionFlags { get; set; } // On a collision, check the collider and remember if the last collider was moving // Used to modify the standing of avatars (avatars on stationary things stand still) - protected bool ColliderIsMoving; + public bool ColliderIsMoving; + // Used by BSCharacter to manage standing (and not slipping) + public bool IsStationary; // Count of collisions for this object protected long CollisionAccumulation { get; set; } @@ -293,7 +365,7 @@ public abstract class BSPhysObject : PhysicsActor protected CollisionEventUpdate CollisionCollection; // Remember collisions from last tick for fancy collision based actions // (like a BSCharacter walking up stairs). - protected CollisionEventUpdate CollisionsLastTick; + public CollisionEventUpdate CollisionsLastTick; // The simulation step is telling this object about a collision. // Return 'true' if a collision was processed and should be sent up. @@ -424,104 +496,6 @@ public abstract class BSPhysObject : PhysicsActor public BSActorCollection PhysicalActors; - // There are some actions that must be performed for a physical object before each simulation step. - // These actions are optional so, rather than scanning all the physical objects and asking them - // if they have anything to do, a physical object registers for an event call before the step is performed. - // This bookkeeping makes it easy to add, remove and clean up after all these registrations. - private Dictionary RegisteredPrestepActions = new Dictionary(); - private Dictionary RegisteredPoststepActions = new Dictionary(); - protected void RegisterPreStepAction(string op, uint id, BSScene.PreStepAction actn) - { - string identifier = op + "-" + id.ToString(); - - lock (RegisteredPrestepActions) - { - // Clean out any existing action - UnRegisterPreStepAction(op, id); - RegisteredPrestepActions[identifier] = actn; - PhysicsScene.BeforeStep += actn; - } - DetailLog("{0},BSPhysObject.RegisterPreStepAction,id={1}", LocalID, identifier); - } - - // Unregister a pre step action. Safe to call if the action has not been registered. - // Returns 'true' if an action was actually removed - protected bool UnRegisterPreStepAction(string op, uint id) - { - string identifier = op + "-" + id.ToString(); - bool removed = false; - lock (RegisteredPrestepActions) - { - if (RegisteredPrestepActions.ContainsKey(identifier)) - { - PhysicsScene.BeforeStep -= RegisteredPrestepActions[identifier]; - RegisteredPrestepActions.Remove(identifier); - removed = true; - } - } - DetailLog("{0},BSPhysObject.UnRegisterPreStepAction,id={1},removed={2}", LocalID, identifier, removed); - return removed; - } - - protected void UnRegisterAllPreStepActions() - { - lock (RegisteredPrestepActions) - { - foreach (KeyValuePair kvp in RegisteredPrestepActions) - { - PhysicsScene.BeforeStep -= kvp.Value; - } - RegisteredPrestepActions.Clear(); - } - DetailLog("{0},BSPhysObject.UnRegisterAllPreStepActions,", LocalID); - } - - protected void RegisterPostStepAction(string op, uint id, BSScene.PostStepAction actn) - { - string identifier = op + "-" + id.ToString(); - - lock (RegisteredPoststepActions) - { - // Clean out any existing action - UnRegisterPostStepAction(op, id); - RegisteredPoststepActions[identifier] = actn; - PhysicsScene.AfterStep += actn; - } - DetailLog("{0},BSPhysObject.RegisterPostStepAction,id={1}", LocalID, identifier); - } - - // Unregister a pre step action. Safe to call if the action has not been registered. - // Returns 'true' if an action was actually removed. - protected bool UnRegisterPostStepAction(string op, uint id) - { - string identifier = op + "-" + id.ToString(); - bool removed = false; - lock (RegisteredPoststepActions) - { - if (RegisteredPoststepActions.ContainsKey(identifier)) - { - PhysicsScene.AfterStep -= RegisteredPoststepActions[identifier]; - RegisteredPoststepActions.Remove(identifier); - removed = true; - } - } - DetailLog("{0},BSPhysObject.UnRegisterPostStepAction,id={1},removed={2}", LocalID, identifier, removed); - return removed; - } - - protected void UnRegisterAllPostStepActions() - { - lock (RegisteredPoststepActions) - { - foreach (KeyValuePair kvp in RegisteredPoststepActions) - { - PhysicsScene.AfterStep -= kvp.Value; - } - RegisteredPoststepActions.Clear(); - } - DetailLog("{0},BSPhysObject.UnRegisterAllPostStepActions,", LocalID); - } - // When an update to the physical properties happens, this event is fired to let // different actors to modify the update before it is passed around public delegate void PreUpdatePropertyAction(ref EntityProperties entprop); @@ -533,46 +507,6 @@ public abstract class BSPhysObject : PhysicsActor actions(ref entprop); } - private Dictionary RegisteredPreUpdatePropertyActions = new Dictionary(); - public void RegisterPreUpdatePropertyAction(string identifier, PreUpdatePropertyAction actn) - { - lock (RegisteredPreUpdatePropertyActions) - { - // Clean out any existing action - UnRegisterPreUpdatePropertyAction(identifier); - RegisteredPreUpdatePropertyActions[identifier] = actn; - OnPreUpdateProperty += actn; - } - DetailLog("{0},BSPhysObject.RegisterPreUpdatePropertyAction,id={1}", LocalID, identifier); - } - public bool UnRegisterPreUpdatePropertyAction(string identifier) - { - bool removed = false; - lock (RegisteredPreUpdatePropertyActions) - { - if (RegisteredPreUpdatePropertyActions.ContainsKey(identifier)) - { - OnPreUpdateProperty -= RegisteredPreUpdatePropertyActions[identifier]; - RegisteredPreUpdatePropertyActions.Remove(identifier); - removed = true; - } - } - DetailLog("{0},BSPhysObject.UnRegisterPreUpdatePropertyAction,id={1},removed={2}", LocalID, identifier, removed); - return removed; - } - public void UnRegisterAllPreUpdatePropertyActions() - { - lock (RegisteredPreUpdatePropertyActions) - { - foreach (KeyValuePair kvp in RegisteredPreUpdatePropertyActions) - { - OnPreUpdateProperty -= kvp.Value; - } - RegisteredPreUpdatePropertyActions.Clear(); - } - DetailLog("{0},BSPhysObject.UnRegisterAllPreUpdatePropertyAction,", LocalID); - } - #endregion // Per Simulation Step actions // High performance detailed logging routine used by the physical objects. diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index e56276a..71fea59 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -55,9 +55,6 @@ public class BSPrim : BSPhysObject private OMV.Vector3 _position; private float _mass; // the mass of this object - private OMV.Vector3 _force; - private OMV.Vector3 _velocity; - private OMV.Vector3 _torque; private OMV.Vector3 _acceleration; private OMV.Quaternion _orientation; private int _physicsActorType; @@ -73,16 +70,13 @@ public class BSPrim : BSPhysObject private int CrossingFailures { get; set; } public BSDynamics VehicleActor; - public string VehicleActorName = "BasicVehicle"; + public const string VehicleActorName = "BasicVehicle"; - private BSVMotor _targetMotor; - private OMV.Vector3 _PIDTarget; - private float _PIDTau; - - private BSFMotor _hoverMotor; - private float _PIDHoverHeight; - private PIDHoverType _PIDHoverType; - private float _PIDHoverTau; + public const string HoverActorName = "HoverActor"; + public const String LockedAxisActorName = "BSPrim.LockedAxis"; + public const string MoveToTargetActorName = "MoveToTargetActor"; + public const string SetForceActorName = "SetForceActor"; + public const string SetTorqueActorName = "SetTorqueActor"; public BSPrim(uint localID, String primName, BSScene parent_scene, OMV.Vector3 pos, OMV.Vector3 size, OMV.Quaternion rotation, PrimitiveBaseShape pbs, bool pisPhysical) @@ -95,7 +89,7 @@ public class BSPrim : BSPhysObject Scale = size; // prims are the size the user wants them to be (different for BSCharactes). _orientation = rotation; _buoyancy = 0f; - _velocity = OMV.Vector3.Zero; + RawVelocity = OMV.Vector3.Zero; _rotationalVelocity = OMV.Vector3.Zero; BaseShape = pbs; _isPhysical = pisPhysical; @@ -233,7 +227,7 @@ public class BSPrim : BSPhysObject // Called at taint time! public override void ZeroMotion(bool inTaintTime) { - _velocity = OMV.Vector3.Zero; + RawVelocity = OMV.Vector3.Zero; _acceleration = OMV.Vector3.Zero; _rotationalVelocity = OMV.Vector3.Zero; @@ -270,19 +264,17 @@ public class BSPrim : BSPhysObject if (axis.Z != 1) locking.Z = 0f; LockedAxis = locking; - if (LockedAxis != LockedAxisFree) + CreateRemoveActor(LockedAxis != LockedAxisFree /* creatActor */, LockedAxisActorName, false /* inTaintTime */, delegate() { - PhysicsScene.TaintedObject("BSPrim.LockAngularMotion", delegate() - { - // If there is not already an axis locker, make one - if (!PhysicalActors.HasActor(LockedAxisActorName)) - { - DetailLog("{0},BSPrim.LockAngularMotion,taint,registeringLockAxisActor", LocalID); - PhysicalActors.Add(LockedAxisActorName, new BSActorLockAxis(PhysicsScene, this, LockedAxisActorName)); - } - UpdatePhysicalParameters(); - }); - } + return new BSActorLockAxis(PhysicsScene, this, LockedAxisActorName); + }); + + // Update parameters so the new actor's Refresh() action is called at the right time. + PhysicsScene.TaintedObject("BSPrim.LockAngularMotion", delegate() + { + UpdatePhysicalParameters(); + }); + return; } @@ -407,9 +399,9 @@ public class BSPrim : BSPhysObject ZeroMotion(inTaintTime); ret = true; } - if (_velocity.LengthSquared() > BSParam.MaxLinearVelocity) + if (RawVelocity.LengthSquared() > BSParam.MaxLinearVelocity) { - _velocity = Util.ClampV(_velocity, BSParam.MaxLinearVelocity); + RawVelocity = Util.ClampV(RawVelocity, BSParam.MaxLinearVelocity); ret = true; } if (_rotationalVelocity.LengthSquared() > BSParam.MaxAngularVelocitySquared) @@ -506,35 +498,13 @@ public class BSPrim : BSPhysObject } public override OMV.Vector3 Force { - get { return _force; } + get { return RawForce; } set { - _force = value; - if (_force != OMV.Vector3.Zero) - { - // If the force is non-zero, it must be reapplied each tick because - // Bullet clears the forces applied last frame. - RegisterPreStepAction("BSPrim.setForce", LocalID, - delegate(float timeStep) - { - if (!IsPhysicallyActive || _force == OMV.Vector3.Zero) - { - UnRegisterPreStepAction("BSPrim.setForce", LocalID); - return; - } - - DetailLog("{0},BSPrim.setForce,preStep,force={1}", LocalID, _force); - if (PhysBody.HasPhysicalBody) - { - PhysicsScene.PE.ApplyCentralForce(PhysBody, _force); - ActivateIfPhysical(false); - } - } - ); - } - else + RawForce = value; + CreateRemoveActor(RawForce == OMV.Vector3.Zero, SetForceActorName, false /* inTaintTime */, delegate() { - UnRegisterPreStepAction("BSPrim.setForce", LocalID); - } + return new BSActorSetForce(PhysicsScene, this, SetForceActorName); + }); } } @@ -670,62 +640,39 @@ public class BSPrim : BSPhysObject } } } - public override OMV.Vector3 RawVelocity - { - get { return _velocity; } - set { _velocity = value; } - } public override OMV.Vector3 Velocity { - get { return _velocity; } + get { return RawVelocity; } set { - _velocity = value; + RawVelocity = value; PhysicsScene.TaintedObject("BSPrim.setVelocity", delegate() { - // DetailLog("{0},BSPrim.SetVelocity,taint,vel={1}", LocalID, _velocity); - ForceVelocity = _velocity; + // DetailLog("{0},BSPrim.SetVelocity,taint,vel={1}", LocalID, RawVelocity); + ForceVelocity = RawVelocity; }); } } public override OMV.Vector3 ForceVelocity { - get { return _velocity; } + get { return RawVelocity; } set { PhysicsScene.AssertInTaintTime("BSPrim.ForceVelocity"); - _velocity = Util.ClampV(value, BSParam.MaxLinearVelocity); + RawVelocity = Util.ClampV(value, BSParam.MaxLinearVelocity); if (PhysBody.HasPhysicalBody) { - DetailLog("{0},BSPrim.ForceVelocity,taint,vel={1}", LocalID, _velocity); - PhysicsScene.PE.SetLinearVelocity(PhysBody, _velocity); + DetailLog("{0},BSPrim.ForceVelocity,taint,vel={1}", LocalID, RawVelocity); + PhysicsScene.PE.SetLinearVelocity(PhysBody, RawVelocity); ActivateIfPhysical(false); } } } public override OMV.Vector3 Torque { - get { return _torque; } + get { return RawTorque; } set { - _torque = value; - if (_torque != OMV.Vector3.Zero) + RawTorque = value; + CreateRemoveActor(RawTorque == OMV.Vector3.Zero, SetTorqueActorName, false /* inTaintTime */, delegate() { - // If the torque is non-zero, it must be reapplied each tick because - // Bullet clears the forces applied last frame. - RegisterPreStepAction("BSPrim.setTorque", LocalID, - delegate(float timeStep) - { - if (!IsPhysicallyActive || _torque == OMV.Vector3.Zero) - { - UnRegisterPreStepAction("BSPrim.setTorque", LocalID); - return; - } - - if (PhysBody.HasPhysicalBody) - AddAngularForce(_torque, false, true); - } - ); - } - else - { - UnRegisterPreStepAction("BSPrim.setTorque", LocalID); - } + return new BSActorSetTorque(PhysicsScene, this, SetTorqueActorName); + }); // DetailLog("{0},BSPrim.SetTorque,call,torque={1}", LocalID, _torque); } } @@ -909,7 +856,7 @@ public class BSPrim : BSPhysObject // For good measure, make sure the transform is set through to the motion state ForcePosition = _position; - ForceVelocity = _velocity; + ForceVelocity = RawVelocity; ForceRotationalVelocity = _rotationalVelocity; // A dynamic object has mass @@ -966,15 +913,6 @@ public class BSPrim : BSPhysObject } } - // Enable physical actions. Bullet will keep sleeping non-moving physical objects so - // they need waking up when parameters are changed. - // Called in taint-time!! - private void ActivateIfPhysical(bool forceIt) - { - if (IsPhysical && PhysBody.HasPhysicalBody) - PhysicsScene.PE.Activate(PhysBody, forceIt); - } - // Turn on or off the flag controlling whether collision events are returned to the simulator. private void EnableCollisions(bool wantsCollisionEvents) { @@ -1096,78 +1034,13 @@ public class BSPrim : BSPhysObject } } - // Used for MoveTo - public override OMV.Vector3 PIDTarget { - set - { - // TODO: add a sanity check -- don't move more than a region or something like that. - _PIDTarget = value; - } - } - public override float PIDTau { - set { _PIDTau = value; } - } public override bool PIDActive { set { - if (value) - { - // We're taking over after this. - ZeroMotion(true); - - _targetMotor = new BSVMotor("BSPrim.PIDTarget", - _PIDTau, // timeScale - BSMotor.Infinite, // decay time scale - BSMotor.InfiniteVector, // friction timescale - 1f // efficiency - ); - _targetMotor.PhysicsScene = PhysicsScene; // DEBUG DEBUG so motor will output detail log messages. - _targetMotor.SetTarget(_PIDTarget); - _targetMotor.SetCurrent(RawPosition); - /* - _targetMotor = new BSPIDVMotor("BSPrim.PIDTarget"); - _targetMotor.PhysicsScene = PhysicsScene; // DEBUG DEBUG so motor will output detail log messages. - - _targetMotor.SetTarget(_PIDTarget); - _targetMotor.SetCurrent(RawPosition); - _targetMotor.TimeScale = _PIDTau; - _targetMotor.Efficiency = 1f; - */ - - RegisterPreStepAction("BSPrim.PIDTarget", LocalID, delegate(float timeStep) - { - if (!IsPhysicallyActive) - { - UnRegisterPreStepAction("BSPrim.PIDTarget", LocalID); - return; - } - - OMV.Vector3 origPosition = RawPosition; // DEBUG DEBUG (for printout below) - - // 'movePosition' is where we'd like the prim to be at this moment. - OMV.Vector3 movePosition = RawPosition + _targetMotor.Step(timeStep); - - // If we are very close to our target, turn off the movement motor. - if (_targetMotor.ErrorIsZero()) - { - DetailLog("{0},BSPrim.PIDTarget,zeroMovement,movePos={1},pos={2},mass={3}", - LocalID, movePosition, RawPosition, Mass); - ForcePosition = _targetMotor.TargetValue; - _targetMotor.Enabled = false; - } - else - { - _position = movePosition; - PositionSanityCheck(true /* intaintTime */); - ForcePosition = _position; - } - DetailLog("{0},BSPrim.PIDTarget,move,fromPos={1},movePos={2}", LocalID, origPosition, movePosition); - }); - } - else + base.MoveToTargetActive = value; + CreateRemoveActor(MoveToTargetActive, MoveToTargetActorName, false /* inTaintTime */, delegate() { - // Stop any targetting - UnRegisterPreStepAction("BSPrim.PIDTarget", LocalID); - } + return new BSActorMoveToTarget(PhysicsScene, this, MoveToTargetActorName); + }); } } @@ -1175,88 +1048,14 @@ public class BSPrim : BSPhysObject // Hover Height will override MoveTo target's Z public override bool PIDHoverActive { set { - if (value) - { - // Turning the target on - _hoverMotor = new BSFMotor("BSPrim.Hover", - _PIDHoverTau, // timeScale - BSMotor.Infinite, // decay time scale - BSMotor.Infinite, // friction timescale - 1f // efficiency - ); - _hoverMotor.SetTarget(ComputeCurrentPIDHoverHeight()); - _hoverMotor.SetCurrent(RawPosition.Z); - _hoverMotor.PhysicsScene = PhysicsScene; // DEBUG DEBUG so motor will output detail log messages. - - RegisterPreStepAction("BSPrim.Hover", LocalID, delegate(float timeStep) - { - // Don't do hovering while the object is selected. - if (!IsPhysicallyActive) - return; - - _hoverMotor.SetCurrent(RawPosition.Z); - _hoverMotor.SetTarget(ComputeCurrentPIDHoverHeight()); - float targetHeight = _hoverMotor.Step(timeStep); - - // 'targetHeight' is where we'd like the Z of the prim to be at this moment. - // Compute the amount of force to push us there. - float moveForce = (targetHeight - RawPosition.Z) * Mass; - // Undo anything the object thinks it's doing at the moment - moveForce = -RawVelocity.Z * Mass; - - PhysicsScene.PE.ApplyCentralImpulse(PhysBody, new OMV.Vector3(0f, 0f, moveForce)); - DetailLog("{0},BSPrim.Hover,move,targHt={1},moveForce={2},mass={3}", LocalID, targetHeight, moveForce, Mass); - }); - } - else + base.HoverActive = value; + CreateRemoveActor(HoverActive /* creatActor */, HoverActorName, false /* inTaintTime */, delegate() { - UnRegisterPreStepAction("BSPrim.Hover", LocalID); - } - } - } - public override float PIDHoverHeight { - set { _PIDHoverHeight = value; } - } - public override PIDHoverType PIDHoverType { - set { _PIDHoverType = value; } - } - public override float PIDHoverTau { - set { _PIDHoverTau = value; } - } - // Based on current position, determine what we should be hovering at now. - // Must recompute often. What if we walked offa cliff> - private float ComputeCurrentPIDHoverHeight() - { - float ret = _PIDHoverHeight; - float groundHeight = PhysicsScene.TerrainManager.GetTerrainHeightAtXYZ(RawPosition); - - switch (_PIDHoverType) - { - case PIDHoverType.Ground: - ret = groundHeight + _PIDHoverHeight; - break; - case PIDHoverType.GroundAndWater: - float waterHeight = PhysicsScene.TerrainManager.GetWaterLevelAtXYZ(RawPosition); - if (groundHeight > waterHeight) - { - ret = groundHeight + _PIDHoverHeight; - } - else - { - ret = waterHeight + _PIDHoverHeight; - } - break; + return new BSActorHover(PhysicsScene, this, HoverActorName); + }); } - return ret; } - - // For RotLookAt - public override OMV.Quaternion APIDTarget { set { return; } } - public override bool APIDActive { set { return; } } - public override float APIDStrength { set { return; } } - public override float APIDDamping { set { return; } } - public override void AddForce(OMV.Vector3 force, bool pushforce) { // Per documentation, max force is limited. OMV.Vector3 addForce = Util.ClampV(force, BSParam.MaxAddForceMagnitude); @@ -1324,10 +1123,8 @@ public class BSPrim : BSPhysObject } } - public override void AddAngularForce(OMV.Vector3 force, bool pushforce) { - AddAngularForce(force, pushforce, false); - } - public void AddAngularForce(OMV.Vector3 force, bool pushforce, bool inTaintTime) + // BSPhysObject.AddAngularForce() + public override void AddAngularForce(OMV.Vector3 force, bool pushforce, bool inTaintTime) { if (force.IsFinite()) { @@ -1694,8 +1491,8 @@ public class BSPrim : BSPhysObject _orientation = entprop.Rotation; // DEBUG DEBUG DEBUG -- smooth velocity changes a bit. The simulator seems to be // very sensitive to velocity changes. - if (entprop.Velocity == OMV.Vector3.Zero || !entprop.Velocity.ApproxEquals(_velocity, BSParam.UpdateVelocityChangeThreshold)) - _velocity = entprop.Velocity; + if (entprop.Velocity == OMV.Vector3.Zero || !entprop.Velocity.ApproxEquals(RawVelocity, BSParam.UpdateVelocityChangeThreshold)) + RawVelocity = entprop.Velocity; _acceleration = entprop.Acceleration; _rotationalVelocity = entprop.RotationalVelocity; @@ -1705,7 +1502,7 @@ public class BSPrim : BSPhysObject if (PositionSanityCheck(true /* inTaintTime */ )) { entprop.Position = _position; - entprop.Velocity = _velocity; + entprop.Velocity = RawVelocity; entprop.RotationalVelocity = _rotationalVelocity; entprop.Acceleration = _acceleration; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimTODO.txt b/OpenSim/Region/Physics/BulletSPlugin/BulletSimTODO.txt index 8a15abe..a0131c7 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimTODO.txt +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimTODO.txt @@ -6,7 +6,6 @@ Enable vehicle border crossings (at least as poorly as ODE) Terrain skirts Avatar created in previous region and not new region when crossing border Vehicle recreated in new sim at small Z value (offset from root value?) (DONE) -Lock axis Deleting a linkset while standing on the root will leave the physical shape of the root behind. Not sure if it is because standing on it. Done with large prim linksets. Linkset child rotations. @@ -344,3 +343,5 @@ Angular motion around Z moves the vehicle in world Z and not vehicle Z in ODE. Verify that angular motion specified around Z moves in the vehicle coordinates. DONE 20130120: BulletSim properly applies force in vehicle relative coordinates. Nebadon vehicles turning funny in arena (DONE) +Lock axis (DONE 20130401) + -- cgit v1.1 From a7a1b8b7e9269b446e3396a35153b00942c1e35b Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Sun, 7 Apr 2013 14:05:35 -0700 Subject: BulletSim: clean up actor code so routines use the same coding pattern. Fix a few enabling problems. --- .../Physics/BulletSPlugin/BSActorAvatarMove.cs | 22 ++--- .../Region/Physics/BulletSPlugin/BSActorHover.cs | 6 +- .../Physics/BulletSPlugin/BSActorLockAxis.cs | 105 ++++++++++----------- .../Physics/BulletSPlugin/BSActorMoveToTarget.cs | 12 +-- .../Physics/BulletSPlugin/BSActorSetForce.cs | 2 +- .../Physics/BulletSPlugin/BSActorSetTorque.cs | 4 +- OpenSim/Region/Physics/BulletSPlugin/BSActors.cs | 49 +++++++--- .../Region/Physics/BulletSPlugin/BSCharacter.cs | 3 + .../Region/Physics/BulletSPlugin/BSPhysObject.cs | 35 +++---- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 22 ++--- 10 files changed, 137 insertions(+), 123 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs b/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs index 634a898..8416740 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs @@ -67,14 +67,6 @@ public class BSActorAvatarMove : BSActor { m_physicsScene.DetailLog("{0},BSActorAvatarMove,refresh", m_controllingPrim.LocalID); - // If not active any more, get rid of me (shouldn't ever happen, but just to be safe) - if (m_controllingPrim.RawForce == OMV.Vector3.Zero) - { - m_physicsScene.DetailLog("{0},BSActorAvatarMove,refresh,notAvatarMove,removing={1}", m_controllingPrim.LocalID, ActorName); - m_controllingPrim.PhysicalActors.RemoveAndRelease(ActorName); - return; - } - // If the object is physically active, add the hoverer prestep action if (isActive) { @@ -95,14 +87,19 @@ public class BSActorAvatarMove : BSActor // Nothing to do for the hoverer since it is all software at pre-step action time. } + // Usually called when target velocity changes to set the current velocity and the target + // into the movement motor. public void SetVelocityAndTarget(OMV.Vector3 vel, OMV.Vector3 targ, bool inTaintTime) { m_physicsScene.TaintedObject(inTaintTime, "BSActorAvatarMove.setVelocityAndTarget", delegate() { - m_velocityMotor.Reset(); - m_velocityMotor.SetTarget(targ); - m_velocityMotor.SetCurrent(vel); - m_velocityMotor.Enabled = true; + if (m_velocityMotor != null) + { + m_velocityMotor.Reset(); + m_velocityMotor.SetTarget(targ); + m_velocityMotor.SetCurrent(vel); + m_velocityMotor.Enabled = true; + } }); } @@ -119,6 +116,7 @@ public class BSActorAvatarMove : BSActor 1f // efficiency ); // _velocityMotor.PhysicsScene = PhysicsScene; // DEBUG DEBUG so motor will output detail log messages. + SetVelocityAndTarget(m_controllingPrim.RawVelocity, m_controllingPrim.TargetVelocity, true /* inTaintTime */); m_physicsScene.BeforeStep += Mover; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSActorHover.cs b/OpenSim/Region/Physics/BulletSPlugin/BSActorHover.cs index 8dd3700..e8310df 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSActorHover.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSActorHover.cs @@ -67,12 +67,10 @@ public class BSActorHover : BSActor { m_physicsScene.DetailLog("{0},BSActorHover,refresh", m_controllingPrim.LocalID); - // If not active any more, get rid of me (shouldn't ever happen, but just to be safe) + // If not active any more, turn me off if (!m_controllingPrim.HoverActive) { - m_physicsScene.DetailLog("{0},BSActorHover,refresh,notHovering,removing={1}", m_controllingPrim.LocalID, ActorName); - m_controllingPrim.PhysicalActors.RemoveAndRelease(ActorName); - return; + SetEnabled(false); } // If the object is physically active, add the hoverer prestep action diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSActorLockAxis.cs b/OpenSim/Region/Physics/BulletSPlugin/BSActorLockAxis.cs index c40a499..09ee32b 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSActorLockAxis.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSActorLockAxis.cs @@ -36,7 +36,6 @@ namespace OpenSim.Region.Physics.BulletSPlugin { public class BSActorLockAxis : BSActor { - bool TryExperimentalLockAxisCode = true; BSConstraint LockAxisConstraint = null; public BSActorLockAxis(BSScene physicsScene, BSPhysObject pObj, string actorName) @@ -69,18 +68,13 @@ public class BSActorLockAxis : BSActor // If all the axis are free, we don't need to exist if (m_controllingPrim.LockedAxis == m_controllingPrim.LockedAxisFree) { - m_physicsScene.DetailLog("{0},BSActorLockAxis,refresh,allAxisFree,removing={1}", m_controllingPrim.LocalID, ActorName); - m_controllingPrim.PhysicalActors.RemoveAndRelease(ActorName); - return; + Enabled = false; } + // If the object is physically active, add the axis locking constraint - if (Enabled - && m_controllingPrim.IsPhysicallyActive - && TryExperimentalLockAxisCode - && m_controllingPrim.LockedAxis != m_controllingPrim.LockedAxisFree) + if (isActive) { - if (LockAxisConstraint == null) - AddAxisLockConstraint(); + AddAxisLockConstraint(); } else { @@ -108,58 +102,61 @@ public class BSActorLockAxis : BSActor private void AddAxisLockConstraint() { - // Lock that axis by creating a 6DOF constraint that has one end in the world and - // the other in the object. - // http://www.bulletphysics.org/Bullet/phpBB3/viewtopic.php?p=20817 - // http://www.bulletphysics.org/Bullet/phpBB3/viewtopic.php?p=26380 + if (LockAxisConstraint == null) + { + // Lock that axis by creating a 6DOF constraint that has one end in the world and + // the other in the object. + // http://www.bulletphysics.org/Bullet/phpBB3/viewtopic.php?p=20817 + // http://www.bulletphysics.org/Bullet/phpBB3/viewtopic.php?p=26380 - // Remove any existing axis constraint (just to be sure) - RemoveAxisLockConstraint(); + // Remove any existing axis constraint (just to be sure) + RemoveAxisLockConstraint(); - BSConstraint6Dof axisConstrainer = new BSConstraint6Dof(m_physicsScene.World, m_controllingPrim.PhysBody, - OMV.Vector3.Zero, OMV.Quaternion.Identity, - false /* useLinearReferenceFrameB */, true /* disableCollisionsBetweenLinkedBodies */); - LockAxisConstraint = axisConstrainer; - m_physicsScene.Constraints.AddConstraint(LockAxisConstraint); + BSConstraint6Dof axisConstrainer = new BSConstraint6Dof(m_physicsScene.World, m_controllingPrim.PhysBody, + OMV.Vector3.Zero, OMV.Quaternion.Identity, + false /* useLinearReferenceFrameB */, true /* disableCollisionsBetweenLinkedBodies */); + LockAxisConstraint = axisConstrainer; + m_physicsScene.Constraints.AddConstraint(LockAxisConstraint); - // The constraint is tied to the world and oriented to the prim. + // The constraint is tied to the world and oriented to the prim. - // Free to move linearly in the region - OMV.Vector3 linearLow = OMV.Vector3.Zero; - OMV.Vector3 linearHigh = m_physicsScene.TerrainManager.DefaultRegionSize; - axisConstrainer.SetLinearLimits(linearLow, linearHigh); + // Free to move linearly in the region + OMV.Vector3 linearLow = OMV.Vector3.Zero; + OMV.Vector3 linearHigh = m_physicsScene.TerrainManager.DefaultRegionSize; + axisConstrainer.SetLinearLimits(linearLow, linearHigh); - // Angular with some axis locked - float fPI = (float)Math.PI; - OMV.Vector3 angularLow = new OMV.Vector3(-fPI, -fPI, -fPI); - OMV.Vector3 angularHigh = new OMV.Vector3(fPI, fPI, fPI); - if (m_controllingPrim.LockedAxis.X != 1f) - { - angularLow.X = 0f; - angularHigh.X = 0f; - } - if (m_controllingPrim.LockedAxis.Y != 1f) - { - angularLow.Y = 0f; - angularHigh.Y = 0f; - } - if (m_controllingPrim.LockedAxis.Z != 1f) - { - angularLow.Z = 0f; - angularHigh.Z = 0f; - } - if (!axisConstrainer.SetAngularLimits(angularLow, angularHigh)) - { - m_physicsScene.DetailLog("{0},BSActorLockAxis.AddAxisLockConstraint,failedSetAngularLimits", m_controllingPrim.LocalID); - } + // Angular with some axis locked + float fPI = (float)Math.PI; + OMV.Vector3 angularLow = new OMV.Vector3(-fPI, -fPI, -fPI); + OMV.Vector3 angularHigh = new OMV.Vector3(fPI, fPI, fPI); + if (m_controllingPrim.LockedAxis.X != 1f) + { + angularLow.X = 0f; + angularHigh.X = 0f; + } + if (m_controllingPrim.LockedAxis.Y != 1f) + { + angularLow.Y = 0f; + angularHigh.Y = 0f; + } + if (m_controllingPrim.LockedAxis.Z != 1f) + { + angularLow.Z = 0f; + angularHigh.Z = 0f; + } + if (!axisConstrainer.SetAngularLimits(angularLow, angularHigh)) + { + m_physicsScene.DetailLog("{0},BSActorLockAxis.AddAxisLockConstraint,failedSetAngularLimits", m_controllingPrim.LocalID); + } - m_physicsScene.DetailLog("{0},BSActorLockAxis.AddAxisLockConstraint,create,linLow={1},linHi={2},angLow={3},angHi={4}", - m_controllingPrim.LocalID, linearLow, linearHigh, angularLow, angularHigh); + m_physicsScene.DetailLog("{0},BSActorLockAxis.AddAxisLockConstraint,create,linLow={1},linHi={2},angLow={3},angHi={4}", + m_controllingPrim.LocalID, linearLow, linearHigh, angularLow, angularHigh); - // Constants from one of the posts mentioned above and used in Bullet's ConstraintDemo. - axisConstrainer.TranslationalLimitMotor(true /* enable */, 5.0f, 0.1f); + // Constants from one of the posts mentioned above and used in Bullet's ConstraintDemo. + axisConstrainer.TranslationalLimitMotor(true /* enable */, 5.0f, 0.1f); - axisConstrainer.RecomputeConstraintVariables(m_controllingPrim.RawMass); + axisConstrainer.RecomputeConstraintVariables(m_controllingPrim.RawMass); + } } private void RemoveAxisLockConstraint() diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSActorMoveToTarget.cs b/OpenSim/Region/Physics/BulletSPlugin/BSActorMoveToTarget.cs index 3517ef2..16c2b14 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSActorMoveToTarget.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSActorMoveToTarget.cs @@ -67,15 +67,12 @@ public class BSActorMoveToTarget : BSActor { m_physicsScene.DetailLog("{0},BSActorMoveToTarget,refresh", m_controllingPrim.LocalID); - // If not active any more, get rid of me (shouldn't ever happen, but just to be safe) - if (!m_controllingPrim.HoverActive) + // If not active any more... + if (!m_controllingPrim.MoveToTargetActive) { - m_physicsScene.DetailLog("{0},BSActorMoveToTarget,refresh,notMoveToTarget,removing={1}", m_controllingPrim.LocalID, ActorName); - m_controllingPrim.PhysicalActors.RemoveAndRelease(ActorName); - return; + Enabled = false; } - // If the object is physically active, add the hoverer prestep action if (isActive) { ActivateMoveToTarget(); @@ -92,7 +89,7 @@ public class BSActorMoveToTarget : BSActor // BSActor.RemoveBodyDependencies() public override void RemoveBodyDependencies() { - // Nothing to do for the hoverer since it is all software at pre-step action time. + // Nothing to do for the moveToTarget since it is all software at pre-step action time. } // If a hover motor has not been created, create one and start the hovering. @@ -144,7 +141,6 @@ public class BSActorMoveToTarget : BSActor m_physicsScene.DetailLog("{0},BSPrim.PIDTarget,zeroMovement,movePos={1},pos={2},mass={3}", m_controllingPrim.LocalID, movePosition, m_controllingPrim.RawPosition, m_controllingPrim.Mass); m_controllingPrim.ForcePosition = m_targetMotor.TargetValue; - m_targetMotor.Enabled = false; } else { diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSActorSetForce.cs b/OpenSim/Region/Physics/BulletSPlugin/BSActorSetForce.cs index d942490..3ad138d 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSActorSetForce.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSActorSetForce.cs @@ -71,7 +71,7 @@ public class BSActorSetForce : BSActor if (m_controllingPrim.RawForce == OMV.Vector3.Zero) { m_physicsScene.DetailLog("{0},BSActorSetForce,refresh,notSetForce,removing={1}", m_controllingPrim.LocalID, ActorName); - m_controllingPrim.PhysicalActors.RemoveAndRelease(ActorName); + Enabled = false; return; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSActorSetTorque.cs b/OpenSim/Region/Physics/BulletSPlugin/BSActorSetTorque.cs index e0f719f..159a3a8 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSActorSetTorque.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSActorSetTorque.cs @@ -70,8 +70,8 @@ public class BSActorSetTorque : BSActor // If not active any more, get rid of me (shouldn't ever happen, but just to be safe) if (m_controllingPrim.RawTorque == OMV.Vector3.Zero) { - m_physicsScene.DetailLog("{0},BSActorSetTorque,refresh,notSetTorque,removing={1}", m_controllingPrim.LocalID, ActorName); - m_controllingPrim.PhysicalActors.RemoveAndRelease(ActorName); + m_physicsScene.DetailLog("{0},BSActorSetTorque,refresh,notSetTorque,disabling={1}", m_controllingPrim.LocalID, ActorName); + Enabled = false; return; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSActors.cs b/OpenSim/Region/Physics/BulletSPlugin/BSActors.cs index fb4d452..12a8817 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSActors.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSActors.cs @@ -42,24 +42,36 @@ public class BSActorCollection } public void Add(string name, BSActor actor) { - m_actors[name] = actor; + lock (m_actors) + { + if (!m_actors.ContainsKey(name)) + { + m_actors[name] = actor; + } + } } public bool RemoveAndRelease(string name) { bool ret = false; - if (m_actors.ContainsKey(name)) + lock (m_actors) { - BSActor beingRemoved = m_actors[name]; - beingRemoved.Dispose(); - m_actors.Remove(name); - ret = true; + if (m_actors.ContainsKey(name)) + { + BSActor beingRemoved = m_actors[name]; + m_actors.Remove(name); + beingRemoved.Dispose(); + ret = true; + } } return ret; } public void Clear() { - Release(); - m_actors.Clear(); + lock (m_actors) + { + Release(); + m_actors.Clear(); + } } public void Dispose() { @@ -69,15 +81,22 @@ public class BSActorCollection { return m_actors.ContainsKey(name); } + public bool TryGetActor(string actorName, out BSActor theActor) + { + return m_actors.TryGetValue(actorName, out theActor); + } public void ForEachActor(Action act) { - foreach (KeyValuePair kvp in m_actors) - act(kvp.Value); + lock (m_actors) + { + foreach (KeyValuePair kvp in m_actors) + act(kvp.Value); + } } public void Enable(bool enabl) { - ForEachActor(a => a.Enable(enabl)); + ForEachActor(a => a.SetEnabled(enabl)); } public void Release() { @@ -106,7 +125,7 @@ public abstract class BSActor { protected BSScene m_physicsScene { get; private set; } protected BSPhysObject m_controllingPrim { get; private set; } - protected bool Enabled { get; set; } + public virtual bool Enabled { get; set; } public string ActorName { get; private set; } public BSActor(BSScene physicsScene, BSPhysObject pObj, string actorName) @@ -122,8 +141,10 @@ public abstract class BSActor { get { return Enabled; } } - // Turn the actor on an off. - public virtual void Enable(bool setEnabled) + + // Turn the actor on an off. Only used by ActorCollection to set all enabled/disabled. + // Anyone else should assign true/false to 'Enabled'. + public void SetEnabled(bool setEnabled) { Enabled = setEnabled; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index 09c9b16..a0d58d3 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -160,6 +160,9 @@ public sealed class BSCharacter : BSPhysObject // Make so capsule does not fall over PhysicsScene.PE.SetAngularFactorV(PhysBody, OMV.Vector3.Zero); + // The avatar mover sets some parameters. + PhysicalActors.Refresh(); + PhysicsScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.CF_CHARACTER_OBJECT); PhysicsScene.PE.AddObjectToWorld(PhysicsScene.World, PhysBody); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index 644bc7e..64bf395 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -282,30 +282,31 @@ public abstract class BSPhysObject : PhysicsActor // 'actors' act on the physical object to change or constrain its motion. These can range from // hovering to complex vehicle motion. + // May be called at non-taint time as this just adds the actor to the action list and the real + // work is done during the simulation step. + // Note that, if the actor is already in the list and we are disabling same, the actor is just left + // in the list disabled. public delegate BSActor CreateActor(); - public void CreateRemoveActor(bool createRemove, string actorName, bool inTaintTime, CreateActor creator) + public void EnableActor(bool enableActor, string actorName, CreateActor creator) { - if (createRemove) + lock (PhysicalActors) { - PhysicsScene.TaintedObject(inTaintTime, "BSPrim.CreateRemoveActor:" + actorName, delegate() + BSActor theActor; + if (PhysicalActors.TryGetActor(actorName, out theActor)) { - if (!PhysicalActors.HasActor(actorName)) - { - DetailLog("{0},BSPrim.CreateRemoveActor,taint,registerActor,a={1}", LocalID, actorName); - PhysicalActors.Add(actorName, creator()); - } - }); - } - else - { - PhysicsScene.TaintedObject(inTaintTime, "BSPrim.CreateRemoveActor:" + actorName, delegate() + // The actor already exists so just turn it on or off + theActor.Enabled = enableActor; + } + else { - if (PhysicalActors.HasActor(actorName)) + // The actor does not exist. If it should, create it. + if (enableActor) { - DetailLog("{0},BSPrim.CreateRemoveActor,taint,unregisterActor,a={1}", LocalID, actorName); - PhysicalActors.RemoveAndRelease(actorName); + theActor = creator(); + PhysicalActors.Add(actorName, theActor); + theActor.Enabled = true; } - }); + } } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 71fea59..16c7a90 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -95,6 +95,7 @@ public class BSPrim : BSPhysObject _isPhysical = pisPhysical; _isVolumeDetect = false; + // We keep a handle to the vehicle actor so we can set vehicle parameters later. VehicleActor = new BSDynamics(PhysicsScene, this, VehicleActorName); PhysicalActors.Add(VehicleActorName, VehicleActor); @@ -264,7 +265,7 @@ public class BSPrim : BSPhysObject if (axis.Z != 1) locking.Z = 0f; LockedAxis = locking; - CreateRemoveActor(LockedAxis != LockedAxisFree /* creatActor */, LockedAxisActorName, false /* inTaintTime */, delegate() + EnableActor(LockedAxis != LockedAxisFree, LockedAxisActorName, delegate() { return new BSActorLockAxis(PhysicsScene, this, LockedAxisActorName); }); @@ -501,7 +502,7 @@ public class BSPrim : BSPhysObject get { return RawForce; } set { RawForce = value; - CreateRemoveActor(RawForce == OMV.Vector3.Zero, SetForceActorName, false /* inTaintTime */, delegate() + EnableActor(RawForce != OMV.Vector3.Zero, SetForceActorName, delegate() { return new BSActorSetForce(PhysicsScene, this, SetForceActorName); }); @@ -510,14 +511,13 @@ public class BSPrim : BSPhysObject public override int VehicleType { get { - return (int)VehicleActor.Type; // if we are a vehicle, return that type + return (int)VehicleActor.Type; } set { Vehicle type = (Vehicle)value; PhysicsScene.TaintedObject("setVehicleType", delegate() { - // Done at taint time so we're sure the physics engine is not using the variables // Vehicle code changes the parameters for this vehicle type. VehicleActor.ProcessTypeChange(type); ActivateIfPhysical(false); @@ -669,11 +669,11 @@ public class BSPrim : BSPhysObject get { return RawTorque; } set { RawTorque = value; - CreateRemoveActor(RawTorque == OMV.Vector3.Zero, SetTorqueActorName, false /* inTaintTime */, delegate() + EnableActor(RawTorque != OMV.Vector3.Zero, SetTorqueActorName, delegate() { return new BSActorSetTorque(PhysicsScene, this, SetTorqueActorName); }); - // DetailLog("{0},BSPrim.SetTorque,call,torque={1}", LocalID, _torque); + DetailLog("{0},BSPrim.SetTorque,call,torque={1}", LocalID, RawTorque); } } public override OMV.Vector3 Acceleration { @@ -786,7 +786,6 @@ public class BSPrim : BSPhysObject MakeDynamic(IsStatic); // Update vehicle specific parameters (after MakeDynamic() so can change physical parameters) - VehicleActor.Refresh(); PhysicalActors.Refresh(); // Arrange for collision events if the simulator wants them @@ -1037,7 +1036,7 @@ public class BSPrim : BSPhysObject public override bool PIDActive { set { base.MoveToTargetActive = value; - CreateRemoveActor(MoveToTargetActive, MoveToTargetActorName, false /* inTaintTime */, delegate() + EnableActor(MoveToTargetActive, MoveToTargetActorName, delegate() { return new BSActorMoveToTarget(PhysicsScene, this, MoveToTargetActorName); }); @@ -1049,7 +1048,7 @@ public class BSPrim : BSPhysObject public override bool PIDHoverActive { set { base.HoverActive = value; - CreateRemoveActor(HoverActive /* creatActor */, HoverActorName, false /* inTaintTime */, delegate() + EnableActor(HoverActive, HoverActorName, delegate() { return new BSActorHover(PhysicsScene, this, HoverActorName); }); @@ -1458,7 +1457,7 @@ public class BSPrim : BSPhysObject { // Create the correct physical representation for this type of object. // Updates base.PhysBody and base.PhysShape with the new information. - // Ignore 'forceRebuild'. This routine makes the right choices and changes of necessary. + // Ignore 'forceRebuild'. 'GetBodyAndShape' makes the right choices and changes of necessary. PhysicsScene.Shapes.GetBodyAndShape(false /*forceRebuild */, PhysicsScene.World, this, null, delegate(BulletBody dBody) { // Called if the current prim body is about to be destroyed. @@ -1472,9 +1471,9 @@ public class BSPrim : BSPhysObject return; } + // Called at taint-time protected virtual void RemoveBodyDependencies() { - VehicleActor.RemoveBodyDependencies(); PhysicalActors.RemoveBodyDependencies(); } @@ -1482,6 +1481,7 @@ public class BSPrim : BSPhysObject // the world that things have changed. public override void UpdateProperties(EntityProperties entprop) { + // Let anyone (like the actors) modify the updated properties before they are pushed into the object and the simulator. TriggerPreUpdatePropertyAction(ref entprop); // DetailLog("{0},BSPrim.UpdateProperties,entry,entprop={1}", LocalID, entprop); // DEBUG DEBUG -- cgit v1.1 From 99f39836a1879a807bb7d6bf5bf793c3a99584c4 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Mon, 8 Apr 2013 06:27:01 -0700 Subject: BulletSim: moving comments around. No functional change. --- OpenSim/Region/Physics/BulletSPlugin/BSActorSetTorque.cs | 2 +- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 10 +--------- OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs | 9 +++++++++ 3 files changed, 11 insertions(+), 10 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSActorSetTorque.cs b/OpenSim/Region/Physics/BulletSPlugin/BSActorSetTorque.cs index 159a3a8..7a791ec 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSActorSetTorque.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSActorSetTorque.cs @@ -65,7 +65,7 @@ public class BSActorSetTorque : BSActor // BSActor.Refresh() public override void Refresh() { - m_physicsScene.DetailLog("{0},BSActorSetTorque,refresh", m_controllingPrim.LocalID); + m_physicsScene.DetailLog("{0},BSActorSetTorque,refresh,torque={1}", m_controllingPrim.LocalID, m_controllingPrim.RawTorque); // If not active any more, get rid of me (shouldn't ever happen, but just to be safe) if (m_controllingPrim.RawTorque == OMV.Vector3.Zero) diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 16c7a90..3423d2e 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -1514,16 +1514,8 @@ public class BSPrim : BSPhysObject LastEntityProperties = CurrentEntityProperties; CurrentEntityProperties = entprop; + // Note that BSPrim can be overloaded by BSPrimLinkable which controls updates from root and children prims. base.RequestPhysicsterseUpdate(); - /* - else - { - // For debugging, report the movement of children - DetailLog("{0},BSPrim.UpdateProperties,child,pos={1},orient={2},vel={3},accel={4},rotVel={5}", - LocalID, entprop.Position, entprop.Rotation, entprop.Velocity, - entprop.Acceleration, entprop.RotationalVelocity); - } - */ } } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs index d65d407..28242d4 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs @@ -163,6 +163,15 @@ public class BSPrimLinkable : BSPrimDisplaced // TODO: this will have to change when linksets are articulated. base.UpdateProperties(entprop); } + /* + else + { + // For debugging, report the movement of children + DetailLog("{0},BSPrim.UpdateProperties,child,pos={1},orient={2},vel={3},accel={4},rotVel={5}", + LocalID, entprop.Position, entprop.Rotation, entprop.Velocity, + entprop.Acceleration, entprop.RotationalVelocity); + } + */ // The linkset might like to know about changing locations Linkset.UpdateProperties(UpdatedProperties.EntPropUpdates, this); } -- cgit v1.1 From 17fd075f39df71d628db08b7c280150f231f8a26 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 9 Apr 2013 11:55:29 -0700 Subject: BulletSim: fix problem where large sets of mega-regions weren't registering all the terrain with the base region. --- OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs index cd15850..5240ad8 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs @@ -213,13 +213,13 @@ public sealed class BSTerrainManager : IDisposable }); } - // Another region is calling this region passing a terrain. + // Another region is calling this region and passing a terrain. // A region that is not the mega-region root will pass its terrain to the root region so the root region // physics engine will have all the terrains. private void AddMegaRegionChildTerrain(uint id, float[] heightMap, Vector3 minCoords, Vector3 maxCoords) { // Since we are called by another region's thread, the action must be rescheduled onto our processing thread. - PhysicsScene.PostTaintObject("TerrainManager.AddMegaRegionChild" + m_worldOffset.ToString(), 0, delegate() + PhysicsScene.PostTaintObject("TerrainManager.AddMegaRegionChild" + minCoords.ToString(), id, delegate() { UpdateTerrain(id, heightMap, minCoords, maxCoords); }); @@ -306,7 +306,7 @@ public sealed class BSTerrainManager : IDisposable newTerrainID = ++m_terrainCount; DetailLog("{0},BSTerrainManager.UpdateTerrain:NewTerrain,taint,newID={1},minCoord={2},maxCoord={3}", - BSScene.DetailLogZero, newTerrainID, minCoords, minCoords); + BSScene.DetailLogZero, newTerrainID, minCoords, maxCoords); BSTerrainPhys newTerrainPhys = BuildPhysicalTerrain(terrainRegionBase, id, heightMap, minCoords, maxCoords); m_terrains.Add(terrainRegionBase, newTerrainPhys); -- cgit v1.1 From 59135c9a31875dc514b3ea2fe14021571807701d Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 9 Apr 2013 16:32:54 -0700 Subject: BulletSim: add Bullet HACD library invocation. Turned off by default as not totally debugged. Updated DLLs and SOs with more debugged HACD library code. --- OpenSim/Region/Physics/BulletSPlugin/BSParam.cs | 53 ++++- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 1 + .../Physics/BulletSPlugin/BSShapeCollection.cs | 223 ++++++++++++--------- 3 files changed, 183 insertions(+), 94 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs index 385ed9e..06df85e 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs @@ -86,6 +86,7 @@ public static class BSParam public static bool ShouldForceSimplePrimMeshing { get; private set; } // if a cube or sphere, let Bullet do internal shapes public static bool ShouldUseHullsForPhysicalObjects { get; private set; } // 'true' if should create hulls for physical objects public static bool ShouldRemoveZeroWidthTriangles { get; private set; } + public static bool ShouldUseBulletHACD { get; set; } public static float TerrainImplementation { get; private set; } public static int TerrainMeshMagnification { get; private set; } @@ -149,6 +150,15 @@ public static class BSParam public static float CSHullVolumeConservationThresholdPercent { get; private set; } public static int CSHullMaxVertices { get; private set; } public static float CSHullMaxSkinWidth { get; private set; } + public static float BHullMaxVerticesPerHull { get; private set; } // 100 + public static float BHullMinClusters { get; private set; } // 2 + public static float BHullCompacityWeight { get; private set; } // 0.1 + public static float BHullVolumeWeight { get; private set; } // 0.0 + public static float BHullConcavity { get; private set; } // 100 + public static bool BHullAddExtraDistPoints { get; private set; } // false + public static bool BHullAddNeighboursDistPoints { get; private set; } // false + public static bool BHullAddFacesPoints { get; private set; } // false + public static bool BHullShouldAdjustCollisionMargin { get; private set; } // false // Linkset implementation parameters public static float LinksetImplementation { get; private set; } @@ -325,6 +335,10 @@ public static class BSParam true, (s) => { return ShouldRemoveZeroWidthTriangles; }, (s,v) => { ShouldRemoveZeroWidthTriangles = v; } ), + new ParameterDefn("ShouldUseBulletHACD", "If true, use the Bullet version of HACD", + false, + (s) => { return ShouldUseBulletHACD; }, + (s,v) => { ShouldUseBulletHACD = v; } ), new ParameterDefn("CrossingFailuresBeforeOutOfBounds", "How forgiving we are about getting into adjactent regions", 5, @@ -663,10 +677,47 @@ public static class BSParam (s) => { return CSHullMaxVertices; }, (s,v) => { CSHullMaxVertices = v; } ), new ParameterDefn("CSHullMaxSkinWidth", "CS impl: skin width to apply to output hulls.", - 0, + 0f, (s) => { return CSHullMaxSkinWidth; }, (s,v) => { CSHullMaxSkinWidth = v; } ), + new ParameterDefn("BHullMaxVerticesPerHull", "Bullet impl: max number of vertices per created hull", + 100f, + (s) => { return BHullMaxVerticesPerHull; }, + (s,v) => { BHullMaxVerticesPerHull = v; } ), + new ParameterDefn("BHullMinClusters", "Bullet impl: minimum number of hulls to create per mesh", + 2f, + (s) => { return BHullMinClusters; }, + (s,v) => { BHullMinClusters = v; } ), + new ParameterDefn("BHullCompacityWeight", "Bullet impl: weight factor for how compact to make hulls", + 2f, + (s) => { return BHullCompacityWeight; }, + (s,v) => { BHullCompacityWeight = v; } ), + new ParameterDefn("BHullVolumeWeight", "Bullet impl: weight factor for volume in created hull", + 0.1f, + (s) => { return BHullVolumeWeight; }, + (s,v) => { BHullVolumeWeight = v; } ), + new ParameterDefn("BHullConcavity", "Bullet impl: weight factor for how convex a created hull can be", + 100f, + (s) => { return BHullConcavity; }, + (s,v) => { BHullConcavity = v; } ), + new ParameterDefn("BHullAddExtraDistPoints", "Bullet impl: whether to add extra vertices for long distance vectors", + false, + (s) => { return BHullAddExtraDistPoints; }, + (s,v) => { BHullAddExtraDistPoints = v; } ), + new ParameterDefn("BHullAddNeighboursDistPoints", "Bullet impl: whether to add extra vertices between neighbor hulls", + false, + (s) => { return BHullAddNeighboursDistPoints; }, + (s,v) => { BHullAddNeighboursDistPoints = v; } ), + new ParameterDefn("BHullAddFacesPoints", "Bullet impl: whether to add extra vertices to break up hull faces", + false, + (s) => { return BHullAddFacesPoints; }, + (s,v) => { BHullAddFacesPoints = v; } ), + new ParameterDefn("BHullShouldAdjustCollisionMargin", "Bullet impl: whether to shrink resulting hulls to account for collision margin", + false, + (s) => { return BHullShouldAdjustCollisionMargin; }, + (s,v) => { BHullShouldAdjustCollisionMargin = v; } ), + new ParameterDefn("LinksetImplementation", "Type of linkset implementation (0=Constraint, 1=Compound, 2=Manual)", (float)BSLinkset.LinksetImplementation.Compound, (s) => { return LinksetImplementation; }, diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index 9818b05..8e05b58 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -316,6 +316,7 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters break; case "bulletxna": ret = new BSAPIXNA(engineName, this); + BSParam.ShouldUseBulletHACD = false; break; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index b6ac23d..bfa69b2 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -720,7 +720,7 @@ public sealed class BSShapeCollection : IDisposable // Remove usage of the previous shape. DereferenceShape(prim.PhysShape, shapeCallback); - newShape = CreatePhysicalHull(prim.PhysObjectName, newHullKey, prim.BaseShape, prim.Size, lod); + newShape = CreatePhysicalHull(prim, newHullKey, prim.BaseShape, prim.Size, lod); // It might not have been created if we're waiting for an asset. newShape = VerifyMeshCreated(newShape, prim); @@ -731,7 +731,7 @@ public sealed class BSShapeCollection : IDisposable } List m_hulls; - private BulletShape CreatePhysicalHull(string objName, System.UInt64 newHullKey, PrimitiveBaseShape pbs, OMV.Vector3 size, float lod) + private BulletShape CreatePhysicalHull(BSPhysObject prim, System.UInt64 newHullKey, PrimitiveBaseShape pbs, OMV.Vector3 size, float lod) { BulletShape newShape = new BulletShape(); @@ -745,116 +745,153 @@ public sealed class BSShapeCollection : IDisposable } else { - // Build a new hull in the physical world. - // Pass true for physicalness as this prevents the creation of bounding box which is not needed - IMesh meshData = PhysicsScene.mesher.CreateMesh(objName, pbs, size, lod, true /* isPhysical */, false /* shouldCache */); - if (meshData != null) + if (BSParam.ShouldUseBulletHACD) { - - int[] indices = meshData.getIndexListAsInt(); - List vertices = meshData.getVertexList(); - - //format conversion from IMesh format to DecompDesc format - List convIndices = new List(); - List convVertices = new List(); - for (int ii = 0; ii < indices.GetLength(0); ii++) + DetailLog("{0},BSShapeCollection.CreatePhysicalHull,shouldUseBulletHACD,entry", prim.LocalID); + MeshDesc meshDesc; + if (!Meshes.TryGetValue(newHullKey, out meshDesc)) { - convIndices.Add(indices[ii]); + // That's odd because the mesh should have been created before the hull + // but, since it doesn't exist, create it. + newShape = CreatePhysicalMesh(prim, newHullKey, prim.BaseShape, prim.Size, lod); + DetailLog("{0},BSShapeCollection.CreatePhysicalHull,noMeshBuiltNew,hasBody={1}", prim.LocalID, newShape.HasPhysicalShape); + + if (newShape.HasPhysicalShape) + { + ReferenceShape(newShape); + Meshes.TryGetValue(newHullKey, out meshDesc); + } } - foreach (OMV.Vector3 vv in vertices) + if (meshDesc.shape.HasPhysicalShape) { - convVertices.Add(new float3(vv.X, vv.Y, vv.Z)); + HACDParams parms; + parms.maxVerticesPerHull = BSParam.BHullMaxVerticesPerHull; + parms.minClusters = BSParam.BHullMinClusters; + parms.compacityWeight = BSParam.BHullCompacityWeight; + parms.volumeWeight = BSParam.BHullVolumeWeight; + parms.concavity = BSParam.BHullConcavity; + parms.addExtraDistPoints = BSParam.NumericBool(BSParam.BHullAddExtraDistPoints); + parms.addNeighboursDistPoints = BSParam.NumericBool(BSParam.BHullAddNeighboursDistPoints); + parms.addFacesPoints = BSParam.NumericBool(BSParam.BHullAddFacesPoints); + parms.shouldAdjustCollisionMargin = BSParam.NumericBool(BSParam.BHullShouldAdjustCollisionMargin); + + DetailLog("{0},BSShapeCollection.CreatePhysicalHull,hullFromMesh,beforeCall", prim.LocalID, newShape.HasPhysicalShape); + newShape = PhysicsScene.PE.BuildHullShapeFromMesh(PhysicsScene.World, meshDesc.shape, parms); + DetailLog("{0},BSShapeCollection.CreatePhysicalHull,hullFromMesh,hasBody={1}", prim.LocalID, newShape.HasPhysicalShape); } - - uint maxDepthSplit = (uint)BSParam.CSHullMaxDepthSplit; - if (BSParam.CSHullMaxDepthSplit != BSParam.CSHullMaxDepthSplitForSimpleShapes) + DetailLog("{0},BSShapeCollection.CreatePhysicalHull,shouldUseBulletHACD,exit,hasBody={1}", prim.LocalID, newShape.HasPhysicalShape); + } + if (!newShape.HasPhysicalShape) + { + // Build a new hull in the physical world. + // Pass true for physicalness as this prevents the creation of bounding box which is not needed + IMesh meshData = PhysicsScene.mesher.CreateMesh(prim.PhysObjectName, pbs, size, lod, true /* isPhysical */, false /* shouldCache */); + if (meshData != null) { - // Simple primitive shapes we know are convex so they are better implemented with - // fewer hulls. - // Check for simple shape (prim without cuts) and reduce split parameter if so. - if (PrimHasNoCuts(pbs)) + int[] indices = meshData.getIndexListAsInt(); + List vertices = meshData.getVertexList(); + + //format conversion from IMesh format to DecompDesc format + List convIndices = new List(); + List convVertices = new List(); + for (int ii = 0; ii < indices.GetLength(0); ii++) { - maxDepthSplit = (uint)BSParam.CSHullMaxDepthSplitForSimpleShapes; + convIndices.Add(indices[ii]); + } + foreach (OMV.Vector3 vv in vertices) + { + convVertices.Add(new float3(vv.X, vv.Y, vv.Z)); } - } - // setup and do convex hull conversion - m_hulls = new List(); - DecompDesc dcomp = new DecompDesc(); - dcomp.mIndices = convIndices; - dcomp.mVertices = convVertices; - dcomp.mDepth = maxDepthSplit; - dcomp.mCpercent = BSParam.CSHullConcavityThresholdPercent; - dcomp.mPpercent = BSParam.CSHullVolumeConservationThresholdPercent; - dcomp.mMaxVertices = (uint)BSParam.CSHullMaxVertices; - dcomp.mSkinWidth = BSParam.CSHullMaxSkinWidth; - ConvexBuilder convexBuilder = new ConvexBuilder(HullReturn); - // create the hull into the _hulls variable - convexBuilder.process(dcomp); - - DetailLog("{0},BSShapeCollection.CreatePhysicalHull,key={1},inVert={2},inInd={3},split={4},hulls={5}", - BSScene.DetailLogZero, newHullKey, indices.GetLength(0), vertices.Count, maxDepthSplit, m_hulls.Count); - - // Convert the vertices and indices for passing to unmanaged. - // The hull information is passed as a large floating point array. - // The format is: - // convHulls[0] = number of hulls - // convHulls[1] = number of vertices in first hull - // convHulls[2] = hull centroid X coordinate - // convHulls[3] = hull centroid Y coordinate - // convHulls[4] = hull centroid Z coordinate - // convHulls[5] = first hull vertex X - // convHulls[6] = first hull vertex Y - // convHulls[7] = first hull vertex Z - // convHulls[8] = second hull vertex X - // ... - // convHulls[n] = number of vertices in second hull - // convHulls[n+1] = second hull centroid X coordinate - // ... - // - // TODO: is is very inefficient. Someday change the convex hull generator to return - // data structures that do not need to be converted in order to pass to Bullet. - // And maybe put the values directly into pinned memory rather than marshaling. - int hullCount = m_hulls.Count; - int totalVertices = 1; // include one for the count of the hulls - foreach (ConvexResult cr in m_hulls) - { - totalVertices += 4; // add four for the vertex count and centroid - totalVertices += cr.HullIndices.Count * 3; // we pass just triangles - } - float[] convHulls = new float[totalVertices]; + uint maxDepthSplit = (uint)BSParam.CSHullMaxDepthSplit; + if (BSParam.CSHullMaxDepthSplit != BSParam.CSHullMaxDepthSplitForSimpleShapes) + { + // Simple primitive shapes we know are convex so they are better implemented with + // fewer hulls. + // Check for simple shape (prim without cuts) and reduce split parameter if so. + if (PrimHasNoCuts(pbs)) + { + maxDepthSplit = (uint)BSParam.CSHullMaxDepthSplitForSimpleShapes; + } + } - convHulls[0] = (float)hullCount; - int jj = 1; - foreach (ConvexResult cr in m_hulls) - { - // copy vertices for index access - float3[] verts = new float3[cr.HullVertices.Count]; - int kk = 0; - foreach (float3 ff in cr.HullVertices) + // setup and do convex hull conversion + m_hulls = new List(); + DecompDesc dcomp = new DecompDesc(); + dcomp.mIndices = convIndices; + dcomp.mVertices = convVertices; + dcomp.mDepth = maxDepthSplit; + dcomp.mCpercent = BSParam.CSHullConcavityThresholdPercent; + dcomp.mPpercent = BSParam.CSHullVolumeConservationThresholdPercent; + dcomp.mMaxVertices = (uint)BSParam.CSHullMaxVertices; + dcomp.mSkinWidth = BSParam.CSHullMaxSkinWidth; + ConvexBuilder convexBuilder = new ConvexBuilder(HullReturn); + // create the hull into the _hulls variable + convexBuilder.process(dcomp); + + DetailLog("{0},BSShapeCollection.CreatePhysicalHull,key={1},inVert={2},inInd={3},split={4},hulls={5}", + BSScene.DetailLogZero, newHullKey, indices.GetLength(0), vertices.Count, maxDepthSplit, m_hulls.Count); + + // Convert the vertices and indices for passing to unmanaged. + // The hull information is passed as a large floating point array. + // The format is: + // convHulls[0] = number of hulls + // convHulls[1] = number of vertices in first hull + // convHulls[2] = hull centroid X coordinate + // convHulls[3] = hull centroid Y coordinate + // convHulls[4] = hull centroid Z coordinate + // convHulls[5] = first hull vertex X + // convHulls[6] = first hull vertex Y + // convHulls[7] = first hull vertex Z + // convHulls[8] = second hull vertex X + // ... + // convHulls[n] = number of vertices in second hull + // convHulls[n+1] = second hull centroid X coordinate + // ... + // + // TODO: is is very inefficient. Someday change the convex hull generator to return + // data structures that do not need to be converted in order to pass to Bullet. + // And maybe put the values directly into pinned memory rather than marshaling. + int hullCount = m_hulls.Count; + int totalVertices = 1; // include one for the count of the hulls + foreach (ConvexResult cr in m_hulls) { - verts[kk++] = ff; + totalVertices += 4; // add four for the vertex count and centroid + totalVertices += cr.HullIndices.Count * 3; // we pass just triangles } + float[] convHulls = new float[totalVertices]; - // add to the array one hull's worth of data - convHulls[jj++] = cr.HullIndices.Count; - convHulls[jj++] = 0f; // centroid x,y,z - convHulls[jj++] = 0f; - convHulls[jj++] = 0f; - foreach (int ind in cr.HullIndices) + convHulls[0] = (float)hullCount; + int jj = 1; + foreach (ConvexResult cr in m_hulls) { - convHulls[jj++] = verts[ind].x; - convHulls[jj++] = verts[ind].y; - convHulls[jj++] = verts[ind].z; + // copy vertices for index access + float3[] verts = new float3[cr.HullVertices.Count]; + int kk = 0; + foreach (float3 ff in cr.HullVertices) + { + verts[kk++] = ff; + } + + // add to the array one hull's worth of data + convHulls[jj++] = cr.HullIndices.Count; + convHulls[jj++] = 0f; // centroid x,y,z + convHulls[jj++] = 0f; + convHulls[jj++] = 0f; + foreach (int ind in cr.HullIndices) + { + convHulls[jj++] = verts[ind].x; + convHulls[jj++] = verts[ind].y; + convHulls[jj++] = verts[ind].z; + } } + // create the hull data structure in Bullet + newShape = PhysicsScene.PE.CreateHullShape(PhysicsScene.World, hullCount, convHulls); } - // create the hull data structure in Bullet - newShape = PhysicsScene.PE.CreateHullShape(PhysicsScene.World, hullCount, convHulls); } + newShape.shapeKey = newHullKey; } - newShape.shapeKey = newHullKey; - return newShape; } -- cgit v1.1 From 9cc41d511872fcd74a074ab484db2b981f3f5676 Mon Sep 17 00:00:00 2001 From: Vegaslon Date: Tue, 9 Apr 2013 17:23:50 -0400 Subject: Another algorithm for AngularVerticalAttraction. This one Takes into account all rotations before it and makes the corrections more close to the time that sl does. Signed-off-by: Robert Adams --- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 23 ++++++++++++++++++++++ 1 file changed, 23 insertions(+) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index 0fd1f73..723be0b 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -1358,6 +1358,28 @@ namespace OpenSim.Region.Physics.BulletSPlugin // If vertical attaction timescale is reasonable if (enableAngularVerticalAttraction && m_verticalAttractionTimescale < m_verticalAttractionCutoff) { + //Another formula to try got from : + //http://answers.unity3d.com/questions/10425/how-to-stabilize-angular-motion-alignment-of-hover.html + Vector3 VehicleUpAxis = Vector3.UnitZ *VehicleOrientation; + //Flipping what was originally a timescale into a speed variable and then multiplying it by 2 since only computing half + //the distance between the angles. + float VerticalAttractionSpeed=(1/m_verticalAttractionTimescale)*2.0f; + //making a prediction of where the up axis will be when this is applied rather then where it is now this makes for a smoother + //adjustment and less fighting between the various forces + Vector3 predictedUp = VehicleUpAxis * Quaternion.CreateFromAxisAngle(VehicleRotationalVelocity, 0f); + //this is only half the distance to the target so it will take 2 seconds to complete the turn. + Vector3 torqueVector = Vector3.Cross(predictedUp, Vector3.UnitZ); + //Scaling vector by our timescale since it is an acceleration it is r/s^2 or radians a timescale squared + Vector3 vertContributionV=torqueVector * VerticalAttractionSpeed *VerticalAttractionSpeed; + VehicleRotationalVelocity += vertContributionV; + VDetailLog("{0}, MoveAngular,verticalAttraction,UpAxis={1},PredictedUp={2},torqueVector={3},contrib={4}", + ControllingPrim.LocalID, + VehicleUpAxis, + predictedUp, + torqueVector, + vertContributionV); + //===================================================================== + /* // Possible solution derived from a discussion at: // http://stackoverflow.com/questions/14939657/computing-vector-from-quaternion-works-computing-quaternion-from-vector-does-no @@ -1392,6 +1414,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin differenceAngle, correctionRotation, vertContributionV); + */ // =================================================================== /* -- cgit v1.1 From b53713cdda3c4e49913a6a82239da35d62f74e68 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 9 Apr 2013 17:14:15 -0700 Subject: BulletSim: some formatting changes. --- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 27 ++++++++++++++-------- 1 file changed, 17 insertions(+), 10 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index 723be0b..612c68b 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -1360,19 +1360,26 @@ namespace OpenSim.Region.Physics.BulletSPlugin { //Another formula to try got from : //http://answers.unity3d.com/questions/10425/how-to-stabilize-angular-motion-alignment-of-hover.html - Vector3 VehicleUpAxis = Vector3.UnitZ *VehicleOrientation; - //Flipping what was originally a timescale into a speed variable and then multiplying it by 2 since only computing half - //the distance between the angles. - float VerticalAttractionSpeed=(1/m_verticalAttractionTimescale)*2.0f; - //making a prediction of where the up axis will be when this is applied rather then where it is now this makes for a smoother - //adjustment and less fighting between the various forces + + Vector3 VehicleUpAxis = Vector3.UnitZ * VehicleOrientation; + + // Flipping what was originally a timescale into a speed variable and then multiplying it by 2 + // since only computing half the distance between the angles. + float VerticalAttractionSpeed = (1 / m_verticalAttractionTimescale) * 2.0f; + + // Make a prediction of where the up axis will be when this is applied rather then where it is now as + // this makes for a smoother adjustment and less fighting between the various forces. Vector3 predictedUp = VehicleUpAxis * Quaternion.CreateFromAxisAngle(VehicleRotationalVelocity, 0f); - //this is only half the distance to the target so it will take 2 seconds to complete the turn. + + // This is only half the distance to the target so it will take 2 seconds to complete the turn. Vector3 torqueVector = Vector3.Cross(predictedUp, Vector3.UnitZ); - //Scaling vector by our timescale since it is an acceleration it is r/s^2 or radians a timescale squared - Vector3 vertContributionV=torqueVector * VerticalAttractionSpeed *VerticalAttractionSpeed; + + // Scale vector by our timescale since it is an acceleration it is r/s^2 or radians a timescale squared + Vector3 vertContributionV = torqueVector * VerticalAttractionSpeed * VerticalAttractionSpeed; + VehicleRotationalVelocity += vertContributionV; - VDetailLog("{0}, MoveAngular,verticalAttraction,UpAxis={1},PredictedUp={2},torqueVector={3},contrib={4}", + + VDetailLog("{0}, MoveAngular,verticalAttraction,UpAxis={1},PredictedUp={2},torqueVector={3},contrib={4}", ControllingPrim.LocalID, VehicleUpAxis, predictedUp, -- cgit v1.1 From 5f2cbfc0fd27198f8f05f4a9a4e2908d8b11752e Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 9 Apr 2013 17:53:18 -0700 Subject: BulletSim: fixing problems with llMoveToTarget. Not all fixed yet. --- OpenSim/Region/Physics/BulletSPlugin/BSActorHover.cs | 2 +- .../Region/Physics/BulletSPlugin/BSActorMoveToTarget.cs | 16 +++++++++++----- OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs | 6 ++++++ 3 files changed, 18 insertions(+), 6 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSActorHover.cs b/OpenSim/Region/Physics/BulletSPlugin/BSActorHover.cs index e8310df..92ace66 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSActorHover.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSActorHover.cs @@ -50,7 +50,7 @@ public class BSActorHover : BSActor // BSActor.isActive public override bool isActive { - get { return Enabled && m_controllingPrim.IsPhysicallyActive; } + get { return Enabled; } } // Release any connections and resources used by the actor. diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSActorMoveToTarget.cs b/OpenSim/Region/Physics/BulletSPlugin/BSActorMoveToTarget.cs index 16c2b14..56aacc5 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSActorMoveToTarget.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSActorMoveToTarget.cs @@ -50,7 +50,7 @@ public class BSActorMoveToTarget : BSActor // BSActor.isActive public override bool isActive { - get { return Enabled && m_controllingPrim.IsPhysicallyActive; } + get { return Enabled; } } // Release any connections and resources used by the actor. @@ -65,7 +65,9 @@ public class BSActorMoveToTarget : BSActor // BSActor.Refresh() public override void Refresh() { - m_physicsScene.DetailLog("{0},BSActorMoveToTarget,refresh", m_controllingPrim.LocalID); + m_physicsScene.DetailLog("{0},BSActorMoveToTarget,refresh,enabled={1},active={2},target={3},tau={4}", + m_controllingPrim.LocalID, Enabled, m_controllingPrim.MoveToTargetActive, + m_controllingPrim.MoveToTargetTarget, m_controllingPrim.MoveToTargetTau ); // If not active any more... if (!m_controllingPrim.MoveToTargetActive) @@ -100,7 +102,7 @@ public class BSActorMoveToTarget : BSActor // We're taking over after this. m_controllingPrim.ZeroMotion(true); - m_targetMotor = new BSVMotor("BSPrim.PIDTarget", + m_targetMotor = new BSVMotor("BSActorMoveToTargget.Activate", m_controllingPrim.MoveToTargetTau, // timeScale BSMotor.Infinite, // decay time scale BSMotor.InfiniteVector, // friction timescale @@ -138,15 +140,19 @@ public class BSActorMoveToTarget : BSActor // If we are very close to our target, turn off the movement motor. if (m_targetMotor.ErrorIsZero()) { - m_physicsScene.DetailLog("{0},BSPrim.PIDTarget,zeroMovement,movePos={1},pos={2},mass={3}", + m_physicsScene.DetailLog("{0},BSActorMoveToTarget.Mover,zeroMovement,movePos={1},pos={2},mass={3}", m_controllingPrim.LocalID, movePosition, m_controllingPrim.RawPosition, m_controllingPrim.Mass); m_controllingPrim.ForcePosition = m_targetMotor.TargetValue; + // Setting the position does not cause the physics engine to generate a property update. Force it. + m_physicsScene.PE.PushUpdate(m_controllingPrim.PhysBody); } else { m_controllingPrim.ForcePosition = movePosition; + // Setting the position does not cause the physics engine to generate a property update. Force it. + m_physicsScene.PE.PushUpdate(m_controllingPrim.PhysBody); } - m_physicsScene.DetailLog("{0},BSPrim.PIDTarget,move,fromPos={1},movePos={2}", m_controllingPrim.LocalID, origPosition, movePosition); + m_physicsScene.DetailLog("{0},BSActorMoveToTarget.Mover,move,fromPos={1},movePos={2}", m_controllingPrim.LocalID, origPosition, movePosition); } } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index 64bf395..98eb4ca 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -295,6 +295,7 @@ public abstract class BSPhysObject : PhysicsActor if (PhysicalActors.TryGetActor(actorName, out theActor)) { // The actor already exists so just turn it on or off + DetailLog("{0},BSPhysObject.EnableActor,enablingExistingActor,name={1},enable={2}", LocalID, actorName, enableActor); theActor.Enabled = enableActor; } else @@ -302,10 +303,15 @@ public abstract class BSPhysObject : PhysicsActor // The actor does not exist. If it should, create it. if (enableActor) { + DetailLog("{0},BSPhysObject.EnableActor,creatingActor,name={1}", LocalID, actorName); theActor = creator(); PhysicalActors.Add(actorName, theActor); theActor.Enabled = true; } + else + { + DetailLog("{0},BSPhysObject.EnableActor,notCreatingActorSinceNotEnabled,name={1}", LocalID, actorName); + } } } } -- cgit v1.1 From e1ac68315491a0962bd4d089f7190e1b82607f43 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Sun, 21 Apr 2013 15:59:39 -0700 Subject: BulletSim: fix crash when deleting llVolumeDetect enabled objects. Bullet's check for an object being linked into the world does not work for Bullet's ghost objects so BulletSim was deleting the object while it was still linked into the physical world structures. --- OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index bfa69b2..1976c42 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -162,11 +162,8 @@ public sealed class BSShapeCollection : IDisposable // If the caller needs to know the old body is going away, pass the event up. if (bodyCallback != null) bodyCallback(body); - if (PhysicsScene.PE.IsInWorld(PhysicsScene.World, body)) - { - PhysicsScene.PE.RemoveObjectFromWorld(PhysicsScene.World, body); - if (DDetail) DetailLog("{0},BSShapeCollection.DereferenceBody,removingFromWorld. Body={1}", body.ID, body); - } + // Removing an object not in the world is a NOOP + PhysicsScene.PE.RemoveObjectFromWorld(PhysicsScene.World, body); // Zero any reference to the shape so it is not freed when the body is deleted. PhysicsScene.PE.SetCollisionShape(PhysicsScene.World, body, null); -- cgit v1.1 From 522ab85045066cb58bb76881032adab7cc6a2d68 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 23 Apr 2013 18:31:12 -0700 Subject: BulletSim: improve avatar stair walking up. Add more parameters to control force of both position change and up force that move avatars over barrier. Default parameters are for steps up to 0.5m in height. --- .../Physics/BulletSPlugin/BSActorAvatarMove.cs | 103 +++++++++++++++++---- OpenSim/Region/Physics/BulletSPlugin/BSParam.cs | 15 ++- .../Region/Physics/BulletSPlugin/BSPhysObject.cs | 22 ++++- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 5 + .../Region/Physics/BulletSPlugin/BulletSimTODO.txt | 3 + 5 files changed, 123 insertions(+), 25 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs b/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs index 8416740..bd5ee0b1 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs @@ -40,10 +40,16 @@ public class BSActorAvatarMove : BSActor { BSVMotor m_velocityMotor; + // Set to true if we think we're going up stairs. + // This state is remembered because collisions will turn on and off as we go up stairs. + int m_walkingUpStairs; + float m_lastStepUp; + public BSActorAvatarMove(BSScene physicsScene, BSPhysObject pObj, string actorName) : base(physicsScene, pObj, actorName) { m_velocityMotor = null; + m_walkingUpStairs = 0; m_physicsScene.DetailLog("{0},BSActorAvatarMove,constructor", m_controllingPrim.LocalID); } @@ -119,6 +125,8 @@ public class BSActorAvatarMove : BSActor SetVelocityAndTarget(m_controllingPrim.RawVelocity, m_controllingPrim.TargetVelocity, true /* inTaintTime */); m_physicsScene.BeforeStep += Mover; + + m_walkingUpStairs = 0; } } @@ -216,8 +224,6 @@ public class BSActorAvatarMove : BSActor // 'stepVelocity' is now the speed we'd like the avatar to move in. Turn that into an instantanous force. OMV.Vector3 moveForce = (stepVelocity - m_controllingPrim.RawVelocity) * m_controllingPrim.Mass; - // Should we check for move force being small and forcing velocity to zero? - // Add special movement force to allow avatars to walk up stepped surfaces. moveForce += WalkUpStairs(); @@ -233,24 +239,33 @@ public class BSActorAvatarMove : BSActor { OMV.Vector3 ret = OMV.Vector3.Zero; + m_physicsScene.DetailLog("{0},BSCharacter.WalkUpStairs,IsColliding={1},flying={2},targSpeed={3},collisions={4},avHeight={5}", + m_controllingPrim.LocalID, m_controllingPrim.IsColliding, m_controllingPrim.Flying, + m_controllingPrim.TargetVelocitySpeed, m_controllingPrim.CollisionsLastTick.Count, m_controllingPrim.Size.Z); // This test is done if moving forward, not flying and is colliding with something. - // DetailLog("{0},BSCharacter.WalkUpStairs,IsColliding={1},flying={2},targSpeed={3},collisions={4}", - // LocalID, IsColliding, Flying, TargetSpeed, CollisionsLastTick.Count); - if (m_controllingPrim.IsColliding && !m_controllingPrim.Flying && m_controllingPrim.TargetVelocitySpeed > 0.1f /* && ForwardSpeed < 0.1f */) + // Check for stairs climbing if colliding, not flying and moving forward + if ( m_controllingPrim.IsColliding + && !m_controllingPrim.Flying + && m_controllingPrim.TargetVelocitySpeed > 0.1f ) { // The range near the character's feet where we will consider stairs - float nearFeetHeightMin = m_controllingPrim.RawPosition.Z - (m_controllingPrim.Size.Z / 2f) + 0.05f; + // float nearFeetHeightMin = m_controllingPrim.RawPosition.Z - (m_controllingPrim.Size.Z / 2f) + 0.05f; + // Note: there is a problem with the computation of the capsule height. Thus RawPosition is off + // from the height. Revisit size and this computation when height is scaled properly. + float nearFeetHeightMin = m_controllingPrim.RawPosition.Z - (m_controllingPrim.Size.Z / 2f) - 0.05f; float nearFeetHeightMax = nearFeetHeightMin + BSParam.AvatarStepHeight; - // Look for a collision point that is near the character's feet and is oriented the same as the charactor is + // Look for a collision point that is near the character's feet and is oriented the same as the charactor is. + // Find the highest 'good' collision. + OMV.Vector3 highestTouchPosition = OMV.Vector3.Zero; foreach (KeyValuePair kvp in m_controllingPrim.CollisionsLastTick.m_objCollisionList) { // Don't care about collisions with the terrain if (kvp.Key > m_physicsScene.TerrainManager.HighestTerrainID) { OMV.Vector3 touchPosition = kvp.Value.Position; - // DetailLog("{0},BSCharacter.WalkUpStairs,min={1},max={2},touch={3}", - // LocalID, nearFeetHeightMin, nearFeetHeightMax, touchPosition); + m_physicsScene.DetailLog("{0},BSCharacter.WalkUpStairs,min={1},max={2},touch={3}", + m_controllingPrim.LocalID, nearFeetHeightMin, nearFeetHeightMax, touchPosition); if (touchPosition.Z >= nearFeetHeightMin && touchPosition.Z <= nearFeetHeightMax) { // This contact is within the 'near the feet' range. @@ -261,24 +276,76 @@ public class BSActorAvatarMove : BSActor float diff = Math.Abs(OMV.Vector3.Distance(directionFacing, touchNormal)); if (diff < BSParam.AvatarStepApproachFactor) { - // Found the stairs contact point. Push up a little to raise the character. - float upForce = (touchPosition.Z - nearFeetHeightMin) * m_controllingPrim.Mass * BSParam.AvatarStepForceFactor; - ret = new OMV.Vector3(0f, 0f, upForce); - - // Also move the avatar up for the new height - OMV.Vector3 displacement = new OMV.Vector3(0f, 0f, BSParam.AvatarStepHeight / 2f); - m_controllingPrim.ForcePosition = m_controllingPrim.RawPosition + displacement; + if (highestTouchPosition.Z < touchPosition.Z) + highestTouchPosition = touchPosition; } - m_physicsScene.DetailLog("{0},BSCharacter.WalkUpStairs,touchPos={1},nearFeetMin={2},faceDir={3},norm={4},diff={5},ret={6}", - m_controllingPrim.LocalID, touchPosition, nearFeetHeightMin, directionFacing, touchNormal, diff, ret); } } } + m_walkingUpStairs = 0; + // If there is a good step sensing, move the avatar over the step. + if (highestTouchPosition != OMV.Vector3.Zero) + { + // Remember that we are going up stairs. This is needed because collisions + // will stop when we move up so this smoothes out that effect. + m_walkingUpStairs = BSParam.AvatarStepSmoothingSteps; + + m_lastStepUp = highestTouchPosition.Z - nearFeetHeightMin; + ret = ComputeStairCorrection(m_lastStepUp); + m_physicsScene.DetailLog("{0},BSCharacter.WalkUpStairs,touchPos={1},nearFeetMin={2},ret={3}", + m_controllingPrim.LocalID, highestTouchPosition, nearFeetHeightMin, ret); + } + } + else + { + // If we used to be going up stairs but are not now, smooth the case where collision goes away while + // we are bouncing up the stairs. + if (m_walkingUpStairs > 0) + { + m_walkingUpStairs--; + ret = ComputeStairCorrection(m_lastStepUp); + } } return ret; } + private OMV.Vector3 ComputeStairCorrection(float stepUp) + { + OMV.Vector3 ret = OMV.Vector3.Zero; + OMV.Vector3 displacement = OMV.Vector3.Zero; + + if (stepUp > 0f) + { + // Found the stairs contact point. Push up a little to raise the character. + if (BSParam.AvatarStepForceFactor > 0f) + { + float upForce = stepUp * m_controllingPrim.Mass * BSParam.AvatarStepForceFactor; + ret = new OMV.Vector3(0f, 0f, upForce); + } + + // Also move the avatar up for the new height + if (BSParam.AvatarStepUpCorrectionFactor > 0f) + { + // Move the avatar up related to the height of the collision + displacement = new OMV.Vector3(0f, 0f, stepUp * BSParam.AvatarStepUpCorrectionFactor); + m_controllingPrim.ForcePosition = m_controllingPrim.RawPosition + displacement; + } + else + { + if (BSParam.AvatarStepUpCorrectionFactor < 0f) + { + // Move the avatar up about the specified step height + displacement = new OMV.Vector3(0f, 0f, BSParam.AvatarStepHeight); + m_controllingPrim.ForcePosition = m_controllingPrim.RawPosition + displacement; + } + } + m_physicsScene.DetailLog("{0},BSCharacter.WalkUpStairs.ComputeStairCorrection,disp={1},force={2}", + m_controllingPrim.LocalID, displacement, ret); + + } + return ret; + } } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs index 06df85e..980d405 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs @@ -128,6 +128,8 @@ public static class BSParam public static float AvatarStepHeight { get; private set; } public static float AvatarStepApproachFactor { get; private set; } public static float AvatarStepForceFactor { get; private set; } + public static float AvatarStepUpCorrectionFactor { get; private set; } + public static int AvatarStepSmoothingSteps { get; private set; } // Vehicle parameters public static float VehicleMaxLinearVelocity { get; private set; } @@ -234,6 +236,7 @@ public static class BSParam objectSet = pObjSetter; } /* Wish I could simplify using this definition but CLR doesn't store references so closure around delegates of references won't work + * TODO: Maybe use reflection and the name of the variable to create a reference for the getter/setter. public ParameterDefn(string pName, string pDesc, T pDefault, ref T loc) : base(pName, pDesc) { @@ -561,7 +564,7 @@ public static class BSParam (s) => { return AvatarBelowGroundUpCorrectionMeters; }, (s,v) => { AvatarBelowGroundUpCorrectionMeters = v; } ), new ParameterDefn("AvatarStepHeight", "Height of a step obstacle to consider step correction", - 0.3f, + 0.6f, (s) => { return AvatarStepHeight; }, (s,v) => { AvatarStepHeight = v; } ), new ParameterDefn("AvatarStepApproachFactor", "Factor to control angle of approach to step (0=straight on)", @@ -569,9 +572,17 @@ public static class BSParam (s) => { return AvatarStepApproachFactor; }, (s,v) => { AvatarStepApproachFactor = v; } ), new ParameterDefn("AvatarStepForceFactor", "Controls the amount of force up applied to step up onto a step", - 2.0f, + 1.0f, (s) => { return AvatarStepForceFactor; }, (s,v) => { AvatarStepForceFactor = v; } ), + new ParameterDefn("AvatarStepUpCorrectionFactor", "Multiplied by height of step collision to create up movement at step", + 1.0f, + (s) => { return AvatarStepUpCorrectionFactor; }, + (s,v) => { AvatarStepUpCorrectionFactor = v; } ), + new ParameterDefn("AvatarStepSmoothingSteps", "Number of frames after a step collision that we continue walking up stairs", + 2, + (s) => { return AvatarStepSmoothingSteps; }, + (s,v) => { AvatarStepSmoothingSteps = v; } ), new ParameterDefn("VehicleMaxLinearVelocity", "Maximum velocity magnitude that can be assigned to a vehicle", 1000.0f, diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index 98eb4ca..309d004 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -96,7 +96,7 @@ public abstract class BSPhysObject : PhysicsActor SetMaterial((int)MaterialAttributes.Material.Wood); CollisionCollection = new CollisionEventUpdate(); - CollisionsLastTick = CollisionCollection; + CollisionsLastReported = CollisionCollection; SubscribedEventsMs = 0; CollidingStep = 0; CollidingGroundStep = 0; @@ -368,11 +368,14 @@ public abstract class BSPhysObject : PhysicsActor } } - // The collisions that have been collected this tick + // The collisions that have been collected for the next collision reporting (throttled by subscription) protected CollisionEventUpdate CollisionCollection; - // Remember collisions from last tick for fancy collision based actions + // This is the collision collection last reported to the Simulator. + public CollisionEventUpdate CollisionsLastReported; + // Remember the collisions recorded in the last tick for fancy collision checking // (like a BSCharacter walking up stairs). public CollisionEventUpdate CollisionsLastTick; + private long CollisionsLastTickStep = -1; // The simulation step is telling this object about a collision. // Return 'true' if a collision was processed and should be sent up. @@ -399,6 +402,15 @@ public abstract class BSPhysObject : PhysicsActor // For movement tests, remember if we are colliding with an object that is moving. ColliderIsMoving = collidee != null ? (collidee.RawVelocity != OMV.Vector3.Zero) : false; + // Make a collection of the collisions that happened the last simulation tick. + // This is different than the collection created for sending up to the simulator as it is cleared every tick. + if (CollisionsLastTickStep != PhysicsScene.SimulationStep) + { + CollisionsLastTick = new CollisionEventUpdate(); + CollisionsLastTickStep = PhysicsScene.SimulationStep; + } + CollisionsLastTick.AddCollider(collidingWith, new ContactPoint(contactPoint, contactNormal, pentrationDepth)); + // If someone has subscribed for collision events log the collision so it will be reported up if (SubscribedEvents()) { CollisionCollection.AddCollider(collidingWith, new ContactPoint(contactPoint, contactNormal, pentrationDepth)); @@ -419,7 +431,7 @@ public abstract class BSPhysObject : PhysicsActor bool ret = true; // If the 'no collision' call, force it to happen right now so quick collision_end - bool force = (CollisionCollection.Count == 0 && CollisionsLastTick.Count != 0); + bool force = (CollisionCollection.Count == 0 && CollisionsLastReported.Count != 0); // throttle the collisions to the number of milliseconds specified in the subscription if (force || (PhysicsScene.SimulationNowTime >= NextCollisionOkTime)) @@ -438,7 +450,7 @@ public abstract class BSPhysObject : PhysicsActor base.SendCollisionUpdate(CollisionCollection); // Remember the collisions from this tick for some collision specific processing. - CollisionsLastTick = CollisionCollection; + CollisionsLastReported = CollisionCollection; // The CollisionCollection instance is passed around in the simulator. // Make sure we don't have a handle to that one and that a new one is used for next time. diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 3423d2e..4bc266b 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -69,12 +69,17 @@ public class BSPrim : BSPhysObject private int CrossingFailures { get; set; } + // Keep a handle to the vehicle actor so it is easy to set parameters on same. public BSDynamics VehicleActor; public const string VehicleActorName = "BasicVehicle"; + // Parameters for the hover actor public const string HoverActorName = "HoverActor"; + // Parameters for the axis lock actor public const String LockedAxisActorName = "BSPrim.LockedAxis"; + // Parameters for the move to target actor public const string MoveToTargetActorName = "MoveToTargetActor"; + // Parameters for the setForce and setTorque actors public const string SetForceActorName = "SetForceActor"; public const string SetTorqueActorName = "SetTorqueActor"; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimTODO.txt b/OpenSim/Region/Physics/BulletSPlugin/BulletSimTODO.txt index a0131c7..1284ae7 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimTODO.txt +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimTODO.txt @@ -42,6 +42,8 @@ One sided meshes? Should terrain be built into a closed shape? VEHICLES TODO LIST: ================================================= +UBit improvements to remove rubber-banding of avatars sitting on vehicle child prims: + https://github.com/UbitUmarov/Ubit-opensim Border crossing with linked vehicle causes crash 20121129.1411: editting/moving phys object across region boundries causes crash getPos-> btRigidBody::upcast -> getBodyType -> BOOM @@ -167,6 +169,7 @@ Eliminate collisions between objects in a linkset. (LinksetConstraint) MORE ====================================================== +Compute avatar size and scale correctly. Now it is a bit off from the capsule size. Create tests for different interface components Have test objects/scripts measure themselves and turn color if correct/bad Test functions in SL and calibrate correctness there -- cgit v1.1 From e324f6f3f0f8d894190cd7a9733687ac4308b2c1 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Wed, 24 Apr 2013 08:03:45 -0700 Subject: BulletSim: update DLLs and SOs to they have no dependencies on newer glibc (2.14) since that is not yet in some Linux distributions. Add unmanaged API calls and code for creating single convex hull shapes. --- OpenSim/Region/Physics/BulletSPlugin/BSAPIUnman.cs | 27 ++++++++++++++++++++++ OpenSim/Region/Physics/BulletSPlugin/BSAPIXNA.cs | 10 ++++++++ .../Region/Physics/BulletSPlugin/BSApiTemplate.cs | 7 ++++++ 3 files changed, 44 insertions(+) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSAPIUnman.cs b/OpenSim/Region/Physics/BulletSPlugin/BSAPIUnman.cs index f5b84d4..fdf2cb9 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSAPIUnman.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSAPIUnman.cs @@ -268,6 +268,25 @@ public override BulletShape BuildHullShapeFromMesh(BulletWorld world, BulletShap BSPhysicsShapeType.SHAPE_HULL); } +public override BulletShape BuildConvexHullShapeFromMesh(BulletWorld world, BulletShape meshShape) +{ + BulletWorldUnman worldu = world as BulletWorldUnman; + BulletShapeUnman shapeu = meshShape as BulletShapeUnman; + return new BulletShapeUnman( + BSAPICPP.BuildConvexHullShapeFromMesh2(worldu.ptr, shapeu.ptr), + BSPhysicsShapeType.SHAPE_CONVEXHULL); +} + +public override BulletShape CreateConvexHullShape(BulletWorld world, + int indicesCount, int[] indices, + int verticesCount, float[] vertices) +{ + BulletWorldUnman worldu = world as BulletWorldUnman; + return new BulletShapeUnman( + BSAPICPP.CreateConvexHullShape2(worldu.ptr, indicesCount, indices, verticesCount, vertices), + BSPhysicsShapeType.SHAPE_CONVEXHULL); +} + public override BulletShape BuildNativeShape(BulletWorld world, ShapeData shapeData) { BulletWorldUnman worldu = world as BulletWorldUnman; @@ -1414,6 +1433,14 @@ public static extern IntPtr CreateHullShape2(IntPtr world, public static extern IntPtr BuildHullShapeFromMesh2(IntPtr world, IntPtr meshShape, HACDParams parms); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern IntPtr BuildConvexHullShapeFromMesh2(IntPtr world, IntPtr meshShape); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern IntPtr CreateConvexHullShape2(IntPtr world, + int indicesCount, [MarshalAs(UnmanagedType.LPArray)] int[] indices, + int verticesCount, [MarshalAs(UnmanagedType.LPArray)] float[] vertices ); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern IntPtr BuildNativeShape2(IntPtr world, ShapeData shapeData); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSAPIXNA.cs b/OpenSim/Region/Physics/BulletSPlugin/BSAPIXNA.cs index f6b4359..b37265a 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSAPIXNA.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSAPIXNA.cs @@ -1778,6 +1778,16 @@ private sealed class BulletConstraintXNA : BulletConstraint /* TODO */ return null; } + public override BulletShape BuildConvexHullShapeFromMesh(BulletWorld world, BulletShape meshShape) + { + /* TODO */ return null; + } + + public override BulletShape CreateConvexHullShape(BulletWorld pWorld, int pIndicesCount, int[] indices, int pVerticesCount, float[] verticesAsFloats) + { + /* TODO */ return null; + } + public override BulletShape CreateMeshShape(BulletWorld pWorld, int pIndicesCount, int[] indices, int pVerticesCount, float[] verticesAsFloats) { //DumpRaw(indices,verticesAsFloats,pIndicesCount,pVerticesCount); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSApiTemplate.cs b/OpenSim/Region/Physics/BulletSPlugin/BSApiTemplate.cs index d0d9f34..bfeec24 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSApiTemplate.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSApiTemplate.cs @@ -70,6 +70,7 @@ public enum BSPhysicsShapeType SHAPE_COMPOUND = 22, SHAPE_HEIGHTMAP = 23, SHAPE_AVATAR = 24, + SHAPE_CONVEXHULL= 25, }; // The native shapes have predefined shape hash keys @@ -325,6 +326,12 @@ public abstract BulletShape CreateHullShape(BulletWorld world, public abstract BulletShape BuildHullShapeFromMesh(BulletWorld world, BulletShape meshShape, HACDParams parms); +public abstract BulletShape BuildConvexHullShapeFromMesh(BulletWorld world, BulletShape meshShape); + +public abstract BulletShape CreateConvexHullShape(BulletWorld world, + int indicesCount, int[] indices, + int verticesCount, float[] vertices ); + public abstract BulletShape BuildNativeShape(BulletWorld world, ShapeData shapeData); public abstract bool IsNativeShape(BulletShape shape); -- cgit v1.1 From c22a2ab7d21803050317527476c2e18aa2edb40f Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Wed, 24 Apr 2013 08:05:42 -0700 Subject: BulletSim: partial addition of BSShape class code preparing for different physical mesh representations (simplified convex meshes) and avatar mesh. --- .../Physics/BulletSPlugin/BSShapeCollection.cs | 28 +-- OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs | 215 +++++++++++++++++---- 2 files changed, 191 insertions(+), 52 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index 1976c42..bc26460 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -612,7 +612,7 @@ public sealed class BSShapeCollection : IDisposable newShape = CreatePhysicalMesh(prim, newMeshKey, prim.BaseShape, prim.Size, lod); // Take evasive action if the mesh was not constructed. - newShape = VerifyMeshCreated(newShape, prim); + newShape = VerifyMeshCreated(PhysicsScene, newShape, prim); ReferenceShape(newShape); @@ -719,7 +719,7 @@ public sealed class BSShapeCollection : IDisposable newShape = CreatePhysicalHull(prim, newHullKey, prim.BaseShape, prim.Size, lod); // It might not have been created if we're waiting for an asset. - newShape = VerifyMeshCreated(newShape, prim); + newShape = VerifyMeshCreated(PhysicsScene, newShape, prim); ReferenceShape(newShape); @@ -923,7 +923,7 @@ public sealed class BSShapeCollection : IDisposable // Create a hash of all the shape parameters to be used as a key // for this particular shape. - private System.UInt64 ComputeShapeKey(OMV.Vector3 size, PrimitiveBaseShape pbs, out float retLod) + public static System.UInt64 ComputeShapeKey(OMV.Vector3 size, PrimitiveBaseShape pbs, out float retLod) { // level of detail based on size and type of the object float lod = BSParam.MeshLOD; @@ -944,7 +944,7 @@ public sealed class BSShapeCollection : IDisposable return pbs.GetMeshKey(size, lod); } // For those who don't want the LOD - private System.UInt64 ComputeShapeKey(OMV.Vector3 size, PrimitiveBaseShape pbs) + public static System.UInt64 ComputeShapeKey(OMV.Vector3 size, PrimitiveBaseShape pbs) { float lod; return ComputeShapeKey(size, pbs, out lod); @@ -957,7 +957,7 @@ public sealed class BSShapeCollection : IDisposable // us to not loop forever. // Called after creating a physical mesh or hull. If the physical shape was created, // just return. - private BulletShape VerifyMeshCreated(BulletShape newShape, BSPhysObject prim) + public static BulletShape VerifyMeshCreated(BSScene physicsScene, BulletShape newShape, BSPhysObject prim) { // If the shape was successfully created, nothing more to do if (newShape.HasPhysicalShape) @@ -969,7 +969,7 @@ public sealed class BSShapeCollection : IDisposable if (prim.PrimAssetState == BSPhysObject.PrimAssetCondition.Fetched) { prim.PrimAssetState = BSPhysObject.PrimAssetCondition.Failed; - PhysicsScene.Logger.WarnFormat("{0} Fetched asset would not mesh. {1}, texture={2}", + physicsScene.Logger.WarnFormat("{0} Fetched asset would not mesh. {1}, texture={2}", LogHeader, prim.PhysObjectName, prim.BaseShape.SculptTexture); } else @@ -981,14 +981,14 @@ public sealed class BSShapeCollection : IDisposable && prim.BaseShape.SculptTexture != OMV.UUID.Zero ) { - DetailLog("{0},BSShapeCollection.VerifyMeshCreated,fetchAsset", prim.LocalID); + physicsScene.DetailLog("{0},BSShapeCollection.VerifyMeshCreated,fetchAsset", prim.LocalID); // Multiple requestors will know we're waiting for this asset prim.PrimAssetState = BSPhysObject.PrimAssetCondition.Waiting; BSPhysObject xprim = prim; Util.FireAndForget(delegate { - RequestAssetDelegate assetProvider = PhysicsScene.RequestAssetMethod; + RequestAssetDelegate assetProvider = physicsScene.RequestAssetMethod; if (assetProvider != null) { BSPhysObject yprim = xprim; // probably not necessary, but, just in case. @@ -1016,7 +1016,7 @@ public sealed class BSShapeCollection : IDisposable yprim.PrimAssetState = BSPhysObject.PrimAssetCondition.Fetched; else yprim.PrimAssetState = BSPhysObject.PrimAssetCondition.Failed; - DetailLog("{0},BSShapeCollection,fetchAssetCallback,found={1},isSculpt={2},ids={3}", + physicsScene.DetailLog("{0},BSShapeCollection,fetchAssetCallback,found={1},isSculpt={2},ids={3}", yprim.LocalID, assetFound, yprim.BaseShape.SculptEntry, mismatchIDs ); }); @@ -1024,8 +1024,8 @@ public sealed class BSShapeCollection : IDisposable else { xprim.PrimAssetState = BSPhysObject.PrimAssetCondition.Failed; - PhysicsScene.Logger.ErrorFormat("{0} Physical object requires asset but no asset provider. Name={1}", - LogHeader, PhysicsScene.Name); + physicsScene.Logger.ErrorFormat("{0} Physical object requires asset but no asset provider. Name={1}", + LogHeader, physicsScene.Name); } }); } @@ -1033,15 +1033,15 @@ public sealed class BSShapeCollection : IDisposable { if (prim.PrimAssetState == BSPhysObject.PrimAssetCondition.Failed) { - PhysicsScene.Logger.WarnFormat("{0} Mesh failed to fetch asset. obj={1}, texture={2}", + physicsScene.Logger.WarnFormat("{0} Mesh failed to fetch asset. obj={1}, texture={2}", LogHeader, prim.PhysObjectName, prim.BaseShape.SculptTexture); } } } // While we wait for the mesh defining asset to be loaded, stick in a simple box for the object. - BulletShape fillinShape = BuildPhysicalNativeShape(prim, BSPhysicsShapeType.SHAPE_BOX, FixedShapeKey.KEY_BOX); - DetailLog("{0},BSShapeCollection.VerifyMeshCreated,boxTempShape", prim.LocalID); + BulletShape fillinShape = physicsScene.Shapes.BuildPhysicalNativeShape(prim, BSPhysicsShapeType.SHAPE_BOX, FixedShapeKey.KEY_BOX); + physicsScene.DetailLog("{0},BSShapeCollection.VerifyMeshCreated,boxTempShape", prim.LocalID); return fillinShape; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs index ee18379..dd5ae1a 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs @@ -29,6 +29,9 @@ using System; using System.Collections.Generic; using System.Text; +using OpenSim.Framework; +using OpenSim.Region.Physics.Manager; + using OMV = OpenMetaverse; namespace OpenSim.Region.Physics.BulletSPlugin @@ -37,11 +40,19 @@ public abstract class BSShape { public int referenceCount { get; set; } public DateTime lastReferenced { get; set; } + public BulletShape physShapeInfo { get; set; } public BSShape() { referenceCount = 0; lastReferenced = DateTime.Now; + physShapeInfo = new BulletShape(); + } + public BSShape(BulletShape pShape) + { + referenceCount = 0; + lastReferenced = DateTime.Now; + physShapeInfo = pShape; } // Get a reference to a physical shape. Create if it doesn't exist @@ -79,21 +90,30 @@ public abstract class BSShape return ret; } - public static BSShape GetShapeReferenceNonSpecial(BSScene physicsScene, bool forceRebuild, BSPhysObject prim) + private static BSShape GetShapeReferenceNonSpecial(BSScene physicsScene, bool forceRebuild, BSPhysObject prim) { + BSShapeMesh.GetReference(physicsScene, forceRebuild, prim); + BSShapeHull.GetReference(physicsScene, forceRebuild, prim); return null; } - public static BSShape GetShapeReferenceNonNative(BSScene physicsScene, bool forceRebuild, BSPhysObject prim) + + // Called when this shape is being used again. + public virtual void IncrementReference() { - return null; + referenceCount++; + lastReferenced = DateTime.Now; + } + + // Called when this shape is being used again. + public virtual void DecrementReference() + { + referenceCount--; + lastReferenced = DateTime.Now; } // Release the use of a physical shape. public abstract void Dereference(BSScene physicsScene); - // All shapes have a static call to get a reference to the physical shape - // protected abstract static BSShape GetReference(); - // Returns a string for debugging that uniquily identifies the memory used by this instance public virtual string AddrString { @@ -112,6 +132,7 @@ public abstract class BSShape } } +// ============================================================================================================ public class BSShapeNull : BSShape { public BSShapeNull() : base() @@ -121,23 +142,39 @@ public class BSShapeNull : BSShape public override void Dereference(BSScene physicsScene) { /* The magic of garbage collection will make this go away */ } } +// ============================================================================================================ public class BSShapeNative : BSShape { private static string LogHeader = "[BULLETSIM SHAPE NATIVE]"; - public BSShapeNative() : base() + public BSShapeNative(BulletShape pShape) : base(pShape) { } + public static BSShape GetReference(BSScene physicsScene, BSPhysObject prim, - BSPhysicsShapeType shapeType, FixedShapeKey shapeKey) + BSPhysicsShapeType shapeType, FixedShapeKey shapeKey) { // Native shapes are not shared and are always built anew. - //return new BSShapeNative(physicsScene, prim, shapeType, shapeKey); - return null; + return new BSShapeNative(CreatePhysicalNativeShape(physicsScene, prim, shapeType, shapeKey)); } - private BSShapeNative(BSScene physicsScene, BSPhysObject prim, - BSPhysicsShapeType shapeType, FixedShapeKey shapeKey) + // Make this reference to the physical shape go away since native shapes are not shared. + public override void Dereference(BSScene physicsScene) + { + // Native shapes are not tracked and are released immediately + if (physShapeInfo.HasPhysicalShape) + { + physicsScene.DetailLog("{0},BSShapeNative.DereferenceShape,deleteNativeShape,shape={1}", BSScene.DetailLogZero, this); + physicsScene.PE.DeleteCollisionShape(physicsScene.World, physShapeInfo); + } + physShapeInfo.Clear(); + // Garbage collection will free up this instance. + } + + private static BulletShape CreatePhysicalNativeShape(BSScene physicsScene, BSPhysObject prim, + BSPhysicsShapeType shapeType, FixedShapeKey shapeKey) { + BulletShape newShape; + ShapeData nativeShapeData = new ShapeData(); nativeShapeData.Type = shapeType; nativeShapeData.ID = prim.LocalID; @@ -146,63 +183,164 @@ public class BSShapeNative : BSShape nativeShapeData.MeshKey = (ulong)shapeKey; nativeShapeData.HullKey = (ulong)shapeKey; - - /* if (shapeType == BSPhysicsShapeType.SHAPE_CAPSULE) { - ptr = PhysicsScene.PE.BuildCapsuleShape(physicsScene.World, 1f, 1f, prim.Scale); - physicsScene.DetailLog("{0},BSShapeCollection.BuiletPhysicalNativeShape,capsule,scale={1}", prim.LocalID, prim.Scale); + newShape = physicsScene.PE.BuildCapsuleShape(physicsScene.World, 1f, 1f, prim.Scale); + physicsScene.DetailLog("{0},BSShapeNative,capsule,scale={1}", prim.LocalID, prim.Scale); } else { - ptr = PhysicsScene.PE.BuildNativeShape(physicsScene.World, nativeShapeData); + newShape = physicsScene.PE.BuildNativeShape(physicsScene.World, nativeShapeData); } - if (ptr == IntPtr.Zero) + if (!newShape.HasPhysicalShape) { physicsScene.Logger.ErrorFormat("{0} BuildPhysicalNativeShape failed. ID={1}, shape={2}", LogHeader, prim.LocalID, shapeType); } - type = shapeType; - key = (UInt64)shapeKey; - */ - } - // Make this reference to the physical shape go away since native shapes are not shared. - public override void Dereference(BSScene physicsScene) - { - /* - // Native shapes are not tracked and are released immediately - physicsScene.DetailLog("{0},BSShapeCollection.DereferenceShape,deleteNativeShape,shape={1}", BSScene.DetailLogZero, this); - PhysicsScene.PE.DeleteCollisionShape(physicsScene.World, this); - ptr = IntPtr.Zero; - // Garbage collection will free up this instance. - */ + newShape.type = shapeType; + newShape.isNativeShape = true; + newShape.shapeKey = (UInt64)shapeKey; + return newShape; } + } +// ============================================================================================================ public class BSShapeMesh : BSShape { private static string LogHeader = "[BULLETSIM SHAPE MESH]"; private static Dictionary Meshes = new Dictionary(); - public BSShapeMesh() : base() + public BSShapeMesh(BulletShape pShape) : base(pShape) { } - public static BSShape GetReference() { return new BSShapeNull(); } - public override void Dereference(BSScene physicsScene) { } + public static BSShape GetReference(BSScene physicsScene, bool forceRebuild, BSPhysObject prim) + { + float lod; + System.UInt64 newMeshKey = BSShapeCollection.ComputeShapeKey(prim.Size, prim.BaseShape, out lod); + + physicsScene.DetailLog("{0},BSShapeMesh,create,oldKey={1},newKey={2},size={3},lod={4}", + prim.LocalID, prim.PhysShape.shapeKey.ToString("X"), newMeshKey.ToString("X"), prim.Size, lod); + + BSShapeMesh retMesh; + lock (Meshes) + { + if (Meshes.TryGetValue(newMeshKey, out retMesh)) + { + // The mesh has already been created. Return a new reference to same. + retMesh.IncrementReference(); + } + else + { + // An instance of this mesh has not been created. Build and remember same. + BulletShape newShape = CreatePhysicalMesh(physicsScene, prim, newMeshKey, prim.BaseShape, prim.Size, lod); + // Take evasive action if the mesh was not constructed. + newShape = BSShapeCollection.VerifyMeshCreated(physicsScene, newShape, prim); + + retMesh = new BSShapeMesh(newShape); + + Meshes.Add(newMeshKey, retMesh); + } + } + return retMesh; + } + public override void Dereference(BSScene physicsScene) + { + lock (Meshes) + { + this.DecrementReference(); + // TODO: schedule aging and destruction of unused meshes. + } + } + + private static BulletShape CreatePhysicalMesh(BSScene physicsScene, BSPhysObject prim, System.UInt64 newMeshKey, + PrimitiveBaseShape pbs, OMV.Vector3 size, float lod) + { + BulletShape newShape = null; + + IMesh meshData = physicsScene.mesher.CreateMesh(prim.PhysObjectName, pbs, size, lod, + false, // say it is not physical so a bounding box is not built + false // do not cache the mesh and do not use previously built versions + ); + + if (meshData != null) + { + + int[] indices = meshData.getIndexListAsInt(); + int realIndicesIndex = indices.Length; + float[] verticesAsFloats = meshData.getVertexListAsFloat(); + + if (BSParam.ShouldRemoveZeroWidthTriangles) + { + // Remove degenerate triangles. These are triangles with two of the vertices + // are the same. This is complicated by the problem that vertices are not + // made unique in sculpties so we have to compare the values in the vertex. + realIndicesIndex = 0; + for (int tri = 0; tri < indices.Length; tri += 3) + { + // Compute displacements into vertex array for each vertex of the triangle + int v1 = indices[tri + 0] * 3; + int v2 = indices[tri + 1] * 3; + int v3 = indices[tri + 2] * 3; + // Check to see if any two of the vertices are the same + if (!( ( verticesAsFloats[v1 + 0] == verticesAsFloats[v2 + 0] + && verticesAsFloats[v1 + 1] == verticesAsFloats[v2 + 1] + && verticesAsFloats[v1 + 2] == verticesAsFloats[v2 + 2]) + || ( verticesAsFloats[v2 + 0] == verticesAsFloats[v3 + 0] + && verticesAsFloats[v2 + 1] == verticesAsFloats[v3 + 1] + && verticesAsFloats[v2 + 2] == verticesAsFloats[v3 + 2]) + || ( verticesAsFloats[v1 + 0] == verticesAsFloats[v3 + 0] + && verticesAsFloats[v1 + 1] == verticesAsFloats[v3 + 1] + && verticesAsFloats[v1 + 2] == verticesAsFloats[v3 + 2]) ) + ) + { + // None of the vertices of the triangles are the same. This is a good triangle; + indices[realIndicesIndex + 0] = indices[tri + 0]; + indices[realIndicesIndex + 1] = indices[tri + 1]; + indices[realIndicesIndex + 2] = indices[tri + 2]; + realIndicesIndex += 3; + } + } + } + physicsScene.DetailLog("{0},BSShapeCollection.CreatePhysicalMesh,origTri={1},realTri={2},numVerts={3}", + BSScene.DetailLogZero, indices.Length / 3, realIndicesIndex / 3, verticesAsFloats.Length / 3); + + if (realIndicesIndex != 0) + { + newShape = physicsScene.PE.CreateMeshShape(physicsScene.World, + realIndicesIndex, indices, verticesAsFloats.Length / 3, verticesAsFloats); + } + else + { + physicsScene.Logger.DebugFormat("{0} All mesh triangles degenerate. Prim {1} at {2} in {3}", + LogHeader, prim.PhysObjectName, prim.RawPosition, physicsScene.Name); + } + } + newShape.shapeKey = newMeshKey; + + return newShape; + } } +// ============================================================================================================ public class BSShapeHull : BSShape { private static string LogHeader = "[BULLETSIM SHAPE HULL]"; private static Dictionary Hulls = new Dictionary(); - public BSShapeHull() : base() + public BSShapeHull(BulletShape pShape) : base(pShape) + { + } + public static BSShape GetReference(BSScene physicsScene, bool forceRebuild, BSPhysObject prim) + { + return new BSShapeNull(); + } + public override void Dereference(BSScene physicsScene) { } - public static BSShape GetReference() { return new BSShapeNull(); } - public override void Dereference(BSScene physicsScene) { } } +// ============================================================================================================ public class BSShapeCompound : BSShape { private static string LogHeader = "[BULLETSIM SHAPE COMPOUND]"; @@ -216,6 +354,7 @@ public class BSShapeCompound : BSShape public override void Dereference(BSScene physicsScene) { } } +// ============================================================================================================ public class BSShapeAvatar : BSShape { private static string LogHeader = "[BULLETSIM SHAPE AVATAR]"; -- cgit v1.1 From 890cb6a29373a54dde2d06b13e42d07676710dc2 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Sat, 27 Apr 2013 14:00:58 -0700 Subject: BulletSim: complete BSShape classes. --- .../Physics/BulletSPlugin/BSShapeCollection.cs | 2 +- OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs | 327 ++++++++++++++++++++- .../Region/Physics/BulletSPlugin/BulletSimTODO.txt | 6 +- 3 files changed, 316 insertions(+), 19 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index bc26460..0f9b3c3 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -499,7 +499,7 @@ public sealed class BSShapeCollection : IDisposable } // return 'true' if this shape description does not include any cutting or twisting. - private bool PrimHasNoCuts(PrimitiveBaseShape pbs) + public static bool PrimHasNoCuts(PrimitiveBaseShape pbs) { return pbs.ProfileBegin == 0 && pbs.ProfileEnd == 0 && pbs.ProfileHollow == 0 diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs index dd5ae1a..e427dbc 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs @@ -31,6 +31,7 @@ using System.Text; using OpenSim.Framework; using OpenSim.Region.Physics.Manager; +using OpenSim.Region.Physics.ConvexDecompositionDotNet; using OMV = OpenMetaverse; @@ -73,7 +74,7 @@ public abstract class BSShape if (ret == null && prim.PreferredPhysicalShape == BSPhysicsShapeType.SHAPE_COMPOUND) { // Getting a reference to a compound shape gets you the compound shape with the root prim shape added - ret = BSShapeCompound.GetReference(prim); + ret = BSShapeCompound.GetReference(physicsScene, prim); physicsScene.DetailLog("{0},BSShapeCollection.CreateGeom,compoundShape,shape={1}", prim.LocalID, ret); } @@ -92,6 +93,7 @@ public abstract class BSShape } private static BSShape GetShapeReferenceNonSpecial(BSScene physicsScene, bool forceRebuild, BSPhysObject prim) { + // TODO: work needed here!! BSShapeMesh.GetReference(physicsScene, forceRebuild, prim); BSShapeHull.GetReference(physicsScene, forceRebuild, prim); return null; @@ -209,7 +211,7 @@ public class BSShapeNative : BSShape public class BSShapeMesh : BSShape { private static string LogHeader = "[BULLETSIM SHAPE MESH]"; - private static Dictionary Meshes = new Dictionary(); + public static Dictionary Meshes = new Dictionary(); public BSShapeMesh(BulletShape pShape) : base(pShape) { @@ -219,10 +221,10 @@ public class BSShapeMesh : BSShape float lod; System.UInt64 newMeshKey = BSShapeCollection.ComputeShapeKey(prim.Size, prim.BaseShape, out lod); - physicsScene.DetailLog("{0},BSShapeMesh,create,oldKey={1},newKey={2},size={3},lod={4}", + physicsScene.DetailLog("{0},BSShapeMesh,getReference,oldKey={1},newKey={2},size={3},lod={4}", prim.LocalID, prim.PhysShape.shapeKey.ToString("X"), newMeshKey.ToString("X"), prim.Size, lod); - BSShapeMesh retMesh; + BSShapeMesh retMesh = new BSShapeMesh(new BulletShape()); lock (Meshes) { if (Meshes.TryGetValue(newMeshKey, out retMesh)) @@ -233,13 +235,17 @@ public class BSShapeMesh : BSShape else { // An instance of this mesh has not been created. Build and remember same. - BulletShape newShape = CreatePhysicalMesh(physicsScene, prim, newMeshKey, prim.BaseShape, prim.Size, lod); - // Take evasive action if the mesh was not constructed. - newShape = BSShapeCollection.VerifyMeshCreated(physicsScene, newShape, prim); + BulletShape newShape = retMesh.CreatePhysicalMesh(physicsScene, prim, newMeshKey, prim.BaseShape, prim.Size, lod); - retMesh = new BSShapeMesh(newShape); + // Check to see if mesh was created (might require an asset). + newShape = BSShapeCollection.VerifyMeshCreated(physicsScene, newShape, prim); + if (newShape.type == BSPhysicsShapeType.SHAPE_MESH) + { + // If a mesh was what was created, remember the built shape for later sharing. + Meshes.Add(newMeshKey, retMesh); + } - Meshes.Add(newMeshKey, retMesh); + retMesh.physShapeInfo = newShape; } } return retMesh; @@ -252,8 +258,28 @@ public class BSShapeMesh : BSShape // TODO: schedule aging and destruction of unused meshes. } } + // Loop through all the known meshes and return the description based on the physical address. + public static bool TryGetMeshByPtr(BulletShape pShape, out BSShapeMesh outMesh) + { + bool ret = false; + BSShapeMesh foundDesc = null; + lock (Meshes) + { + foreach (BSShapeMesh sm in Meshes.Values) + { + if (sm.physShapeInfo.ReferenceSame(pShape)) + { + foundDesc = sm; + ret = true; + break; + } - private static BulletShape CreatePhysicalMesh(BSScene physicsScene, BSPhysObject prim, System.UInt64 newMeshKey, + } + } + outMesh = foundDesc; + return ret; + } + private BulletShape CreatePhysicalMesh(BSScene physicsScene, BSPhysObject prim, System.UInt64 newMeshKey, PrimitiveBaseShape pbs, OMV.Vector3 size, float lod) { BulletShape newShape = null; @@ -326,32 +352,301 @@ public class BSShapeMesh : BSShape public class BSShapeHull : BSShape { private static string LogHeader = "[BULLETSIM SHAPE HULL]"; - private static Dictionary Hulls = new Dictionary(); + public static Dictionary Hulls = new Dictionary(); public BSShapeHull(BulletShape pShape) : base(pShape) { } public static BSShape GetReference(BSScene physicsScene, bool forceRebuild, BSPhysObject prim) { - return new BSShapeNull(); + float lod; + System.UInt64 newHullKey = BSShapeCollection.ComputeShapeKey(prim.Size, prim.BaseShape, out lod); + + physicsScene.DetailLog("{0},BSShapeHull,getReference,oldKey={1},newKey={2},size={3},lod={4}", + prim.LocalID, prim.PhysShape.shapeKey.ToString("X"), newHullKey.ToString("X"), prim.Size, lod); + + BSShapeHull retHull = new BSShapeHull(new BulletShape()); + lock (Hulls) + { + if (Hulls.TryGetValue(newHullKey, out retHull)) + { + // The mesh has already been created. Return a new reference to same. + retHull.IncrementReference(); + } + else + { + // An instance of this mesh has not been created. Build and remember same. + BulletShape newShape = retHull.CreatePhysicalHull(physicsScene, prim, newHullKey, prim.BaseShape, prim.Size, lod); + + // Check to see if mesh was created (might require an asset). + newShape = BSShapeCollection.VerifyMeshCreated(physicsScene, newShape, prim); + if (newShape.type == BSPhysicsShapeType.SHAPE_MESH) + { + // If a mesh was what was created, remember the built shape for later sharing. + Hulls.Add(newHullKey, retHull); + } + + retHull = new BSShapeHull(newShape); + retHull.physShapeInfo = newShape; + } + } + return retHull; } public override void Dereference(BSScene physicsScene) { } + List m_hulls; + private BulletShape CreatePhysicalHull(BSScene physicsScene, BSPhysObject prim, System.UInt64 newHullKey, + PrimitiveBaseShape pbs, OMV.Vector3 size, float lod) + { + BulletShape newShape = new BulletShape(); + IntPtr hullPtr = IntPtr.Zero; + + if (BSParam.ShouldUseBulletHACD) + { + physicsScene.DetailLog("{0},BSShapeCollection.CreatePhysicalHull,shouldUseBulletHACD,entry", prim.LocalID); + BSShape meshShape = BSShapeMesh.GetReference(physicsScene, true, prim); + + if (meshShape.physShapeInfo.HasPhysicalShape) + { + HACDParams parms; + parms.maxVerticesPerHull = BSParam.BHullMaxVerticesPerHull; + parms.minClusters = BSParam.BHullMinClusters; + parms.compacityWeight = BSParam.BHullCompacityWeight; + parms.volumeWeight = BSParam.BHullVolumeWeight; + parms.concavity = BSParam.BHullConcavity; + parms.addExtraDistPoints = BSParam.NumericBool(BSParam.BHullAddExtraDistPoints); + parms.addNeighboursDistPoints = BSParam.NumericBool(BSParam.BHullAddNeighboursDistPoints); + parms.addFacesPoints = BSParam.NumericBool(BSParam.BHullAddFacesPoints); + parms.shouldAdjustCollisionMargin = BSParam.NumericBool(BSParam.BHullShouldAdjustCollisionMargin); + + physicsScene.DetailLog("{0},BSShapeCollection.CreatePhysicalHull,hullFromMesh,beforeCall", prim.LocalID, newShape.HasPhysicalShape); + newShape = physicsScene.PE.BuildHullShapeFromMesh(physicsScene.World, meshShape.physShapeInfo, parms); + physicsScene.DetailLog("{0},BSShapeCollection.CreatePhysicalHull,hullFromMesh,hasBody={1}", prim.LocalID, newShape.HasPhysicalShape); + } + // Now done with the mesh shape. + meshShape.DecrementReference(); + physicsScene.DetailLog("{0},BSShapeCollection.CreatePhysicalHull,shouldUseBulletHACD,exit,hasBody={1}", prim.LocalID, newShape.HasPhysicalShape); + } + if (!newShape.HasPhysicalShape) + { + // Build a new hull in the physical world. + // Pass true for physicalness as this prevents the creation of bounding box which is not needed + IMesh meshData = physicsScene.mesher.CreateMesh(prim.PhysObjectName, pbs, size, lod, true /* isPhysical */, false /* shouldCache */); + if (meshData != null) + { + int[] indices = meshData.getIndexListAsInt(); + List vertices = meshData.getVertexList(); + + //format conversion from IMesh format to DecompDesc format + List convIndices = new List(); + List convVertices = new List(); + for (int ii = 0; ii < indices.GetLength(0); ii++) + { + convIndices.Add(indices[ii]); + } + foreach (OMV.Vector3 vv in vertices) + { + convVertices.Add(new float3(vv.X, vv.Y, vv.Z)); + } + + uint maxDepthSplit = (uint)BSParam.CSHullMaxDepthSplit; + if (BSParam.CSHullMaxDepthSplit != BSParam.CSHullMaxDepthSplitForSimpleShapes) + { + // Simple primitive shapes we know are convex so they are better implemented with + // fewer hulls. + // Check for simple shape (prim without cuts) and reduce split parameter if so. + if (BSShapeCollection.PrimHasNoCuts(pbs)) + { + maxDepthSplit = (uint)BSParam.CSHullMaxDepthSplitForSimpleShapes; + } + } + + // setup and do convex hull conversion + m_hulls = new List(); + DecompDesc dcomp = new DecompDesc(); + dcomp.mIndices = convIndices; + dcomp.mVertices = convVertices; + dcomp.mDepth = maxDepthSplit; + dcomp.mCpercent = BSParam.CSHullConcavityThresholdPercent; + dcomp.mPpercent = BSParam.CSHullVolumeConservationThresholdPercent; + dcomp.mMaxVertices = (uint)BSParam.CSHullMaxVertices; + dcomp.mSkinWidth = BSParam.CSHullMaxSkinWidth; + ConvexBuilder convexBuilder = new ConvexBuilder(HullReturn); + // create the hull into the _hulls variable + convexBuilder.process(dcomp); + + physicsScene.DetailLog("{0},BSShapeCollection.CreatePhysicalHull,key={1},inVert={2},inInd={3},split={4},hulls={5}", + BSScene.DetailLogZero, newHullKey, indices.GetLength(0), vertices.Count, maxDepthSplit, m_hulls.Count); + + // Convert the vertices and indices for passing to unmanaged. + // The hull information is passed as a large floating point array. + // The format is: + // convHulls[0] = number of hulls + // convHulls[1] = number of vertices in first hull + // convHulls[2] = hull centroid X coordinate + // convHulls[3] = hull centroid Y coordinate + // convHulls[4] = hull centroid Z coordinate + // convHulls[5] = first hull vertex X + // convHulls[6] = first hull vertex Y + // convHulls[7] = first hull vertex Z + // convHulls[8] = second hull vertex X + // ... + // convHulls[n] = number of vertices in second hull + // convHulls[n+1] = second hull centroid X coordinate + // ... + // + // TODO: is is very inefficient. Someday change the convex hull generator to return + // data structures that do not need to be converted in order to pass to Bullet. + // And maybe put the values directly into pinned memory rather than marshaling. + int hullCount = m_hulls.Count; + int totalVertices = 1; // include one for the count of the hulls + foreach (ConvexResult cr in m_hulls) + { + totalVertices += 4; // add four for the vertex count and centroid + totalVertices += cr.HullIndices.Count * 3; // we pass just triangles + } + float[] convHulls = new float[totalVertices]; + + convHulls[0] = (float)hullCount; + int jj = 1; + foreach (ConvexResult cr in m_hulls) + { + // copy vertices for index access + float3[] verts = new float3[cr.HullVertices.Count]; + int kk = 0; + foreach (float3 ff in cr.HullVertices) + { + verts[kk++] = ff; + } + + // add to the array one hull's worth of data + convHulls[jj++] = cr.HullIndices.Count; + convHulls[jj++] = 0f; // centroid x,y,z + convHulls[jj++] = 0f; + convHulls[jj++] = 0f; + foreach (int ind in cr.HullIndices) + { + convHulls[jj++] = verts[ind].x; + convHulls[jj++] = verts[ind].y; + convHulls[jj++] = verts[ind].z; + } + } + // create the hull data structure in Bullet + newShape = physicsScene.PE.CreateHullShape(physicsScene.World, hullCount, convHulls); + } + newShape.shapeKey = newHullKey; + } + return newShape; + } + // Callback from convex hull creater with a newly created hull. + // Just add it to our collection of hulls for this shape. + private void HullReturn(ConvexResult result) + { + m_hulls.Add(result); + return; + } + // Loop through all the known hulls and return the description based on the physical address. + public static bool TryGetHullByPtr(BulletShape pShape, out BSShapeHull outHull) + { + bool ret = false; + BSShapeHull foundDesc = null; + lock (Hulls) + { + foreach (BSShapeHull sh in Hulls.Values) + { + if (sh.physShapeInfo.ReferenceSame(pShape)) + { + foundDesc = sh; + ret = true; + break; + } + + } + } + outHull = foundDesc; + return ret; + } } + // ============================================================================================================ public class BSShapeCompound : BSShape { private static string LogHeader = "[BULLETSIM SHAPE COMPOUND]"; - public BSShapeCompound() : base() + public BSShapeCompound(BulletShape pShape) : base(pShape) { } - public static BSShape GetReference(BSPhysObject prim) + public static BSShape GetReference(BSScene physicsScene, BSPhysObject prim) { - return new BSShapeNull(); + // Compound shapes are not shared so a new one is created every time. + return new BSShapeCompound(CreatePhysicalCompoundShape(physicsScene, prim)); + } + // Dereferencing a compound shape releases the hold on all the child shapes. + public override void Dereference(BSScene physicsScene) + { + if (!physicsScene.PE.IsCompound(physShapeInfo)) + { + // Failed the sanity check!! + physicsScene.Logger.ErrorFormat("{0} Attempt to free a compound shape that is not compound!! type={1}, ptr={2}", + LogHeader, physShapeInfo.type, physShapeInfo.AddrString); + physicsScene.DetailLog("{0},BSShapeCollection.DereferenceCompound,notACompoundShape,type={1},ptr={2}", + BSScene.DetailLogZero, physShapeInfo.type, physShapeInfo.AddrString); + return; + } + + int numChildren = physicsScene.PE.GetNumberOfCompoundChildren(physShapeInfo); + physicsScene.DetailLog("{0},BSShapeCollection.DereferenceCompound,shape={1},children={2}", + BSScene.DetailLogZero, physShapeInfo, numChildren); + + // Loop through all the children dereferencing each. + for (int ii = numChildren - 1; ii >= 0; ii--) + { + BulletShape childShape = physicsScene.PE.RemoveChildShapeFromCompoundShapeIndex(physShapeInfo, ii); + DereferenceAnonCollisionShape(physicsScene, childShape); + } + physicsScene.PE.DeleteCollisionShape(physicsScene.World, physShapeInfo); + } + private static BulletShape CreatePhysicalCompoundShape(BSScene physicsScene, BSPhysObject prim) + { + BulletShape cShape = physicsScene.PE.CreateCompoundShape(physicsScene.World, false); + return cShape; + } + // Sometimes we have a pointer to a collision shape but don't know what type it is. + // Figure out type and call the correct dereference routine. + // Called at taint-time. + private void DereferenceAnonCollisionShape(BSScene physicsScene, BulletShape pShape) + { + BSShapeMesh meshDesc; + if (BSShapeMesh.TryGetMeshByPtr(pShape, out meshDesc)) + { + meshDesc.Dereference(physicsScene); + } + else + { + BSShapeHull hullDesc; + if (BSShapeHull.TryGetHullByPtr(pShape, out hullDesc)) + { + hullDesc.Dereference(physicsScene); + } + else + { + if (physicsScene.PE.IsCompound(pShape)) + { + BSShapeCompound recursiveCompound = new BSShapeCompound(pShape); + recursiveCompound.Dereference(physicsScene); + } + else + { + if (physicsScene.PE.IsNativeShape(pShape)) + { + BSShapeNative nativeShape = new BSShapeNative(pShape); + nativeShape.Dereference(physicsScene); + } + } + } + } } - public override void Dereference(BSScene physicsScene) { } } // ============================================================================================================ diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimTODO.txt b/OpenSim/Region/Physics/BulletSPlugin/BulletSimTODO.txt index 1284ae7..c67081a 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimTODO.txt +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimTODO.txt @@ -11,6 +11,8 @@ Deleting a linkset while standing on the root will leave the physical shape of t Linkset child rotations. Nebadon spiral tube has middle sections which are rotated wrong. Select linked spiral tube. Delink and note where the middle section ends up. +Refarb compound linkset creation to create a pseudo-root for center-of-mass + Let children change their shape to physical indendently and just add shapes to compound Vehicle angular vertical attraction vehicle angular banking Center-of-gravity @@ -27,14 +29,13 @@ llLookAt Avatars walking up stairs (HALF DONE) Avatar movement flying into a wall doesn't stop avatar who keeps appearing to move through the obstacle (DONE) - walking up stairs is not calibrated correctly (stairs out of Kepler cabin) + walking up stairs is not calibrated correctly (stairs out of Kepler cabin) (DONE) avatar capsule rotation completed (NOT DONE - Bullet's capsule shape is not the solution) Vehicle script tuning/debugging Avanti speed script Weapon shooter script Move material definitions (friction, ...) into simulator. Add material densities to the material types. -Terrain detail: double terrain mesh detail One sided meshes? Should terrain be built into a closed shape? When meshes get partially wedged into the terrain, they cannot push themselves out. It is possible that Bullet processes collisions whether entering or leaving a mesh. @@ -347,4 +348,5 @@ Angular motion around Z moves the vehicle in world Z and not vehicle Z in ODE. DONE 20130120: BulletSim properly applies force in vehicle relative coordinates. Nebadon vehicles turning funny in arena (DONE) Lock axis (DONE 20130401) +Terrain detail: double terrain mesh detail (DONE) -- cgit v1.1 From e5582939fd8d78b61c6f1eeda6de45d94f4b4926 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Sun, 28 Apr 2013 14:44:21 -0700 Subject: BulletSim: massive refactor of shape classes. Removed shape specific code from BSShapeCollection. Using BSShape* classes to hold references to shape. Simplified shape dependency callbacks. Remove 'PreferredShape' methods and have each class specify shape type. Disable compound shape linkset for a later commit that will simplify linkset implementation. --- OpenSim/Region/Physics/BulletSPlugin/BSAPIUnman.cs | 6 +- OpenSim/Region/Physics/BulletSPlugin/BSAPIXNA.cs | 4 +- .../Physics/BulletSPlugin/BSActorAvatarMove.cs | 4 +- .../Region/Physics/BulletSPlugin/BSActorHover.cs | 4 +- .../Physics/BulletSPlugin/BSActorLockAxis.cs | 4 +- .../Physics/BulletSPlugin/BSActorMoveToTarget.cs | 4 +- .../Physics/BulletSPlugin/BSActorSetForce.cs | 4 +- .../Physics/BulletSPlugin/BSActorSetTorque.cs | 4 +- OpenSim/Region/Physics/BulletSPlugin/BSActors.cs | 6 +- .../Region/Physics/BulletSPlugin/BSCharacter.cs | 19 +- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 4 +- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 9 +- .../Physics/BulletSPlugin/BSLinksetCompound.cs | 35 +- .../Physics/BulletSPlugin/BSLinksetConstraints.cs | 4 +- .../Region/Physics/BulletSPlugin/BSPhysObject.cs | 11 +- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 34 +- .../Region/Physics/BulletSPlugin/BSPrimLinkable.cs | 9 +- .../Physics/BulletSPlugin/BSShapeCollection.cs | 966 ++------------------- OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs | 203 +++-- .../Region/Physics/BulletSPlugin/BulletSimData.cs | 6 +- 20 files changed, 290 insertions(+), 1050 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSAPIUnman.cs b/OpenSim/Region/Physics/BulletSPlugin/BSAPIUnman.cs index fdf2cb9..8a22bc7 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSAPIUnman.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSAPIUnman.cs @@ -79,7 +79,7 @@ private sealed class BulletShapeUnman : BulletShape : base() { ptr = xx; - type = typ; + shapeType = typ; } public override bool HasPhysicalShape { @@ -91,7 +91,7 @@ private sealed class BulletShapeUnman : BulletShape } public override BulletShape Clone() { - return new BulletShapeUnman(ptr, type); + return new BulletShapeUnman(ptr, shapeType); } public override bool ReferenceSame(BulletShape other) { @@ -375,7 +375,7 @@ public override BulletShape DuplicateCollisionShape(BulletWorld world, BulletSha { BulletWorldUnman worldu = world as BulletWorldUnman; BulletShapeUnman srcShapeu = srcShape as BulletShapeUnman; - return new BulletShapeUnman(BSAPICPP.DuplicateCollisionShape2(worldu.ptr, srcShapeu.ptr, id), srcShape.type); + return new BulletShapeUnman(BSAPICPP.DuplicateCollisionShape2(worldu.ptr, srcShapeu.ptr, id), srcShape.shapeType); } public override bool DeleteCollisionShape(BulletWorld world, BulletShape shape) diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSAPIXNA.cs b/OpenSim/Region/Physics/BulletSPlugin/BSAPIXNA.cs index b37265a..1ef8b17 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSAPIXNA.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSAPIXNA.cs @@ -85,7 +85,7 @@ private sealed class BulletShapeXNA : BulletShape : base() { shape = xx; - type = typ; + shapeType = typ; } public override bool HasPhysicalShape { @@ -97,7 +97,7 @@ private sealed class BulletShapeXNA : BulletShape } public override BulletShape Clone() { - return new BulletShapeXNA(shape, type); + return new BulletShapeXNA(shape, shapeType); } public override bool ReferenceSame(BulletShape other) { diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs b/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs index bd5ee0b1..ac05979 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs @@ -87,8 +87,8 @@ public class BSActorAvatarMove : BSActor // The object's physical representation is being rebuilt so pick up any physical dependencies (constraints, ...). // Register a prestep action to restore physical requirements before the next simulation step. // Called at taint-time. - // BSActor.RemoveBodyDependencies() - public override void RemoveBodyDependencies() + // BSActor.RemoveDependencies() + public override void RemoveDependencies() { // Nothing to do for the hoverer since it is all software at pre-step action time. } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSActorHover.cs b/OpenSim/Region/Physics/BulletSPlugin/BSActorHover.cs index 92ace66..3630ca8 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSActorHover.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSActorHover.cs @@ -87,8 +87,8 @@ public class BSActorHover : BSActor // The object's physical representation is being rebuilt so pick up any physical dependencies (constraints, ...). // Register a prestep action to restore physical requirements before the next simulation step. // Called at taint-time. - // BSActor.RemoveBodyDependencies() - public override void RemoveBodyDependencies() + // BSActor.RemoveDependencies() + public override void RemoveDependencies() { // Nothing to do for the hoverer since it is all software at pre-step action time. } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSActorLockAxis.cs b/OpenSim/Region/Physics/BulletSPlugin/BSActorLockAxis.cs index 09ee32b..6059af5 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSActorLockAxis.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSActorLockAxis.cs @@ -85,8 +85,8 @@ public class BSActorLockAxis : BSActor // The object's physical representation is being rebuilt so pick up any physical dependencies (constraints, ...). // Register a prestep action to restore physical requirements before the next simulation step. // Called at taint-time. - // BSActor.RemoveBodyDependencies() - public override void RemoveBodyDependencies() + // BSActor.RemoveDependencies() + public override void RemoveDependencies() { if (LockAxisConstraint != null) { diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSActorMoveToTarget.cs b/OpenSim/Region/Physics/BulletSPlugin/BSActorMoveToTarget.cs index 56aacc5..1b598fd 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSActorMoveToTarget.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSActorMoveToTarget.cs @@ -88,8 +88,8 @@ public class BSActorMoveToTarget : BSActor // The object's physical representation is being rebuilt so pick up any physical dependencies (constraints, ...). // Register a prestep action to restore physical requirements before the next simulation step. // Called at taint-time. - // BSActor.RemoveBodyDependencies() - public override void RemoveBodyDependencies() + // BSActor.RemoveDependencies() + public override void RemoveDependencies() { // Nothing to do for the moveToTarget since it is all software at pre-step action time. } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSActorSetForce.cs b/OpenSim/Region/Physics/BulletSPlugin/BSActorSetForce.cs index 3ad138d..c0f40fd 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSActorSetForce.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSActorSetForce.cs @@ -89,8 +89,8 @@ public class BSActorSetForce : BSActor // The object's physical representation is being rebuilt so pick up any physical dependencies (constraints, ...). // Register a prestep action to restore physical requirements before the next simulation step. // Called at taint-time. - // BSActor.RemoveBodyDependencies() - public override void RemoveBodyDependencies() + // BSActor.RemoveDependencies() + public override void RemoveDependencies() { // Nothing to do for the hoverer since it is all software at pre-step action time. } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSActorSetTorque.cs b/OpenSim/Region/Physics/BulletSPlugin/BSActorSetTorque.cs index 7a791ec..b3806e1 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSActorSetTorque.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSActorSetTorque.cs @@ -89,8 +89,8 @@ public class BSActorSetTorque : BSActor // The object's physical representation is being rebuilt so pick up any physical dependencies (constraints, ...). // Register a prestep action to restore physical requirements before the next simulation step. // Called at taint-time. - // BSActor.RemoveBodyDependencies() - public override void RemoveBodyDependencies() + // BSActor.RemoveDependencies() + public override void RemoveDependencies() { // Nothing to do for the hoverer since it is all software at pre-step action time. } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSActors.cs b/OpenSim/Region/Physics/BulletSPlugin/BSActors.cs index 12a8817..5e3f1c4 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSActors.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSActors.cs @@ -106,9 +106,9 @@ public class BSActorCollection { ForEachActor(a => a.Refresh()); } - public void RemoveBodyDependencies() + public void RemoveDependencies() { - ForEachActor(a => a.RemoveBodyDependencies()); + ForEachActor(a => a.RemoveDependencies()); } } @@ -154,7 +154,7 @@ public abstract class BSActor public abstract void Refresh(); // The object's physical representation is being rebuilt so pick up any physical dependencies (constraints, ...). // Register a prestep action to restore physical requirements before the next simulation step. - public abstract void RemoveBodyDependencies(); + public abstract void RemoveDependencies(); } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index a0d58d3..da23a262 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -123,8 +123,8 @@ public sealed class BSCharacter : BSPhysObject { PhysicsScene.Shapes.DereferenceBody(PhysBody, null /* bodyCallback */); PhysBody.Clear(); - PhysicsScene.Shapes.DereferenceShape(PhysShape, null /* bodyCallback */); - PhysShape.Clear(); + PhysShape.Dereference(PhysicsScene); + PhysShape = new BSShapeNull(); }); } @@ -146,8 +146,8 @@ public sealed class BSCharacter : BSPhysObject Flying = _flying; PhysicsScene.PE.SetRestitution(PhysBody, BSParam.AvatarRestitution); - PhysicsScene.PE.SetMargin(PhysShape, PhysicsScene.Params.collisionMargin); - PhysicsScene.PE.SetLocalScaling(PhysShape, Scale); + PhysicsScene.PE.SetMargin(PhysShape.physShapeInfo, PhysicsScene.Params.collisionMargin); + PhysicsScene.PE.SetLocalScaling(PhysShape.physShapeInfo, Scale); PhysicsScene.PE.SetContactProcessingThreshold(PhysBody, BSParam.ContactProcessingThreshold); if (BSParam.CcdMotionThreshold > 0f) { @@ -205,9 +205,9 @@ public sealed class BSCharacter : BSPhysObject PhysicsScene.TaintedObject("BSCharacter.setSize", delegate() { - if (PhysBody.HasPhysicalBody && PhysShape.HasPhysicalShape) + if (PhysBody.HasPhysicalBody && PhysShape.physShapeInfo.HasPhysicalShape) { - PhysicsScene.PE.SetLocalScaling(PhysShape, Scale); + PhysicsScene.PE.SetLocalScaling(PhysShape.physShapeInfo, Scale); UpdatePhysicalMassProperties(RawMass, true); // Make sure this change appears as a property update event PhysicsScene.PE.PushUpdate(PhysBody); @@ -221,11 +221,6 @@ public sealed class BSCharacter : BSPhysObject { set { BaseShape = value; } } - // I want the physics engine to make an avatar capsule - public override BSPhysicsShapeType PreferredPhysicalShape - { - get {return BSPhysicsShapeType.SHAPE_CAPSULE; } - } public override bool Grabbed { set { _grabbed = value; } @@ -381,7 +376,7 @@ public sealed class BSCharacter : BSPhysObject } public override void UpdatePhysicalMassProperties(float physMass, bool inWorld) { - OMV.Vector3 localInertia = PhysicsScene.PE.CalculateLocalInertia(PhysShape, physMass); + OMV.Vector3 localInertia = PhysicsScene.PE.CalculateLocalInertia(PhysShape.physShapeInfo, physMass); PhysicsScene.PE.SetMassProps(PhysBody, physMass, localInertia); } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index 612c68b..e2e807e 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -625,7 +625,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin // Vehicles report collision events so we know when it's on the ground m_physicsScene.PE.AddToCollisionFlags(ControllingPrim.PhysBody, CollisionFlags.BS_VEHICLE_COLLISIONS); - ControllingPrim.Inertia = m_physicsScene.PE.CalculateLocalInertia(ControllingPrim.PhysShape, m_vehicleMass); + ControllingPrim.Inertia = m_physicsScene.PE.CalculateLocalInertia(ControllingPrim.PhysShape.physShapeInfo, m_vehicleMass); m_physicsScene.PE.SetMassProps(ControllingPrim.PhysBody, m_vehicleMass, ControllingPrim.Inertia); m_physicsScene.PE.UpdateInertiaTensor(ControllingPrim.PhysBody); @@ -649,7 +649,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin } // BSActor.RemoveBodyDependencies - public override void RemoveBodyDependencies() + public override void RemoveDependencies() { Refresh(); } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index 4ece1eb..df1dd34 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -93,13 +93,6 @@ public abstract class BSLinkset // to the physical representation is done via the tainting mechenism. protected object m_linksetActivityLock = new Object(); - // Some linksets have a preferred physical shape. - // Returns SHAPE_UNKNOWN if there is no preference. Causes the correct shape to be selected. - public virtual BSPhysicsShapeType PreferredPhysicalShape(BSPrimLinkable requestor) - { - return BSPhysicsShapeType.SHAPE_UNKNOWN; - } - // We keep the prim's mass in the linkset structure since it could be dependent on other prims public float LinksetMass { get; protected set; } @@ -263,7 +256,7 @@ public abstract class BSLinkset // This is called when the root body is changing. // Returns 'true' of something was actually removed and would need restoring // Called at taint-time!! - public abstract bool RemoveBodyDependencies(BSPrimLinkable child); + public abstract bool RemoveDependencies(BSPrimLinkable child); // ================================================================ protected virtual float ComputeLinksetMass() diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs index e05562a..a20bbc3 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs @@ -98,19 +98,6 @@ public sealed class BSLinksetCompound : BSLinkset { } - // For compound implimented linksets, if there are children, use compound shape for the root. - public override BSPhysicsShapeType PreferredPhysicalShape(BSPrimLinkable requestor) - { - // Returning 'unknown' means we don't have a preference. - BSPhysicsShapeType ret = BSPhysicsShapeType.SHAPE_UNKNOWN; - if (IsRoot(requestor) && HasAnyChildren) - { - ret = BSPhysicsShapeType.SHAPE_COMPOUND; - } - // DetailLog("{0},BSLinksetCompound.PreferredPhysicalShape,call,shape={1}", LinksetRoot.LocalID, ret); - return ret; - } - // When physical properties are changed the linkset needs to recalculate // its internal properties. public override void Refresh(BSPrimLinkable requestor) @@ -218,22 +205,22 @@ public sealed class BSLinksetCompound : BSLinkset // and that is caused by us updating the object. if ((whichUpdated & ~(UpdatedProperties.Position | UpdatedProperties.Orientation)) == 0) { - // Find the physical instance of the child - if (LinksetRoot.PhysShape.HasPhysicalShape && PhysicsScene.PE.IsCompound(LinksetRoot.PhysShape)) + // Find the physical instance of the child + if (LinksetRoot.PhysShape.HasPhysicalShape && PhysicsScene.PE.IsCompound(LinksetRoot.PhysShape.physShapeInfo)) { // It is possible that the linkset is still under construction and the child is not yet // inserted into the compound shape. A rebuild of the linkset in a pre-step action will // build the whole thing with the new position or rotation. // The index must be checked because Bullet references the child array but does no validity // checking of the child index passed. - int numLinksetChildren = PhysicsScene.PE.GetNumberOfCompoundChildren(LinksetRoot.PhysShape); + int numLinksetChildren = PhysicsScene.PE.GetNumberOfCompoundChildren(LinksetRoot.PhysShape.physShapeInfo); if (updated.LinksetChildIndex < numLinksetChildren) { - BulletShape linksetChildShape = PhysicsScene.PE.GetChildShapeFromCompoundShapeIndex(LinksetRoot.PhysShape, updated.LinksetChildIndex); + BulletShape linksetChildShape = PhysicsScene.PE.GetChildShapeFromCompoundShapeIndex(LinksetRoot.PhysShape.physShapeInfo, updated.LinksetChildIndex); if (linksetChildShape.HasPhysicalShape) { // Found the child shape within the compound shape - PhysicsScene.PE.UpdateChildTransform(LinksetRoot.PhysShape, updated.LinksetChildIndex, + PhysicsScene.PE.UpdateChildTransform(LinksetRoot.PhysShape.physShapeInfo, updated.LinksetChildIndex, updated.RawPosition - LinksetRoot.RawPosition, updated.RawOrientation * OMV.Quaternion.Inverse(LinksetRoot.RawOrientation), true /* shouldRecalculateLocalAabb */); @@ -278,7 +265,7 @@ public sealed class BSLinksetCompound : BSLinkset // Since we don't keep in world relationships, do nothing unless it's a child changing. // Returns 'true' of something was actually removed and would need restoring // Called at taint-time!! - public override bool RemoveBodyDependencies(BSPrimLinkable child) + public override bool RemoveDependencies(BSPrimLinkable child) { bool ret = false; @@ -404,11 +391,12 @@ public sealed class BSLinksetCompound : BSLinkset { try { + /* // Suppress rebuilding while rebuilding. (We know rebuilding is on only one thread.) Rebuilding = true; // Cause the root shape to be rebuilt as a compound object with just the root in it - LinksetRoot.ForceBodyShapeRebuild(true /* inTaintTime */); + LinksetRoot.ForceBodyShapeRebuild(true /* inTaintTime ); // The center of mass for the linkset is the geometric center of the group. // Compute a displacement for each component so it is relative to the center-of-mass. @@ -430,10 +418,10 @@ public sealed class BSLinksetCompound : BSLinkset LinksetRoot.ForcePosition = LinksetRoot.RawPosition; // Update the local transform for the root child shape so it is offset from the <0,0,0> which is COM - PhysicsScene.PE.UpdateChildTransform(LinksetRoot.PhysShape, 0 /* childIndex */, + PhysicsScene.PE.UpdateChildTransform(LinksetRoot.PhysShape.physShapeInfo, 0 /* childIndex , -centerDisplacement, OMV.Quaternion.Identity, // LinksetRoot.RawOrientation, - false /* shouldRecalculateLocalAabb (is done later after linkset built) */); + false /* shouldRecalculateLocalAabb (is done later after linkset built) ); DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,COM,com={1},rootPos={2},centerDisp={3}", LinksetRoot.LocalID, centerOfMassW, LinksetRoot.RawPosition, centerDisplacement); @@ -501,6 +489,7 @@ public sealed class BSLinksetCompound : BSLinkset // Enable the physical position updator to return the position and rotation of the root shape PhysicsScene.PE.AddToCollisionFlags(LinksetRoot.PhysBody, CollisionFlags.BS_RETURN_ROOT_COMPOUND_SHAPE); + */ } finally { @@ -508,7 +497,7 @@ public sealed class BSLinksetCompound : BSLinkset } // See that the Aabb surrounds the new shape - PhysicsScene.PE.RecalculateCompoundShapeLocalAabb(LinksetRoot.PhysShape); + PhysicsScene.PE.RecalculateCompoundShapeLocalAabb(LinksetRoot.PhysShape.physShapeInfo); } } } \ No newline at end of file diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs index 6d252ca..1811772 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs @@ -93,11 +93,11 @@ public sealed class BSLinksetConstraints : BSLinkset // up to rebuild the constraints before the next simulation step. // Returns 'true' of something was actually removed and would need restoring // Called at taint-time!! - public override bool RemoveBodyDependencies(BSPrimLinkable child) + public override bool RemoveDependencies(BSPrimLinkable child) { bool ret = false; - DetailLog("{0},BSLinksetConstraint.RemoveBodyDependencies,removeChildrenForRoot,rID={1},rBody={2}", + DetailLog("{0},BSLinksetConstraint.RemoveDependencies,removeChildrenForRoot,rID={1},rBody={2}", child.LocalID, LinksetRoot.LocalID, LinksetRoot.PhysBody.AddrString); lock (m_linksetActivityLock) diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index 309d004..b6eb619 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -88,7 +88,7 @@ public abstract class BSPhysObject : PhysicsActor // We don't have any physical representation yet. PhysBody = new BulletBody(localID); - PhysShape = new BulletShape(); + PhysShape = new BSShapeNull(); PrimAssetState = PrimAssetCondition.Unknown; @@ -138,7 +138,7 @@ public abstract class BSPhysObject : PhysicsActor // Reference to the physical body (btCollisionObject) of this object public BulletBody PhysBody; // Reference to the physical shape (btCollisionShape) of this object - public BulletShape PhysShape; + public BSShape PhysShape; // The physical representation of the prim might require an asset fetch. // The asset state is first 'Unknown' then 'Waiting' then either 'Failed' or 'Fetched'. @@ -151,13 +151,6 @@ public abstract class BSPhysObject : PhysicsActor // The objects base shape information. Null if not a prim type shape. public PrimitiveBaseShape BaseShape { get; protected set; } - // Some types of objects have preferred physical representations. - // Returns SHAPE_UNKNOWN if there is no preference. - public virtual BSPhysicsShapeType PreferredPhysicalShape - { - get { return BSPhysicsShapeType.SHAPE_UNKNOWN; } - } - // When the physical properties are updated, an EntityProperty holds the update values. // Keep the current and last EntityProperties to enable computation of differences // between the current update and the previous values. diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 4bc266b..5d12338 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -134,8 +134,8 @@ public class BSPrim : BSPhysObject // If there are physical body and shape, release my use of same. PhysicsScene.Shapes.DereferenceBody(PhysBody, null); PhysBody.Clear(); - PhysicsScene.Shapes.DereferenceShape(PhysShape, null); - PhysShape.Clear(); + PhysShape.Dereference(PhysicsScene); + PhysShape = new BSShapeNull(); }); } @@ -161,25 +161,13 @@ public class BSPrim : BSPhysObject ForceBodyShapeRebuild(false); } } - // 'unknown' says to choose the best type - public override BSPhysicsShapeType PreferredPhysicalShape - { get { return BSPhysicsShapeType.SHAPE_UNKNOWN; } } - public override bool ForceBodyShapeRebuild(bool inTaintTime) { - if (inTaintTime) + PhysicsScene.TaintedObject(inTaintTime, "BSPrim.ForceBodyShapeRebuild", delegate() { _mass = CalculateMass(); // changing the shape changes the mass CreateGeomAndObject(true); - } - else - { - PhysicsScene.TaintedObject("BSPrim.ForceBodyShapeRebuild", delegate() - { - _mass = CalculateMass(); // changing the shape changes the mass - CreateGeomAndObject(true); - }); - } + }); return true; } public override bool Grabbed { @@ -462,7 +450,7 @@ public class BSPrim : BSPhysObject Gravity = ComputeGravity(Buoyancy); PhysicsScene.PE.SetGravity(PhysBody, Gravity); - Inertia = PhysicsScene.PE.CalculateLocalInertia(PhysShape, physMass); + Inertia = PhysicsScene.PE.CalculateLocalInertia(PhysShape.physShapeInfo, physMass); PhysicsScene.PE.SetMassProps(PhysBody, physMass, Inertia); PhysicsScene.PE.UpdateInertiaTensor(PhysBody); @@ -805,7 +793,8 @@ public class BSPrim : BSPhysObject PhysicsScene.PE.UpdateSingleAabb(PhysicsScene.World, PhysBody); DetailLog("{0},BSPrim.UpdatePhysicalParameters,taintExit,static={1},solid={2},mass={3},collide={4},cf={5:X},cType={6},body={7},shape={8}", - LocalID, IsStatic, IsSolid, Mass, SubscribedEvents(), CurrentCollisionFlags, PhysBody.collisionType, PhysBody, PhysShape); + LocalID, IsStatic, IsSolid, Mass, SubscribedEvents(), + CurrentCollisionFlags, PhysBody.collisionType, PhysBody, PhysShape); } // "Making dynamic" means changing to and from static. @@ -1463,12 +1452,13 @@ public class BSPrim : BSPhysObject // Create the correct physical representation for this type of object. // Updates base.PhysBody and base.PhysShape with the new information. // Ignore 'forceRebuild'. 'GetBodyAndShape' makes the right choices and changes of necessary. - PhysicsScene.Shapes.GetBodyAndShape(false /*forceRebuild */, PhysicsScene.World, this, null, delegate(BulletBody dBody) + PhysicsScene.Shapes.GetBodyAndShape(false /*forceRebuild */, PhysicsScene.World, this, delegate(BulletBody pBody, BulletShape pShape) { // Called if the current prim body is about to be destroyed. // Remove all the physical dependencies on the old body. // (Maybe someday make the changing of BSShape an event to be subscribed to by BSLinkset, ...) - RemoveBodyDependencies(); + // Note: this virtual function is overloaded by BSPrimLinkable to remove linkset constraints. + RemoveDependencies(); }); // Make sure the properties are set on the new object @@ -1477,9 +1467,9 @@ public class BSPrim : BSPhysObject } // Called at taint-time - protected virtual void RemoveBodyDependencies() + protected virtual void RemoveDependencies() { - PhysicalActors.RemoveBodyDependencies(); + PhysicalActors.RemoveDependencies(); } // The physics engine says that properties have updated. Update same and inform diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs index 28242d4..81104ec 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs @@ -61,9 +61,6 @@ public class BSPrimLinkable : BSPrimDisplaced base.Destroy(); } - public override BSPhysicsShapeType PreferredPhysicalShape - { get { return Linkset.PreferredPhysicalShape(this); } } - public override void link(Manager.PhysicsActor obj) { BSPrimLinkable parent = obj as BSPrimLinkable; @@ -149,10 +146,10 @@ public class BSPrimLinkable : BSPrimDisplaced } // Body is being taken apart. Remove physical dependencies and schedule a rebuild. - protected override void RemoveBodyDependencies() + protected override void RemoveDependencies() { - Linkset.RemoveBodyDependencies(this); - base.RemoveBodyDependencies(); + Linkset.RemoveDependencies(this); + base.RemoveDependencies(); } public override void UpdateProperties(EntityProperties entprop) diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index 0f9b3c3..3c23509 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -38,38 +38,15 @@ public sealed class BSShapeCollection : IDisposable { private static string LogHeader = "[BULLETSIM SHAPE COLLECTION]"; - private BSScene PhysicsScene { get; set; } + private BSScene m_physicsScene { get; set; } private Object m_collectionActivityLock = new Object(); - // Description of a Mesh - private struct MeshDesc - { - public BulletShape shape; - public int referenceCount; - public DateTime lastReferenced; - public UInt64 shapeKey; - } - - // Description of a hull. - // Meshes and hulls have the same shape hash key but we only need hulls for efficient collision calculations. - private struct HullDesc - { - public BulletShape shape; - public int referenceCount; - public DateTime lastReferenced; - public UInt64 shapeKey; - } - - // The sharable set of meshes and hulls. Indexed by their shape hash. - private Dictionary Meshes = new Dictionary(); - private Dictionary Hulls = new Dictionary(); - private bool DDetail = false; public BSShapeCollection(BSScene physScene) { - PhysicsScene = physScene; + m_physicsScene = physScene; // Set the next to 'true' for very detailed shape update detailed logging (detailed details?) // While detailed debugging is still active, this is better than commenting out all the // DetailLog statements. When debugging slows down, this and the protected logging @@ -86,22 +63,18 @@ public sealed class BSShapeCollection : IDisposable // Mostly used for changing bodies out from under Linksets. // Useful for other cases where parameters need saving. // Passing 'null' says no callback. - public delegate void ShapeDestructionCallback(BulletShape shape); - public delegate void BodyDestructionCallback(BulletBody body); + public delegate void PhysicalDestructionCallback(BulletBody pBody, BulletShape pShape); // Called to update/change the body and shape for an object. - // First checks the shape and updates that if necessary then makes - // sure the body is of the right type. + // The object has some shape and body on it. Here we decide if that is the correct shape + // for the current state of the object (static/dynamic/...). + // If bodyCallback is not null, it is called if either the body or the shape are changed + // so dependencies (like constraints) can be removed before the physical object is dereferenced. // Return 'true' if either the body or the shape changed. - // 'shapeCallback' and 'bodyCallback' are, if non-null, functions called just before - // the current shape or body is destroyed. This allows the caller to remove any - // higher level dependencies on the shape or body. Mostly used for LinkSets to - // remove the physical constraints before the body is destroyed. - // Called at taint-time!! - public bool GetBodyAndShape(bool forceRebuild, BulletWorld sim, BSPhysObject prim, - ShapeDestructionCallback shapeCallback, BodyDestructionCallback bodyCallback) + // Called at taint-time. + public bool GetBodyAndShape(bool forceRebuild, BulletWorld sim, BSPhysObject prim, PhysicalDestructionCallback bodyCallback) { - PhysicsScene.AssertInTaintTime("BSShapeCollection.GetBodyAndShape"); + m_physicsScene.AssertInTaintTime("BSShapeCollection.GetBodyAndShape"); bool ret = false; @@ -111,12 +84,12 @@ public sealed class BSShapeCollection : IDisposable // Do we have the correct geometry for this type of object? // Updates prim.BSShape with information/pointers to shape. // Returns 'true' of BSShape is changed to a new shape. - bool newGeom = CreateGeom(forceRebuild, prim, shapeCallback); + bool newGeom = CreateGeom(forceRebuild, prim, bodyCallback); // If we had to select a new shape geometry for the object, // rebuild the body around it. // Updates prim.BSBody with information/pointers to requested body // Returns 'true' if BSBody was changed. - bool newBody = CreateBody((newGeom || forceRebuild), prim, PhysicsScene.World, bodyCallback); + bool newBody = CreateBody((newGeom || forceRebuild), prim, m_physicsScene.World, bodyCallback); ret = newGeom || newBody; } DetailLog("{0},BSShapeCollection.GetBodyAndShape,taintExit,force={1},ret={2},body={3},shape={4}", @@ -127,271 +100,20 @@ public sealed class BSShapeCollection : IDisposable public bool GetBodyAndShape(bool forceRebuild, BulletWorld sim, BSPhysObject prim) { - return GetBodyAndShape(forceRebuild, sim, prim, null, null); - } - - // Track another user of a body. - // We presume the caller has allocated the body. - // Bodies only have one user so the body is just put into the world if not already there. - private void ReferenceBody(BulletBody body) - { - lock (m_collectionActivityLock) - { - if (DDetail) DetailLog("{0},BSShapeCollection.ReferenceBody,newBody,body={1}", body.ID, body); - if (!PhysicsScene.PE.IsInWorld(PhysicsScene.World, body)) - { - PhysicsScene.PE.AddObjectToWorld(PhysicsScene.World, body); - if (DDetail) DetailLog("{0},BSShapeCollection.ReferenceBody,addedToWorld,ref={1}", body.ID, body); - } - } - } - - // Release the usage of a body. - // Called when releasing use of a BSBody. BSShape is handled separately. - // Called in taint time. - public void DereferenceBody(BulletBody body, BodyDestructionCallback bodyCallback ) - { - if (!body.HasPhysicalBody) - return; - - PhysicsScene.AssertInTaintTime("BSShapeCollection.DereferenceBody"); - - lock (m_collectionActivityLock) - { - if (DDetail) DetailLog("{0},BSShapeCollection.DereferenceBody,DestroyingBody,body={1}", body.ID, body); - // If the caller needs to know the old body is going away, pass the event up. - if (bodyCallback != null) bodyCallback(body); - - // Removing an object not in the world is a NOOP - PhysicsScene.PE.RemoveObjectFromWorld(PhysicsScene.World, body); - - // Zero any reference to the shape so it is not freed when the body is deleted. - PhysicsScene.PE.SetCollisionShape(PhysicsScene.World, body, null); - PhysicsScene.PE.DestroyObject(PhysicsScene.World, body); - } - } - - // Track the datastructures and use count for a shape. - // When creating a hull, this is called first to reference the mesh - // and then again to reference the hull. - // Meshes and hulls for the same shape have the same hash key. - // NOTE that native shapes are not added to the mesh list or removed. - // Returns 'true' if this is the initial reference to the shape. Otherwise reused. - public bool ReferenceShape(BulletShape shape) - { - bool ret = false; - switch (shape.type) - { - case BSPhysicsShapeType.SHAPE_MESH: - MeshDesc meshDesc; - if (Meshes.TryGetValue(shape.shapeKey, out meshDesc)) - { - // There is an existing instance of this mesh. - meshDesc.referenceCount++; - if (DDetail) DetailLog("{0},BSShapeCollection.ReferenceShape,existingMesh,key={1},cnt={2}", - BSScene.DetailLogZero, shape.shapeKey.ToString("X"), meshDesc.referenceCount); - } - else - { - // This is a new reference to a mesh - meshDesc.shape = shape.Clone(); - meshDesc.shapeKey = shape.shapeKey; - // We keep a reference to the underlying IMesh data so a hull can be built - meshDesc.referenceCount = 1; - if (DDetail) DetailLog("{0},BSShapeCollection.ReferenceShape,newMesh,key={1},cnt={2}", - BSScene.DetailLogZero, shape.shapeKey.ToString("X"), meshDesc.referenceCount); - ret = true; - } - meshDesc.lastReferenced = System.DateTime.Now; - Meshes[shape.shapeKey] = meshDesc; - break; - case BSPhysicsShapeType.SHAPE_HULL: - HullDesc hullDesc; - if (Hulls.TryGetValue(shape.shapeKey, out hullDesc)) - { - // There is an existing instance of this hull. - hullDesc.referenceCount++; - if (DDetail) DetailLog("{0},BSShapeCollection.ReferenceShape,existingHull,key={1},cnt={2}", - BSScene.DetailLogZero, shape.shapeKey.ToString("X"), hullDesc.referenceCount); - } - else - { - // This is a new reference to a hull - hullDesc.shape = shape.Clone(); - hullDesc.shapeKey = shape.shapeKey; - hullDesc.referenceCount = 1; - if (DDetail) DetailLog("{0},BSShapeCollection.ReferenceShape,newHull,key={1},cnt={2}", - BSScene.DetailLogZero, shape.shapeKey.ToString("X"), hullDesc.referenceCount); - ret = true; - - } - hullDesc.lastReferenced = System.DateTime.Now; - Hulls[shape.shapeKey] = hullDesc; - break; - case BSPhysicsShapeType.SHAPE_UNKNOWN: - break; - default: - // Native shapes are not tracked and they don't go into any list - break; - } - return ret; - } - - // Release the usage of a shape. - public void DereferenceShape(BulletShape shape, ShapeDestructionCallback shapeCallback) - { - if (!shape.HasPhysicalShape) - return; - - PhysicsScene.AssertInTaintTime("BSShapeCollection.DereferenceShape"); - - if (shape.HasPhysicalShape) - { - if (shape.isNativeShape) - { - // Native shapes are not tracked and are released immediately - if (DDetail) DetailLog("{0},BSShapeCollection.DereferenceShape,deleteNativeShape,ptr={1}", - BSScene.DetailLogZero, shape.AddrString); - if (shapeCallback != null) shapeCallback(shape); - PhysicsScene.PE.DeleteCollisionShape(PhysicsScene.World, shape); - } - else - { - switch (shape.type) - { - case BSPhysicsShapeType.SHAPE_HULL: - DereferenceHull(shape, shapeCallback); - break; - case BSPhysicsShapeType.SHAPE_MESH: - DereferenceMesh(shape, shapeCallback); - break; - case BSPhysicsShapeType.SHAPE_COMPOUND: - DereferenceCompound(shape, shapeCallback); - break; - case BSPhysicsShapeType.SHAPE_UNKNOWN: - break; - default: - break; - } - } - } - } - - // Count down the reference count for a mesh shape - // Called at taint-time. - private void DereferenceMesh(BulletShape shape, ShapeDestructionCallback shapeCallback) - { - MeshDesc meshDesc; - if (Meshes.TryGetValue(shape.shapeKey, out meshDesc)) - { - meshDesc.referenceCount--; - // TODO: release the Bullet storage - if (shapeCallback != null) shapeCallback(shape); - meshDesc.lastReferenced = System.DateTime.Now; - Meshes[shape.shapeKey] = meshDesc; - if (DDetail) DetailLog("{0},BSShapeCollection.DereferenceMesh,shape={1},refCnt={2}", - BSScene.DetailLogZero, shape, meshDesc.referenceCount); - - } + return GetBodyAndShape(forceRebuild, sim, prim, null); } - // Count down the reference count for a hull shape - // Called at taint-time. - private void DereferenceHull(BulletShape shape, ShapeDestructionCallback shapeCallback) + // If the existing prim's shape is to be replaced, remove the tie to the existing shape + // before replacing it. + private void DereferenceExistingShape(BSPhysObject prim, PhysicalDestructionCallback shapeCallback) { - HullDesc hullDesc; - if (Hulls.TryGetValue(shape.shapeKey, out hullDesc)) + if (prim.PhysShape.HasPhysicalShape) { - hullDesc.referenceCount--; - // TODO: release the Bullet storage (aging old entries?) - - // Tell upper layers that, if they have dependencies on this shape, this link is going away - if (shapeCallback != null) shapeCallback(shape); - - hullDesc.lastReferenced = System.DateTime.Now; - Hulls[shape.shapeKey] = hullDesc; - if (DDetail) DetailLog("{0},BSShapeCollection.DereferenceHull,shape={1},refCnt={2}", - BSScene.DetailLogZero, shape, hullDesc.referenceCount); - } - } - - // Remove a reference to a compound shape. - // Taking a compound shape apart is a little tricky because if you just delete the - // physical shape, it will free all the underlying children. We can't do that because - // they could be shared. So, this removes each of the children from the compound and - // dereferences them separately before destroying the compound collision object itself. - // Called at taint-time. - private void DereferenceCompound(BulletShape shape, ShapeDestructionCallback shapeCallback) - { - if (!PhysicsScene.PE.IsCompound(shape)) - { - // Failed the sanity check!! - PhysicsScene.Logger.ErrorFormat("{0} Attempt to free a compound shape that is not compound!! type={1}, ptr={2}", - LogHeader, shape.type, shape.AddrString); - if (DDetail) DetailLog("{0},BSShapeCollection.DereferenceCompound,notACompoundShape,type={1},ptr={2}", - BSScene.DetailLogZero, shape.type, shape.AddrString); - return; - } - - int numChildren = PhysicsScene.PE.GetNumberOfCompoundChildren(shape); - if (DDetail) DetailLog("{0},BSShapeCollection.DereferenceCompound,shape={1},children={2}", BSScene.DetailLogZero, shape, numChildren); - - for (int ii = numChildren - 1; ii >= 0; ii--) - { - BulletShape childShape = PhysicsScene.PE.RemoveChildShapeFromCompoundShapeIndex(shape, ii); - DereferenceAnonCollisionShape(childShape); - } - PhysicsScene.PE.DeleteCollisionShape(PhysicsScene.World, shape); - } - - // Sometimes we have a pointer to a collision shape but don't know what type it is. - // Figure out type and call the correct dereference routine. - // Called at taint-time. - private void DereferenceAnonCollisionShape(BulletShape shapeInfo) - { - MeshDesc meshDesc; - HullDesc hullDesc; - - if (TryGetMeshByPtr(shapeInfo, out meshDesc)) - { - shapeInfo.type = BSPhysicsShapeType.SHAPE_MESH; - shapeInfo.shapeKey = meshDesc.shapeKey; - } - else - { - if (TryGetHullByPtr(shapeInfo, out hullDesc)) - { - shapeInfo.type = BSPhysicsShapeType.SHAPE_HULL; - shapeInfo.shapeKey = hullDesc.shapeKey; - } - else - { - if (PhysicsScene.PE.IsCompound(shapeInfo)) - { - shapeInfo.type = BSPhysicsShapeType.SHAPE_COMPOUND; - } - else - { - if (PhysicsScene.PE.IsNativeShape(shapeInfo)) - { - shapeInfo.isNativeShape = true; - shapeInfo.type = BSPhysicsShapeType.SHAPE_BOX; // (technically, type doesn't matter) - } - } - } - } - - if (DDetail) DetailLog("{0},BSShapeCollection.DereferenceAnonCollisionShape,shape={1}", BSScene.DetailLogZero, shapeInfo); - - if (shapeInfo.type != BSPhysicsShapeType.SHAPE_UNKNOWN) - { - DereferenceShape(shapeInfo, null); - } - else - { - PhysicsScene.Logger.ErrorFormat("{0} Could not decypher shape type. Region={1}, addr={2}", - LogHeader, PhysicsScene.RegionName, shapeInfo.AddrString); + if (shapeCallback != null) + shapeCallback(prim.PhysBody, prim.PhysShape.physShapeInfo); + prim.PhysShape.Dereference(m_physicsScene); } + prim.PhysShape = new BSShapeNull(); } // Create the geometry information in Bullet for later use. @@ -402,40 +124,7 @@ public sealed class BSShapeCollection : IDisposable // Info in prim.BSShape is updated to the new shape. // Returns 'true' if the geometry was rebuilt. // Called at taint-time! - private bool CreateGeom(bool forceRebuild, BSPhysObject prim, ShapeDestructionCallback shapeCallback) - { - bool ret = false; - bool haveShape = false; - - if (!haveShape && prim.PreferredPhysicalShape == BSPhysicsShapeType.SHAPE_CAPSULE) - { - // an avatar capsule is close to a native shape (it is not shared) - GetReferenceToNativeShape(prim, BSPhysicsShapeType.SHAPE_CAPSULE, FixedShapeKey.KEY_CAPSULE, shapeCallback); - if (DDetail) DetailLog("{0},BSShapeCollection.CreateGeom,avatarCapsule,shape={1}", prim.LocalID, prim.PhysShape); - ret = true; - haveShape = true; - } - - // Compound shapes are handled special as they are rebuilt from scratch. - // This isn't too great a hardship since most of the child shapes will have already been created. - if (!haveShape && prim.PreferredPhysicalShape == BSPhysicsShapeType.SHAPE_COMPOUND) - { - ret = GetReferenceToCompoundShape(prim, shapeCallback); - if (DDetail) DetailLog("{0},BSShapeCollection.CreateGeom,compoundShape,shape={1}", prim.LocalID, prim.PhysShape); - haveShape = true; - } - - if (!haveShape) - { - ret = CreateGeomNonSpecial(forceRebuild, prim, shapeCallback); - } - - return ret; - } - - // Create a mesh, hull or native shape. - // Return 'true' if the prim's shape was changed. - public bool CreateGeomNonSpecial(bool forceRebuild, BSPhysObject prim, ShapeDestructionCallback shapeCallback) + private bool CreateGeom(bool forceRebuild, BSPhysObject prim, PhysicalDestructionCallback shapeCallback) { bool ret = false; bool haveShape = false; @@ -443,19 +132,21 @@ public sealed class BSShapeCollection : IDisposable PrimitiveBaseShape pbs = prim.BaseShape; // If the prim attributes are simple, this could be a simple Bullet native shape + // Native shapes work whether to object is static or physical. if (!haveShape && nativeShapePossible && pbs != null - && !pbs.SculptEntry - && ((pbs.SculptEntry && !BSParam.ShouldMeshSculptedPrim) || PrimHasNoCuts(pbs)) ) + && PrimHasNoCuts(pbs) + && ( !pbs.SculptEntry || (pbs.SculptEntry && !BSParam.ShouldMeshSculptedPrim) ) + ) { // Get the scale of any existing shape so we can see if the new shape is same native type and same size. OMV.Vector3 scaleOfExistingShape = OMV.Vector3.Zero; if (prim.PhysShape.HasPhysicalShape) - scaleOfExistingShape = PhysicsScene.PE.GetLocalScaling(prim.PhysShape); + scaleOfExistingShape = m_physicsScene.PE.GetLocalScaling(prim.PhysShape.physShapeInfo); if (DDetail) DetailLog("{0},BSShapeCollection.CreateGeom,maybeNative,force={1},primScale={2},primSize={3},primShape={4}", - prim.LocalID, forceRebuild, prim.Scale, prim.Size, prim.PhysShape.type); + prim.LocalID, forceRebuild, prim.Scale, prim.Size, prim.PhysShape.physShapeInfo.shapeType); // It doesn't look like Bullet scales native spheres so make sure the scales are all equal if ((pbs.ProfileShape == ProfileShape.HalfCircle && pbs.PathCurve == (byte)Extrusion.Curve1) @@ -463,26 +154,28 @@ public sealed class BSShapeCollection : IDisposable { haveShape = true; if (forceRebuild - || prim.Scale != scaleOfExistingShape - || prim.PhysShape.type != BSPhysicsShapeType.SHAPE_SPHERE - ) + || prim.PhysShape.ShapeType != BSPhysicsShapeType.SHAPE_SPHERE + ) { - ret = GetReferenceToNativeShape(prim, BSPhysicsShapeType.SHAPE_SPHERE, - FixedShapeKey.KEY_SPHERE, shapeCallback); + DereferenceExistingShape(prim, shapeCallback); + prim.PhysShape = BSShapeNative.GetReference(m_physicsScene, prim, + BSPhysicsShapeType.SHAPE_SPHERE, FixedShapeKey.KEY_SPHERE); } if (DDetail) DetailLog("{0},BSShapeCollection.CreateGeom,sphere,force={1},rebuilt={2},shape={3}", prim.LocalID, forceRebuild, ret, prim.PhysShape); } + // If we didn't make a sphere, maybe a box will work. if (!haveShape && pbs.ProfileShape == ProfileShape.Square && pbs.PathCurve == (byte)Extrusion.Straight) { haveShape = true; if (forceRebuild || prim.Scale != scaleOfExistingShape - || prim.PhysShape.type != BSPhysicsShapeType.SHAPE_BOX + || prim.PhysShape.ShapeType != BSPhysicsShapeType.SHAPE_BOX ) { - ret = GetReferenceToNativeShape( prim, BSPhysicsShapeType.SHAPE_BOX, - FixedShapeKey.KEY_BOX, shapeCallback); + DereferenceExistingShape(prim, shapeCallback); + prim.PhysShape = BSShapeNative.GetReference(m_physicsScene, prim, + BSPhysicsShapeType.SHAPE_BOX, FixedShapeKey.KEY_BOX); } if (DDetail) DetailLog("{0},BSShapeCollection.CreateGeom,box,force={1},rebuilt={2},shape={3}", prim.LocalID, forceRebuild, ret, prim.PhysShape); @@ -511,7 +204,7 @@ public sealed class BSShapeCollection : IDisposable } // return 'true' if the prim's shape was changed. - public bool CreateGeomMeshOrHull(BSPhysObject prim, ShapeDestructionCallback shapeCallback) + private bool CreateGeomMeshOrHull(BSPhysObject prim, PhysicalDestructionCallback shapeCallback) { bool ret = false; @@ -520,537 +213,70 @@ public sealed class BSShapeCollection : IDisposable if (prim.IsPhysical && BSParam.ShouldUseHullsForPhysicalObjects) { // Update prim.BSShape to reference a hull of this shape. - ret = GetReferenceToHull(prim, shapeCallback); + DereferenceExistingShape(prim, shapeCallback); + prim.PhysShape = BSShapeMesh.GetReference(m_physicsScene, false /*forceRebuild*/, prim); if (DDetail) DetailLog("{0},BSShapeCollection.CreateGeom,hull,shape={1},key={2}", - prim.LocalID, prim.PhysShape, prim.PhysShape.shapeKey.ToString("X")); + prim.LocalID, prim.PhysShape, prim.PhysShape.physShapeInfo.shapeKey.ToString("X")); } else { - ret = GetReferenceToMesh(prim, shapeCallback); + // Update prim.BSShape to reference a mesh of this shape. + DereferenceExistingShape(prim, shapeCallback); + prim.PhysShape = BSShapeHull.GetReference(m_physicsScene, false /*forceRebuild*/, prim); if (DDetail) DetailLog("{0},BSShapeCollection.CreateGeom,mesh,shape={1},key={2}", - prim.LocalID, prim.PhysShape, prim.PhysShape.shapeKey.ToString("X")); + prim.LocalID, prim.PhysShape, prim.PhysShape.physShapeInfo.shapeKey.ToString("X")); } return ret; } - // Creates a native shape and assignes it to prim.BSShape. - // "Native" shapes are never shared. they are created here and destroyed in DereferenceShape(). - private bool GetReferenceToNativeShape(BSPhysObject prim, - BSPhysicsShapeType shapeType, FixedShapeKey shapeKey, - ShapeDestructionCallback shapeCallback) - { - // release any previous shape - DereferenceShape(prim.PhysShape, shapeCallback); - - BulletShape newShape = BuildPhysicalNativeShape(prim, shapeType, shapeKey); - - // Don't need to do a 'ReferenceShape()' here because native shapes are not shared. - if (DDetail) DetailLog("{0},BSShapeCollection.AddNativeShapeToPrim,create,newshape={1},scale={2}", - prim.LocalID, newShape, prim.Scale); - - // native shapes are scaled by Bullet - prim.PhysShape = newShape; - return true; - } - - private BulletShape BuildPhysicalNativeShape(BSPhysObject prim, BSPhysicsShapeType shapeType, - FixedShapeKey shapeKey) - { - BulletShape newShape; - // Need to make sure the passed shape information is for the native type. - ShapeData nativeShapeData = new ShapeData(); - nativeShapeData.Type = shapeType; - nativeShapeData.ID = prim.LocalID; - nativeShapeData.Scale = prim.Scale; - nativeShapeData.Size = prim.Scale; // unneeded, I think. - nativeShapeData.MeshKey = (ulong)shapeKey; - nativeShapeData.HullKey = (ulong)shapeKey; - - if (shapeType == BSPhysicsShapeType.SHAPE_CAPSULE) - { - - newShape = PhysicsScene.PE.BuildCapsuleShape(PhysicsScene.World, 1f, 1f, prim.Scale); - if (DDetail) DetailLog("{0},BSShapeCollection.BuildPhysicalNativeShape,capsule,scale={1}", prim.LocalID, prim.Scale); - } - else - { - // Native shapes are scaled in Bullet so set the scaling to the size - newShape = PhysicsScene.PE.BuildNativeShape(PhysicsScene.World, nativeShapeData); - - } - if (!newShape.HasPhysicalShape) - { - PhysicsScene.Logger.ErrorFormat("{0} BuildPhysicalNativeShape failed. ID={1}, shape={2}", - LogHeader, prim.LocalID, shapeType); - } - newShape.shapeKey = (System.UInt64)shapeKey; - newShape.isNativeShape = true; - - return newShape; - } - - // Builds a mesh shape in the physical world and updates prim.BSShape. - // Dereferences previous shape in BSShape and adds a reference for this new shape. - // Returns 'true' of a mesh was actually built. Otherwise . - // Called at taint-time! - private bool GetReferenceToMesh(BSPhysObject prim, ShapeDestructionCallback shapeCallback) - { - BulletShape newShape = new BulletShape(); - - float lod; - System.UInt64 newMeshKey = ComputeShapeKey(prim.Size, prim.BaseShape, out lod); - - // if this new shape is the same as last time, don't recreate the mesh - if (newMeshKey == prim.PhysShape.shapeKey && prim.PhysShape.type == BSPhysicsShapeType.SHAPE_MESH) - return false; - - if (DDetail) DetailLog("{0},BSShapeCollection.GetReferenceToMesh,create,oldKey={1},newKey={2},size={3},lod={4}", - prim.LocalID, prim.PhysShape.shapeKey.ToString("X"), newMeshKey.ToString("X"), prim.Size, lod); - - // Since we're recreating new, get rid of the reference to the previous shape - DereferenceShape(prim.PhysShape, shapeCallback); - - newShape = CreatePhysicalMesh(prim, newMeshKey, prim.BaseShape, prim.Size, lod); - // Take evasive action if the mesh was not constructed. - newShape = VerifyMeshCreated(PhysicsScene, newShape, prim); - - ReferenceShape(newShape); - - prim.PhysShape = newShape; - - return true; // 'true' means a new shape has been added to this prim - } - - private BulletShape CreatePhysicalMesh(BSPhysObject prim, System.UInt64 newMeshKey, PrimitiveBaseShape pbs, OMV.Vector3 size, float lod) + // Track another user of a body. + // We presume the caller has allocated the body. + // Bodies only have one user so the body is just put into the world if not already there. + private void ReferenceBody(BulletBody body) { - BulletShape newShape = new BulletShape(); - - MeshDesc meshDesc; - if (Meshes.TryGetValue(newMeshKey, out meshDesc)) - { - // If the mesh has already been built just use it. - newShape = meshDesc.shape.Clone(); - } - else + lock (m_collectionActivityLock) { - IMesh meshData = PhysicsScene.mesher.CreateMesh(prim.PhysObjectName, pbs, size, lod, - false, // say it is not physical so a bounding box is not built - false // do not cache the mesh and do not use previously built versions - ); - - if (meshData != null) + if (DDetail) DetailLog("{0},BSShapeCollection.ReferenceBody,newBody,body={1}", body.ID, body); + if (!m_physicsScene.PE.IsInWorld(m_physicsScene.World, body)) { - - int[] indices = meshData.getIndexListAsInt(); - int realIndicesIndex = indices.Length; - float[] verticesAsFloats = meshData.getVertexListAsFloat(); - - if (BSParam.ShouldRemoveZeroWidthTriangles) - { - // Remove degenerate triangles. These are triangles with two of the vertices - // are the same. This is complicated by the problem that vertices are not - // made unique in sculpties so we have to compare the values in the vertex. - realIndicesIndex = 0; - for (int tri = 0; tri < indices.Length; tri += 3) - { - // Compute displacements into vertex array for each vertex of the triangle - int v1 = indices[tri + 0] * 3; - int v2 = indices[tri + 1] * 3; - int v3 = indices[tri + 2] * 3; - // Check to see if any two of the vertices are the same - if (!( ( verticesAsFloats[v1 + 0] == verticesAsFloats[v2 + 0] - && verticesAsFloats[v1 + 1] == verticesAsFloats[v2 + 1] - && verticesAsFloats[v1 + 2] == verticesAsFloats[v2 + 2]) - || ( verticesAsFloats[v2 + 0] == verticesAsFloats[v3 + 0] - && verticesAsFloats[v2 + 1] == verticesAsFloats[v3 + 1] - && verticesAsFloats[v2 + 2] == verticesAsFloats[v3 + 2]) - || ( verticesAsFloats[v1 + 0] == verticesAsFloats[v3 + 0] - && verticesAsFloats[v1 + 1] == verticesAsFloats[v3 + 1] - && verticesAsFloats[v1 + 2] == verticesAsFloats[v3 + 2]) ) - ) - { - // None of the vertices of the triangles are the same. This is a good triangle; - indices[realIndicesIndex + 0] = indices[tri + 0]; - indices[realIndicesIndex + 1] = indices[tri + 1]; - indices[realIndicesIndex + 2] = indices[tri + 2]; - realIndicesIndex += 3; - } - } - } - DetailLog("{0},BSShapeCollection.CreatePhysicalMesh,origTri={1},realTri={2},numVerts={3}", - BSScene.DetailLogZero, indices.Length / 3, realIndicesIndex / 3, verticesAsFloats.Length / 3); - - if (realIndicesIndex != 0) - { - newShape = PhysicsScene.PE.CreateMeshShape(PhysicsScene.World, - realIndicesIndex, indices, verticesAsFloats.Length / 3, verticesAsFloats); - } - else - { - PhysicsScene.Logger.DebugFormat("{0} All mesh triangles degenerate. Prim {1} at {2} in {3}", - LogHeader, prim.PhysObjectName, prim.RawPosition, PhysicsScene.Name); - } + m_physicsScene.PE.AddObjectToWorld(m_physicsScene.World, body); + if (DDetail) DetailLog("{0},BSShapeCollection.ReferenceBody,addedToWorld,ref={1}", body.ID, body); } } - newShape.shapeKey = newMeshKey; - - return newShape; - } - - // See that hull shape exists in the physical world and update prim.BSShape. - // We could be creating the hull because scale changed or whatever. - // Return 'true' if a new hull was built. Otherwise, returning a shared hull instance. - private bool GetReferenceToHull(BSPhysObject prim, ShapeDestructionCallback shapeCallback) - { - BulletShape newShape; - - float lod; - System.UInt64 newHullKey = ComputeShapeKey(prim.Size, prim.BaseShape, out lod); - - // if the hull hasn't changed, don't rebuild it - if (newHullKey == prim.PhysShape.shapeKey && prim.PhysShape.type == BSPhysicsShapeType.SHAPE_HULL) - return false; - - if (DDetail) DetailLog("{0},BSShapeCollection.GetReferenceToHull,create,oldKey={1},newKey={2}", - prim.LocalID, prim.PhysShape.shapeKey.ToString("X"), newHullKey.ToString("X")); - - // Remove usage of the previous shape. - DereferenceShape(prim.PhysShape, shapeCallback); - - newShape = CreatePhysicalHull(prim, newHullKey, prim.BaseShape, prim.Size, lod); - // It might not have been created if we're waiting for an asset. - newShape = VerifyMeshCreated(PhysicsScene, newShape, prim); - - ReferenceShape(newShape); - - prim.PhysShape = newShape; - return true; // 'true' means a new shape has been added to this prim } - List m_hulls; - private BulletShape CreatePhysicalHull(BSPhysObject prim, System.UInt64 newHullKey, PrimitiveBaseShape pbs, OMV.Vector3 size, float lod) + // Release the usage of a body. + // Called when releasing use of a BSBody. BSShape is handled separately. + // Called in taint time. + public void DereferenceBody(BulletBody body, PhysicalDestructionCallback bodyCallback ) { + if (!body.HasPhysicalBody) + return; - BulletShape newShape = new BulletShape(); - IntPtr hullPtr = IntPtr.Zero; + m_physicsScene.AssertInTaintTime("BSShapeCollection.DereferenceBody"); - HullDesc hullDesc; - if (Hulls.TryGetValue(newHullKey, out hullDesc)) - { - // If the hull shape already has been created, just use the one shared instance. - newShape = hullDesc.shape.Clone(); - } - else + lock (m_collectionActivityLock) { - if (BSParam.ShouldUseBulletHACD) - { - DetailLog("{0},BSShapeCollection.CreatePhysicalHull,shouldUseBulletHACD,entry", prim.LocalID); - MeshDesc meshDesc; - if (!Meshes.TryGetValue(newHullKey, out meshDesc)) - { - // That's odd because the mesh should have been created before the hull - // but, since it doesn't exist, create it. - newShape = CreatePhysicalMesh(prim, newHullKey, prim.BaseShape, prim.Size, lod); - DetailLog("{0},BSShapeCollection.CreatePhysicalHull,noMeshBuiltNew,hasBody={1}", prim.LocalID, newShape.HasPhysicalShape); - - if (newShape.HasPhysicalShape) - { - ReferenceShape(newShape); - Meshes.TryGetValue(newHullKey, out meshDesc); - } - } - if (meshDesc.shape.HasPhysicalShape) - { - HACDParams parms; - parms.maxVerticesPerHull = BSParam.BHullMaxVerticesPerHull; - parms.minClusters = BSParam.BHullMinClusters; - parms.compacityWeight = BSParam.BHullCompacityWeight; - parms.volumeWeight = BSParam.BHullVolumeWeight; - parms.concavity = BSParam.BHullConcavity; - parms.addExtraDistPoints = BSParam.NumericBool(BSParam.BHullAddExtraDistPoints); - parms.addNeighboursDistPoints = BSParam.NumericBool(BSParam.BHullAddNeighboursDistPoints); - parms.addFacesPoints = BSParam.NumericBool(BSParam.BHullAddFacesPoints); - parms.shouldAdjustCollisionMargin = BSParam.NumericBool(BSParam.BHullShouldAdjustCollisionMargin); - - DetailLog("{0},BSShapeCollection.CreatePhysicalHull,hullFromMesh,beforeCall", prim.LocalID, newShape.HasPhysicalShape); - newShape = PhysicsScene.PE.BuildHullShapeFromMesh(PhysicsScene.World, meshDesc.shape, parms); - DetailLog("{0},BSShapeCollection.CreatePhysicalHull,hullFromMesh,hasBody={1}", prim.LocalID, newShape.HasPhysicalShape); - } - DetailLog("{0},BSShapeCollection.CreatePhysicalHull,shouldUseBulletHACD,exit,hasBody={1}", prim.LocalID, newShape.HasPhysicalShape); - } - if (!newShape.HasPhysicalShape) - { - // Build a new hull in the physical world. - // Pass true for physicalness as this prevents the creation of bounding box which is not needed - IMesh meshData = PhysicsScene.mesher.CreateMesh(prim.PhysObjectName, pbs, size, lod, true /* isPhysical */, false /* shouldCache */); - if (meshData != null) - { - int[] indices = meshData.getIndexListAsInt(); - List vertices = meshData.getVertexList(); - - //format conversion from IMesh format to DecompDesc format - List convIndices = new List(); - List convVertices = new List(); - for (int ii = 0; ii < indices.GetLength(0); ii++) - { - convIndices.Add(indices[ii]); - } - foreach (OMV.Vector3 vv in vertices) - { - convVertices.Add(new float3(vv.X, vv.Y, vv.Z)); - } - - uint maxDepthSplit = (uint)BSParam.CSHullMaxDepthSplit; - if (BSParam.CSHullMaxDepthSplit != BSParam.CSHullMaxDepthSplitForSimpleShapes) - { - // Simple primitive shapes we know are convex so they are better implemented with - // fewer hulls. - // Check for simple shape (prim without cuts) and reduce split parameter if so. - if (PrimHasNoCuts(pbs)) - { - maxDepthSplit = (uint)BSParam.CSHullMaxDepthSplitForSimpleShapes; - } - } - - // setup and do convex hull conversion - m_hulls = new List(); - DecompDesc dcomp = new DecompDesc(); - dcomp.mIndices = convIndices; - dcomp.mVertices = convVertices; - dcomp.mDepth = maxDepthSplit; - dcomp.mCpercent = BSParam.CSHullConcavityThresholdPercent; - dcomp.mPpercent = BSParam.CSHullVolumeConservationThresholdPercent; - dcomp.mMaxVertices = (uint)BSParam.CSHullMaxVertices; - dcomp.mSkinWidth = BSParam.CSHullMaxSkinWidth; - ConvexBuilder convexBuilder = new ConvexBuilder(HullReturn); - // create the hull into the _hulls variable - convexBuilder.process(dcomp); - - DetailLog("{0},BSShapeCollection.CreatePhysicalHull,key={1},inVert={2},inInd={3},split={4},hulls={5}", - BSScene.DetailLogZero, newHullKey, indices.GetLength(0), vertices.Count, maxDepthSplit, m_hulls.Count); - - // Convert the vertices and indices for passing to unmanaged. - // The hull information is passed as a large floating point array. - // The format is: - // convHulls[0] = number of hulls - // convHulls[1] = number of vertices in first hull - // convHulls[2] = hull centroid X coordinate - // convHulls[3] = hull centroid Y coordinate - // convHulls[4] = hull centroid Z coordinate - // convHulls[5] = first hull vertex X - // convHulls[6] = first hull vertex Y - // convHulls[7] = first hull vertex Z - // convHulls[8] = second hull vertex X - // ... - // convHulls[n] = number of vertices in second hull - // convHulls[n+1] = second hull centroid X coordinate - // ... - // - // TODO: is is very inefficient. Someday change the convex hull generator to return - // data structures that do not need to be converted in order to pass to Bullet. - // And maybe put the values directly into pinned memory rather than marshaling. - int hullCount = m_hulls.Count; - int totalVertices = 1; // include one for the count of the hulls - foreach (ConvexResult cr in m_hulls) - { - totalVertices += 4; // add four for the vertex count and centroid - totalVertices += cr.HullIndices.Count * 3; // we pass just triangles - } - float[] convHulls = new float[totalVertices]; - - convHulls[0] = (float)hullCount; - int jj = 1; - foreach (ConvexResult cr in m_hulls) - { - // copy vertices for index access - float3[] verts = new float3[cr.HullVertices.Count]; - int kk = 0; - foreach (float3 ff in cr.HullVertices) - { - verts[kk++] = ff; - } - - // add to the array one hull's worth of data - convHulls[jj++] = cr.HullIndices.Count; - convHulls[jj++] = 0f; // centroid x,y,z - convHulls[jj++] = 0f; - convHulls[jj++] = 0f; - foreach (int ind in cr.HullIndices) - { - convHulls[jj++] = verts[ind].x; - convHulls[jj++] = verts[ind].y; - convHulls[jj++] = verts[ind].z; - } - } - // create the hull data structure in Bullet - newShape = PhysicsScene.PE.CreateHullShape(PhysicsScene.World, hullCount, convHulls); - } - } - newShape.shapeKey = newHullKey; - } - - return newShape; - } - - // Callback from convex hull creater with a newly created hull. - // Just add it to our collection of hulls for this shape. - private void HullReturn(ConvexResult result) - { - m_hulls.Add(result); - return; - } - - // Compound shapes are always built from scratch. - // This shouldn't be to bad since most of the parts will be meshes that had been built previously. - private bool GetReferenceToCompoundShape(BSPhysObject prim, ShapeDestructionCallback shapeCallback) - { - // Remove reference to the old shape - // Don't need to do this as the shape is freed when the new root shape is created below. - // DereferenceShape(prim.PhysShape, true, shapeCallback); - - BulletShape cShape = PhysicsScene.PE.CreateCompoundShape(PhysicsScene.World, false); - - // Create the shape for the root prim and add it to the compound shape. Cannot be a native shape. - CreateGeomMeshOrHull(prim, shapeCallback); - PhysicsScene.PE.AddChildShapeToCompoundShape(cShape, prim.PhysShape, OMV.Vector3.Zero, OMV.Quaternion.Identity); - if (DDetail) DetailLog("{0},BSShapeCollection.GetReferenceToCompoundShape,addRootPrim,compShape={1},rootShape={2}", - prim.LocalID, cShape, prim.PhysShape); - - prim.PhysShape = cShape; - - return true; - } - - // Create a hash of all the shape parameters to be used as a key - // for this particular shape. - public static System.UInt64 ComputeShapeKey(OMV.Vector3 size, PrimitiveBaseShape pbs, out float retLod) - { - // level of detail based on size and type of the object - float lod = BSParam.MeshLOD; - - // prims with curvy internal cuts need higher lod - if (pbs.HollowShape == HollowShape.Circle) - lod = BSParam.MeshCircularLOD; - - if (pbs.SculptEntry) - lod = BSParam.SculptLOD; - - // Mega prims usually get more detail because one can interact with shape approximations at this size. - float maxAxis = Math.Max(size.X, Math.Max(size.Y, size.Z)); - if (maxAxis > BSParam.MeshMegaPrimThreshold) - lod = BSParam.MeshMegaPrimLOD; - - retLod = lod; - return pbs.GetMeshKey(size, lod); - } - // For those who don't want the LOD - public static System.UInt64 ComputeShapeKey(OMV.Vector3 size, PrimitiveBaseShape pbs) - { - float lod; - return ComputeShapeKey(size, pbs, out lod); - } - - // The creation of a mesh or hull can fail if an underlying asset is not available. - // There are two cases: 1) the asset is not in the cache and it needs to be fetched; - // and 2) the asset cannot be converted (like failed decompression of JPEG2000s). - // The first case causes the asset to be fetched. The second case requires - // us to not loop forever. - // Called after creating a physical mesh or hull. If the physical shape was created, - // just return. - public static BulletShape VerifyMeshCreated(BSScene physicsScene, BulletShape newShape, BSPhysObject prim) - { - // If the shape was successfully created, nothing more to do - if (newShape.HasPhysicalShape) - return newShape; + if (DDetail) DetailLog("{0},BSShapeCollection.DereferenceBody,DestroyingBody,body={1}", body.ID, body); + // If the caller needs to know the old body is going away, pass the event up. + if (bodyCallback != null) + bodyCallback(body, null); - // VerifyMeshCreated is called after trying to create the mesh. If we think the asset had been - // fetched but we end up here again, the meshing of the asset must have failed. - // Prevent trying to keep fetching the mesh by declaring failure. - if (prim.PrimAssetState == BSPhysObject.PrimAssetCondition.Fetched) - { - prim.PrimAssetState = BSPhysObject.PrimAssetCondition.Failed; - physicsScene.Logger.WarnFormat("{0} Fetched asset would not mesh. {1}, texture={2}", - LogHeader, prim.PhysObjectName, prim.BaseShape.SculptTexture); - } - else - { - // If this mesh has an underlying asset and we have not failed getting it before, fetch the asset - if (prim.BaseShape.SculptEntry - && prim.PrimAssetState != BSPhysObject.PrimAssetCondition.Failed - && prim.PrimAssetState != BSPhysObject.PrimAssetCondition.Waiting - && prim.BaseShape.SculptTexture != OMV.UUID.Zero - ) - { - physicsScene.DetailLog("{0},BSShapeCollection.VerifyMeshCreated,fetchAsset", prim.LocalID); - // Multiple requestors will know we're waiting for this asset - prim.PrimAssetState = BSPhysObject.PrimAssetCondition.Waiting; + // Removing an object not in the world is a NOOP + m_physicsScene.PE.RemoveObjectFromWorld(m_physicsScene.World, body); - BSPhysObject xprim = prim; - Util.FireAndForget(delegate - { - RequestAssetDelegate assetProvider = physicsScene.RequestAssetMethod; - if (assetProvider != null) - { - BSPhysObject yprim = xprim; // probably not necessary, but, just in case. - assetProvider(yprim.BaseShape.SculptTexture, delegate(AssetBase asset) - { - bool assetFound = false; - string mismatchIDs = String.Empty; // DEBUG DEBUG - if (asset != null && yprim.BaseShape.SculptEntry) - { - if (yprim.BaseShape.SculptTexture.ToString() == asset.ID) - { - yprim.BaseShape.SculptData = asset.Data; - // This will cause the prim to see that the filler shape is not the right - // one and try again to build the object. - // No race condition with the normal shape setting since the rebuild is at taint time. - yprim.ForceBodyShapeRebuild(false /* inTaintTime */); - assetFound = true; - } - else - { - mismatchIDs = yprim.BaseShape.SculptTexture.ToString() + "/" + asset.ID; - } - } - if (assetFound) - yprim.PrimAssetState = BSPhysObject.PrimAssetCondition.Fetched; - else - yprim.PrimAssetState = BSPhysObject.PrimAssetCondition.Failed; - physicsScene.DetailLog("{0},BSShapeCollection,fetchAssetCallback,found={1},isSculpt={2},ids={3}", - yprim.LocalID, assetFound, yprim.BaseShape.SculptEntry, mismatchIDs ); + // Zero any reference to the shape so it is not freed when the body is deleted. + m_physicsScene.PE.SetCollisionShape(m_physicsScene.World, body, null); - }); - } - else - { - xprim.PrimAssetState = BSPhysObject.PrimAssetCondition.Failed; - physicsScene.Logger.ErrorFormat("{0} Physical object requires asset but no asset provider. Name={1}", - LogHeader, physicsScene.Name); - } - }); - } - else - { - if (prim.PrimAssetState == BSPhysObject.PrimAssetCondition.Failed) - { - physicsScene.Logger.WarnFormat("{0} Mesh failed to fetch asset. obj={1}, texture={2}", - LogHeader, prim.PhysObjectName, prim.BaseShape.SculptTexture); - } - } + m_physicsScene.PE.DestroyObject(m_physicsScene.World, body); } - - // While we wait for the mesh defining asset to be loaded, stick in a simple box for the object. - BulletShape fillinShape = physicsScene.Shapes.BuildPhysicalNativeShape(prim, BSPhysicsShapeType.SHAPE_BOX, FixedShapeKey.KEY_BOX); - physicsScene.DetailLog("{0},BSShapeCollection.VerifyMeshCreated,boxTempShape", prim.LocalID); - - return fillinShape; } // Create a body object in Bullet. // Updates prim.BSBody with the information about the new body if one is created. // Returns 'true' if an object was actually created. // Called at taint-time. - private bool CreateBody(bool forceRebuild, BSPhysObject prim, BulletWorld sim, BodyDestructionCallback bodyCallback) + private bool CreateBody(bool forceRebuild, BSPhysObject prim, BulletWorld sim, PhysicalDestructionCallback bodyCallback) { bool ret = false; @@ -1061,7 +287,7 @@ public sealed class BSShapeCollection : IDisposable // If not a solid object, body is a GhostObject. Otherwise a RigidBody. if (!mustRebuild) { - CollisionObjectTypes bodyType = (CollisionObjectTypes)PhysicsScene.PE.GetBodyType(prim.PhysBody); + CollisionObjectTypes bodyType = (CollisionObjectTypes)m_physicsScene.PE.GetBodyType(prim.PhysBody); if (prim.IsSolid && bodyType != CollisionObjectTypes.CO_RIGID_BODY || !prim.IsSolid && bodyType != CollisionObjectTypes.CO_GHOST_OBJECT) { @@ -1079,12 +305,12 @@ public sealed class BSShapeCollection : IDisposable BulletBody aBody; if (prim.IsSolid) { - aBody = PhysicsScene.PE.CreateBodyFromShape(sim, prim.PhysShape, prim.LocalID, prim.RawPosition, prim.RawOrientation); + aBody = m_physicsScene.PE.CreateBodyFromShape(sim, prim.PhysShape.physShapeInfo, prim.LocalID, prim.RawPosition, prim.RawOrientation); if (DDetail) DetailLog("{0},BSShapeCollection.CreateBody,mesh,body={1}", prim.LocalID, aBody); } else { - aBody = PhysicsScene.PE.CreateGhostFromShape(sim, prim.PhysShape, prim.LocalID, prim.RawPosition, prim.RawOrientation); + aBody = m_physicsScene.PE.CreateGhostFromShape(sim, prim.PhysShape.physShapeInfo, prim.LocalID, prim.RawPosition, prim.RawOrientation); if (DDetail) DetailLog("{0},BSShapeCollection.CreateBody,ghost,body={1}", prim.LocalID, aBody); } @@ -1098,46 +324,10 @@ public sealed class BSShapeCollection : IDisposable return ret; } - private bool TryGetMeshByPtr(BulletShape shape, out MeshDesc outDesc) - { - bool ret = false; - MeshDesc foundDesc = new MeshDesc(); - foreach (MeshDesc md in Meshes.Values) - { - if (md.shape.ReferenceSame(shape)) - { - foundDesc = md; - ret = true; - break; - } - - } - outDesc = foundDesc; - return ret; - } - - private bool TryGetHullByPtr(BulletShape shape, out HullDesc outDesc) - { - bool ret = false; - HullDesc foundDesc = new HullDesc(); - foreach (HullDesc hd in Hulls.Values) - { - if (hd.shape.ReferenceSame(shape)) - { - foundDesc = hd; - ret = true; - break; - } - - } - outDesc = foundDesc; - return ret; - } - private void DetailLog(string msg, params Object[] args) { - if (PhysicsScene.PhysicsLogging.Enabled) - PhysicsScene.DetailLog(msg, args); + if (m_physicsScene.PhysicsLogging.Enabled) + m_physicsScene.DetailLog(msg, args); } } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs index e427dbc..a7b3f02 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs @@ -39,6 +39,8 @@ namespace OpenSim.Region.Physics.BulletSPlugin { public abstract class BSShape { + private static string LogHeader = "[BULLETSIM SHAPE]"; + public int referenceCount { get; set; } public DateTime lastReferenced { get; set; } public BulletShape physShapeInfo { get; set; } @@ -56,49 +58,6 @@ public abstract class BSShape physShapeInfo = pShape; } - // Get a reference to a physical shape. Create if it doesn't exist - public static BSShape GetShapeReference(BSScene physicsScene, bool forceRebuild, BSPhysObject prim) - { - BSShape ret = null; - - if (prim.PreferredPhysicalShape == BSPhysicsShapeType.SHAPE_CAPSULE) - { - // an avatar capsule is close to a native shape (it is not shared) - ret = BSShapeNative.GetReference(physicsScene, prim, BSPhysicsShapeType.SHAPE_CAPSULE, - FixedShapeKey.KEY_CAPSULE); - physicsScene.DetailLog("{0},BSShape.GetShapeReference,avatarCapsule,shape={1}", prim.LocalID, ret); - } - - // Compound shapes are handled special as they are rebuilt from scratch. - // This isn't too great a hardship since most of the child shapes will have already been created. - if (ret == null && prim.PreferredPhysicalShape == BSPhysicsShapeType.SHAPE_COMPOUND) - { - // Getting a reference to a compound shape gets you the compound shape with the root prim shape added - ret = BSShapeCompound.GetReference(physicsScene, prim); - physicsScene.DetailLog("{0},BSShapeCollection.CreateGeom,compoundShape,shape={1}", prim.LocalID, ret); - } - - // Avatars have their own unique shape - if (ret == null && prim.PreferredPhysicalShape == BSPhysicsShapeType.SHAPE_AVATAR) - { - // Getting a reference to a compound shape gets you the compound shape with the root prim shape added - ret = BSShapeAvatar.GetReference(prim); - physicsScene.DetailLog("{0},BSShapeCollection.CreateGeom,avatarShape,shape={1}", prim.LocalID, ret); - } - - if (ret == null) - ret = GetShapeReferenceNonSpecial(physicsScene, forceRebuild, prim); - - return ret; - } - private static BSShape GetShapeReferenceNonSpecial(BSScene physicsScene, bool forceRebuild, BSPhysObject prim) - { - // TODO: work needed here!! - BSShapeMesh.GetReference(physicsScene, forceRebuild, prim); - BSShapeHull.GetReference(physicsScene, forceRebuild, prim); - return null; - } - // Called when this shape is being used again. public virtual void IncrementReference() { @@ -116,6 +75,27 @@ public abstract class BSShape // Release the use of a physical shape. public abstract void Dereference(BSScene physicsScene); + // Return 'true' if there is an allocated physics physical shape under this class instance. + public virtual bool HasPhysicalShape + { + get + { + if (physShapeInfo != null) + return physShapeInfo.HasPhysicalShape; + return false; + } + } + public virtual BSPhysicsShapeType ShapeType + { + get + { + BSPhysicsShapeType ret = BSPhysicsShapeType.SHAPE_UNKNOWN; + if (physShapeInfo != null && physShapeInfo.HasPhysicalShape) + ret = physShapeInfo.shapeType; + return ret; + } + } + // Returns a string for debugging that uniquily identifies the memory used by this instance public virtual string AddrString { @@ -132,6 +112,119 @@ public abstract class BSShape buff.Append(">"); return buff.ToString(); } + + // Create a hash of all the shape parameters to be used as a key for this particular shape. + public static System.UInt64 ComputeShapeKey(OMV.Vector3 size, PrimitiveBaseShape pbs, out float retLod) + { + // level of detail based on size and type of the object + float lod = BSParam.MeshLOD; + if (pbs.SculptEntry) + lod = BSParam.SculptLOD; + + // Mega prims usually get more detail because one can interact with shape approximations at this size. + float maxAxis = Math.Max(size.X, Math.Max(size.Y, size.Z)); + if (maxAxis > BSParam.MeshMegaPrimThreshold) + lod = BSParam.MeshMegaPrimLOD; + + retLod = lod; + return pbs.GetMeshKey(size, lod); + } + + // The creation of a mesh or hull can fail if an underlying asset is not available. + // There are two cases: 1) the asset is not in the cache and it needs to be fetched; + // and 2) the asset cannot be converted (like failed decompression of JPEG2000s). + // The first case causes the asset to be fetched. The second case requires + // us to not loop forever. + // Called after creating a physical mesh or hull. If the physical shape was created, + // just return. + public static BulletShape VerifyMeshCreated(BSScene physicsScene, BulletShape newShape, BSPhysObject prim) + { + // If the shape was successfully created, nothing more to do + if (newShape.HasPhysicalShape) + return newShape; + + // VerifyMeshCreated is called after trying to create the mesh. If we think the asset had been + // fetched but we end up here again, the meshing of the asset must have failed. + // Prevent trying to keep fetching the mesh by declaring failure. + if (prim.PrimAssetState == BSPhysObject.PrimAssetCondition.Fetched) + { + prim.PrimAssetState = BSPhysObject.PrimAssetCondition.Failed; + physicsScene.Logger.WarnFormat("{0} Fetched asset would not mesh. {1}, texture={2}", + LogHeader, prim.PhysObjectName, prim.BaseShape.SculptTexture); + } + else + { + // If this mesh has an underlying asset and we have not failed getting it before, fetch the asset + if (prim.BaseShape.SculptEntry + && prim.PrimAssetState != BSPhysObject.PrimAssetCondition.Failed + && prim.PrimAssetState != BSPhysObject.PrimAssetCondition.Waiting + && prim.BaseShape.SculptTexture != OMV.UUID.Zero + ) + { + physicsScene.DetailLog("{0},BSShapeCollection.VerifyMeshCreated,fetchAsset", prim.LocalID); + // Multiple requestors will know we're waiting for this asset + prim.PrimAssetState = BSPhysObject.PrimAssetCondition.Waiting; + + BSPhysObject xprim = prim; + Util.FireAndForget(delegate + { + RequestAssetDelegate assetProvider = physicsScene.RequestAssetMethod; + if (assetProvider != null) + { + BSPhysObject yprim = xprim; // probably not necessary, but, just in case. + assetProvider(yprim.BaseShape.SculptTexture, delegate(AssetBase asset) + { + bool assetFound = false; + string mismatchIDs = String.Empty; // DEBUG DEBUG + if (asset != null && yprim.BaseShape.SculptEntry) + { + if (yprim.BaseShape.SculptTexture.ToString() == asset.ID) + { + yprim.BaseShape.SculptData = asset.Data; + // This will cause the prim to see that the filler shape is not the right + // one and try again to build the object. + // No race condition with the normal shape setting since the rebuild is at taint time. + yprim.ForceBodyShapeRebuild(false /* inTaintTime */); + assetFound = true; + } + else + { + mismatchIDs = yprim.BaseShape.SculptTexture.ToString() + "/" + asset.ID; + } + } + if (assetFound) + yprim.PrimAssetState = BSPhysObject.PrimAssetCondition.Fetched; + else + yprim.PrimAssetState = BSPhysObject.PrimAssetCondition.Failed; + physicsScene.DetailLog("{0},BSShapeCollection,fetchAssetCallback,found={1},isSculpt={2},ids={3}", + yprim.LocalID, assetFound, yprim.BaseShape.SculptEntry, mismatchIDs ); + }); + } + else + { + xprim.PrimAssetState = BSPhysObject.PrimAssetCondition.Failed; + physicsScene.Logger.ErrorFormat("{0} Physical object requires asset but no asset provider. Name={1}", + LogHeader, physicsScene.Name); + } + }); + } + else + { + if (prim.PrimAssetState == BSPhysObject.PrimAssetCondition.Failed) + { + physicsScene.Logger.WarnFormat("{0} Mesh failed to fetch asset. obj={1}, texture={2}", + LogHeader, prim.PhysObjectName, prim.BaseShape.SculptTexture); + } + } + } + + // While we wait for the mesh defining asset to be loaded, stick in a simple box for the object. + BSShape fillShape = BSShapeNative.GetReference(physicsScene, prim, BSPhysicsShapeType.SHAPE_BOX, FixedShapeKey.KEY_BOX); + physicsScene.DetailLog("{0},BSShapeCollection.VerifyMeshCreated,boxTempShape", prim.LocalID); + + return fillShape.physShapeInfo; + } + } // ============================================================================================================ @@ -199,7 +292,7 @@ public class BSShapeNative : BSShape physicsScene.Logger.ErrorFormat("{0} BuildPhysicalNativeShape failed. ID={1}, shape={2}", LogHeader, prim.LocalID, shapeType); } - newShape.type = shapeType; + newShape.shapeType = shapeType; newShape.isNativeShape = true; newShape.shapeKey = (UInt64)shapeKey; return newShape; @@ -219,10 +312,11 @@ public class BSShapeMesh : BSShape public static BSShape GetReference(BSScene physicsScene, bool forceRebuild, BSPhysObject prim) { float lod; - System.UInt64 newMeshKey = BSShapeCollection.ComputeShapeKey(prim.Size, prim.BaseShape, out lod); + System.UInt64 newMeshKey = BSShape.ComputeShapeKey(prim.Size, prim.BaseShape, out lod); physicsScene.DetailLog("{0},BSShapeMesh,getReference,oldKey={1},newKey={2},size={3},lod={4}", - prim.LocalID, prim.PhysShape.shapeKey.ToString("X"), newMeshKey.ToString("X"), prim.Size, lod); + prim.LocalID, prim.PhysShape.physShapeInfo.shapeKey.ToString("X"), + newMeshKey.ToString("X"), prim.Size, lod); BSShapeMesh retMesh = new BSShapeMesh(new BulletShape()); lock (Meshes) @@ -238,8 +332,8 @@ public class BSShapeMesh : BSShape BulletShape newShape = retMesh.CreatePhysicalMesh(physicsScene, prim, newMeshKey, prim.BaseShape, prim.Size, lod); // Check to see if mesh was created (might require an asset). - newShape = BSShapeCollection.VerifyMeshCreated(physicsScene, newShape, prim); - if (newShape.type == BSPhysicsShapeType.SHAPE_MESH) + newShape = VerifyMeshCreated(physicsScene, newShape, prim); + if (newShape.shapeType == BSPhysicsShapeType.SHAPE_MESH) { // If a mesh was what was created, remember the built shape for later sharing. Meshes.Add(newMeshKey, retMesh); @@ -360,10 +454,10 @@ public class BSShapeHull : BSShape public static BSShape GetReference(BSScene physicsScene, bool forceRebuild, BSPhysObject prim) { float lod; - System.UInt64 newHullKey = BSShapeCollection.ComputeShapeKey(prim.Size, prim.BaseShape, out lod); + System.UInt64 newHullKey = BSShape.ComputeShapeKey(prim.Size, prim.BaseShape, out lod); physicsScene.DetailLog("{0},BSShapeHull,getReference,oldKey={1},newKey={2},size={3},lod={4}", - prim.LocalID, prim.PhysShape.shapeKey.ToString("X"), newHullKey.ToString("X"), prim.Size, lod); + prim.LocalID, prim.PhysShape.physShapeInfo.shapeKey.ToString("X"), newHullKey.ToString("X"), prim.Size, lod); BSShapeHull retHull = new BSShapeHull(new BulletShape()); lock (Hulls) @@ -379,8 +473,8 @@ public class BSShapeHull : BSShape BulletShape newShape = retHull.CreatePhysicalHull(physicsScene, prim, newHullKey, prim.BaseShape, prim.Size, lod); // Check to see if mesh was created (might require an asset). - newShape = BSShapeCollection.VerifyMeshCreated(physicsScene, newShape, prim); - if (newShape.type == BSPhysicsShapeType.SHAPE_MESH) + newShape = VerifyMeshCreated(physicsScene, newShape, prim); + if (newShape.shapeType == BSPhysicsShapeType.SHAPE_MESH) { // If a mesh was what was created, remember the built shape for later sharing. Hulls.Add(newHullKey, retHull); @@ -569,7 +663,6 @@ public class BSShapeHull : BSShape } } - // ============================================================================================================ public class BSShapeCompound : BSShape { @@ -589,9 +682,9 @@ public class BSShapeCompound : BSShape { // Failed the sanity check!! physicsScene.Logger.ErrorFormat("{0} Attempt to free a compound shape that is not compound!! type={1}, ptr={2}", - LogHeader, physShapeInfo.type, physShapeInfo.AddrString); + LogHeader, physShapeInfo.shapeType, physShapeInfo.AddrString); physicsScene.DetailLog("{0},BSShapeCollection.DereferenceCompound,notACompoundShape,type={1},ptr={2}", - BSScene.DetailLogZero, physShapeInfo.type, physShapeInfo.AddrString); + BSScene.DetailLogZero, physShapeInfo.shapeType, physShapeInfo.AddrString); return; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimData.cs b/OpenSim/Region/Physics/BulletSPlugin/BulletSimData.cs index 8012d91..906e4f9 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimData.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimData.cs @@ -104,11 +104,11 @@ public class BulletShape { public BulletShape() { - type = BSPhysicsShapeType.SHAPE_UNKNOWN; + shapeType = BSPhysicsShapeType.SHAPE_UNKNOWN; shapeKey = (System.UInt64)FixedShapeKey.KEY_NONE; isNativeShape = false; } - public BSPhysicsShapeType type; + public BSPhysicsShapeType shapeType; public System.UInt64 shapeKey; public bool isNativeShape; @@ -133,7 +133,7 @@ public class BulletShape buff.Append(") is its center-of-mass - OMV.Vector3 centerOfMassW = LinksetRoot.RawPosition; - if (!disableCOM) // DEBUG DEBUG - { - // Compute a center-of-mass in world coordinates. - centerOfMassW = ComputeLinksetCenterOfMass(); - } + OMV.Vector3 centerOfMassW = ComputeLinksetCenterOfMass(); OMV.Quaternion invRootOrientation = OMV.Quaternion.Inverse(LinksetRoot.RawOrientation); @@ -414,20 +416,7 @@ public sealed class BSLinksetCompound : BSLinkset OMV.Vector3 centerDisplacement = (centerOfMassW - LinksetRoot.RawPosition) * invRootOrientation; LinksetRoot.SetEffectiveCenterOfMassW(centerDisplacement); - // This causes the physical position of the root prim to be offset to accomodate for the displacements - LinksetRoot.ForcePosition = LinksetRoot.RawPosition; - - // Update the local transform for the root child shape so it is offset from the <0,0,0> which is COM - PhysicsScene.PE.UpdateChildTransform(LinksetRoot.PhysShape.physShapeInfo, 0 /* childIndex , - -centerDisplacement, - OMV.Quaternion.Identity, // LinksetRoot.RawOrientation, - false /* shouldRecalculateLocalAabb (is done later after linkset built) ); - - DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,COM,com={1},rootPos={2},centerDisp={3}", - LinksetRoot.LocalID, centerOfMassW, LinksetRoot.RawPosition, centerDisplacement); - - DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,start,rBody={1},rShape={2},numChildren={3}", - LinksetRoot.LocalID, LinksetRoot.PhysBody, LinksetRoot.PhysShape, NumberOfChildren); + // TODO: add phantom root shape to be the center-of-mass // Add a shape for each of the other children in the linkset int memberIndex = 1; @@ -440,56 +429,31 @@ public sealed class BSLinksetCompound : BSLinkset else { cPrim.LinksetChildIndex = memberIndex; + } - if (cPrim.PhysShape.isNativeShape) - { - // A native shape is turned into a hull collision shape because native - // shapes are not shared so we have to hullify it so it will be tracked - // and freed at the correct time. This also solves the scaling problem - // (native shapes scale but hull/meshes are assumed to not be). - // TODO: decide of the native shape can just be used in the compound shape. - // Use call to CreateGeomNonSpecial(). - BulletShape saveShape = cPrim.PhysShape; - cPrim.PhysShape.Clear(); // Don't let the create free the child's shape - PhysicsScene.Shapes.CreateGeomMeshOrHull(cPrim, null); - BulletShape newShape = cPrim.PhysShape; - cPrim.PhysShape = saveShape; - - OMV.Vector3 offsetPos = (cPrim.RawPosition - LinksetRoot.RawPosition) * invRootOrientation - centerDisplacement; - OMV.Quaternion offsetRot = cPrim.RawOrientation * invRootOrientation; - PhysicsScene.PE.AddChildShapeToCompoundShape(LinksetRoot.PhysShape, newShape, offsetPos, offsetRot); - DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,addNative,indx={1},rShape={2},cShape={3},offPos={4},offRot={5}", - LinksetRoot.LocalID, memberIndex, LinksetRoot.PhysShape, newShape, offsetPos, offsetRot); - } - else - { - // For the shared shapes (meshes and hulls), just use the shape in the child. - // The reference count added here will be decremented when the compound shape - // is destroyed in BSShapeCollection (the child shapes are looped over and dereferenced). - if (PhysicsScene.Shapes.ReferenceShape(cPrim.PhysShape)) - { - PhysicsScene.Logger.ErrorFormat("{0} Rebuilt sharable shape when building linkset! Region={1}, primID={2}, shape={3}", - LogHeader, PhysicsScene.RegionName, cPrim.LocalID, cPrim.PhysShape); - } - OMV.Vector3 offsetPos = (cPrim.RawPosition - LinksetRoot.RawPosition) * invRootOrientation - centerDisplacement; - OMV.Quaternion offsetRot = cPrim.RawOrientation * invRootOrientation; - PhysicsScene.PE.AddChildShapeToCompoundShape(LinksetRoot.PhysShape, cPrim.PhysShape, offsetPos, offsetRot); - DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,addNonNative,indx={1},rShape={2},cShape={3},offPos={4},offRot={5}", + BSShape childShape = cPrim.PhysShape; + childShape.IncrementReference(); + OMV.Vector3 offsetPos = (cPrim.RawPosition - LinksetRoot.RawPosition) * invRootOrientation - centerDisplacement; + OMV.Quaternion offsetRot = cPrim.RawOrientation * invRootOrientation; + PhysicsScene.PE.AddChildShapeToCompoundShape(LinksetShape.physShapeInfo, childShape.physShapeInfo, offsetPos, offsetRot); + DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,addChild,indx={1},rShape={2},cShape={3},offPos={4},offRot={5}", LinksetRoot.LocalID, memberIndex, LinksetRoot.PhysShape, cPrim.PhysShape, offsetPos, offsetRot); - } - memberIndex++; - } + memberIndex++; + return false; // 'false' says to move onto the next child in the list }); + // Sneak the built compound shape in as the shape of the root prim. + // Note this doesn't touch the root prim's PhysShape so be sure the manage the difference. + PhysicsScene.PE.SetCollisionShape(PhysicsScene.World, LinksetRoot.PhysBody, LinksetShape.physShapeInfo); + // With all of the linkset packed into the root prim, it has the mass of everyone. LinksetMass = ComputeLinksetMass(); LinksetRoot.UpdatePhysicalMassProperties(LinksetMass, true); // Enable the physical position updator to return the position and rotation of the root shape PhysicsScene.PE.AddToCollisionFlags(LinksetRoot.PhysBody, CollisionFlags.BS_RETURN_ROOT_COMPOUND_SHAPE); - */ } finally { -- cgit v1.1 From ad1787770ed02f71feaa002ab689467e187803bb Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Sun, 28 Apr 2013 21:50:47 -0700 Subject: BulletSim: rename variable 'PhysicsScene' to be either 'PhysScene' or 'm_physicsScene' to match coding conventions and reduce confusion. --- .../Region/Physics/BulletSPlugin/BSCharacter.cs | 112 ++++++------ OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 8 +- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 10 +- .../Physics/BulletSPlugin/BSLinksetCompound.cs | 34 ++-- .../Physics/BulletSPlugin/BSLinksetConstraints.cs | 16 +- .../Region/Physics/BulletSPlugin/BSPhysObject.cs | 52 +++--- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 188 ++++++++++----------- .../Region/Physics/BulletSPlugin/BSPrimLinkable.cs | 8 +- .../Physics/BulletSPlugin/BSTerrainHeightmap.cs | 28 +-- .../Physics/BulletSPlugin/BSTerrainManager.cs | 56 +++--- .../Region/Physics/BulletSPlugin/BSTerrainMesh.cs | 52 +++--- 11 files changed, 282 insertions(+), 282 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index da23a262..e12fc8e 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -95,18 +95,18 @@ public sealed class BSCharacter : BSPhysObject // the avatar seeking to reach the motor's target speed. // This motor runs as a prestep action for the avatar so it will keep the avatar // standing as well as moving. Destruction of the avatar will destroy the pre-step action. - m_moveActor = new BSActorAvatarMove(PhysicsScene, this, AvatarMoveActorName); + m_moveActor = new BSActorAvatarMove(PhysScene, this, AvatarMoveActorName); PhysicalActors.Add(AvatarMoveActorName, m_moveActor); DetailLog("{0},BSCharacter.create,call,size={1},scale={2},density={3},volume={4},mass={5}", LocalID, _size, Scale, Density, _avatarVolume, RawMass); // do actual creation in taint time - PhysicsScene.TaintedObject("BSCharacter.create", delegate() + PhysScene.TaintedObject("BSCharacter.create", delegate() { DetailLog("{0},BSCharacter.create,taint", LocalID); // New body and shape into PhysBody and PhysShape - PhysicsScene.Shapes.GetBodyAndShape(true, PhysicsScene.World, this); + PhysScene.Shapes.GetBodyAndShape(true, PhysScene.World, this); SetPhysicalProperties(); }); @@ -119,18 +119,18 @@ public sealed class BSCharacter : BSPhysObject base.Destroy(); DetailLog("{0},BSCharacter.Destroy", LocalID); - PhysicsScene.TaintedObject("BSCharacter.destroy", delegate() + PhysScene.TaintedObject("BSCharacter.destroy", delegate() { - PhysicsScene.Shapes.DereferenceBody(PhysBody, null /* bodyCallback */); + PhysScene.Shapes.DereferenceBody(PhysBody, null /* bodyCallback */); PhysBody.Clear(); - PhysShape.Dereference(PhysicsScene); + PhysShape.Dereference(PhysScene); PhysShape = new BSShapeNull(); }); } private void SetPhysicalProperties() { - PhysicsScene.PE.RemoveObjectFromWorld(PhysicsScene.World, PhysBody); + PhysScene.PE.RemoveObjectFromWorld(PhysScene.World, PhysBody); ZeroMotion(true); ForcePosition = _position; @@ -145,35 +145,35 @@ public sealed class BSCharacter : BSPhysObject // Needs to be reset especially when an avatar is recreated after crossing a region boundry. Flying = _flying; - PhysicsScene.PE.SetRestitution(PhysBody, BSParam.AvatarRestitution); - PhysicsScene.PE.SetMargin(PhysShape.physShapeInfo, PhysicsScene.Params.collisionMargin); - PhysicsScene.PE.SetLocalScaling(PhysShape.physShapeInfo, Scale); - PhysicsScene.PE.SetContactProcessingThreshold(PhysBody, BSParam.ContactProcessingThreshold); + PhysScene.PE.SetRestitution(PhysBody, BSParam.AvatarRestitution); + PhysScene.PE.SetMargin(PhysShape.physShapeInfo, PhysScene.Params.collisionMargin); + PhysScene.PE.SetLocalScaling(PhysShape.physShapeInfo, Scale); + PhysScene.PE.SetContactProcessingThreshold(PhysBody, BSParam.ContactProcessingThreshold); if (BSParam.CcdMotionThreshold > 0f) { - PhysicsScene.PE.SetCcdMotionThreshold(PhysBody, BSParam.CcdMotionThreshold); - PhysicsScene.PE.SetCcdSweptSphereRadius(PhysBody, BSParam.CcdSweptSphereRadius); + PhysScene.PE.SetCcdMotionThreshold(PhysBody, BSParam.CcdMotionThreshold); + PhysScene.PE.SetCcdSweptSphereRadius(PhysBody, BSParam.CcdSweptSphereRadius); } UpdatePhysicalMassProperties(RawMass, false); // Make so capsule does not fall over - PhysicsScene.PE.SetAngularFactorV(PhysBody, OMV.Vector3.Zero); + PhysScene.PE.SetAngularFactorV(PhysBody, OMV.Vector3.Zero); // The avatar mover sets some parameters. PhysicalActors.Refresh(); - PhysicsScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.CF_CHARACTER_OBJECT); + PhysScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.CF_CHARACTER_OBJECT); - PhysicsScene.PE.AddObjectToWorld(PhysicsScene.World, PhysBody); + PhysScene.PE.AddObjectToWorld(PhysScene.World, PhysBody); // PhysicsScene.PE.ForceActivationState(PhysBody, ActivationState.ACTIVE_TAG); - PhysicsScene.PE.ForceActivationState(PhysBody, ActivationState.DISABLE_DEACTIVATION); - PhysicsScene.PE.UpdateSingleAabb(PhysicsScene.World, PhysBody); + PhysScene.PE.ForceActivationState(PhysBody, ActivationState.DISABLE_DEACTIVATION); + PhysScene.PE.UpdateSingleAabb(PhysScene.World, PhysBody); // Do this after the object has been added to the world PhysBody.collisionType = CollisionType.Avatar; - PhysBody.ApplyCollisionMask(PhysicsScene); + PhysBody.ApplyCollisionMask(PhysScene); } @@ -203,14 +203,14 @@ public sealed class BSCharacter : BSPhysObject DetailLog("{0},BSCharacter.setSize,call,size={1},scale={2},density={3},volume={4},mass={5}", LocalID, _size, Scale, Density, _avatarVolume, RawMass); - PhysicsScene.TaintedObject("BSCharacter.setSize", delegate() + PhysScene.TaintedObject("BSCharacter.setSize", delegate() { if (PhysBody.HasPhysicalBody && PhysShape.physShapeInfo.HasPhysicalShape) { - PhysicsScene.PE.SetLocalScaling(PhysShape.physShapeInfo, Scale); + PhysScene.PE.SetLocalScaling(PhysShape.physShapeInfo, Scale); UpdatePhysicalMassProperties(RawMass, true); // Make sure this change appears as a property update event - PhysicsScene.PE.PushUpdate(PhysBody); + PhysScene.PE.PushUpdate(PhysBody); } }); @@ -247,24 +247,24 @@ public sealed class BSCharacter : BSPhysObject _rotationalVelocity = OMV.Vector3.Zero; // Zero some other properties directly into the physics engine - PhysicsScene.TaintedObject(inTaintTime, "BSCharacter.ZeroMotion", delegate() + PhysScene.TaintedObject(inTaintTime, "BSCharacter.ZeroMotion", delegate() { if (PhysBody.HasPhysicalBody) - PhysicsScene.PE.ClearAllForces(PhysBody); + PhysScene.PE.ClearAllForces(PhysBody); }); } public override void ZeroAngularMotion(bool inTaintTime) { _rotationalVelocity = OMV.Vector3.Zero; - PhysicsScene.TaintedObject(inTaintTime, "BSCharacter.ZeroMotion", delegate() + PhysScene.TaintedObject(inTaintTime, "BSCharacter.ZeroMotion", delegate() { if (PhysBody.HasPhysicalBody) { - PhysicsScene.PE.SetInterpolationAngularVelocity(PhysBody, OMV.Vector3.Zero); - PhysicsScene.PE.SetAngularVelocity(PhysBody, OMV.Vector3.Zero); + PhysScene.PE.SetInterpolationAngularVelocity(PhysBody, OMV.Vector3.Zero); + PhysScene.PE.SetAngularVelocity(PhysBody, OMV.Vector3.Zero); // The next also get rid of applied linear force but the linear velocity is untouched. - PhysicsScene.PE.ClearForces(PhysBody); + PhysScene.PE.ClearForces(PhysBody); } }); } @@ -286,7 +286,7 @@ public sealed class BSCharacter : BSPhysObject set { _position = value; - PhysicsScene.TaintedObject("BSCharacter.setPosition", delegate() + PhysScene.TaintedObject("BSCharacter.setPosition", delegate() { DetailLog("{0},BSCharacter.SetPosition,taint,pos={1},orient={2}", LocalID, _position, _orientation); PositionSanityCheck(); @@ -296,14 +296,14 @@ public sealed class BSCharacter : BSPhysObject } public override OMV.Vector3 ForcePosition { get { - _position = PhysicsScene.PE.GetPosition(PhysBody); + _position = PhysScene.PE.GetPosition(PhysBody); return _position; } set { _position = value; if (PhysBody.HasPhysicalBody) { - PhysicsScene.PE.SetTranslation(PhysBody, _position, _orientation); + PhysScene.PE.SetTranslation(PhysBody, _position, _orientation); } } } @@ -317,18 +317,18 @@ public sealed class BSCharacter : BSPhysObject bool ret = false; // TODO: check for out of bounds - if (!PhysicsScene.TerrainManager.IsWithinKnownTerrain(RawPosition)) + if (!PhysScene.TerrainManager.IsWithinKnownTerrain(RawPosition)) { // The character is out of the known/simulated area. // Force the avatar position to be within known. ScenePresence will use the position // plus the velocity to decide if the avatar is moving out of the region. - RawPosition = PhysicsScene.TerrainManager.ClampPositionIntoKnownTerrain(RawPosition); + RawPosition = PhysScene.TerrainManager.ClampPositionIntoKnownTerrain(RawPosition); DetailLog("{0},BSCharacter.PositionSanityCheck,notWithinKnownTerrain,clampedPos={1}", LocalID, RawPosition); return true; } // If below the ground, move the avatar up - float terrainHeight = PhysicsScene.TerrainManager.GetTerrainHeightAtXYZ(RawPosition); + float terrainHeight = PhysScene.TerrainManager.GetTerrainHeightAtXYZ(RawPosition); if (Position.Z < terrainHeight) { DetailLog("{0},BSCharacter.PositionSanityCheck,adjustForUnderGround,pos={1},terrain={2}", LocalID, _position, terrainHeight); @@ -337,7 +337,7 @@ public sealed class BSCharacter : BSPhysObject } if ((CurrentCollisionFlags & CollisionFlags.BS_FLOATS_ON_WATER) != 0) { - float waterHeight = PhysicsScene.TerrainManager.GetWaterLevelAtXYZ(_position); + float waterHeight = PhysScene.TerrainManager.GetWaterLevelAtXYZ(_position); if (Position.Z < waterHeight) { _position.Z = waterHeight; @@ -358,7 +358,7 @@ public sealed class BSCharacter : BSPhysObject { // The new position value must be pushed into the physics engine but we can't // just assign to "Position" because of potential call loops. - PhysicsScene.TaintedObject(inTaintTime, "BSCharacter.PositionSanityCheck", delegate() + PhysScene.TaintedObject(inTaintTime, "BSCharacter.PositionSanityCheck", delegate() { DetailLog("{0},BSCharacter.PositionSanityCheck,taint,pos={1},orient={2}", LocalID, _position, _orientation); ForcePosition = _position; @@ -376,8 +376,8 @@ public sealed class BSCharacter : BSPhysObject } public override void UpdatePhysicalMassProperties(float physMass, bool inWorld) { - OMV.Vector3 localInertia = PhysicsScene.PE.CalculateLocalInertia(PhysShape.physShapeInfo, physMass); - PhysicsScene.PE.SetMassProps(PhysBody, physMass, localInertia); + OMV.Vector3 localInertia = PhysScene.PE.CalculateLocalInertia(PhysShape.physShapeInfo, physMass); + PhysScene.PE.SetMassProps(PhysBody, physMass, localInertia); } public override OMV.Vector3 Force { @@ -385,11 +385,11 @@ public sealed class BSCharacter : BSPhysObject set { RawForce = value; // m_log.DebugFormat("{0}: Force = {1}", LogHeader, _force); - PhysicsScene.TaintedObject("BSCharacter.SetForce", delegate() + PhysScene.TaintedObject("BSCharacter.SetForce", delegate() { DetailLog("{0},BSCharacter.setForce,taint,force={1}", LocalID, RawForce); if (PhysBody.HasPhysicalBody) - PhysicsScene.PE.SetObjectForce(PhysBody, RawForce); + PhysScene.PE.SetObjectForce(PhysBody, RawForce); }); } } @@ -432,7 +432,7 @@ public sealed class BSCharacter : BSPhysObject set { RawVelocity = value; // m_log.DebugFormat("{0}: set velocity = {1}", LogHeader, RawVelocity); - PhysicsScene.TaintedObject("BSCharacter.setVelocity", delegate() + PhysScene.TaintedObject("BSCharacter.setVelocity", delegate() { if (m_moveActor != null) m_moveActor.SetVelocityAndTarget(RawVelocity, RawVelocity, true /* inTaintTime */); @@ -445,11 +445,11 @@ public sealed class BSCharacter : BSPhysObject public override OMV.Vector3 ForceVelocity { get { return RawVelocity; } set { - PhysicsScene.AssertInTaintTime("BSCharacter.ForceVelocity"); + PhysScene.AssertInTaintTime("BSCharacter.ForceVelocity"); RawVelocity = value; - PhysicsScene.PE.SetLinearVelocity(PhysBody, RawVelocity); - PhysicsScene.PE.Activate(PhysBody, true); + PhysScene.PE.SetLinearVelocity(PhysBody, RawVelocity); + PhysScene.PE.Activate(PhysBody, true); } } public override OMV.Vector3 Torque { @@ -479,7 +479,7 @@ public sealed class BSCharacter : BSPhysObject if (_orientation != value) { _orientation = value; - PhysicsScene.TaintedObject("BSCharacter.setOrientation", delegate() + PhysScene.TaintedObject("BSCharacter.setOrientation", delegate() { ForceOrientation = _orientation; }); @@ -491,7 +491,7 @@ public sealed class BSCharacter : BSPhysObject { get { - _orientation = PhysicsScene.PE.GetOrientation(PhysBody); + _orientation = PhysScene.PE.GetOrientation(PhysBody); return _orientation; } set @@ -500,7 +500,7 @@ public sealed class BSCharacter : BSPhysObject if (PhysBody.HasPhysicalBody) { // _position = PhysicsScene.PE.GetPosition(BSBody); - PhysicsScene.PE.SetTranslation(PhysBody, _position, _orientation); + PhysScene.PE.SetTranslation(PhysBody, _position, _orientation); } } } @@ -549,14 +549,14 @@ public sealed class BSCharacter : BSPhysObject public override bool FloatOnWater { set { _floatOnWater = value; - PhysicsScene.TaintedObject("BSCharacter.setFloatOnWater", delegate() + PhysScene.TaintedObject("BSCharacter.setFloatOnWater", delegate() { if (PhysBody.HasPhysicalBody) { if (_floatOnWater) - CurrentCollisionFlags = PhysicsScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.BS_FLOATS_ON_WATER); + CurrentCollisionFlags = PhysScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.BS_FLOATS_ON_WATER); else - CurrentCollisionFlags = PhysicsScene.PE.RemoveFromCollisionFlags(PhysBody, CollisionFlags.BS_FLOATS_ON_WATER); + CurrentCollisionFlags = PhysScene.PE.RemoveFromCollisionFlags(PhysBody, CollisionFlags.BS_FLOATS_ON_WATER); } }); } @@ -577,7 +577,7 @@ public sealed class BSCharacter : BSPhysObject public override float Buoyancy { get { return _buoyancy; } set { _buoyancy = value; - PhysicsScene.TaintedObject("BSCharacter.setBuoyancy", delegate() + PhysScene.TaintedObject("BSCharacter.setBuoyancy", delegate() { DetailLog("{0},BSCharacter.setBuoyancy,taint,buoy={1}", LocalID, _buoyancy); ForceBuoyancy = _buoyancy; @@ -587,7 +587,7 @@ public sealed class BSCharacter : BSPhysObject public override float ForceBuoyancy { get { return _buoyancy; } set { - PhysicsScene.AssertInTaintTime("BSCharacter.ForceBuoyancy"); + PhysScene.AssertInTaintTime("BSCharacter.ForceBuoyancy"); _buoyancy = value; DetailLog("{0},BSCharacter.setForceBuoyancy,taint,buoy={1}", LocalID, _buoyancy); @@ -595,7 +595,7 @@ public sealed class BSCharacter : BSPhysObject float grav = BSParam.Gravity * (1f - _buoyancy); Gravity = new OMV.Vector3(0f, 0f, grav); if (PhysBody.HasPhysicalBody) - PhysicsScene.PE.SetGravity(PhysBody, Gravity); + PhysScene.PE.SetGravity(PhysBody, Gravity); } } @@ -613,7 +613,7 @@ public sealed class BSCharacter : BSPhysObject public override void AddForce(OMV.Vector3 force, bool pushforce) { // Since this force is being applied in only one step, make this a force per second. - OMV.Vector3 addForce = force / PhysicsScene.LastTimeStep; + OMV.Vector3 addForce = force / PhysScene.LastTimeStep; AddForce(addForce, pushforce, false); } private void AddForce(OMV.Vector3 force, bool pushforce, bool inTaintTime) { @@ -622,13 +622,13 @@ public sealed class BSCharacter : BSPhysObject OMV.Vector3 addForce = Util.ClampV(force, BSParam.MaxAddForceMagnitude); // DetailLog("{0},BSCharacter.addForce,call,force={1}", LocalID, addForce); - PhysicsScene.TaintedObject(inTaintTime, "BSCharacter.AddForce", delegate() + PhysScene.TaintedObject(inTaintTime, "BSCharacter.AddForce", delegate() { // Bullet adds this central force to the total force for this tick // DetailLog("{0},BSCharacter.addForce,taint,force={1}", LocalID, addForce); if (PhysBody.HasPhysicalBody) { - PhysicsScene.PE.ApplyCentralForce(PhysBody, addForce); + PhysScene.PE.ApplyCentralForce(PhysBody, addForce); } }); } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index e2e807e..56d2415 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -789,7 +789,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin if ((m_knownHas & m_knownChangedTerrainHeight) == 0 || pos != lastRememberedHeightPos) { lastRememberedHeightPos = pos; - m_knownTerrainHeight = ControllingPrim.PhysicsScene.TerrainManager.GetTerrainHeightAtXYZ(pos); + m_knownTerrainHeight = ControllingPrim.PhysScene.TerrainManager.GetTerrainHeightAtXYZ(pos); m_knownHas |= m_knownChangedTerrainHeight; } return m_knownTerrainHeight; @@ -801,7 +801,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin { if ((m_knownHas & m_knownChangedWaterLevel) == 0) { - m_knownWaterLevel = ControllingPrim.PhysicsScene.TerrainManager.GetWaterLevelAtXYZ(pos); + m_knownWaterLevel = ControllingPrim.PhysScene.TerrainManager.GetWaterLevelAtXYZ(pos); m_knownHas |= m_knownChangedWaterLevel; } return (float)m_knownWaterLevel; @@ -1637,8 +1637,8 @@ namespace OpenSim.Region.Physics.BulletSPlugin // Invoke the detailed logger and output something if it's enabled. private void VDetailLog(string msg, params Object[] args) { - if (ControllingPrim.PhysicsScene.VehicleLoggingEnabled) - ControllingPrim.PhysicsScene.DetailLog(msg, args); + if (ControllingPrim.PhysScene.VehicleLoggingEnabled) + ControllingPrim.PhysScene.DetailLog(msg, args); } } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index df1dd34..6d0d0eb 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -80,7 +80,7 @@ public abstract class BSLinkset public BSPrimLinkable LinksetRoot { get; protected set; } - public BSScene PhysicsScene { get; private set; } + protected BSScene m_physicsScene { get; private set; } static int m_nextLinksetID = 1; public int LinksetID { get; private set; } @@ -115,7 +115,7 @@ public abstract class BSLinkset // We create LOTS of linksets. if (m_nextLinksetID <= 0) m_nextLinksetID = 1; - PhysicsScene = scene; + m_physicsScene = scene; LinksetRoot = parent; m_children = new HashSet(); LinksetMass = parent.RawMass; @@ -158,7 +158,7 @@ public abstract class BSLinkset } // The child is down to a linkset of just itself - return BSLinkset.Factory(PhysicsScene, child); + return BSLinkset.Factory(m_physicsScene, child); } // Return 'true' if the passed object is the root object of this linkset @@ -316,8 +316,8 @@ public abstract class BSLinkset // Invoke the detailed logger and output something if it's enabled. protected void DetailLog(string msg, params Object[] args) { - if (PhysicsScene.PhysicsLogging.Enabled) - PhysicsScene.DetailLog(msg, args); + if (m_physicsScene.PhysicsLogging.Enabled) + m_physicsScene.DetailLog(msg, args); } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs index be01808..01ada3f 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs @@ -121,7 +121,7 @@ public sealed class BSLinksetCompound : BSLinkset // If a linkset with just a root prim (simple non-linked prim) don't bother rebuilding. if (!Rebuilding && HasAnyChildren) { - PhysicsScene.PostTaintObject("BSLinksetCompound.ScheduleRebuild", LinksetRoot.LocalID, delegate() + m_physicsScene.PostTaintObject("BSLinksetCompound.ScheduleRebuild", LinksetRoot.LocalID, delegate() { if (HasAnyChildren) RecomputeLinksetCompound(); @@ -147,10 +147,10 @@ public sealed class BSLinksetCompound : BSLinkset { // The origional prims are removed from the world as the shape of the root compound // shape takes over. - PhysicsScene.PE.AddToCollisionFlags(child.PhysBody, CollisionFlags.CF_NO_CONTACT_RESPONSE); - PhysicsScene.PE.ForceActivationState(child.PhysBody, ActivationState.DISABLE_SIMULATION); + m_physicsScene.PE.AddToCollisionFlags(child.PhysBody, CollisionFlags.CF_NO_CONTACT_RESPONSE); + m_physicsScene.PE.ForceActivationState(child.PhysBody, ActivationState.DISABLE_SIMULATION); // We don't want collisions from the old linkset children. - PhysicsScene.PE.RemoveFromCollisionFlags(child.PhysBody, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); + m_physicsScene.PE.RemoveFromCollisionFlags(child.PhysBody, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); child.PhysBody.collisionType = CollisionType.LinksetChild; @@ -175,12 +175,12 @@ public sealed class BSLinksetCompound : BSLinkset else { // The non-physical children can come back to life. - PhysicsScene.PE.RemoveFromCollisionFlags(child.PhysBody, CollisionFlags.CF_NO_CONTACT_RESPONSE); + m_physicsScene.PE.RemoveFromCollisionFlags(child.PhysBody, CollisionFlags.CF_NO_CONTACT_RESPONSE); child.PhysBody.collisionType = CollisionType.LinksetChild; // Don't force activation so setting of DISABLE_SIMULATION can stay if used. - PhysicsScene.PE.Activate(child.PhysBody, false); + m_physicsScene.PE.Activate(child.PhysBody, false); ret = true; } return ret; @@ -196,7 +196,7 @@ public sealed class BSLinksetCompound : BSLinkset // but it also means all the child positions get updated. // What would cause an unnecessary rebuild so we make sure the linkset is in a // region before bothering to do a rebuild. - if (!IsRoot(updated) && PhysicsScene.TerrainManager.IsWithinKnownTerrain(LinksetRoot.RawPosition)) + if (!IsRoot(updated) && m_physicsScene.TerrainManager.IsWithinKnownTerrain(LinksetRoot.RawPosition)) { // If a child of the linkset is updating only the position or rotation, that can be done // without rebuilding the linkset. @@ -209,21 +209,21 @@ public sealed class BSLinksetCompound : BSLinkset if ((whichUpdated & ~(UpdatedProperties.Position | UpdatedProperties.Orientation)) == 0) { // Find the physical instance of the child - if (LinksetRoot.PhysShape.HasPhysicalShape && PhysicsScene.PE.IsCompound(LinksetRoot.PhysShape.physShapeInfo)) + if (LinksetRoot.PhysShape.HasPhysicalShape && m_physicsScene.PE.IsCompound(LinksetRoot.PhysShape.physShapeInfo)) { // It is possible that the linkset is still under construction and the child is not yet // inserted into the compound shape. A rebuild of the linkset in a pre-step action will // build the whole thing with the new position or rotation. // The index must be checked because Bullet references the child array but does no validity // checking of the child index passed. - int numLinksetChildren = PhysicsScene.PE.GetNumberOfCompoundChildren(LinksetRoot.PhysShape.physShapeInfo); + int numLinksetChildren = m_physicsScene.PE.GetNumberOfCompoundChildren(LinksetRoot.PhysShape.physShapeInfo); if (updated.LinksetChildIndex < numLinksetChildren) { - BulletShape linksetChildShape = PhysicsScene.PE.GetChildShapeFromCompoundShapeIndex(LinksetRoot.PhysShape.physShapeInfo, updated.LinksetChildIndex); + BulletShape linksetChildShape = m_physicsScene.PE.GetChildShapeFromCompoundShapeIndex(LinksetRoot.PhysShape.physShapeInfo, updated.LinksetChildIndex); if (linksetChildShape.HasPhysicalShape) { // Found the child shape within the compound shape - PhysicsScene.PE.UpdateChildTransform(LinksetRoot.PhysShape.physShapeInfo, updated.LinksetChildIndex, + m_physicsScene.PE.UpdateChildTransform(LinksetRoot.PhysShape.physShapeInfo, updated.LinksetChildIndex, updated.RawPosition - LinksetRoot.RawPosition, updated.RawOrientation * OMV.Quaternion.Inverse(LinksetRoot.RawOrientation), true /* shouldRecalculateLocalAabb */); @@ -401,9 +401,9 @@ public sealed class BSLinksetCompound : BSLinkset // Here we build the compound shape made up of all the children. // Free up any shape we'd previously built. - LinksetShape.Dereference(PhysicsScene); + LinksetShape.Dereference(m_physicsScene); - LinksetShape = BSShapeCompound.GetReference(PhysicsScene, LinksetRoot); + LinksetShape = BSShapeCompound.GetReference(m_physicsScene, LinksetRoot); // The center of mass for the linkset is the geometric center of the group. // Compute a displacement for each component so it is relative to the center-of-mass. @@ -435,7 +435,7 @@ public sealed class BSLinksetCompound : BSLinkset childShape.IncrementReference(); OMV.Vector3 offsetPos = (cPrim.RawPosition - LinksetRoot.RawPosition) * invRootOrientation - centerDisplacement; OMV.Quaternion offsetRot = cPrim.RawOrientation * invRootOrientation; - PhysicsScene.PE.AddChildShapeToCompoundShape(LinksetShape.physShapeInfo, childShape.physShapeInfo, offsetPos, offsetRot); + m_physicsScene.PE.AddChildShapeToCompoundShape(LinksetShape.physShapeInfo, childShape.physShapeInfo, offsetPos, offsetRot); DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,addChild,indx={1},rShape={2},cShape={3},offPos={4},offRot={5}", LinksetRoot.LocalID, memberIndex, LinksetRoot.PhysShape, cPrim.PhysShape, offsetPos, offsetRot); @@ -446,14 +446,14 @@ public sealed class BSLinksetCompound : BSLinkset // Sneak the built compound shape in as the shape of the root prim. // Note this doesn't touch the root prim's PhysShape so be sure the manage the difference. - PhysicsScene.PE.SetCollisionShape(PhysicsScene.World, LinksetRoot.PhysBody, LinksetShape.physShapeInfo); + m_physicsScene.PE.SetCollisionShape(m_physicsScene.World, LinksetRoot.PhysBody, LinksetShape.physShapeInfo); // With all of the linkset packed into the root prim, it has the mass of everyone. LinksetMass = ComputeLinksetMass(); LinksetRoot.UpdatePhysicalMassProperties(LinksetMass, true); // Enable the physical position updator to return the position and rotation of the root shape - PhysicsScene.PE.AddToCollisionFlags(LinksetRoot.PhysBody, CollisionFlags.BS_RETURN_ROOT_COMPOUND_SHAPE); + m_physicsScene.PE.AddToCollisionFlags(LinksetRoot.PhysBody, CollisionFlags.BS_RETURN_ROOT_COMPOUND_SHAPE); } finally { @@ -461,7 +461,7 @@ public sealed class BSLinksetCompound : BSLinkset } // See that the Aabb surrounds the new shape - PhysicsScene.PE.RecalculateCompoundShapeLocalAabb(LinksetRoot.PhysShape.physShapeInfo); + m_physicsScene.PE.RecalculateCompoundShapeLocalAabb(LinksetRoot.PhysShape.physShapeInfo); } } } \ No newline at end of file diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs index 1811772..a06a44d 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs @@ -51,7 +51,7 @@ public sealed class BSLinksetConstraints : BSLinkset if (HasAnyChildren && IsRoot(requestor)) { // Queue to happen after all the other taint processing - PhysicsScene.PostTaintObject("BSLinksetContraints.Refresh", requestor.LocalID, delegate() + m_physicsScene.PostTaintObject("BSLinksetContraints.Refresh", requestor.LocalID, delegate() { if (HasAnyChildren && IsRoot(requestor)) RecomputeLinksetConstraints(); @@ -142,7 +142,7 @@ public sealed class BSLinksetConstraints : BSLinkset rootx.LocalID, rootx.PhysBody.AddrString, childx.LocalID, childx.PhysBody.AddrString); - PhysicsScene.TaintedObject("BSLinksetConstraints.RemoveChildFromLinkset", delegate() + m_physicsScene.TaintedObject("BSLinksetConstraints.RemoveChildFromLinkset", delegate() { PhysicallyUnlinkAChildFromRoot(rootx, childx); }); @@ -187,7 +187,7 @@ public sealed class BSLinksetConstraints : BSLinkset // http://bulletphysics.org/Bullet/phpBB3/viewtopic.php?t=4818 BSConstraint6Dof constrain = new BSConstraint6Dof( - PhysicsScene.World, rootPrim.PhysBody, childPrim.PhysBody, midPoint, true, true ); + m_physicsScene.World, rootPrim.PhysBody, childPrim.PhysBody, midPoint, true, true ); // PhysicsScene.World, childPrim.BSBody, rootPrim.BSBody, midPoint, true, true ); /* NOTE: below is an attempt to build constraint with full frame computation, etc. @@ -216,7 +216,7 @@ public sealed class BSLinksetConstraints : BSLinkset // ================================================================================== */ - PhysicsScene.Constraints.AddConstraint(constrain); + m_physicsScene.Constraints.AddConstraint(constrain); // zero linear and angular limits makes the objects unable to move in relation to each other constrain.SetLinearLimits(OMV.Vector3.Zero, OMV.Vector3.Zero); @@ -248,10 +248,10 @@ public sealed class BSLinksetConstraints : BSLinkset childPrim.LocalID, childPrim.PhysBody.AddrString); // Find the constraint for this link and get rid of it from the overall collection and from my list - if (PhysicsScene.Constraints.RemoveAndDestroyConstraint(rootPrim.PhysBody, childPrim.PhysBody)) + if (m_physicsScene.Constraints.RemoveAndDestroyConstraint(rootPrim.PhysBody, childPrim.PhysBody)) { // Make the child refresh its location - PhysicsScene.PE.PushUpdate(childPrim.PhysBody); + m_physicsScene.PE.PushUpdate(childPrim.PhysBody); ret = true; } @@ -265,7 +265,7 @@ public sealed class BSLinksetConstraints : BSLinkset { DetailLog("{0},BSLinksetConstraint.PhysicallyUnlinkAllChildren,taint", rootPrim.LocalID); - return PhysicsScene.Constraints.RemoveAndDestroyConstraint(rootPrim.PhysBody); + return m_physicsScene.Constraints.RemoveAndDestroyConstraint(rootPrim.PhysBody); } // Call each of the constraints that make up this linkset and recompute the @@ -289,7 +289,7 @@ public sealed class BSLinksetConstraints : BSLinkset child.UpdatePhysicalMassProperties(linksetMass, true); BSConstraint constrain; - if (!PhysicsScene.Constraints.TryGetConstraint(LinksetRoot.PhysBody, child.PhysBody, out constrain)) + if (!m_physicsScene.Constraints.TryGetConstraint(LinksetRoot.PhysBody, child.PhysBody, out constrain)) { // If constraint doesn't exist yet, create it. constrain = BuildConstraint(LinksetRoot, child); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index b6eb619..6a3ada2 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -72,14 +72,14 @@ public abstract class BSPhysObject : PhysicsActor } protected BSPhysObject(BSScene parentScene, uint localID, string name, string typeName) { - PhysicsScene = parentScene; + PhysScene = parentScene; LocalID = localID; PhysObjectName = name; Name = name; // PhysicsActor also has the name of the object. Someday consolidate. TypeName = typeName; // The collection of things that push me around - PhysicalActors = new BSActorCollection(PhysicsScene); + PhysicalActors = new BSActorCollection(PhysScene); // Initialize variables kept in base. GravModifier = 1.0f; @@ -112,13 +112,13 @@ public abstract class BSPhysObject : PhysicsActor public virtual void Destroy() { PhysicalActors.Enable(false); - PhysicsScene.TaintedObject("BSPhysObject.Destroy", delegate() + PhysScene.TaintedObject("BSPhysObject.Destroy", delegate() { PhysicalActors.Dispose(); }); } - public BSScene PhysicsScene { get; protected set; } + public BSScene PhysScene { get; protected set; } // public override uint LocalID { get; set; } // Use the LocalID definition in PhysicsActor public string PhysObjectName { get; protected set; } public string TypeName { get; protected set; } @@ -270,7 +270,7 @@ public abstract class BSPhysObject : PhysicsActor public void ActivateIfPhysical(bool forceIt) { if (IsPhysical && PhysBody.HasPhysicalBody) - PhysicsScene.PE.Activate(PhysBody, forceIt); + PhysScene.PE.Activate(PhysBody, forceIt); } // 'actors' act on the physical object to change or constrain its motion. These can range from @@ -333,29 +333,29 @@ public abstract class BSPhysObject : PhysicsActor protected long CollisionAccumulation { get; set; } public override bool IsColliding { - get { return (CollidingStep == PhysicsScene.SimulationStep); } + get { return (CollidingStep == PhysScene.SimulationStep); } set { if (value) - CollidingStep = PhysicsScene.SimulationStep; + CollidingStep = PhysScene.SimulationStep; else CollidingStep = 0; } } public override bool CollidingGround { - get { return (CollidingGroundStep == PhysicsScene.SimulationStep); } + get { return (CollidingGroundStep == PhysScene.SimulationStep); } set { if (value) - CollidingGroundStep = PhysicsScene.SimulationStep; + CollidingGroundStep = PhysScene.SimulationStep; else CollidingGroundStep = 0; } } public override bool CollidingObj { - get { return (CollidingObjectStep == PhysicsScene.SimulationStep); } + get { return (CollidingObjectStep == PhysScene.SimulationStep); } set { if (value) - CollidingObjectStep = PhysicsScene.SimulationStep; + CollidingObjectStep = PhysScene.SimulationStep; else CollidingObjectStep = 0; } @@ -380,14 +380,14 @@ public abstract class BSPhysObject : PhysicsActor bool ret = false; // The following lines make IsColliding(), CollidingGround() and CollidingObj work - CollidingStep = PhysicsScene.SimulationStep; - if (collidingWith <= PhysicsScene.TerrainManager.HighestTerrainID) + CollidingStep = PhysScene.SimulationStep; + if (collidingWith <= PhysScene.TerrainManager.HighestTerrainID) { - CollidingGroundStep = PhysicsScene.SimulationStep; + CollidingGroundStep = PhysScene.SimulationStep; } else { - CollidingObjectStep = PhysicsScene.SimulationStep; + CollidingObjectStep = PhysScene.SimulationStep; } CollisionAccumulation++; @@ -397,10 +397,10 @@ public abstract class BSPhysObject : PhysicsActor // Make a collection of the collisions that happened the last simulation tick. // This is different than the collection created for sending up to the simulator as it is cleared every tick. - if (CollisionsLastTickStep != PhysicsScene.SimulationStep) + if (CollisionsLastTickStep != PhysScene.SimulationStep) { CollisionsLastTick = new CollisionEventUpdate(); - CollisionsLastTickStep = PhysicsScene.SimulationStep; + CollisionsLastTickStep = PhysScene.SimulationStep; } CollisionsLastTick.AddCollider(collidingWith, new ContactPoint(contactPoint, contactNormal, pentrationDepth)); @@ -427,9 +427,9 @@ public abstract class BSPhysObject : PhysicsActor bool force = (CollisionCollection.Count == 0 && CollisionsLastReported.Count != 0); // throttle the collisions to the number of milliseconds specified in the subscription - if (force || (PhysicsScene.SimulationNowTime >= NextCollisionOkTime)) + if (force || (PhysScene.SimulationNowTime >= NextCollisionOkTime)) { - NextCollisionOkTime = PhysicsScene.SimulationNowTime + SubscribedEventsMs; + NextCollisionOkTime = PhysScene.SimulationNowTime + SubscribedEventsMs; // We are called if we previously had collisions. If there are no collisions // this time, send up one last empty event so OpenSim can sense collision end. @@ -464,10 +464,10 @@ public abstract class BSPhysObject : PhysicsActor // make sure first collision happens NextCollisionOkTime = Util.EnvironmentTickCountSubtract(SubscribedEventsMs); - PhysicsScene.TaintedObject(TypeName+".SubscribeEvents", delegate() + PhysScene.TaintedObject(TypeName+".SubscribeEvents", delegate() { if (PhysBody.HasPhysicalBody) - CurrentCollisionFlags = PhysicsScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); + CurrentCollisionFlags = PhysScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); }); } else @@ -479,11 +479,11 @@ public abstract class BSPhysObject : PhysicsActor public override void UnSubscribeEvents() { // DetailLog("{0},{1}.UnSubscribeEvents,unsubscribing", LocalID, TypeName); SubscribedEventsMs = 0; - PhysicsScene.TaintedObject(TypeName+".UnSubscribeEvents", delegate() + PhysScene.TaintedObject(TypeName+".UnSubscribeEvents", delegate() { // Make sure there is a body there because sometimes destruction happens in an un-ideal order. if (PhysBody.HasPhysicalBody) - CurrentCollisionFlags = PhysicsScene.PE.RemoveFromCollisionFlags(PhysBody, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); + CurrentCollisionFlags = PhysScene.PE.RemoveFromCollisionFlags(PhysBody, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); }); } // Return 'true' if the simulator wants collision events @@ -497,7 +497,7 @@ public abstract class BSPhysObject : PhysicsActor { // Scale the collision count by the time since the last collision. // The "+1" prevents dividing by zero. - long timeAgo = PhysicsScene.SimulationStep - CollidingStep + 1; + long timeAgo = PhysScene.SimulationStep - CollidingStep + 1; CollisionScore = CollisionAccumulation / timeAgo; } public override float CollisionScore { get; set; } @@ -524,8 +524,8 @@ public abstract class BSPhysObject : PhysicsActor // High performance detailed logging routine used by the physical objects. protected void DetailLog(string msg, params Object[] args) { - if (PhysicsScene.PhysicsLogging.Enabled) - PhysicsScene.DetailLog(msg, args); + if (PhysScene.PhysicsLogging.Enabled) + PhysScene.DetailLog(msg, args); } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 5d12338..0d45579 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -101,21 +101,21 @@ public class BSPrim : BSPhysObject _isVolumeDetect = false; // We keep a handle to the vehicle actor so we can set vehicle parameters later. - VehicleActor = new BSDynamics(PhysicsScene, this, VehicleActorName); + VehicleActor = new BSDynamics(PhysScene, this, VehicleActorName); PhysicalActors.Add(VehicleActorName, VehicleActor); _mass = CalculateMass(); // DetailLog("{0},BSPrim.constructor,call", LocalID); // do the actual object creation at taint time - PhysicsScene.TaintedObject("BSPrim.create", delegate() + PhysScene.TaintedObject("BSPrim.create", delegate() { // Make sure the object is being created with some sanity. ExtremeSanityCheck(true /* inTaintTime */); CreateGeomAndObject(true); - CurrentCollisionFlags = PhysicsScene.PE.GetCollisionFlags(PhysBody); + CurrentCollisionFlags = PhysScene.PE.GetCollisionFlags(PhysBody); }); } @@ -128,13 +128,13 @@ public class BSPrim : BSPhysObject // Undo any vehicle properties this.VehicleType = (int)Vehicle.TYPE_NONE; - PhysicsScene.TaintedObject("BSPrim.Destroy", delegate() + PhysScene.TaintedObject("BSPrim.Destroy", delegate() { DetailLog("{0},BSPrim.Destroy,taint,", LocalID); // If there are physical body and shape, release my use of same. - PhysicsScene.Shapes.DereferenceBody(PhysBody, null); + PhysScene.Shapes.DereferenceBody(PhysBody, null); PhysBody.Clear(); - PhysShape.Dereference(PhysicsScene); + PhysShape.Dereference(PhysScene); PhysShape = new BSShapeNull(); }); } @@ -163,7 +163,7 @@ public class BSPrim : BSPhysObject } public override bool ForceBodyShapeRebuild(bool inTaintTime) { - PhysicsScene.TaintedObject(inTaintTime, "BSPrim.ForceBodyShapeRebuild", delegate() + PhysScene.TaintedObject(inTaintTime, "BSPrim.ForceBodyShapeRebuild", delegate() { _mass = CalculateMass(); // changing the shape changes the mass CreateGeomAndObject(true); @@ -180,7 +180,7 @@ public class BSPrim : BSPhysObject if (value != _isSelected) { _isSelected = value; - PhysicsScene.TaintedObject("BSPrim.setSelected", delegate() + PhysScene.TaintedObject("BSPrim.setSelected", delegate() { DetailLog("{0},BSPrim.selected,taint,selected={1}", LocalID, _isSelected); SetObjectDynamic(false); @@ -226,23 +226,23 @@ public class BSPrim : BSPhysObject _rotationalVelocity = OMV.Vector3.Zero; // Zero some other properties in the physics engine - PhysicsScene.TaintedObject(inTaintTime, "BSPrim.ZeroMotion", delegate() + PhysScene.TaintedObject(inTaintTime, "BSPrim.ZeroMotion", delegate() { if (PhysBody.HasPhysicalBody) - PhysicsScene.PE.ClearAllForces(PhysBody); + PhysScene.PE.ClearAllForces(PhysBody); }); } public override void ZeroAngularMotion(bool inTaintTime) { _rotationalVelocity = OMV.Vector3.Zero; // Zero some other properties in the physics engine - PhysicsScene.TaintedObject(inTaintTime, "BSPrim.ZeroMotion", delegate() + PhysScene.TaintedObject(inTaintTime, "BSPrim.ZeroMotion", delegate() { // DetailLog("{0},BSPrim.ZeroAngularMotion,call,rotVel={1}", LocalID, _rotationalVelocity); if (PhysBody.HasPhysicalBody) { - PhysicsScene.PE.SetInterpolationAngularVelocity(PhysBody, _rotationalVelocity); - PhysicsScene.PE.SetAngularVelocity(PhysBody, _rotationalVelocity); + PhysScene.PE.SetInterpolationAngularVelocity(PhysBody, _rotationalVelocity); + PhysScene.PE.SetAngularVelocity(PhysBody, _rotationalVelocity); } }); } @@ -260,11 +260,11 @@ public class BSPrim : BSPhysObject EnableActor(LockedAxis != LockedAxisFree, LockedAxisActorName, delegate() { - return new BSActorLockAxis(PhysicsScene, this, LockedAxisActorName); + return new BSActorLockAxis(PhysScene, this, LockedAxisActorName); }); // Update parameters so the new actor's Refresh() action is called at the right time. - PhysicsScene.TaintedObject("BSPrim.LockAngularMotion", delegate() + PhysScene.TaintedObject("BSPrim.LockAngularMotion", delegate() { UpdatePhysicalParameters(); }); @@ -294,7 +294,7 @@ public class BSPrim : BSPhysObject _position = value; PositionSanityCheck(false); - PhysicsScene.TaintedObject("BSPrim.setPosition", delegate() + PhysScene.TaintedObject("BSPrim.setPosition", delegate() { DetailLog("{0},BSPrim.SetPosition,taint,pos={1},orient={2}", LocalID, _position, _orientation); ForcePosition = _position; @@ -304,14 +304,14 @@ public class BSPrim : BSPhysObject public override OMV.Vector3 ForcePosition { get { - _position = PhysicsScene.PE.GetPosition(PhysBody); + _position = PhysScene.PE.GetPosition(PhysBody); return _position; } set { _position = value; if (PhysBody.HasPhysicalBody) { - PhysicsScene.PE.SetTranslation(PhysBody, _position, _orientation); + PhysScene.PE.SetTranslation(PhysBody, _position, _orientation); ActivateIfPhysical(false); } } @@ -328,7 +328,7 @@ public class BSPrim : BSPhysObject if (!IsPhysicallyActive) return ret; - if (!PhysicsScene.TerrainManager.IsWithinKnownTerrain(RawPosition)) + if (!PhysScene.TerrainManager.IsWithinKnownTerrain(RawPosition)) { // The physical object is out of the known/simulated area. // Upper levels of code will handle the transition to other areas so, for @@ -336,7 +336,7 @@ public class BSPrim : BSPhysObject return ret; } - float terrainHeight = PhysicsScene.TerrainManager.GetTerrainHeightAtXYZ(RawPosition); + float terrainHeight = PhysScene.TerrainManager.GetTerrainHeightAtXYZ(RawPosition); OMV.Vector3 upForce = OMV.Vector3.Zero; float approxSize = Math.Max(Size.X, Math.Max(Size.Y, Size.Z)); if ((RawPosition.Z + approxSize / 2f) < terrainHeight) @@ -357,7 +357,7 @@ public class BSPrim : BSPhysObject if ((CurrentCollisionFlags & CollisionFlags.BS_FLOATS_ON_WATER) != 0) { - float waterHeight = PhysicsScene.TerrainManager.GetWaterLevelAtXYZ(_position); + float waterHeight = PhysScene.TerrainManager.GetWaterLevelAtXYZ(_position); // TODO: a floating motor so object will bob in the water if (Math.Abs(RawPosition.Z - waterHeight) > 0.1f) { @@ -365,7 +365,7 @@ public class BSPrim : BSPhysObject upForce.Z = (waterHeight - RawPosition.Z) * 1f; // Apply upforce and overcome gravity. - OMV.Vector3 correctionForce = upForce - PhysicsScene.DefaultGravity; + OMV.Vector3 correctionForce = upForce - PhysScene.DefaultGravity; DetailLog("{0},BSPrim.PositionSanityCheck,applyForce,pos={1},upForce={2},correctionForce={3}", LocalID, _position, upForce, correctionForce); AddForce(correctionForce, false, inTaintTime); ret = true; @@ -431,10 +431,10 @@ public class BSPrim : BSPhysObject { if (IsStatic) { - PhysicsScene.PE.SetGravity(PhysBody, PhysicsScene.DefaultGravity); + PhysScene.PE.SetGravity(PhysBody, PhysScene.DefaultGravity); Inertia = OMV.Vector3.Zero; - PhysicsScene.PE.SetMassProps(PhysBody, 0f, Inertia); - PhysicsScene.PE.UpdateInertiaTensor(PhysBody); + PhysScene.PE.SetMassProps(PhysBody, 0f, Inertia); + PhysScene.PE.UpdateInertiaTensor(PhysBody); } else { @@ -443,16 +443,16 @@ public class BSPrim : BSPhysObject // Changing interesting properties doesn't change proxy and collision cache // information. The Bullet solution is to re-add the object to the world // after parameters are changed. - PhysicsScene.PE.RemoveObjectFromWorld(PhysicsScene.World, PhysBody); + PhysScene.PE.RemoveObjectFromWorld(PhysScene.World, PhysBody); } // The computation of mass props requires gravity to be set on the object. Gravity = ComputeGravity(Buoyancy); - PhysicsScene.PE.SetGravity(PhysBody, Gravity); + PhysScene.PE.SetGravity(PhysBody, Gravity); - Inertia = PhysicsScene.PE.CalculateLocalInertia(PhysShape.physShapeInfo, physMass); - PhysicsScene.PE.SetMassProps(PhysBody, physMass, Inertia); - PhysicsScene.PE.UpdateInertiaTensor(PhysBody); + Inertia = PhysScene.PE.CalculateLocalInertia(PhysShape.physShapeInfo, physMass); + PhysScene.PE.SetMassProps(PhysBody, physMass, Inertia); + PhysScene.PE.UpdateInertiaTensor(PhysBody); DetailLog("{0},BSPrim.UpdateMassProperties,mass={1},localInertia={2},grav={3},inWorld={4}", LocalID, physMass, Inertia, Gravity, inWorld); @@ -468,7 +468,7 @@ public class BSPrim : BSPhysObject // Return what gravity should be set to this very moment public OMV.Vector3 ComputeGravity(float buoyancy) { - OMV.Vector3 ret = PhysicsScene.DefaultGravity; + OMV.Vector3 ret = PhysScene.DefaultGravity; if (!IsStatic) { @@ -497,7 +497,7 @@ public class BSPrim : BSPhysObject RawForce = value; EnableActor(RawForce != OMV.Vector3.Zero, SetForceActorName, delegate() { - return new BSActorSetForce(PhysicsScene, this, SetForceActorName); + return new BSActorSetForce(PhysScene, this, SetForceActorName); }); } } @@ -509,7 +509,7 @@ public class BSPrim : BSPhysObject set { Vehicle type = (Vehicle)value; - PhysicsScene.TaintedObject("setVehicleType", delegate() + PhysScene.TaintedObject("setVehicleType", delegate() { // Vehicle code changes the parameters for this vehicle type. VehicleActor.ProcessTypeChange(type); @@ -519,7 +519,7 @@ public class BSPrim : BSPhysObject } public override void VehicleFloatParam(int param, float value) { - PhysicsScene.TaintedObject("BSPrim.VehicleFloatParam", delegate() + PhysScene.TaintedObject("BSPrim.VehicleFloatParam", delegate() { VehicleActor.ProcessFloatVehicleParam((Vehicle)param, value); ActivateIfPhysical(false); @@ -527,7 +527,7 @@ public class BSPrim : BSPhysObject } public override void VehicleVectorParam(int param, OMV.Vector3 value) { - PhysicsScene.TaintedObject("BSPrim.VehicleVectorParam", delegate() + PhysScene.TaintedObject("BSPrim.VehicleVectorParam", delegate() { VehicleActor.ProcessVectorVehicleParam((Vehicle)param, value); ActivateIfPhysical(false); @@ -535,7 +535,7 @@ public class BSPrim : BSPhysObject } public override void VehicleRotationParam(int param, OMV.Quaternion rotation) { - PhysicsScene.TaintedObject("BSPrim.VehicleRotationParam", delegate() + PhysScene.TaintedObject("BSPrim.VehicleRotationParam", delegate() { VehicleActor.ProcessRotationVehicleParam((Vehicle)param, rotation); ActivateIfPhysical(false); @@ -543,7 +543,7 @@ public class BSPrim : BSPhysObject } public override void VehicleFlags(int param, bool remove) { - PhysicsScene.TaintedObject("BSPrim.VehicleFlags", delegate() + PhysScene.TaintedObject("BSPrim.VehicleFlags", delegate() { VehicleActor.ProcessVehicleFlags(param, remove); }); @@ -555,7 +555,7 @@ public class BSPrim : BSPhysObject if (_isVolumeDetect != newValue) { _isVolumeDetect = newValue; - PhysicsScene.TaintedObject("BSPrim.SetVolumeDetect", delegate() + PhysScene.TaintedObject("BSPrim.SetVolumeDetect", delegate() { // DetailLog("{0},setVolumeDetect,taint,volDetect={1}", LocalID, _isVolumeDetect); SetObjectDynamic(true); @@ -566,7 +566,7 @@ public class BSPrim : BSPhysObject public override void SetMaterial(int material) { base.SetMaterial(material); - PhysicsScene.TaintedObject("BSPrim.SetMaterial", delegate() + PhysScene.TaintedObject("BSPrim.SetMaterial", delegate() { UpdatePhysicalParameters(); }); @@ -579,7 +579,7 @@ public class BSPrim : BSPhysObject if (base.Friction != value) { base.Friction = value; - PhysicsScene.TaintedObject("BSPrim.setFriction", delegate() + PhysScene.TaintedObject("BSPrim.setFriction", delegate() { UpdatePhysicalParameters(); }); @@ -594,7 +594,7 @@ public class BSPrim : BSPhysObject if (base.Restitution != value) { base.Restitution = value; - PhysicsScene.TaintedObject("BSPrim.setRestitution", delegate() + PhysScene.TaintedObject("BSPrim.setRestitution", delegate() { UpdatePhysicalParameters(); }); @@ -611,7 +611,7 @@ public class BSPrim : BSPhysObject if (base.Density != value) { base.Density = value; - PhysicsScene.TaintedObject("BSPrim.setDensity", delegate() + PhysScene.TaintedObject("BSPrim.setDensity", delegate() { UpdatePhysicalParameters(); }); @@ -626,7 +626,7 @@ public class BSPrim : BSPhysObject if (base.GravModifier != value) { base.GravModifier = value; - PhysicsScene.TaintedObject("BSPrim.setGravityModifier", delegate() + PhysScene.TaintedObject("BSPrim.setGravityModifier", delegate() { UpdatePhysicalParameters(); }); @@ -637,7 +637,7 @@ public class BSPrim : BSPhysObject get { return RawVelocity; } set { RawVelocity = value; - PhysicsScene.TaintedObject("BSPrim.setVelocity", delegate() + PhysScene.TaintedObject("BSPrim.setVelocity", delegate() { // DetailLog("{0},BSPrim.SetVelocity,taint,vel={1}", LocalID, RawVelocity); ForceVelocity = RawVelocity; @@ -647,13 +647,13 @@ public class BSPrim : BSPhysObject public override OMV.Vector3 ForceVelocity { get { return RawVelocity; } set { - PhysicsScene.AssertInTaintTime("BSPrim.ForceVelocity"); + PhysScene.AssertInTaintTime("BSPrim.ForceVelocity"); RawVelocity = Util.ClampV(value, BSParam.MaxLinearVelocity); if (PhysBody.HasPhysicalBody) { DetailLog("{0},BSPrim.ForceVelocity,taint,vel={1}", LocalID, RawVelocity); - PhysicsScene.PE.SetLinearVelocity(PhysBody, RawVelocity); + PhysScene.PE.SetLinearVelocity(PhysBody, RawVelocity); ActivateIfPhysical(false); } } @@ -664,7 +664,7 @@ public class BSPrim : BSPhysObject RawTorque = value; EnableActor(RawTorque != OMV.Vector3.Zero, SetTorqueActorName, delegate() { - return new BSActorSetTorque(PhysicsScene, this, SetTorqueActorName); + return new BSActorSetTorque(PhysScene, this, SetTorqueActorName); }); DetailLog("{0},BSPrim.SetTorque,call,torque={1}", LocalID, RawTorque); } @@ -687,7 +687,7 @@ public class BSPrim : BSPhysObject return; _orientation = value; - PhysicsScene.TaintedObject("BSPrim.setOrientation", delegate() + PhysScene.TaintedObject("BSPrim.setOrientation", delegate() { ForceOrientation = _orientation; }); @@ -698,14 +698,14 @@ public class BSPrim : BSPhysObject { get { - _orientation = PhysicsScene.PE.GetOrientation(PhysBody); + _orientation = PhysScene.PE.GetOrientation(PhysBody); return _orientation; } set { _orientation = value; if (PhysBody.HasPhysicalBody) - PhysicsScene.PE.SetTranslation(PhysBody, _position, _orientation); + PhysScene.PE.SetTranslation(PhysBody, _position, _orientation); } } public override int PhysicsActorType { @@ -718,7 +718,7 @@ public class BSPrim : BSPhysObject if (_isPhysical != value) { _isPhysical = value; - PhysicsScene.TaintedObject("BSPrim.setIsPhysical", delegate() + PhysScene.TaintedObject("BSPrim.setIsPhysical", delegate() { DetailLog("{0},setIsPhysical,taint,isPhys={1}", LocalID, _isPhysical); SetObjectDynamic(true); @@ -773,7 +773,7 @@ public class BSPrim : BSPhysObject // Mangling all the physical properties requires the object not be in the physical world. // This is a NOOP if the object is not in the world (BulletSim and Bullet ignore objects not found). - PhysicsScene.PE.RemoveObjectFromWorld(PhysicsScene.World, PhysBody); + PhysScene.PE.RemoveObjectFromWorld(PhysScene.World, PhysBody); // Set up the object physicalness (does gravity and collisions move this object) MakeDynamic(IsStatic); @@ -790,7 +790,7 @@ public class BSPrim : BSPhysObject AddObjectToPhysicalWorld(); // Rebuild its shape - PhysicsScene.PE.UpdateSingleAabb(PhysicsScene.World, PhysBody); + PhysScene.PE.UpdateSingleAabb(PhysScene.World, PhysBody); DetailLog("{0},BSPrim.UpdatePhysicalParameters,taintExit,static={1},solid={2},mass={3},collide={4},cf={5:X},cType={6},body={7},shape={8}", LocalID, IsStatic, IsSolid, Mass, SubscribedEvents(), @@ -807,28 +807,28 @@ public class BSPrim : BSPhysObject if (makeStatic) { // Become a Bullet 'static' object type - CurrentCollisionFlags = PhysicsScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.CF_STATIC_OBJECT); + CurrentCollisionFlags = PhysScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.CF_STATIC_OBJECT); // Stop all movement ZeroMotion(true); // Set various physical properties so other object interact properly - PhysicsScene.PE.SetFriction(PhysBody, Friction); - PhysicsScene.PE.SetRestitution(PhysBody, Restitution); - PhysicsScene.PE.SetContactProcessingThreshold(PhysBody, BSParam.ContactProcessingThreshold); + PhysScene.PE.SetFriction(PhysBody, Friction); + PhysScene.PE.SetRestitution(PhysBody, Restitution); + PhysScene.PE.SetContactProcessingThreshold(PhysBody, BSParam.ContactProcessingThreshold); // Mass is zero which disables a bunch of physics stuff in Bullet UpdatePhysicalMassProperties(0f, false); // Set collision detection parameters if (BSParam.CcdMotionThreshold > 0f) { - PhysicsScene.PE.SetCcdMotionThreshold(PhysBody, BSParam.CcdMotionThreshold); - PhysicsScene.PE.SetCcdSweptSphereRadius(PhysBody, BSParam.CcdSweptSphereRadius); + PhysScene.PE.SetCcdMotionThreshold(PhysBody, BSParam.CcdMotionThreshold); + PhysScene.PE.SetCcdSweptSphereRadius(PhysBody, BSParam.CcdSweptSphereRadius); } // The activation state is 'disabled' so Bullet will not try to act on it. // PhysicsScene.PE.ForceActivationState(PhysBody, ActivationState.DISABLE_SIMULATION); // Start it out sleeping and physical actions could wake it up. - PhysicsScene.PE.ForceActivationState(PhysBody, ActivationState.ISLAND_SLEEPING); + PhysScene.PE.ForceActivationState(PhysBody, ActivationState.ISLAND_SLEEPING); // This collides like a static object PhysBody.collisionType = CollisionType.Static; @@ -836,11 +836,11 @@ public class BSPrim : BSPhysObject else { // Not a Bullet static object - CurrentCollisionFlags = PhysicsScene.PE.RemoveFromCollisionFlags(PhysBody, CollisionFlags.CF_STATIC_OBJECT); + CurrentCollisionFlags = PhysScene.PE.RemoveFromCollisionFlags(PhysBody, CollisionFlags.CF_STATIC_OBJECT); // Set various physical properties so other object interact properly - PhysicsScene.PE.SetFriction(PhysBody, Friction); - PhysicsScene.PE.SetRestitution(PhysBody, Restitution); + PhysScene.PE.SetFriction(PhysBody, Friction); + PhysScene.PE.SetRestitution(PhysBody, Restitution); // DetailLog("{0},BSPrim.MakeDynamic,frict={1},rest={2}", LocalID, Friction, Restitution); // per http://www.bulletphysics.org/Bullet/phpBB3/viewtopic.php?t=3382 @@ -858,22 +858,22 @@ public class BSPrim : BSPhysObject // Set collision detection parameters if (BSParam.CcdMotionThreshold > 0f) { - PhysicsScene.PE.SetCcdMotionThreshold(PhysBody, BSParam.CcdMotionThreshold); - PhysicsScene.PE.SetCcdSweptSphereRadius(PhysBody, BSParam.CcdSweptSphereRadius); + PhysScene.PE.SetCcdMotionThreshold(PhysBody, BSParam.CcdMotionThreshold); + PhysScene.PE.SetCcdSweptSphereRadius(PhysBody, BSParam.CcdSweptSphereRadius); } // Various values for simulation limits - PhysicsScene.PE.SetDamping(PhysBody, BSParam.LinearDamping, BSParam.AngularDamping); - PhysicsScene.PE.SetDeactivationTime(PhysBody, BSParam.DeactivationTime); - PhysicsScene.PE.SetSleepingThresholds(PhysBody, BSParam.LinearSleepingThreshold, BSParam.AngularSleepingThreshold); - PhysicsScene.PE.SetContactProcessingThreshold(PhysBody, BSParam.ContactProcessingThreshold); + PhysScene.PE.SetDamping(PhysBody, BSParam.LinearDamping, BSParam.AngularDamping); + PhysScene.PE.SetDeactivationTime(PhysBody, BSParam.DeactivationTime); + PhysScene.PE.SetSleepingThresholds(PhysBody, BSParam.LinearSleepingThreshold, BSParam.AngularSleepingThreshold); + PhysScene.PE.SetContactProcessingThreshold(PhysBody, BSParam.ContactProcessingThreshold); // This collides like an object. PhysBody.collisionType = CollisionType.Dynamic; // Force activation of the object so Bullet will act on it. // Must do the ForceActivationState2() to overcome the DISABLE_SIMULATION from static objects. - PhysicsScene.PE.ForceActivationState(PhysBody, ActivationState.ACTIVE_TAG); + PhysScene.PE.ForceActivationState(PhysBody, ActivationState.ACTIVE_TAG); } } @@ -883,7 +883,7 @@ public class BSPrim : BSPhysObject // the functions after this one set up the state of a possibly newly created collision body. private void MakeSolid(bool makeSolid) { - CollisionObjectTypes bodyType = (CollisionObjectTypes)PhysicsScene.PE.GetBodyType(PhysBody); + CollisionObjectTypes bodyType = (CollisionObjectTypes)PhysScene.PE.GetBodyType(PhysBody); if (makeSolid) { // Verify the previous code created the correct shape for this type of thing. @@ -891,7 +891,7 @@ public class BSPrim : BSPhysObject { m_log.ErrorFormat("{0} MakeSolid: physical body of wrong type for solidity. id={1}, type={2}", LogHeader, LocalID, bodyType); } - CurrentCollisionFlags = PhysicsScene.PE.RemoveFromCollisionFlags(PhysBody, CollisionFlags.CF_NO_CONTACT_RESPONSE); + CurrentCollisionFlags = PhysScene.PE.RemoveFromCollisionFlags(PhysBody, CollisionFlags.CF_NO_CONTACT_RESPONSE); } else { @@ -899,7 +899,7 @@ public class BSPrim : BSPhysObject { m_log.ErrorFormat("{0} MakeSolid: physical body of wrong type for non-solidness. id={1}, type={2}", LogHeader, LocalID, bodyType); } - CurrentCollisionFlags = PhysicsScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.CF_NO_CONTACT_RESPONSE); + CurrentCollisionFlags = PhysScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.CF_NO_CONTACT_RESPONSE); // Change collision info from a static object to a ghosty collision object PhysBody.collisionType = CollisionType.VolumeDetect; @@ -911,11 +911,11 @@ public class BSPrim : BSPhysObject { if (wantsCollisionEvents) { - CurrentCollisionFlags = PhysicsScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); + CurrentCollisionFlags = PhysScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); } else { - CurrentCollisionFlags = PhysicsScene.PE.RemoveFromCollisionFlags(PhysBody, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); + CurrentCollisionFlags = PhysScene.PE.RemoveFromCollisionFlags(PhysBody, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); } } @@ -926,7 +926,7 @@ public class BSPrim : BSPhysObject { if (PhysBody.HasPhysicalBody) { - PhysicsScene.PE.AddObjectToWorld(PhysicsScene.World, PhysBody); + PhysScene.PE.AddObjectToWorld(PhysScene.World, PhysBody); } else { @@ -961,12 +961,12 @@ public class BSPrim : BSPhysObject public override bool FloatOnWater { set { _floatOnWater = value; - PhysicsScene.TaintedObject("BSPrim.setFloatOnWater", delegate() + PhysScene.TaintedObject("BSPrim.setFloatOnWater", delegate() { if (_floatOnWater) - CurrentCollisionFlags = PhysicsScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.BS_FLOATS_ON_WATER); + CurrentCollisionFlags = PhysScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.BS_FLOATS_ON_WATER); else - CurrentCollisionFlags = PhysicsScene.PE.RemoveFromCollisionFlags(PhysBody, CollisionFlags.BS_FLOATS_ON_WATER); + CurrentCollisionFlags = PhysScene.PE.RemoveFromCollisionFlags(PhysBody, CollisionFlags.BS_FLOATS_ON_WATER); }); } } @@ -978,7 +978,7 @@ public class BSPrim : BSPhysObject _rotationalVelocity = value; Util.ClampV(_rotationalVelocity, BSParam.MaxAngularVelocity); // m_log.DebugFormat("{0}: RotationalVelocity={1}", LogHeader, _rotationalVelocity); - PhysicsScene.TaintedObject("BSPrim.setRotationalVelocity", delegate() + PhysScene.TaintedObject("BSPrim.setRotationalVelocity", delegate() { ForceRotationalVelocity = _rotationalVelocity; }); @@ -993,7 +993,7 @@ public class BSPrim : BSPhysObject if (PhysBody.HasPhysicalBody) { DetailLog("{0},BSPrim.ForceRotationalVel,taint,rotvel={1}", LocalID, _rotationalVelocity); - PhysicsScene.PE.SetAngularVelocity(PhysBody, _rotationalVelocity); + PhysScene.PE.SetAngularVelocity(PhysBody, _rotationalVelocity); // PhysicsScene.PE.SetInterpolationAngularVelocity(PhysBody, _rotationalVelocity); ActivateIfPhysical(false); } @@ -1009,7 +1009,7 @@ public class BSPrim : BSPhysObject get { return _buoyancy; } set { _buoyancy = value; - PhysicsScene.TaintedObject("BSPrim.setBuoyancy", delegate() + PhysScene.TaintedObject("BSPrim.setBuoyancy", delegate() { ForceBuoyancy = _buoyancy; }); @@ -1032,7 +1032,7 @@ public class BSPrim : BSPhysObject base.MoveToTargetActive = value; EnableActor(MoveToTargetActive, MoveToTargetActorName, delegate() { - return new BSActorMoveToTarget(PhysicsScene, this, MoveToTargetActorName); + return new BSActorMoveToTarget(PhysScene, this, MoveToTargetActorName); }); } } @@ -1044,7 +1044,7 @@ public class BSPrim : BSPhysObject base.HoverActive = value; EnableActor(HoverActive, HoverActorName, delegate() { - return new BSActorHover(PhysicsScene, this, HoverActorName); + return new BSActorHover(PhysScene, this, HoverActorName); }); } } @@ -1054,7 +1054,7 @@ public class BSPrim : BSPhysObject OMV.Vector3 addForce = Util.ClampV(force, BSParam.MaxAddForceMagnitude); // Since this force is being applied in only one step, make this a force per second. - addForce /= PhysicsScene.LastTimeStep; + addForce /= PhysScene.LastTimeStep; AddForce(addForce, pushforce, false /* inTaintTime */); } @@ -1069,13 +1069,13 @@ public class BSPrim : BSPhysObject // DetailLog("{0},BSPrim.addForce,call,force={1}", LocalID, addForce); OMV.Vector3 addForce = force; - PhysicsScene.TaintedObject(inTaintTime, "BSPrim.AddForce", delegate() + PhysScene.TaintedObject(inTaintTime, "BSPrim.AddForce", delegate() { // Bullet adds this central force to the total force for this tick DetailLog("{0},BSPrim.addForce,taint,force={1}", LocalID, addForce); if (PhysBody.HasPhysicalBody) { - PhysicsScene.PE.ApplyCentralForce(PhysBody, addForce); + PhysScene.PE.ApplyCentralForce(PhysBody, addForce); ActivateIfPhysical(false); } }); @@ -1097,13 +1097,13 @@ public class BSPrim : BSPhysObject OMV.Vector3 addImpulse = Util.ClampV(impulse, BSParam.MaxAddForceMagnitude); // DetailLog("{0},BSPrim.addForceImpulse,call,impulse={1}", LocalID, impulse); - PhysicsScene.TaintedObject(inTaintTime, "BSPrim.AddImpulse", delegate() + PhysScene.TaintedObject(inTaintTime, "BSPrim.AddImpulse", delegate() { // Bullet adds this impulse immediately to the velocity DetailLog("{0},BSPrim.addForceImpulse,taint,impulseforce={1}", LocalID, addImpulse); if (PhysBody.HasPhysicalBody) { - PhysicsScene.PE.ApplyCentralImpulse(PhysBody, addImpulse); + PhysScene.PE.ApplyCentralImpulse(PhysBody, addImpulse); ActivateIfPhysical(false); } }); @@ -1122,12 +1122,12 @@ public class BSPrim : BSPhysObject if (force.IsFinite()) { OMV.Vector3 angForce = force; - PhysicsScene.TaintedObject(inTaintTime, "BSPrim.AddAngularForce", delegate() + PhysScene.TaintedObject(inTaintTime, "BSPrim.AddAngularForce", delegate() { if (PhysBody.HasPhysicalBody) { DetailLog("{0},BSPrim.AddAngularForce,taint,angForce={1}", LocalID, angForce); - PhysicsScene.PE.ApplyTorque(PhysBody, angForce); + PhysScene.PE.ApplyTorque(PhysBody, angForce); ActivateIfPhysical(false); } }); @@ -1146,11 +1146,11 @@ public class BSPrim : BSPhysObject public void ApplyTorqueImpulse(OMV.Vector3 impulse, bool inTaintTime) { OMV.Vector3 applyImpulse = impulse; - PhysicsScene.TaintedObject(inTaintTime, "BSPrim.ApplyTorqueImpulse", delegate() + PhysScene.TaintedObject(inTaintTime, "BSPrim.ApplyTorqueImpulse", delegate() { if (PhysBody.HasPhysicalBody) { - PhysicsScene.PE.ApplyTorqueImpulse(PhysBody, applyImpulse); + PhysScene.PE.ApplyTorqueImpulse(PhysBody, applyImpulse); ActivateIfPhysical(false); } }); @@ -1452,7 +1452,7 @@ public class BSPrim : BSPhysObject // Create the correct physical representation for this type of object. // Updates base.PhysBody and base.PhysShape with the new information. // Ignore 'forceRebuild'. 'GetBodyAndShape' makes the right choices and changes of necessary. - PhysicsScene.Shapes.GetBodyAndShape(false /*forceRebuild */, PhysicsScene.World, this, delegate(BulletBody pBody, BulletShape pShape) + PhysScene.Shapes.GetBodyAndShape(false /*forceRebuild */, PhysScene.World, this, delegate(BulletBody pBody, BulletShape pShape) { // Called if the current prim body is about to be destroyed. // Remove all the physical dependencies on the old body. diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs index 81104ec..5236909 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs @@ -47,9 +47,9 @@ public class BSPrimLinkable : BSPrimDisplaced OMV.Quaternion rotation, PrimitiveBaseShape pbs, bool pisPhysical) : base(localID, primName, parent_scene, pos, size, rotation, pbs, pisPhysical) { - Linkset = BSLinkset.Factory(PhysicsScene, this); + Linkset = BSLinkset.Factory(PhysScene, this); - PhysicsScene.TaintedObject("BSPrimLinksetCompound.Refresh", delegate() + PhysScene.TaintedObject("BSPrimLinksetCompound.Refresh", delegate() { Linkset.Refresh(this); }); @@ -99,7 +99,7 @@ public class BSPrimLinkable : BSPrimDisplaced set { base.Position = value; - PhysicsScene.TaintedObject("BSPrimLinkset.setPosition", delegate() + PhysScene.TaintedObject("BSPrimLinkset.setPosition", delegate() { Linkset.UpdateProperties(UpdatedProperties.Position, this); }); @@ -113,7 +113,7 @@ public class BSPrimLinkable : BSPrimDisplaced set { base.Orientation = value; - PhysicsScene.TaintedObject("BSPrimLinkset.setOrientation", delegate() + PhysScene.TaintedObject("BSPrimLinkset.setOrientation", delegate() { Linkset.UpdateProperties(UpdatedProperties.Orientation, this); }); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainHeightmap.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainHeightmap.cs index e4fecc3..5a19797 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainHeightmap.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainHeightmap.cs @@ -92,7 +92,7 @@ public sealed class BSTerrainHeightmap : BSTerrainPhys private void BuildHeightmapTerrain() { // Create the terrain shape from the mapInfo - m_mapInfo.terrainShape = PhysicsScene.PE.CreateTerrainShape( m_mapInfo.ID, + m_mapInfo.terrainShape = m_physicsScene.PE.CreateTerrainShape( m_mapInfo.ID, new Vector3(m_mapInfo.sizeX, m_mapInfo.sizeY, 0), m_mapInfo.minZ, m_mapInfo.maxZ, m_mapInfo.heightMap, 1f, BSParam.TerrainCollisionMargin); @@ -103,26 +103,26 @@ public sealed class BSTerrainHeightmap : BSTerrainPhys centerPos.Y = m_mapInfo.minCoords.Y + (m_mapInfo.sizeY / 2f); centerPos.Z = m_mapInfo.minZ + ((m_mapInfo.maxZ - m_mapInfo.minZ) / 2f); - m_mapInfo.terrainBody = PhysicsScene.PE.CreateBodyWithDefaultMotionState(m_mapInfo.terrainShape, + m_mapInfo.terrainBody = m_physicsScene.PE.CreateBodyWithDefaultMotionState(m_mapInfo.terrainShape, m_mapInfo.ID, centerPos, Quaternion.Identity); // Set current terrain attributes - PhysicsScene.PE.SetFriction(m_mapInfo.terrainBody, BSParam.TerrainFriction); - PhysicsScene.PE.SetHitFraction(m_mapInfo.terrainBody, BSParam.TerrainHitFraction); - PhysicsScene.PE.SetRestitution(m_mapInfo.terrainBody, BSParam.TerrainRestitution); - PhysicsScene.PE.SetCollisionFlags(m_mapInfo.terrainBody, CollisionFlags.CF_STATIC_OBJECT); + m_physicsScene.PE.SetFriction(m_mapInfo.terrainBody, BSParam.TerrainFriction); + m_physicsScene.PE.SetHitFraction(m_mapInfo.terrainBody, BSParam.TerrainHitFraction); + m_physicsScene.PE.SetRestitution(m_mapInfo.terrainBody, BSParam.TerrainRestitution); + m_physicsScene.PE.SetCollisionFlags(m_mapInfo.terrainBody, CollisionFlags.CF_STATIC_OBJECT); // Return the new terrain to the world of physical objects - PhysicsScene.PE.AddObjectToWorld(PhysicsScene.World, m_mapInfo.terrainBody); + m_physicsScene.PE.AddObjectToWorld(m_physicsScene.World, m_mapInfo.terrainBody); // redo its bounding box now that it is in the world - PhysicsScene.PE.UpdateSingleAabb(PhysicsScene.World, m_mapInfo.terrainBody); + m_physicsScene.PE.UpdateSingleAabb(m_physicsScene.World, m_mapInfo.terrainBody); m_mapInfo.terrainBody.collisionType = CollisionType.Terrain; - m_mapInfo.terrainBody.ApplyCollisionMask(PhysicsScene); + m_mapInfo.terrainBody.ApplyCollisionMask(m_physicsScene); // Make it so the terrain will not move or be considered for movement. - PhysicsScene.PE.ForceActivationState(m_mapInfo.terrainBody, ActivationState.DISABLE_SIMULATION); + m_physicsScene.PE.ForceActivationState(m_mapInfo.terrainBody, ActivationState.DISABLE_SIMULATION); return; } @@ -134,9 +134,9 @@ public sealed class BSTerrainHeightmap : BSTerrainPhys { if (m_mapInfo.terrainBody.HasPhysicalBody) { - PhysicsScene.PE.RemoveObjectFromWorld(PhysicsScene.World, m_mapInfo.terrainBody); + m_physicsScene.PE.RemoveObjectFromWorld(m_physicsScene.World, m_mapInfo.terrainBody); // Frees both the body and the shape. - PhysicsScene.PE.DestroyObject(PhysicsScene.World, m_mapInfo.terrainBody); + m_physicsScene.PE.DestroyObject(m_physicsScene.World, m_mapInfo.terrainBody); } } m_mapInfo = null; @@ -155,7 +155,7 @@ public sealed class BSTerrainHeightmap : BSTerrainPhys catch { // Sometimes they give us wonky values of X and Y. Give a warning and return something. - PhysicsScene.Logger.WarnFormat("{0} Bad request for terrain height. terrainBase={1}, pos={2}", + m_physicsScene.Logger.WarnFormat("{0} Bad request for terrain height. terrainBase={1}, pos={2}", LogHeader, m_mapInfo.terrainRegionBase, pos); ret = BSTerrainManager.HEIGHT_GETHEIGHT_RET; } @@ -165,7 +165,7 @@ public sealed class BSTerrainHeightmap : BSTerrainPhys // The passed position is relative to the base of the region. public override float GetWaterLevelAtXYZ(Vector3 pos) { - return PhysicsScene.SimpleWaterLevel; + return m_physicsScene.SimpleWaterLevel; } } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs index 5240ad8..0d16eda 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs @@ -50,14 +50,14 @@ public abstract class BSTerrainPhys : IDisposable Mesh = 1 } - public BSScene PhysicsScene { get; private set; } + protected BSScene m_physicsScene { get; private set; } // Base of the region in world coordinates. Coordinates inside the region are relative to this. public Vector3 TerrainBase { get; private set; } public uint ID { get; private set; } public BSTerrainPhys(BSScene physicsScene, Vector3 regionBase, uint id) { - PhysicsScene = physicsScene; + m_physicsScene = physicsScene; TerrainBase = regionBase; ID = id; } @@ -86,7 +86,7 @@ public sealed class BSTerrainManager : IDisposable public Vector3 DefaultRegionSize = new Vector3(Constants.RegionSize, Constants.RegionSize, Constants.RegionHeight); // The scene that I am part of - private BSScene PhysicsScene { get; set; } + private BSScene m_physicsScene { get; set; } // The ground plane created to keep thing from falling to infinity. private BulletBody m_groundPlane; @@ -113,7 +113,7 @@ public sealed class BSTerrainManager : IDisposable public BSTerrainManager(BSScene physicsScene) { - PhysicsScene = physicsScene; + m_physicsScene = physicsScene; m_terrains = new Dictionary(); // Assume one region of default size @@ -132,21 +132,21 @@ public sealed class BSTerrainManager : IDisposable // safe to call Bullet in real time. We hope no one is moving prims around yet. public void CreateInitialGroundPlaneAndTerrain() { - DetailLog("{0},BSTerrainManager.CreateInitialGroundPlaneAndTerrain,region={1}", BSScene.DetailLogZero, PhysicsScene.RegionName); + DetailLog("{0},BSTerrainManager.CreateInitialGroundPlaneAndTerrain,region={1}", BSScene.DetailLogZero, m_physicsScene.RegionName); // The ground plane is here to catch things that are trying to drop to negative infinity - BulletShape groundPlaneShape = PhysicsScene.PE.CreateGroundPlaneShape(BSScene.GROUNDPLANE_ID, 1f, BSParam.TerrainCollisionMargin); - m_groundPlane = PhysicsScene.PE.CreateBodyWithDefaultMotionState(groundPlaneShape, + BulletShape groundPlaneShape = m_physicsScene.PE.CreateGroundPlaneShape(BSScene.GROUNDPLANE_ID, 1f, BSParam.TerrainCollisionMargin); + m_groundPlane = m_physicsScene.PE.CreateBodyWithDefaultMotionState(groundPlaneShape, BSScene.GROUNDPLANE_ID, Vector3.Zero, Quaternion.Identity); - PhysicsScene.PE.AddObjectToWorld(PhysicsScene.World, m_groundPlane); - PhysicsScene.PE.UpdateSingleAabb(PhysicsScene.World, m_groundPlane); + m_physicsScene.PE.AddObjectToWorld(m_physicsScene.World, m_groundPlane); + m_physicsScene.PE.UpdateSingleAabb(m_physicsScene.World, m_groundPlane); // Ground plane does not move - PhysicsScene.PE.ForceActivationState(m_groundPlane, ActivationState.DISABLE_SIMULATION); + m_physicsScene.PE.ForceActivationState(m_groundPlane, ActivationState.DISABLE_SIMULATION); // Everything collides with the ground plane. m_groundPlane.collisionType = CollisionType.Groundplane; - m_groundPlane.ApplyCollisionMask(PhysicsScene); + m_groundPlane.ApplyCollisionMask(m_physicsScene); - BSTerrainPhys initialTerrain = new BSTerrainHeightmap(PhysicsScene, Vector3.Zero, BSScene.TERRAIN_ID, DefaultRegionSize); + BSTerrainPhys initialTerrain = new BSTerrainHeightmap(m_physicsScene, Vector3.Zero, BSScene.TERRAIN_ID, DefaultRegionSize); lock (m_terrains) { // Build an initial terrain and put it in the world. This quickly gets replaced by the real region terrain. @@ -157,12 +157,12 @@ public sealed class BSTerrainManager : IDisposable // Release all the terrain structures we might have allocated public void ReleaseGroundPlaneAndTerrain() { - DetailLog("{0},BSTerrainManager.ReleaseGroundPlaneAndTerrain,region={1}", BSScene.DetailLogZero, PhysicsScene.RegionName); + DetailLog("{0},BSTerrainManager.ReleaseGroundPlaneAndTerrain,region={1}", BSScene.DetailLogZero, m_physicsScene.RegionName); if (m_groundPlane.HasPhysicalBody) { - if (PhysicsScene.PE.RemoveObjectFromWorld(PhysicsScene.World, m_groundPlane)) + if (m_physicsScene.PE.RemoveObjectFromWorld(m_physicsScene.World, m_groundPlane)) { - PhysicsScene.PE.DestroyObject(PhysicsScene.World, m_groundPlane); + m_physicsScene.PE.DestroyObject(m_physicsScene.World, m_groundPlane); } m_groundPlane.Clear(); } @@ -188,7 +188,7 @@ public sealed class BSTerrainManager : IDisposable float[] localHeightMap = heightMap; // If there are multiple requests for changes to the same terrain between ticks, // only do that last one. - PhysicsScene.PostTaintObject("TerrainManager.SetTerrain-"+ m_worldOffset.ToString(), 0, delegate() + m_physicsScene.PostTaintObject("TerrainManager.SetTerrain-"+ m_worldOffset.ToString(), 0, delegate() { if (m_worldOffset != Vector3.Zero && MegaRegionParentPhysicsScene != null) { @@ -219,7 +219,7 @@ public sealed class BSTerrainManager : IDisposable private void AddMegaRegionChildTerrain(uint id, float[] heightMap, Vector3 minCoords, Vector3 maxCoords) { // Since we are called by another region's thread, the action must be rescheduled onto our processing thread. - PhysicsScene.PostTaintObject("TerrainManager.AddMegaRegionChild" + minCoords.ToString(), id, delegate() + m_physicsScene.PostTaintObject("TerrainManager.AddMegaRegionChild" + minCoords.ToString(), id, delegate() { UpdateTerrain(id, heightMap, minCoords, maxCoords); }); @@ -318,26 +318,26 @@ public sealed class BSTerrainManager : IDisposable // TODO: redo terrain implementation selection to allow other base types than heightMap. private BSTerrainPhys BuildPhysicalTerrain(Vector3 terrainRegionBase, uint id, float[] heightMap, Vector3 minCoords, Vector3 maxCoords) { - PhysicsScene.Logger.DebugFormat("{0} Terrain for {1}/{2} created with {3}", - LogHeader, PhysicsScene.RegionName, terrainRegionBase, + m_physicsScene.Logger.DebugFormat("{0} Terrain for {1}/{2} created with {3}", + LogHeader, m_physicsScene.RegionName, terrainRegionBase, (BSTerrainPhys.TerrainImplementation)BSParam.TerrainImplementation); BSTerrainPhys newTerrainPhys = null; switch ((int)BSParam.TerrainImplementation) { case (int)BSTerrainPhys.TerrainImplementation.Heightmap: - newTerrainPhys = new BSTerrainHeightmap(PhysicsScene, terrainRegionBase, id, + newTerrainPhys = new BSTerrainHeightmap(m_physicsScene, terrainRegionBase, id, heightMap, minCoords, maxCoords); break; case (int)BSTerrainPhys.TerrainImplementation.Mesh: - newTerrainPhys = new BSTerrainMesh(PhysicsScene, terrainRegionBase, id, + newTerrainPhys = new BSTerrainMesh(m_physicsScene, terrainRegionBase, id, heightMap, minCoords, maxCoords); break; default: - PhysicsScene.Logger.ErrorFormat("{0} Bad terrain implementation specified. Type={1}/{2},Region={3}/{4}", + m_physicsScene.Logger.ErrorFormat("{0} Bad terrain implementation specified. Type={1}/{2},Region={3}/{4}", LogHeader, (int)BSParam.TerrainImplementation, BSParam.TerrainImplementation, - PhysicsScene.RegionName, terrainRegionBase); + m_physicsScene.RegionName, terrainRegionBase); break; } return newTerrainPhys; @@ -429,8 +429,8 @@ public sealed class BSTerrainManager : IDisposable } else { - PhysicsScene.Logger.ErrorFormat("{0} GetTerrainHeightAtXY: terrain not found: region={1}, x={2}, y={3}", - LogHeader, PhysicsScene.RegionName, tX, tY); + m_physicsScene.Logger.ErrorFormat("{0} GetTerrainHeightAtXY: terrain not found: region={1}, x={2}, y={3}", + LogHeader, m_physicsScene.RegionName, tX, tY); DetailLog("{0},BSTerrainManager.GetTerrainHeightAtXYZ,terrainNotFound,pos={1},base={2}", BSScene.DetailLogZero, pos, terrainBaseXYZ); } @@ -451,8 +451,8 @@ public sealed class BSTerrainManager : IDisposable } else { - PhysicsScene.Logger.ErrorFormat("{0} GetWaterHeightAtXY: terrain not found: pos={1}, terrainBase={2}, height={3}", - LogHeader, PhysicsScene.RegionName, pos, terrainBaseXYZ, ret); + m_physicsScene.Logger.ErrorFormat("{0} GetWaterHeightAtXY: terrain not found: pos={1}, terrainBase={2}, height={3}", + LogHeader, m_physicsScene.RegionName, pos, terrainBaseXYZ, ret); } return ret; } @@ -564,7 +564,7 @@ public sealed class BSTerrainManager : IDisposable private void DetailLog(string msg, params Object[] args) { - PhysicsScene.PhysicsLogging.Write(msg, args); + m_physicsScene.PhysicsLogging.Write(msg, args); } } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainMesh.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainMesh.cs index 2ce1513..ee2a1f2 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainMesh.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainMesh.cs @@ -80,7 +80,7 @@ public sealed class BSTerrainMesh : BSTerrainPhys if (BSParam.TerrainMeshMagnification == 1) { // If a magnification of one, use the old routine that is tried and true. - meshCreationSuccess = BSTerrainMesh.ConvertHeightmapToMesh(PhysicsScene, + meshCreationSuccess = BSTerrainMesh.ConvertHeightmapToMesh(m_physicsScene, initialMap, m_sizeX, m_sizeY, // input size Vector3.Zero, // base for mesh out indicesCount, out indices, out verticesCount, out vertices); @@ -88,7 +88,7 @@ public sealed class BSTerrainMesh : BSTerrainPhys else { // Other magnifications use the newer routine - meshCreationSuccess = BSTerrainMesh.ConvertHeightmapToMesh2(PhysicsScene, + meshCreationSuccess = BSTerrainMesh.ConvertHeightmapToMesh2(m_physicsScene, initialMap, m_sizeX, m_sizeY, // input size BSParam.TerrainMeshMagnification, physicsScene.TerrainManager.DefaultRegionSize, @@ -98,21 +98,21 @@ public sealed class BSTerrainMesh : BSTerrainPhys if (!meshCreationSuccess) { // DISASTER!! - PhysicsScene.DetailLog("{0},BSTerrainMesh.create,failedConversionOfHeightmap,id={1}", BSScene.DetailLogZero, ID); - PhysicsScene.Logger.ErrorFormat("{0} Failed conversion of heightmap to mesh! base={1}", LogHeader, TerrainBase); + m_physicsScene.DetailLog("{0},BSTerrainMesh.create,failedConversionOfHeightmap,id={1}", BSScene.DetailLogZero, ID); + m_physicsScene.Logger.ErrorFormat("{0} Failed conversion of heightmap to mesh! base={1}", LogHeader, TerrainBase); // Something is very messed up and a crash is in our future. return; } - PhysicsScene.DetailLog("{0},BSTerrainMesh.create,meshed,id={1},indices={2},indSz={3},vertices={4},vertSz={5}", + m_physicsScene.DetailLog("{0},BSTerrainMesh.create,meshed,id={1},indices={2},indSz={3},vertices={4},vertSz={5}", BSScene.DetailLogZero, ID, indicesCount, indices.Length, verticesCount, vertices.Length); - m_terrainShape = PhysicsScene.PE.CreateMeshShape(PhysicsScene.World, indicesCount, indices, verticesCount, vertices); + m_terrainShape = m_physicsScene.PE.CreateMeshShape(m_physicsScene.World, indicesCount, indices, verticesCount, vertices); if (!m_terrainShape.HasPhysicalShape) { // DISASTER!! - PhysicsScene.DetailLog("{0},BSTerrainMesh.create,failedCreationOfShape,id={1}", BSScene.DetailLogZero, ID); - PhysicsScene.Logger.ErrorFormat("{0} Failed creation of terrain mesh! base={1}", LogHeader, TerrainBase); + m_physicsScene.DetailLog("{0},BSTerrainMesh.create,failedCreationOfShape,id={1}", BSScene.DetailLogZero, ID); + m_physicsScene.Logger.ErrorFormat("{0} Failed creation of terrain mesh! base={1}", LogHeader, TerrainBase); // Something is very messed up and a crash is in our future. return; } @@ -120,52 +120,52 @@ public sealed class BSTerrainMesh : BSTerrainPhys Vector3 pos = regionBase; Quaternion rot = Quaternion.Identity; - m_terrainBody = PhysicsScene.PE.CreateBodyWithDefaultMotionState(m_terrainShape, ID, pos, rot); + m_terrainBody = m_physicsScene.PE.CreateBodyWithDefaultMotionState(m_terrainShape, ID, pos, rot); if (!m_terrainBody.HasPhysicalBody) { // DISASTER!! - PhysicsScene.Logger.ErrorFormat("{0} Failed creation of terrain body! base={1}", LogHeader, TerrainBase); + m_physicsScene.Logger.ErrorFormat("{0} Failed creation of terrain body! base={1}", LogHeader, TerrainBase); // Something is very messed up and a crash is in our future. return; } physicsScene.PE.SetShapeCollisionMargin(m_terrainShape, BSParam.TerrainCollisionMargin); // Set current terrain attributes - PhysicsScene.PE.SetFriction(m_terrainBody, BSParam.TerrainFriction); - PhysicsScene.PE.SetHitFraction(m_terrainBody, BSParam.TerrainHitFraction); - PhysicsScene.PE.SetRestitution(m_terrainBody, BSParam.TerrainRestitution); - PhysicsScene.PE.SetContactProcessingThreshold(m_terrainBody, BSParam.TerrainContactProcessingThreshold); - PhysicsScene.PE.SetCollisionFlags(m_terrainBody, CollisionFlags.CF_STATIC_OBJECT); + m_physicsScene.PE.SetFriction(m_terrainBody, BSParam.TerrainFriction); + m_physicsScene.PE.SetHitFraction(m_terrainBody, BSParam.TerrainHitFraction); + m_physicsScene.PE.SetRestitution(m_terrainBody, BSParam.TerrainRestitution); + m_physicsScene.PE.SetContactProcessingThreshold(m_terrainBody, BSParam.TerrainContactProcessingThreshold); + m_physicsScene.PE.SetCollisionFlags(m_terrainBody, CollisionFlags.CF_STATIC_OBJECT); // Static objects are not very massive. - PhysicsScene.PE.SetMassProps(m_terrainBody, 0f, Vector3.Zero); + m_physicsScene.PE.SetMassProps(m_terrainBody, 0f, Vector3.Zero); // Put the new terrain to the world of physical objects - PhysicsScene.PE.AddObjectToWorld(PhysicsScene.World, m_terrainBody); + m_physicsScene.PE.AddObjectToWorld(m_physicsScene.World, m_terrainBody); // Redo its bounding box now that it is in the world - PhysicsScene.PE.UpdateSingleAabb(PhysicsScene.World, m_terrainBody); + m_physicsScene.PE.UpdateSingleAabb(m_physicsScene.World, m_terrainBody); m_terrainBody.collisionType = CollisionType.Terrain; - m_terrainBody.ApplyCollisionMask(PhysicsScene); + m_terrainBody.ApplyCollisionMask(m_physicsScene); if (BSParam.UseSingleSidedMeshes) { - PhysicsScene.DetailLog("{0},BSTerrainMesh.settingCustomMaterial,id={1}", BSScene.DetailLogZero, id); - PhysicsScene.PE.AddToCollisionFlags(m_terrainBody, CollisionFlags.CF_CUSTOM_MATERIAL_CALLBACK); + m_physicsScene.DetailLog("{0},BSTerrainMesh.settingCustomMaterial,id={1}", BSScene.DetailLogZero, id); + m_physicsScene.PE.AddToCollisionFlags(m_terrainBody, CollisionFlags.CF_CUSTOM_MATERIAL_CALLBACK); } // Make it so the terrain will not move or be considered for movement. - PhysicsScene.PE.ForceActivationState(m_terrainBody, ActivationState.DISABLE_SIMULATION); + m_physicsScene.PE.ForceActivationState(m_terrainBody, ActivationState.DISABLE_SIMULATION); } public override void Dispose() { if (m_terrainBody.HasPhysicalBody) { - PhysicsScene.PE.RemoveObjectFromWorld(PhysicsScene.World, m_terrainBody); + m_physicsScene.PE.RemoveObjectFromWorld(m_physicsScene.World, m_terrainBody); // Frees both the body and the shape. - PhysicsScene.PE.DestroyObject(PhysicsScene.World, m_terrainBody); + m_physicsScene.PE.DestroyObject(m_physicsScene.World, m_terrainBody); m_terrainBody.Clear(); m_terrainShape.Clear(); } @@ -185,7 +185,7 @@ public sealed class BSTerrainMesh : BSTerrainPhys catch { // Sometimes they give us wonky values of X and Y. Give a warning and return something. - PhysicsScene.Logger.WarnFormat("{0} Bad request for terrain height. terrainBase={1}, pos={2}", + m_physicsScene.Logger.WarnFormat("{0} Bad request for terrain height. terrainBase={1}, pos={2}", LogHeader, TerrainBase, pos); ret = BSTerrainManager.HEIGHT_GETHEIGHT_RET; } @@ -195,7 +195,7 @@ public sealed class BSTerrainMesh : BSTerrainPhys // The passed position is relative to the base of the region. public override float GetWaterLevelAtXYZ(Vector3 pos) { - return PhysicsScene.SimpleWaterLevel; + return m_physicsScene.SimpleWaterLevel; } // Convert the passed heightmap to mesh information suitable for CreateMeshShape2(). -- cgit v1.1 From 92ee288d666963aae2a058cc964be009a504f084 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Mon, 29 Apr 2013 07:54:50 -0700 Subject: BulletSim: remove trailing white space to make git happier. No functional changes. --- OpenSim/Region/Physics/BulletSPlugin/BSAPIUnman.cs | 6 +- OpenSim/Region/Physics/BulletSPlugin/BSAPIXNA.cs | 138 ++++++++++----------- .../Physics/BulletSPlugin/BSActorAvatarMove.cs | 2 +- .../Physics/BulletSPlugin/BSActorLockAxis.cs | 2 +- OpenSim/Region/Physics/BulletSPlugin/BSActors.cs | 2 +- .../Region/Physics/BulletSPlugin/BSApiTemplate.cs | 6 +- .../Region/Physics/BulletSPlugin/BSCharacter.cs | 6 +- .../Physics/BulletSPlugin/BSConstraintHinge.cs | 2 +- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 22 ++-- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 2 +- .../Physics/BulletSPlugin/BSLinksetCompound.cs | 4 +- OpenSim/Region/Physics/BulletSPlugin/BSMotors.cs | 12 +- OpenSim/Region/Physics/BulletSPlugin/BSParam.cs | 6 +- .../Region/Physics/BulletSPlugin/BSPhysObject.cs | 8 +- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 2 +- OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs | 20 +-- .../Physics/BulletSPlugin/BSTerrainHeightmap.cs | 6 +- .../Physics/BulletSPlugin/BSTerrainManager.cs | 10 +- .../Region/Physics/BulletSPlugin/BSTerrainMesh.cs | 6 +- .../Region/Physics/BulletSPlugin/BulletSimData.cs | 42 +++---- 20 files changed, 152 insertions(+), 152 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSAPIUnman.cs b/OpenSim/Region/Physics/BulletSPlugin/BSAPIUnman.cs index 8a22bc7..231f0f8 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSAPIUnman.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSAPIUnman.cs @@ -75,7 +75,7 @@ private sealed class BulletBodyUnman : BulletBody private sealed class BulletShapeUnman : BulletShape { public IntPtr ptr; - public BulletShapeUnman(IntPtr xx, BSPhysicsShapeType typ) + public BulletShapeUnman(IntPtr xx, BSPhysicsShapeType typ) : base() { ptr = xx; @@ -255,7 +255,7 @@ public override BulletShape CreateHullShape(BulletWorld world, int hullCount, fl { BulletWorldUnman worldu = world as BulletWorldUnman; return new BulletShapeUnman( - BSAPICPP.CreateHullShape2(worldu.ptr, hullCount, hulls), + BSAPICPP.CreateHullShape2(worldu.ptr, hullCount, hulls), BSPhysicsShapeType.SHAPE_HULL); } @@ -1503,7 +1503,7 @@ public static extern void DestroyObject2(IntPtr sim, IntPtr obj); public static extern IntPtr CreateGroundPlaneShape2(uint id, float height, float collisionMargin); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern IntPtr CreateTerrainShape2(uint id, Vector3 size, float minHeight, float maxHeight, +public static extern IntPtr CreateTerrainShape2(uint id, Vector3 size, float minHeight, float maxHeight, [MarshalAs(UnmanagedType.LPArray)] float[] heightMap, float scaleFactor, float collisionMargin); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSAPIXNA.cs b/OpenSim/Region/Physics/BulletSPlugin/BSAPIXNA.cs index 1ef8b17..59780ae 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSAPIXNA.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSAPIXNA.cs @@ -81,7 +81,7 @@ private sealed class BulletBodyXNA : BulletBody private sealed class BulletShapeXNA : BulletShape { public CollisionShape shape; - public BulletShapeXNA(CollisionShape xx, BSPhysicsShapeType typ) + public BulletShapeXNA(CollisionShape xx, BSPhysicsShapeType typ) : base() { shape = xx; @@ -137,8 +137,8 @@ private sealed class BulletConstraintXNA : BulletConstraint internal int LastEntityProperty = 0; internal EntityProperties[] UpdatedObjects; - internal Dictionary specialCollisionObjects; - + internal Dictionary specialCollisionObjects; + private static int m_collisionsThisFrame; private BSScene PhysicsScene { get; set; } @@ -151,7 +151,7 @@ private sealed class BulletConstraintXNA : BulletConstraint } /// - /// + /// /// /// /// @@ -174,7 +174,7 @@ private sealed class BulletConstraintXNA : BulletConstraint DiscreteDynamicsWorld world = (pWorld as BulletWorldXNA).world; TypedConstraint constraint = (pConstraint as BulletConstraintXNA).constrain; world.AddConstraint(constraint, pDisableCollisionsBetweenLinkedObjects); - + return true; } @@ -300,7 +300,7 @@ private sealed class BulletConstraintXNA : BulletConstraint public override bool GetForceUpdateAllAabbs(BulletWorld pWorld) { DiscreteDynamicsWorld world = (pWorld as BulletWorldXNA).world; return world.GetForceUpdateAllAabbs(); - + } public override void SetForceUpdateAllAabbs(BulletWorld pWorld, bool pForce) { @@ -404,7 +404,7 @@ private sealed class BulletConstraintXNA : BulletConstraint IndexedMatrix mat = IndexedMatrix.CreateFromQuaternion(vquaternion); mat._origin = vposition; collisionObject.SetWorldTransform(mat); - + } public override Vector3 GetPosition(BulletBody pCollisionObject) @@ -457,7 +457,7 @@ private sealed class BulletConstraintXNA : BulletConstraint { CollisionObject collisionObject = (pCollisionObject as BulletBodyXNA).rigidBody; collisionObject.Activate(pforceactivation); - + } public override Quaternion GetOrientation(BulletBody pCollisionObject) @@ -486,7 +486,7 @@ private sealed class BulletConstraintXNA : BulletConstraint { CollisionObject collisionObject = (pCollisionObject as BulletBodyXNA).rigidBody; return collisionObject.GetCcdSweptSphereRadius(); - + } public override IntPtr GetUserPointer(BulletBody pCollisionObject) @@ -559,8 +559,8 @@ private sealed class BulletConstraintXNA : BulletConstraint } - public override BulletConstraint Create6DofConstraint(BulletWorld pWorld, BulletBody pBody1, BulletBody pBody2, - Vector3 pframe1, Quaternion pframe1rot, Vector3 pframe2, Quaternion pframe2rot, + public override BulletConstraint Create6DofConstraint(BulletWorld pWorld, BulletBody pBody1, BulletBody pBody2, + Vector3 pframe1, Quaternion pframe1rot, Vector3 pframe2, Quaternion pframe2rot, bool puseLinearReferenceFrameA, bool pdisableCollisionsBetweenLinkedBodies) { @@ -604,7 +604,7 @@ private sealed class BulletConstraintXNA : BulletConstraint } /// - /// + /// /// /// /// @@ -824,7 +824,7 @@ private sealed class BulletConstraintXNA : BulletConstraint { RigidBody body = (pBody as BulletBodyXNA).rigidBody; float angularDamping = body.GetAngularDamping(); - body.SetDamping(lin_damping, angularDamping); + body.SetDamping(lin_damping, angularDamping); } public override float GetLinearDamping(BulletBody pBody) @@ -907,7 +907,7 @@ private sealed class BulletConstraintXNA : BulletConstraint RigidBody bo = co as RigidBody; if (bo == null) { - + if (world.IsInWorld(co)) { world.RemoveCollisionObject(co); @@ -915,7 +915,7 @@ private sealed class BulletConstraintXNA : BulletConstraint } else { - + if (world.IsInWorld(bo)) { world.RemoveRigidBody(bo); @@ -947,7 +947,7 @@ private sealed class BulletConstraintXNA : BulletConstraint // TODO: Turn this from a reference copy to a Value Copy. BulletShapeXNA shape2 = new BulletShapeXNA(shape1, BSShapeTypeFromBroadPhaseNativeType(shape1.GetShapeType())); - + return shape2; } @@ -957,7 +957,7 @@ private sealed class BulletConstraintXNA : BulletConstraint return false; } //(sim.ptr, shape.ptr, prim.LocalID, prim.RawPosition, prim.RawOrientation); - + public override BulletBody CreateBodyFromShape(BulletWorld pWorld, BulletShape pShape, uint pLocalID, Vector3 pRawPosition, Quaternion pRawOrientation) { CollisionWorld world = (pWorld as BulletWorldXNA).world; @@ -993,11 +993,11 @@ private sealed class BulletConstraintXNA : BulletConstraint m_startWorldTransform = IndexedMatrix.Identity; */ body.SetUserPointer(pLocalID); - + return new BulletBodyXNA(pLocalID, body); } - + public override BulletBody CreateBodyWithDefaultMotionState( BulletShape pShape, uint pLocalID, Vector3 pRawPosition, Quaternion pRawOrientation) { @@ -1025,7 +1025,7 @@ private sealed class BulletConstraintXNA : BulletConstraint public override Vector3 GetAnisotripicFriction(BulletConstraint pconstrain) { - /* TODO */ + /* TODO */ return Vector3.Zero; } public override Vector3 SetAnisotripicFriction(BulletConstraint pconstrain, Vector3 frict) { /* TODO */ return Vector3.Zero; } @@ -1035,7 +1035,7 @@ private sealed class BulletConstraintXNA : BulletConstraint { CollisionObject collisionObject = (pCollisionObject as BulletBodyXNA).rigidBody; return collisionObject.IsStaticObject(); - + } public override bool IsKinematicObject(BulletBody pCollisionObject) { @@ -1098,10 +1098,10 @@ private sealed class BulletConstraintXNA : BulletConstraint return new BulletWorldXNA(1, PhysicsScene, BSAPIXNA.Initialize2(worldExtent, configparms, maxCollisions, ref collisionArray, maxUpdates, ref updateArray, null)); } - private static DiscreteDynamicsWorld Initialize2(Vector3 worldExtent, + private static DiscreteDynamicsWorld Initialize2(Vector3 worldExtent, ConfigurationParameters[] o, int mMaxCollisionsPerFrame, ref CollisionDesc[] collisionArray, - int mMaxUpdatesPerFrame, ref EntityProperties[] updateArray, + int mMaxUpdatesPerFrame, ref EntityProperties[] updateArray, object mDebugLogCallbackHandle) { CollisionWorld.WorldData.ParamData p = new CollisionWorld.WorldData.ParamData(); @@ -1138,9 +1138,9 @@ private sealed class BulletConstraintXNA : BulletConstraint p.avatarCapsuleDepth = BSParam.AvatarCapsuleDepth; p.avatarCapsuleHeight = BSParam.AvatarCapsuleHeight; p.avatarContactProcessingThreshold = BSParam.AvatarContactProcessingThreshold; - + p.vehicleAngularDamping = BSParam.VehicleAngularDamping; - + p.maxPersistantManifoldPoolSize = o[0].maxPersistantManifoldPoolSize; p.maxCollisionAlgorithmPoolSize = o[0].maxCollisionAlgorithmPoolSize; p.shouldDisableContactPoolDynamicAllocation = o[0].shouldDisableContactPoolDynamicAllocation; @@ -1160,7 +1160,7 @@ private sealed class BulletConstraintXNA : BulletConstraint p.linkConstraintSolverIterations = BSParam.LinkConstraintSolverIterations; p.physicsLoggingFrames = o[0].physicsLoggingFrames; DefaultCollisionConstructionInfo ccci = new DefaultCollisionConstructionInfo(); - + DefaultCollisionConfiguration cci = new DefaultCollisionConfiguration(); CollisionDispatcher m_dispatcher = new CollisionDispatcher(cci); @@ -1263,7 +1263,7 @@ private sealed class BulletConstraintXNA : BulletConstraint } } return ret; - + } public override float GetAngularMotionDisc(BulletShape pShape) @@ -1353,10 +1353,10 @@ private sealed class BulletConstraintXNA : BulletConstraint CollisionShape shape = (pShape as BulletShapeXNA).shape; gObj.SetCollisionShape(shape); gObj.SetUserPointer(pLocalID); - + if (specialCollisionObjects.ContainsKey(pLocalID)) specialCollisionObjects[pLocalID] = gObj; - else + else specialCollisionObjects.Add(pLocalID, gObj); // TODO: Add to Special CollisionObjects! @@ -1447,8 +1447,8 @@ private sealed class BulletConstraintXNA : BulletConstraint return new BulletShapeXNA(ret, BSShapeTypeFromBroadPhaseNativeType(ret.GetShapeType())); } - public override BulletShape GetChildShapeFromCompoundShapeIndex(BulletShape cShape, int indx) { - + public override BulletShape GetChildShapeFromCompoundShapeIndex(BulletShape cShape, int indx) { + if (cShape == null) return null; CompoundShape compoundShape = (cShape as BulletShapeXNA).shape as CompoundShape; @@ -1456,7 +1456,7 @@ private sealed class BulletConstraintXNA : BulletConstraint BulletShape retShape = new BulletShapeXNA(shape, BSShapeTypeFromBroadPhaseNativeType(shape.GetShapeType())); - return retShape; + return retShape; } public BSPhysicsShapeType BSShapeTypeFromBroadPhaseNativeType(BroadphaseNativeTypes pin) @@ -1598,8 +1598,8 @@ private sealed class BulletConstraintXNA : BulletConstraint return new BulletShapeXNA(m_planeshape, BSPhysicsShapeType.SHAPE_GROUNDPLANE); } - public override BulletConstraint Create6DofSpringConstraint(BulletWorld pWorld, BulletBody pBody1, BulletBody pBody2, - Vector3 pframe1, Quaternion pframe1rot, Vector3 pframe2, Quaternion pframe2rot, + public override BulletConstraint Create6DofSpringConstraint(BulletWorld pWorld, BulletBody pBody1, BulletBody pBody2, + Vector3 pframe1, Quaternion pframe1rot, Vector3 pframe2, Quaternion pframe2rot, bool puseLinearReferenceFrameA, bool pdisableCollisionsBetweenLinkedBodies) { @@ -1745,7 +1745,7 @@ private sealed class BulletConstraintXNA : BulletConstraint { DiscreteDynamicsWorld world = (pWorld as BulletWorldXNA).world; CompoundShape compoundshape = new CompoundShape(false); - + compoundshape.SetMargin(world.WorldSettings.Params.collisionMargin); int ii = 1; @@ -1761,7 +1761,7 @@ private sealed class BulletConstraintXNA : BulletConstraint int ender = ((ii + 4) + (vertexCount*3)); for (int iii = ii + 4; iii < ender; iii+=3) { - + virts.Add(new IndexedVector3(pConvHulls[iii], pConvHulls[iii + 1], pConvHulls[iii +2])); } ConvexHullShape convexShape = new ConvexHullShape(virts, vertexCount); @@ -1769,7 +1769,7 @@ private sealed class BulletConstraintXNA : BulletConstraint compoundshape.AddChildShape(ref childTrans, convexShape); ii += (vertexCount*3 + 4); } - + return new BulletShapeXNA(compoundshape, BSPhysicsShapeType.SHAPE_HULL); } @@ -1791,13 +1791,13 @@ private sealed class BulletConstraintXNA : BulletConstraint public override BulletShape CreateMeshShape(BulletWorld pWorld, int pIndicesCount, int[] indices, int pVerticesCount, float[] verticesAsFloats) { //DumpRaw(indices,verticesAsFloats,pIndicesCount,pVerticesCount); - + for (int iter = 0; iter < pVerticesCount; iter++) { if (verticesAsFloats[iter] > 0 && verticesAsFloats[iter] < 0.0001) verticesAsFloats[iter] = 0; if (verticesAsFloats[iter] < 0 && verticesAsFloats[iter] > -0.0001) verticesAsFloats[iter] = 0; } - + ObjectArray indicesarr = new ObjectArray(indices); ObjectArray vertices = new ObjectArray(verticesAsFloats); DumpRaw(indicesarr,vertices,pIndicesCount,pVerticesCount); @@ -1811,7 +1811,7 @@ private sealed class BulletConstraintXNA : BulletConstraint mesh.m_vertexStride = 3; mesh.m_vertexType = PHY_ScalarType.PHY_FLOAT; mesh.m_triangleIndexStride = 3; - + TriangleIndexVertexArray tribuilder = new TriangleIndexVertexArray(); tribuilder.AddIndexedMesh(mesh, PHY_ScalarType.PHY_INTEGER); BvhTriangleMeshShape meshShape = new BvhTriangleMeshShape(tribuilder, true,true); @@ -1822,7 +1822,7 @@ private sealed class BulletConstraintXNA : BulletConstraint } public static void DumpRaw(ObjectArrayindices, ObjectArray vertices, int pIndicesCount,int pVerticesCount ) { - + String fileName = "objTest3.raw"; String completePath = System.IO.Path.Combine(Util.configDir(), fileName); StreamWriter sw = new StreamWriter(completePath); @@ -1848,7 +1848,7 @@ private sealed class BulletConstraintXNA : BulletConstraint string s = vertices[indices[i * 3]].ToString("0.0000"); s += " " + vertices[indices[i * 3 + 1]].ToString("0.0000"); s += " " + vertices[indices[i * 3 + 2]].ToString("0.0000"); - + sw.Write(s + "\n"); } @@ -1870,7 +1870,7 @@ private sealed class BulletConstraintXNA : BulletConstraint mesh.m_vertexStride = 3; mesh.m_vertexType = PHY_ScalarType.PHY_FLOAT; mesh.m_triangleIndexStride = 3; - + TriangleIndexVertexArray tribuilder = new TriangleIndexVertexArray(); tribuilder.AddIndexedMesh(mesh, PHY_ScalarType.PHY_INTEGER); @@ -1901,7 +1901,7 @@ private sealed class BulletConstraintXNA : BulletConstraint sw.Close(); } - public override BulletShape CreateTerrainShape(uint id, Vector3 size, float minHeight, float maxHeight, float[] heightMap, + public override BulletShape CreateTerrainShape(uint id, Vector3 size, float minHeight, float maxHeight, float[] heightMap, float scaleFactor, float collisionMargin) { const int upAxis = 2; @@ -1943,14 +1943,14 @@ private sealed class BulletConstraintXNA : BulletConstraint /* TODO */ updatedEntityCount = 0; collidersCount = 0; - + int ret = PhysicsStep2(world,timeStep,maxSubSteps,fixedTimeStep,out updatedEntityCount,out world.physicsScene.m_updateArray, out collidersCount, out world.physicsScene.m_collisionArray); return ret; } - private int PhysicsStep2(BulletWorld pWorld, float timeStep, int m_maxSubSteps, float m_fixedTimeStep, + private int PhysicsStep2(BulletWorld pWorld, float timeStep, int m_maxSubSteps, float m_fixedTimeStep, out int updatedEntityCount, out EntityProperties[] updatedEntities, out int collidersCount, out CollisionDesc[] colliders) { @@ -1959,24 +1959,24 @@ private sealed class BulletConstraintXNA : BulletConstraint return epic; } - private int PhysicsStepint(BulletWorld pWorld,float timeStep, int m_maxSubSteps, float m_fixedTimeStep, out int updatedEntityCount, + private int PhysicsStepint(BulletWorld pWorld,float timeStep, int m_maxSubSteps, float m_fixedTimeStep, out int updatedEntityCount, out EntityProperties[] updatedEntities, out int collidersCount, out CollisionDesc[] colliders, int maxCollisions, int maxUpdates) { int numSimSteps = 0; Array.Clear(UpdatedObjects, 0, UpdatedObjects.Length); Array.Clear(UpdatedCollisions, 0, UpdatedCollisions.Length); LastEntityProperty=0; - + LastCollisionDesc=0; - + updatedEntityCount = 0; collidersCount = 0; - + if (pWorld is BulletWorldXNA) { @@ -2033,7 +2033,7 @@ private sealed class BulletConstraintXNA : BulletConstraint collidersCount = LastCollisionDesc; colliders = UpdatedCollisions; - + } else @@ -2041,15 +2041,15 @@ private sealed class BulletConstraintXNA : BulletConstraint //if (updatedEntities is null) //updatedEntities = new List(); //updatedEntityCount = 0; - - + + //collidersCount = 0; - + updatedEntities = new EntityProperties[0]; - + colliders = new CollisionDesc[0]; - + } return numSimSteps; } @@ -2057,7 +2057,7 @@ private sealed class BulletConstraintXNA : BulletConstraint { IOverlappingPairCache cache = obj.GetOverlappingPairCache(); ObjectArray pairs = cache.GetOverlappingPairArray(); - + DiscreteDynamicsWorld world = (PhysicsScene.World as BulletWorldXNA).world; PersistentManifoldArray manifoldArray = new PersistentManifoldArray(); BroadphasePair collisionPair; @@ -2069,7 +2069,7 @@ private sealed class BulletConstraintXNA : BulletConstraint ManifoldPoint pt; int numPairs = pairs.Count; - + for (int i = 0; i < numPairs; i++) { manifoldArray.Clear(); @@ -2078,7 +2078,7 @@ private sealed class BulletConstraintXNA : BulletConstraint collisionPair = world.GetPairCache().FindPair(pairs[i].m_pProxy0, pairs[i].m_pProxy1); if (collisionPair == null) continue; - + collisionPair.m_algorithm.GetAllContactManifolds(manifoldArray); for (int j = 0; j < manifoldArray.Count; j++) { @@ -2101,7 +2101,7 @@ private sealed class BulletConstraintXNA : BulletConstraint } private static void RecordCollision(BSAPIXNA world, CollisionObject objA, CollisionObject objB, IndexedVector3 contact, IndexedVector3 norm, float penetration) { - + IndexedVector3 contactNormal = norm; if ((objA.GetCollisionFlags() & BulletXNA.BulletCollision.CollisionFlags.BS_WANTS_COLLISIONS) == 0 && (objB.GetCollisionFlags() & BulletXNA.BulletCollision.CollisionFlags.BS_WANTS_COLLISIONS) == 0) @@ -2171,11 +2171,11 @@ private sealed class BulletConstraintXNA : BulletConstraint if (NotMe is BulletBodyXNA && NotMe.HasPhysicalBody) { CollisionObject AvoidBody = (NotMe as BulletBodyXNA).body; - + IndexedVector3 rOrigin = new IndexedVector3(_RayOrigin.X, _RayOrigin.Y, _RayOrigin.Z); IndexedVector3 rEnd = new IndexedVector3(_RayOrigin.X, _RayOrigin.Y, _RayOrigin.Z - pRayHeight); using ( - ClosestNotMeRayResultCallback rayCallback = + ClosestNotMeRayResultCallback rayCallback = new ClosestNotMeRayResultCallback(rOrigin, rEnd, AvoidBody) ) { @@ -2191,9 +2191,9 @@ private sealed class BulletConstraintXNA : BulletConstraint return false; } } - - + + public class SimMotionState : DefaultMotionState { @@ -2286,12 +2286,12 @@ private sealed class BulletConstraintXNA : BulletConstraint m_lastProperties = m_properties; if (m_world.LastEntityProperty < m_world.UpdatedObjects.Length) m_world.UpdatedObjects[m_world.LastEntityProperty++]=(m_properties); - + //(*m_updatesThisFrame)[m_properties.ID] = &m_properties; } - - - + + + } public override void SetRigidBody(RigidBody body) @@ -2314,7 +2314,7 @@ private sealed class BulletConstraintXNA : BulletConstraint (((v1.Z - nEpsilon) < v2.Z) && (v2.Z < (v1.Z + nEpsilon))) && (((v1.W - nEpsilon) < v2.W) && (v2.W < (v1.W + nEpsilon))); } - + } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs b/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs index ac05979..4e067b5 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs @@ -115,7 +115,7 @@ public class BSActorAvatarMove : BSActor if (m_velocityMotor == null) { // Infinite decay and timescale values so motor only changes current to target values. - m_velocityMotor = new BSVMotor("BSCharacter.Velocity", + m_velocityMotor = new BSVMotor("BSCharacter.Velocity", 0.2f, // time scale BSMotor.Infinite, // decay time scale BSMotor.InfiniteVector, // friction timescale diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSActorLockAxis.cs b/OpenSim/Region/Physics/BulletSPlugin/BSActorLockAxis.cs index 6059af5..7801d8e 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSActorLockAxis.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSActorLockAxis.cs @@ -63,7 +63,7 @@ public class BSActorLockAxis : BSActor // BSActor.Refresh() public override void Refresh() { - m_physicsScene.DetailLog("{0},BSActorLockAxis,refresh,lockedAxis={1},enabled={2},pActive={3}", + m_physicsScene.DetailLog("{0},BSActorLockAxis,refresh,lockedAxis={1},enabled={2},pActive={3}", m_controllingPrim.LocalID, m_controllingPrim.LockedAxis, Enabled, m_controllingPrim.IsPhysicallyActive); // If all the axis are free, we don't need to exist if (m_controllingPrim.LockedAxis == m_controllingPrim.LockedAxisFree) diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSActors.cs b/OpenSim/Region/Physics/BulletSPlugin/BSActors.cs index 5e3f1c4..fff63e4 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSActors.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSActors.cs @@ -117,7 +117,7 @@ public class BSActorCollection /// Each physical object can have 'actors' who are pushing the object around. /// This can be used for hover, locking axis, making vehicles, etc. /// Each physical object can have multiple actors acting on it. -/// +/// /// An actor usually registers itself with physics scene events (pre-step action) /// and modifies the parameters on the host physical object. /// diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSApiTemplate.cs b/OpenSim/Region/Physics/BulletSPlugin/BSApiTemplate.cs index bfeec24..3378c93 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSApiTemplate.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSApiTemplate.cs @@ -298,7 +298,7 @@ public abstract class BSAPITemplate { // Returns the name of the underlying Bullet engine public abstract string BulletEngineName { get; } -public abstract string BulletEngineVersion { get; protected set;} +public abstract string BulletEngineVersion { get; protected set;} // Initialization and simulation public abstract BulletWorld Initialize(Vector3 maxPosition, ConfigurationParameters parms, @@ -373,7 +373,7 @@ public abstract void DestroyObject(BulletWorld sim, BulletBody obj); // ===================================================================================== public abstract BulletShape CreateGroundPlaneShape(UInt32 id, float height, float collisionMargin); -public abstract BulletShape CreateTerrainShape(UInt32 id, Vector3 size, float minHeight, float maxHeight, float[] heightMap, +public abstract BulletShape CreateTerrainShape(UInt32 id, Vector3 size, float minHeight, float maxHeight, float[] heightMap, float scaleFactor, float collisionMargin); // ===================================================================================== @@ -388,7 +388,7 @@ public abstract BulletConstraint Create6DofConstraintToPoint(BulletWorld world, bool useLinearReferenceFrameA, bool disableCollisionsBetweenLinkedBodies); public abstract BulletConstraint Create6DofConstraintFixed(BulletWorld world, BulletBody obj1, - Vector3 frameInBloc, Quaternion frameInBrot, + Vector3 frameInBloc, Quaternion frameInBrot, bool useLinearReferenceFrameB, bool disableCollisionsBetweenLinkedBodies); public abstract BulletConstraint Create6DofSpringConstraint(BulletWorld world, BulletBody obj1, BulletBody obj2, diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index e12fc8e..542f732 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -371,7 +371,7 @@ public sealed class BSCharacter : BSPhysObject public override float Mass { get { return _mass; } } // used when we only want this prim's mass and not the linkset thing - public override float RawMass { + public override float RawMass { get {return _mass; } } public override void UpdatePhysicalMassProperties(float physMass, bool inWorld) @@ -586,7 +586,7 @@ public sealed class BSCharacter : BSPhysObject } public override float ForceBuoyancy { get { return _buoyancy; } - set { + set { PhysScene.AssertInTaintTime("BSCharacter.ForceBuoyancy"); _buoyancy = value; @@ -647,7 +647,7 @@ public sealed class BSCharacter : BSPhysObject private OMV.Vector3 ComputeAvatarScale(OMV.Vector3 size) { OMV.Vector3 newScale; - + // Bullet's capsule total height is the "passed height + radius * 2"; // The base capsule is 1 diameter and 2 height (passed radius=0.5, passed height = 1) // The number we pass in for 'scaling' is the multiplier to get that base diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSConstraintHinge.cs b/OpenSim/Region/Physics/BulletSPlugin/BSConstraintHinge.cs index 7714a03..ed89f63 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSConstraintHinge.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSConstraintHinge.cs @@ -45,7 +45,7 @@ public sealed class BSConstraintHinge : BSConstraint m_body1 = obj1; m_body2 = obj2; m_constraint = PhysicsScene.PE.CreateHingeConstraint(world, obj1, obj2, - pivotInA, pivotInB, axisInA, axisInB, + pivotInA, pivotInB, axisInA, axisInB, useLinearReferenceFrameA, disableCollisionsBetweenLinkedBodies); m_enabled = true; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index 56d2415..f535e50 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -1019,7 +1019,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin Vector3 origVelW = VehicleVelocity; // DEBUG DEBUG VehicleVelocity /= VehicleVelocity.Length(); VehicleVelocity *= BSParam.VehicleMaxLinearVelocity; - VDetailLog("{0}, MoveLinear,clampMax,origVelW={1},lenSq={2},maxVelSq={3},,newVelW={4}", + VDetailLog("{0}, MoveLinear,clampMax,origVelW={1},lenSq={2},maxVelSq={3},,newVelW={4}", ControllingPrim.LocalID, origVelW, newVelocityLengthSq, BSParam.VehicleMaxLinearVelocitySquared, VehicleVelocity); } else if (newVelocityLengthSq < 0.001f) @@ -1094,7 +1094,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin if (VehiclePosition.Z > m_VhoverTargetHeight) m_VhoverTargetHeight = VehiclePosition.Z; } - + if ((m_flags & VehicleFlag.LOCK_HOVER_HEIGHT) != 0) { if (Math.Abs(VehiclePosition.Z - m_VhoverTargetHeight) > 0.2f) @@ -1188,7 +1188,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin // used with conjunction with banking: the strength of the banking will decay when the // vehicle no longer experiences collisions. The decay timescale is the same as // VEHICLE_BANKING_TIMESCALE. This is to help prevent ground vehicles from steering - // when they are in mid jump. + // when they are in mid jump. // TODO: this code is wrong. Also, what should it do for boats (height from water)? // This is just using the ground and a general collision check. Should really be using // a downward raycast to find what is below. @@ -1254,7 +1254,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin VehicleAddForce(appliedGravity); - VDetailLog("{0}, MoveLinear,applyGravity,vehGrav={1},collid={2},fudge={3},mass={4},appliedForce={3}", + VDetailLog("{0}, MoveLinear,applyGravity,vehGrav={1},collid={2},fudge={3},mass={4},appliedForce={3}", ControllingPrim.LocalID, m_VehicleGravity, ControllingPrim.IsColliding, BSParam.VehicleGroundGravityFudge, m_vehicleMass, appliedGravity); } @@ -1330,7 +1330,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin // From http://wiki.secondlife.com/wiki/LlSetVehicleFlags : // This flag prevents linear deflection parallel to world z-axis. This is useful // for preventing ground vehicles with large linear deflection, like bumper cars, - // from climbing their linear deflection into the sky. + // from climbing their linear deflection into the sky. // That is, NO_DEFLECTION_UP says angular motion should not add any pitch or roll movement // TODO: This is here because this is where ODE put it but documentation says it // is a linear effect. Where should this check go? @@ -1463,7 +1463,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin VehicleRotationalVelocity += (vertContributionV * VehicleOrientation); VDetailLog("{0}, MoveAngular,verticalAttraction,,origRotVW={1},vertError={2},unscaledV={3},eff={4},ts={5},vertContribV={6}", - Prim.LocalID, origRotVelW, verticalError, unscaledContribVerticalErrorV, + Prim.LocalID, origRotVelW, verticalError, unscaledContribVerticalErrorV, m_verticalAttractionEfficiency, m_verticalAttractionTimescale, vertContributionV); */ } @@ -1530,13 +1530,13 @@ namespace OpenSim.Region.Physics.BulletSPlugin // produce a angular velocity around the yaw-axis, causing the vehicle to turn. The magnitude // of the yaw effect will be proportional to the // VEHICLE_BANKING_EFFICIENCY, the angle of the roll rotation, and sometimes the vehicle's - // velocity along its preferred axis of motion. + // velocity along its preferred axis of motion. // The VEHICLE_BANKING_EFFICIENCY can vary between -1 and +1. When it is positive then any // positive rotation (by the right-hand rule) about the roll-axis will effect a // (negative) torque around the yaw-axis, making it turn to the right--that is the // vehicle will lean into the turn, which is how real airplanes and motorcycle's work. // Negating the banking coefficient will make it so that the vehicle leans to the - // outside of the turn (not very "physical" but might allow interesting vehicles so why not?). + // outside of the turn (not very "physical" but might allow interesting vehicles so why not?). // The VEHICLE_BANKING_MIX is a fake (i.e. non-physical) parameter that is useful for making // banking vehicles do what you want rather than what the laws of physics allow. // For example, consider a real motorcycle...it must be moving forward in order for @@ -1548,11 +1548,11 @@ namespace OpenSim.Region.Physics.BulletSPlugin // totally static (0.0) and totally dynamic (1.0). By "static" we mean that the // banking effect depends only on the vehicle's rotation about its roll-axis compared // to "dynamic" where the banking is also proportional to its velocity along its - // roll-axis. Finding the best value of the "mixture" will probably require trial and error. + // roll-axis. Finding the best value of the "mixture" will probably require trial and error. // The time it takes for the banking behavior to defeat a preexisting angular velocity about the // world z-axis is determined by the VEHICLE_BANKING_TIMESCALE. So if you want the vehicle to // bank quickly then give it a banking timescale of about a second or less, otherwise you can - // make a sluggish vehicle by giving it a timescale of several seconds. + // make a sluggish vehicle by giving it a timescale of several seconds. public void ComputeAngularBanking() { if (enableAngularBanking && m_bankingEfficiency != 0 && m_verticalAttractionTimescale < m_verticalAttractionCutoff) @@ -1581,7 +1581,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin //VehicleRotationalVelocity += bankingContributionV * VehicleOrientation; VehicleRotationalVelocity += bankingContributionV; - + VDetailLog("{0}, MoveAngular,Banking,rollComp={1},speed={2},rollComp={3},yAng={4},mYAng={5},ret={6}", ControllingPrim.LocalID, rollComponents, VehicleForwardSpeed, rollComponents, yawAngle, mixedYawAngle, bankingContributionV); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index 6d0d0eb..76c2187 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -214,7 +214,7 @@ public abstract class BSLinkset // I am the root of a linkset and a new child is being added // Called while LinkActivity is locked. protected abstract void AddChildToLinkset(BSPrimLinkable child); - + // I am the root of a linkset and one of my children is being removed. // Safe to call even if the child is not really in my linkset. protected abstract void RemoveChildFromLinkset(BSPrimLinkable child); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs index 01ada3f..1fd541f 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs @@ -114,7 +114,7 @@ public sealed class BSLinksetCompound : BSLinkset // Schedule a refresh to happen after all the other taint processing. private void ScheduleRebuild(BSPrimLinkable requestor) { - DetailLog("{0},BSLinksetCompound.ScheduleRebuild,,rebuilding={1},hasChildren={2},actuallyScheduling={3}", + DetailLog("{0},BSLinksetCompound.ScheduleRebuild,,rebuilding={1},hasChildren={2},actuallyScheduling={3}", requestor.LocalID, Rebuilding, HasAnyChildren, (!Rebuilding && HasAnyChildren)); // When rebuilding, it is possible to set properties that would normally require a rebuild. // If already rebuilding, don't request another rebuild. @@ -208,7 +208,7 @@ public sealed class BSLinksetCompound : BSLinkset // and that is caused by us updating the object. if ((whichUpdated & ~(UpdatedProperties.Position | UpdatedProperties.Orientation)) == 0) { - // Find the physical instance of the child + // Find the physical instance of the child if (LinksetRoot.PhysShape.HasPhysicalShape && m_physicsScene.PE.IsCompound(LinksetRoot.PhysShape.physShapeInfo)) { // It is possible that the linkset is still under construction and the child is not yet diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSMotors.cs b/OpenSim/Region/Physics/BulletSPlugin/BSMotors.cs index 9501e2d..0128d8d 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSMotors.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSMotors.cs @@ -102,7 +102,7 @@ public class BSVMotor : BSMotor return ErrorIsZero(LastError); } public virtual bool ErrorIsZero(Vector3 err) - { + { return (err == Vector3.Zero || err.ApproxEquals(Vector3.Zero, ErrorZeroThreshold)); } @@ -115,7 +115,7 @@ public class BSVMotor : BSMotor CurrentValue = TargetValue = Vector3.Zero; ErrorZeroThreshold = 0.001f; } - public BSVMotor(string useName, float timeScale, float decayTimeScale, Vector3 frictionTimeScale, float efficiency) + public BSVMotor(string useName, float timeScale, float decayTimeScale, Vector3 frictionTimeScale, float efficiency) : this(useName) { TimeScale = timeScale; @@ -237,7 +237,7 @@ public class BSVMotor : BSMotor MDetailLog("{0},BSVMotor.Test,{1},===================================== BEGIN Test Output", BSScene.DetailLogZero, UseName); MDetailLog("{0},BSVMotor.Test,{1},timeScale={2},targDlyTS={3},frictTS={4},eff={5},curr={6},tgt={7}", BSScene.DetailLogZero, UseName, - TimeScale, TargetValueDecayTimeScale, FrictionTimescale, Efficiency, + TimeScale, TargetValueDecayTimeScale, FrictionTimescale, Efficiency, CurrentValue, TargetValue); LastError = BSMotor.InfiniteVector; @@ -248,7 +248,7 @@ public class BSVMotor : BSMotor BSScene.DetailLogZero, UseName, CurrentValue, TargetValue, LastError, lastStep); } MDetailLog("{0},BSVMotor.Test,{1},===================================== END Test Output", BSScene.DetailLogZero, UseName); - + } @@ -279,7 +279,7 @@ public class BSFMotor : BSMotor return ErrorIsZero(LastError); } public virtual bool ErrorIsZero(float err) - { + { return (err >= -ErrorZeroThreshold && err <= ErrorZeroThreshold); } @@ -410,7 +410,7 @@ public class BSPIDVMotor : BSVMotor // The factors are vectors for the three dimensions. This is the proportional of each // that is applied. This could be multiplied through the actual factors but it // is sometimes easier to manipulate the factors and their mix separately. - // to + // to public Vector3 FactorMix; // Arbritrary factor range. diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs index 980d405..5ebeace 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs @@ -37,7 +37,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin { public static class BSParam { - private static string LogHeader = "[BULLETSIM PARAMETERS]"; + private static string LogHeader = "[BULLETSIM PARAMETERS]"; // Tuning notes: // From: http://bulletphysics.org/Bullet/phpBB3/viewtopic.php?t=6575 @@ -51,7 +51,7 @@ public static class BSParam // This is separate/independent from the collision margin. The collision margin increases the object a bit // to improve collision detection performance and accuracy. // =================== - // From: + // From: // Level of Detail values kept as float because that's what the Meshmerizer wants public static float MeshLOD { get; private set; } @@ -636,7 +636,7 @@ public static class BSParam new ParameterDefn("ShouldDisableContactPoolDynamicAllocation", "Enable to allow large changes in object count", false, (s) => { return ShouldDisableContactPoolDynamicAllocation; }, - (s,v) => { ShouldDisableContactPoolDynamicAllocation = v; + (s,v) => { ShouldDisableContactPoolDynamicAllocation = v; s.UnmanagedParams[0].shouldDisableContactPoolDynamicAllocation = NumericBool(v); } ), new ParameterDefn("ShouldForceUpdateAllAabbs", "Enable to recomputer AABBs every simulator step", false, diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index 6a3ada2..28d4bd7 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -38,7 +38,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin * Class to wrap all objects. * The rest of BulletSim doesn't need to keep checking for avatars or prims * unless the difference is significant. - * + * * Variables in the physicsl objects are in three forms: * VariableName: used by the simulator and performs taint operations, etc * RawVariableName: direct reference to the BulletSim storage for the variable value @@ -52,7 +52,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin * SOP.ApplyImpulse SOP.ApplyAngularImpulse SOP.SetAngularImpulse SOP.SetForce * SOG.ApplyImpulse SOG.ApplyAngularImpulse SOG.SetAngularImpulse * PA.AddForce PA.AddAngularForce PA.Torque = v PA.Force = v - * BS.ApplyCentralForce BS.ApplyTorque + * BS.ApplyCentralForce BS.ApplyTorque */ // Flags used to denote which properties updates when making UpdateProperties calls to linksets, etc. @@ -353,7 +353,7 @@ public abstract class BSPhysObject : PhysicsActor } public override bool CollidingObj { get { return (CollidingObjectStep == PhysScene.SimulationStep); } - set { + set { if (value) CollidingObjectStep = PhysScene.SimulationStep; else @@ -447,7 +447,7 @@ public abstract class BSPhysObject : PhysicsActor // The CollisionCollection instance is passed around in the simulator. // Make sure we don't have a handle to that one and that a new one is used for next time. - // This fixes an interesting 'gotcha'. If we call CollisionCollection.Clear() here, + // This fixes an interesting 'gotcha'. If we call CollisionCollection.Clear() here, // a race condition is created for the other users of this instance. CollisionCollection = new CollisionEventUpdate(); } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 0d45579..7e2af78 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -420,7 +420,7 @@ public class BSPrim : BSPhysObject get { return _mass; } } // used when we only want this prim's mass and not the linkset thing - public override float RawMass { + public override float RawMass { get { return _mass; } } // Set the physical mass to the passed mass. diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs index bfc7ae7..5c58ad5 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs @@ -142,7 +142,7 @@ public abstract class BSShape // If the shape was successfully created, nothing more to do if (newShape.HasPhysicalShape) return newShape; - + // VerifyMeshCreated is called after trying to create the mesh. If we think the asset had been // fetched but we end up here again, the meshing of the asset must have failed. // Prevent trying to keep fetching the mesh by declaring failure. @@ -155,7 +155,7 @@ public abstract class BSShape else { // If this mesh has an underlying asset and we have not failed getting it before, fetch the asset - if (prim.BaseShape.SculptEntry + if (prim.BaseShape.SculptEntry && prim.PrimAssetState != BSPhysObject.PrimAssetCondition.Failed && prim.PrimAssetState != BSPhysObject.PrimAssetCondition.Waiting && prim.BaseShape.SculptTexture != OMV.UUID.Zero @@ -164,7 +164,7 @@ public abstract class BSShape physicsScene.DetailLog("{0},BSShape.VerifyMeshCreated,fetchAsset", prim.LocalID); // Multiple requestors will know we're waiting for this asset prim.PrimAssetState = BSPhysObject.PrimAssetCondition.Waiting; - + BSPhysObject xprim = prim; Util.FireAndForget(delegate { @@ -245,8 +245,8 @@ public class BSShapeNative : BSShape { } - public static BSShape GetReference(BSScene physicsScene, BSPhysObject prim, - BSPhysicsShapeType shapeType, FixedShapeKey shapeKey) + public static BSShape GetReference(BSScene physicsScene, BSPhysObject prim, + BSPhysicsShapeType shapeType, FixedShapeKey shapeKey) { // Native shapes are not shared and are always built anew. return new BSShapeNative(CreatePhysicalNativeShape(physicsScene, prim, shapeType, shapeKey)); @@ -379,7 +379,7 @@ public class BSShapeMesh : BSShape { BulletShape newShape = null; - IMesh meshData = physicsScene.mesher.CreateMesh(prim.PhysObjectName, pbs, size, lod, + IMesh meshData = physicsScene.mesher.CreateMesh(prim.PhysObjectName, pbs, size, lod, false, // say it is not physical so a bounding box is not built false // do not cache the mesh and do not use previously built versions ); @@ -671,8 +671,8 @@ public class BSShapeCompound : BSShape public BSShapeCompound(BulletShape pShape) : base(pShape) { } - public static BSShape GetReference(BSScene physicsScene, BSPhysObject prim) - { + public static BSShape GetReference(BSScene physicsScene, BSPhysObject prim) + { // Compound shapes are not shared so a new one is created every time. return new BSShapeCompound(CreatePhysicalCompoundShape(physicsScene, prim)); } @@ -750,8 +750,8 @@ public class BSShapeAvatar : BSShape public BSShapeAvatar() : base() { } - public static BSShape GetReference(BSPhysObject prim) - { + public static BSShape GetReference(BSPhysObject prim) + { return new BSShapeNull(); } public override void Dereference(BSScene physicsScene) { } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainHeightmap.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainHeightmap.cs index 5a19797..c7deb4e 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainHeightmap.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainHeightmap.cs @@ -68,7 +68,7 @@ public sealed class BSTerrainHeightmap : BSTerrainPhys // This minCoords and maxCoords passed in give the size of the terrain (min and max Z // are the high and low points of the heightmap). - public BSTerrainHeightmap(BSScene physicsScene, Vector3 regionBase, uint id, float[] initialMap, + public BSTerrainHeightmap(BSScene physicsScene, Vector3 regionBase, uint id, float[] initialMap, Vector3 minCoords, Vector3 maxCoords) : base(physicsScene, regionBase, id) { @@ -92,7 +92,7 @@ public sealed class BSTerrainHeightmap : BSTerrainPhys private void BuildHeightmapTerrain() { // Create the terrain shape from the mapInfo - m_mapInfo.terrainShape = m_physicsScene.PE.CreateTerrainShape( m_mapInfo.ID, + m_mapInfo.terrainShape = m_physicsScene.PE.CreateTerrainShape( m_mapInfo.ID, new Vector3(m_mapInfo.sizeX, m_mapInfo.sizeY, 0), m_mapInfo.minZ, m_mapInfo.maxZ, m_mapInfo.heightMap, 1f, BSParam.TerrainCollisionMargin); @@ -103,7 +103,7 @@ public sealed class BSTerrainHeightmap : BSTerrainPhys centerPos.Y = m_mapInfo.minCoords.Y + (m_mapInfo.sizeY / 2f); centerPos.Z = m_mapInfo.minZ + ((m_mapInfo.maxZ - m_mapInfo.minZ) / 2f); - m_mapInfo.terrainBody = m_physicsScene.PE.CreateBodyWithDefaultMotionState(m_mapInfo.terrainShape, + m_mapInfo.terrainBody = m_physicsScene.PE.CreateBodyWithDefaultMotionState(m_mapInfo.terrainShape, m_mapInfo.ID, centerPos, Quaternion.Identity); // Set current terrain attributes diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs index 0d16eda..c4807c4 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs @@ -135,7 +135,7 @@ public sealed class BSTerrainManager : IDisposable DetailLog("{0},BSTerrainManager.CreateInitialGroundPlaneAndTerrain,region={1}", BSScene.DetailLogZero, m_physicsScene.RegionName); // The ground plane is here to catch things that are trying to drop to negative infinity BulletShape groundPlaneShape = m_physicsScene.PE.CreateGroundPlaneShape(BSScene.GROUNDPLANE_ID, 1f, BSParam.TerrainCollisionMargin); - m_groundPlane = m_physicsScene.PE.CreateBodyWithDefaultMotionState(groundPlaneShape, + m_groundPlane = m_physicsScene.PE.CreateBodyWithDefaultMotionState(groundPlaneShape, BSScene.GROUNDPLANE_ID, Vector3.Zero, Quaternion.Identity); m_physicsScene.PE.AddObjectToWorld(m_physicsScene.World, m_groundPlane); @@ -318,8 +318,8 @@ public sealed class BSTerrainManager : IDisposable // TODO: redo terrain implementation selection to allow other base types than heightMap. private BSTerrainPhys BuildPhysicalTerrain(Vector3 terrainRegionBase, uint id, float[] heightMap, Vector3 minCoords, Vector3 maxCoords) { - m_physicsScene.Logger.DebugFormat("{0} Terrain for {1}/{2} created with {3}", - LogHeader, m_physicsScene.RegionName, terrainRegionBase, + m_physicsScene.Logger.DebugFormat("{0} Terrain for {1}/{2} created with {3}", + LogHeader, m_physicsScene.RegionName, terrainRegionBase, (BSTerrainPhys.TerrainImplementation)BSParam.TerrainImplementation); BSTerrainPhys newTerrainPhys = null; switch ((int)BSParam.TerrainImplementation) @@ -334,8 +334,8 @@ public sealed class BSTerrainManager : IDisposable break; default: m_physicsScene.Logger.ErrorFormat("{0} Bad terrain implementation specified. Type={1}/{2},Region={3}/{4}", - LogHeader, - (int)BSParam.TerrainImplementation, + LogHeader, + (int)BSParam.TerrainImplementation, BSParam.TerrainImplementation, m_physicsScene.RegionName, terrainRegionBase); break; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainMesh.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainMesh.cs index ee2a1f2..e4ca098 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainMesh.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainMesh.cs @@ -51,7 +51,7 @@ public sealed class BSTerrainMesh : BSTerrainPhys BulletShape m_terrainShape; BulletBody m_terrainBody; - public BSTerrainMesh(BSScene physicsScene, Vector3 regionBase, uint id, Vector3 regionSize) + public BSTerrainMesh(BSScene physicsScene, Vector3 regionBase, uint id, Vector3 regionSize) : base(physicsScene, regionBase, id) { } @@ -62,7 +62,7 @@ public sealed class BSTerrainMesh : BSTerrainPhys } // Create terrain mesh from a heightmap. - public BSTerrainMesh(BSScene physicsScene, Vector3 regionBase, uint id, float[] initialMap, + public BSTerrainMesh(BSScene physicsScene, Vector3 regionBase, uint id, float[] initialMap, Vector3 minCoords, Vector3 maxCoords) : base(physicsScene, regionBase, id) { @@ -104,7 +104,7 @@ public sealed class BSTerrainMesh : BSTerrainPhys return; } - m_physicsScene.DetailLog("{0},BSTerrainMesh.create,meshed,id={1},indices={2},indSz={3},vertices={4},vertSz={5}", + m_physicsScene.DetailLog("{0},BSTerrainMesh.create,meshed,id={1},indices={2},indSz={3},vertices={4},vertSz={5}", BSScene.DetailLogZero, ID, indicesCount, indices.Length, verticesCount, vertices.Length); m_terrainShape = m_physicsScene.PE.CreateMeshShape(m_physicsScene.World, indicesCount, indices, verticesCount, vertices); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimData.cs b/OpenSim/Region/Physics/BulletSPlugin/BulletSimData.cs index 906e4f9..d5060e3 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimData.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimData.cs @@ -224,42 +224,42 @@ public static class BulletSimData // As mentioned above, don't use the CollisionFilterGroups definitions directly in the code // but, instead, use references to this dictionary. Finding and debugging // collision flag problems will be made easier. -public static Dictionary CollisionTypeMasks +public static Dictionary CollisionTypeMasks = new Dictionary() { - { CollisionType.Avatar, - new CollisionTypeFilterGroup(CollisionType.Avatar, - (uint)CollisionFilterGroups.BCharacterGroup, + { CollisionType.Avatar, + new CollisionTypeFilterGroup(CollisionType.Avatar, + (uint)CollisionFilterGroups.BCharacterGroup, (uint)CollisionFilterGroups.BAllGroup) }, - { CollisionType.Groundplane, - new CollisionTypeFilterGroup(CollisionType.Groundplane, - (uint)CollisionFilterGroups.BGroundPlaneGroup, + { CollisionType.Groundplane, + new CollisionTypeFilterGroup(CollisionType.Groundplane, + (uint)CollisionFilterGroups.BGroundPlaneGroup, (uint)CollisionFilterGroups.BAllGroup) }, - { CollisionType.Terrain, - new CollisionTypeFilterGroup(CollisionType.Terrain, - (uint)CollisionFilterGroups.BTerrainGroup, + { CollisionType.Terrain, + new CollisionTypeFilterGroup(CollisionType.Terrain, + (uint)CollisionFilterGroups.BTerrainGroup, (uint)(CollisionFilterGroups.BAllGroup & ~CollisionFilterGroups.BStaticGroup)) }, - { CollisionType.Static, - new CollisionTypeFilterGroup(CollisionType.Static, - (uint)CollisionFilterGroups.BStaticGroup, + { CollisionType.Static, + new CollisionTypeFilterGroup(CollisionType.Static, + (uint)CollisionFilterGroups.BStaticGroup, (uint)(CollisionFilterGroups.BCharacterGroup | CollisionFilterGroups.BSolidGroup)) }, - { CollisionType.Dynamic, - new CollisionTypeFilterGroup(CollisionType.Dynamic, - (uint)CollisionFilterGroups.BSolidGroup, + { CollisionType.Dynamic, + new CollisionTypeFilterGroup(CollisionType.Dynamic, + (uint)CollisionFilterGroups.BSolidGroup, (uint)(CollisionFilterGroups.BAllGroup)) }, - { CollisionType.VolumeDetect, - new CollisionTypeFilterGroup(CollisionType.VolumeDetect, - (uint)CollisionFilterGroups.BSensorTrigger, + { CollisionType.VolumeDetect, + new CollisionTypeFilterGroup(CollisionType.VolumeDetect, + (uint)CollisionFilterGroups.BSensorTrigger, (uint)(~CollisionFilterGroups.BSensorTrigger)) }, { CollisionType.LinksetChild, - new CollisionTypeFilterGroup(CollisionType.LinksetChild, - (uint)CollisionFilterGroups.BLinksetChildGroup, + new CollisionTypeFilterGroup(CollisionType.LinksetChild, + (uint)CollisionFilterGroups.BLinksetChildGroup, (uint)(CollisionFilterGroups.BNoneGroup)) // (uint)(CollisionFilterGroups.BCharacterGroup | CollisionFilterGroups.BSolidGroup)) }, -- cgit v1.1 From 15a3f80e2eb82c5e4726d5cd93cfed32da5d6768 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Mon, 29 Apr 2013 17:30:38 -0700 Subject: BulletSim: LinksetCompound work to disable collision for root and child prims so compound shape can do all collisions. Don't try to build a compound linkset for non-physical linksets. Remove and replace root body when compound shape is added so collision cache is rebuilt. --- .../Physics/BulletSPlugin/BSLinksetCompound.cs | 44 +++++++++++++++------- 1 file changed, 30 insertions(+), 14 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs index 1fd541f..e967dfc 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs @@ -143,19 +143,18 @@ public sealed class BSLinksetCompound : BSLinkset // The root is going dynamic. Rebuild the linkset so parts and mass get computed properly. ScheduleRebuild(LinksetRoot); } - else - { - // The origional prims are removed from the world as the shape of the root compound - // shape takes over. - m_physicsScene.PE.AddToCollisionFlags(child.PhysBody, CollisionFlags.CF_NO_CONTACT_RESPONSE); - m_physicsScene.PE.ForceActivationState(child.PhysBody, ActivationState.DISABLE_SIMULATION); - // We don't want collisions from the old linkset children. - m_physicsScene.PE.RemoveFromCollisionFlags(child.PhysBody, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); - child.PhysBody.collisionType = CollisionType.LinksetChild; + // The origional prims are removed from the world as the shape of the root compound + // shape takes over. + m_physicsScene.PE.AddToCollisionFlags(child.PhysBody, CollisionFlags.CF_NO_CONTACT_RESPONSE); + m_physicsScene.PE.ForceActivationState(child.PhysBody, ActivationState.DISABLE_SIMULATION); + // We don't want collisions from the old linkset children. + m_physicsScene.PE.RemoveFromCollisionFlags(child.PhysBody, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); + + child.PhysBody.collisionType = CollisionType.LinksetChild; + + ret = true; - ret = true; - } return ret; } @@ -190,6 +189,13 @@ public sealed class BSLinksetCompound : BSLinkset // Called at taint-time. public override void UpdateProperties(UpdatedProperties whichUpdated, BSPrimLinkable updated) { + if (!LinksetRoot.IsPhysicallyActive) + { + // No reason to do this physical stuff for static linksets. + DetailLog("{0},BSLinksetCompound.UpdateProperties,notPhysical", LinksetRoot.LocalID); + return; + } + // The user moving a child around requires the rebuilding of the linkset compound shape // One problem is this happens when a border is crossed -- the simulator implementation // stores the position into the group which causes the move of the object @@ -392,6 +398,13 @@ public sealed class BSLinksetCompound : BSLinkset private bool disableCOM = true; // DEBUG DEBUG: disable until we get this debugged private void RecomputeLinksetCompound() { + if (!LinksetRoot.IsPhysicallyActive) + { + // There is no reason to build all this physical stuff for a non-physical linkset + DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,notPhysical", LinksetRoot.LocalID); + return; + } + try { // This replaces the physical shape of the root prim with a compound shape made up of the root @@ -403,7 +416,8 @@ public sealed class BSLinksetCompound : BSLinkset // Free up any shape we'd previously built. LinksetShape.Dereference(m_physicsScene); - LinksetShape = BSShapeCompound.GetReference(m_physicsScene, LinksetRoot); + // Get a new compound shape to build the linkset shape in. + LinksetShape = BSShapeCompound.GetReference(m_physicsScene); // The center of mass for the linkset is the geometric center of the group. // Compute a displacement for each component so it is relative to the center-of-mass. @@ -431,8 +445,7 @@ public sealed class BSLinksetCompound : BSLinkset cPrim.LinksetChildIndex = memberIndex; } - BSShape childShape = cPrim.PhysShape; - childShape.IncrementReference(); + BSShape childShape = cPrim.PhysShape.GetReference(m_physicsScene, cPrim); OMV.Vector3 offsetPos = (cPrim.RawPosition - LinksetRoot.RawPosition) * invRootOrientation - centerDisplacement; OMV.Quaternion offsetRot = cPrim.RawOrientation * invRootOrientation; m_physicsScene.PE.AddChildShapeToCompoundShape(LinksetShape.physShapeInfo, childShape.physShapeInfo, offsetPos, offsetRot); @@ -446,7 +459,10 @@ public sealed class BSLinksetCompound : BSLinkset // Sneak the built compound shape in as the shape of the root prim. // Note this doesn't touch the root prim's PhysShape so be sure the manage the difference. + // Object removed and added to world to get collision cache rebuilt for new shape. + m_physicsScene.PE.RemoveObjectFromWorld(m_physicsScene.World, LinksetRoot.PhysBody); m_physicsScene.PE.SetCollisionShape(m_physicsScene.World, LinksetRoot.PhysBody, LinksetShape.physShapeInfo); + m_physicsScene.PE.AddObjectToWorld(m_physicsScene.World, LinksetRoot.PhysBody); // With all of the linkset packed into the root prim, it has the mass of everyone. LinksetMass = ComputeLinksetMass(); -- cgit v1.1 From d322625f9062d7748a1a896b6fd37c51f7f41435 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Mon, 29 Apr 2013 17:30:54 -0700 Subject: BulletSim: Add non-static BSShape.GetReference for getting another reference to an existing shape instance. BSShapeNative rebuilds shape for all references. BSShapeCompound returns another reference copy if the compound shape already exists (for linksets). --- OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs | 125 +++++++++++++++------ .../Region/Physics/BulletSPlugin/BulletSimTODO.txt | 9 ++ 2 files changed, 102 insertions(+), 32 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs index 5c58ad5..f0c9fd5 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs @@ -47,26 +47,31 @@ public abstract class BSShape public BSShape() { - referenceCount = 0; + referenceCount = 1; lastReferenced = DateTime.Now; physShapeInfo = new BulletShape(); } public BSShape(BulletShape pShape) { - referenceCount = 0; + referenceCount = 1; lastReferenced = DateTime.Now; physShapeInfo = pShape; } + // Get another reference to this shape. + public abstract BSShape GetReference(BSScene pPhysicsScene, BSPhysObject pPrim); + // Called when this shape is being used again. - public virtual void IncrementReference() + // Used internally. External callers should call instance.GetReference() to properly copy/reference + // the shape. + protected virtual void IncrementReference() { referenceCount++; lastReferenced = DateTime.Now; } // Called when this shape is being used again. - public virtual void DecrementReference() + protected virtual void DecrementReference() { referenceCount--; lastReferenced = DateTime.Now; @@ -99,12 +104,19 @@ public abstract class BSShape // Returns a string for debugging that uniquily identifies the memory used by this instance public virtual string AddrString { - get { return "unknown"; } + get + { + if (physShapeInfo != null) + return physShapeInfo.AddrString; + return "unknown"; + } } public override string ToString() { StringBuilder buff = new StringBuilder(); + buff.Append(" m_hulls; private BulletShape CreatePhysicalHull(BSScene physicsScene, BSPhysObject prim, System.UInt64 newHullKey, @@ -520,7 +562,7 @@ public class BSShapeHull : BSShape physicsScene.DetailLog("{0},BSShapeHull.CreatePhysicalHull,hullFromMesh,hasBody={1}", prim.LocalID, newShape.HasPhysicalShape); } // Now done with the mesh shape. - meshShape.DecrementReference(); + meshShape.Dereference(physicsScene); physicsScene.DetailLog("{0},BSShapeHull.CreatePhysicalHull,shouldUseBulletHACD,exit,hasBody={1}", prim.LocalID, newShape.HasPhysicalShape); } if (!newShape.HasPhysicalShape) @@ -671,37 +713,52 @@ public class BSShapeCompound : BSShape public BSShapeCompound(BulletShape pShape) : base(pShape) { } - public static BSShape GetReference(BSScene physicsScene, BSPhysObject prim) + public static BSShape GetReference(BSScene physicsScene) + { + // Base compound shapes are not shared so this returns a raw shape. + // A built compound shape can be reused in linksets. + return new BSShapeCompound(CreatePhysicalCompoundShape(physicsScene)); + } + public override BSShape GetReference(BSScene physicsScene, BSPhysObject prim) { - // Compound shapes are not shared so a new one is created every time. - return new BSShapeCompound(CreatePhysicalCompoundShape(physicsScene, prim)); + // Calling this reference means we want another handle to an existing compound shape + // (usually linksets) so return this copy. + IncrementReference(); + return this; } // Dereferencing a compound shape releases the hold on all the child shapes. public override void Dereference(BSScene physicsScene) { - if (!physicsScene.PE.IsCompound(physShapeInfo)) + lock (physShapeInfo) { - // Failed the sanity check!! - physicsScene.Logger.ErrorFormat("{0} Attempt to free a compound shape that is not compound!! type={1}, ptr={2}", - LogHeader, physShapeInfo.shapeType, physShapeInfo.AddrString); - physicsScene.DetailLog("{0},BSShapeCollection.DereferenceCompound,notACompoundShape,type={1},ptr={2}", - BSScene.DetailLogZero, physShapeInfo.shapeType, physShapeInfo.AddrString); - return; - } + Dereference(physicsScene); + if (referenceCount <= 0) + { + if (!physicsScene.PE.IsCompound(physShapeInfo)) + { + // Failed the sanity check!! + physicsScene.Logger.ErrorFormat("{0} Attempt to free a compound shape that is not compound!! type={1}, ptr={2}", + LogHeader, physShapeInfo.shapeType, physShapeInfo.AddrString); + physicsScene.DetailLog("{0},BSShapeCollection.DereferenceCompound,notACompoundShape,type={1},ptr={2}", + BSScene.DetailLogZero, physShapeInfo.shapeType, physShapeInfo.AddrString); + return; + } - int numChildren = physicsScene.PE.GetNumberOfCompoundChildren(physShapeInfo); - physicsScene.DetailLog("{0},BSShapeCollection.DereferenceCompound,shape={1},children={2}", - BSScene.DetailLogZero, physShapeInfo, numChildren); + int numChildren = physicsScene.PE.GetNumberOfCompoundChildren(physShapeInfo); + physicsScene.DetailLog("{0},BSShapeCollection.DereferenceCompound,shape={1},children={2}", + BSScene.DetailLogZero, physShapeInfo, numChildren); - // Loop through all the children dereferencing each. - for (int ii = numChildren - 1; ii >= 0; ii--) - { - BulletShape childShape = physicsScene.PE.RemoveChildShapeFromCompoundShapeIndex(physShapeInfo, ii); - DereferenceAnonCollisionShape(physicsScene, childShape); + // Loop through all the children dereferencing each. + for (int ii = numChildren - 1; ii >= 0; ii--) + { + BulletShape childShape = physicsScene.PE.RemoveChildShapeFromCompoundShapeIndex(physShapeInfo, ii); + DereferenceAnonCollisionShape(physicsScene, childShape); + } + physicsScene.PE.DeleteCollisionShape(physicsScene.World, physShapeInfo); + } } - physicsScene.PE.DeleteCollisionShape(physicsScene.World, physShapeInfo); } - private static BulletShape CreatePhysicalCompoundShape(BSScene physicsScene, BSPhysObject prim) + private static BulletShape CreatePhysicalCompoundShape(BSScene physicsScene) { BulletShape cShape = physicsScene.PE.CreateCompoundShape(physicsScene.World, false); return cShape; @@ -754,6 +811,10 @@ public class BSShapeAvatar : BSShape { return new BSShapeNull(); } + public override BSShape GetReference(BSScene pPhysicsScene, BSPhysObject pPrim) + { + return new BSShapeNull(); + } public override void Dereference(BSScene physicsScene) { } // From the front: diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimTODO.txt b/OpenSim/Region/Physics/BulletSPlugin/BulletSimTODO.txt index c67081a..559a73f 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimTODO.txt +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimTODO.txt @@ -1,3 +1,12 @@ +PROBLEMS TO LOOK INTO +================================================= +Nebadon vehicle ride, get up, ride again. Second time vehicle does not act correctly. + Have to rez new vehicle and delete the old to fix situation. +Hitting RESET on Nebadon's vehicle while riding causes vehicle to get into odd + position state where it will not settle onto ground properly, etc +Two of Nebadon vehicles in a sim max the CPU. This is new. +A sitting, active vehicle bobs up and down a small amount. + CURRENT PRIORITIES ================================================= Use the HACD convex hull routine in Bullet rather than the C# version. -- cgit v1.1 From 7cdb07b386ffe88749fcc6cabadd9851f254699d Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 30 Apr 2013 11:42:11 -0700 Subject: BulletSim: improvements to LinksetCompound and PrimDisplaced. Not all working yet. --- .../Physics/BulletSPlugin/BSLinksetCompound.cs | 37 ++++++++++++++++------ .../Region/Physics/BulletSPlugin/BSPhysObject.cs | 3 +- .../Physics/BulletSPlugin/BSPrimDisplaced.cs | 22 ++++++++++--- OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs | 2 +- .../Region/Physics/BulletSPlugin/BulletSimTODO.txt | 3 ++ 5 files changed, 50 insertions(+), 17 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs index e967dfc..e3ce7fb 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs @@ -395,7 +395,8 @@ public sealed class BSLinksetCompound : BSLinkset // Constraint linksets are rebuilt every time. // Note that this works for rebuilding just the root after a linkset is taken apart. // Called at taint time!! - private bool disableCOM = true; // DEBUG DEBUG: disable until we get this debugged + private bool UseBulletSimRootOffsetHack = false; + private bool disableCOM = true; // For basic linkset debugging, turn off the center-of-mass setting private void RecomputeLinksetCompound() { if (!LinksetRoot.IsPhysicallyActive) @@ -428,11 +429,19 @@ public sealed class BSLinksetCompound : BSLinkset // 'centerDisplacement' is the value to subtract from children to give physical offset position OMV.Vector3 centerDisplacement = (centerOfMassW - LinksetRoot.RawPosition) * invRootOrientation; - LinksetRoot.SetEffectiveCenterOfMassW(centerDisplacement); - - // TODO: add phantom root shape to be the center-of-mass + if (UseBulletSimRootOffsetHack || disableCOM) + { + centerDisplacement = OMV.Vector3.Zero; + LinksetRoot.ClearDisplacement(); + } + else + { + LinksetRoot.SetEffectiveCenterOfMassDisplacement(centerDisplacement); + } + DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,COM,rootPos={1},com={2},comDisp={3}", + LinksetRoot.LocalID, LinksetRoot.RawPosition, centerOfMassW, centerDisplacement); - // Add a shape for each of the other children in the linkset + // Add the shapes of all the components of the linkset int memberIndex = 1; ForEachMember(delegate(BSPrimLinkable cPrim) { @@ -449,8 +458,8 @@ public sealed class BSLinksetCompound : BSLinkset OMV.Vector3 offsetPos = (cPrim.RawPosition - LinksetRoot.RawPosition) * invRootOrientation - centerDisplacement; OMV.Quaternion offsetRot = cPrim.RawOrientation * invRootOrientation; m_physicsScene.PE.AddChildShapeToCompoundShape(LinksetShape.physShapeInfo, childShape.physShapeInfo, offsetPos, offsetRot); - DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,addChild,indx={1},rShape={2},cShape={3},offPos={4},offRot={5}", - LinksetRoot.LocalID, memberIndex, LinksetRoot.PhysShape, cPrim.PhysShape, offsetPos, offsetRot); + DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,addChild,indx={1}cShape={2},offPos={3},offRot={4}", + LinksetRoot.LocalID, memberIndex, cPrim.PhysShape, offsetPos, offsetRot); memberIndex++; @@ -463,13 +472,21 @@ public sealed class BSLinksetCompound : BSLinkset m_physicsScene.PE.RemoveObjectFromWorld(m_physicsScene.World, LinksetRoot.PhysBody); m_physicsScene.PE.SetCollisionShape(m_physicsScene.World, LinksetRoot.PhysBody, LinksetShape.physShapeInfo); m_physicsScene.PE.AddObjectToWorld(m_physicsScene.World, LinksetRoot.PhysBody); + DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,addBody,body={1},shape={2}", + LinksetRoot.LocalID, LinksetRoot.PhysBody, LinksetShape); // With all of the linkset packed into the root prim, it has the mass of everyone. LinksetMass = ComputeLinksetMass(); LinksetRoot.UpdatePhysicalMassProperties(LinksetMass, true); - // Enable the physical position updator to return the position and rotation of the root shape - m_physicsScene.PE.AddToCollisionFlags(LinksetRoot.PhysBody, CollisionFlags.BS_RETURN_ROOT_COMPOUND_SHAPE); + if (UseBulletSimRootOffsetHack) + { + // Enable the physical position updator to return the position and rotation of the root shape. + // This enables a feature in the C++ code to return the world coordinates of the first shape in the + // compound shape. This eleviates the need to offset the returned physical position by the + // center-of-mass offset. + m_physicsScene.PE.AddToCollisionFlags(LinksetRoot.PhysBody, CollisionFlags.BS_RETURN_ROOT_COMPOUND_SHAPE); + } } finally { @@ -477,7 +494,7 @@ public sealed class BSLinksetCompound : BSLinkset } // See that the Aabb surrounds the new shape - m_physicsScene.PE.RecalculateCompoundShapeLocalAabb(LinksetRoot.PhysShape.physShapeInfo); + m_physicsScene.PE.RecalculateCompoundShapeLocalAabb(LinksetShape.physShapeInfo); } } } \ No newline at end of file diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index 28d4bd7..7eba851 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -259,7 +259,8 @@ public abstract class BSPhysObject : PhysicsActor // The user can optionally set the center of mass. The user's setting will override any // computed center-of-mass (like in linksets). - public OMV.Vector3? UserSetCenterOfMass { get; set; } + // Note this is a displacement from the root's coordinates. Zero means use the root prim as center-of-mass. + public OMV.Vector3? UserSetCenterOfMassDisplacement { get; set; } public OMV.Vector3 LockedAxis { get; set; } // zero means locked. one means free. public readonly OMV.Vector3 LockedAxisFree = new OMV.Vector3(1f, 1f, 1f); // All axis are free diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrimDisplaced.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrimDisplaced.cs index f1c3b5c..f5ee671 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrimDisplaced.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrimDisplaced.cs @@ -78,14 +78,16 @@ public class BSPrimDisplaced : BSPrim // Set this sets and computes the displacement from the passed prim to the center-of-mass. // A user set value for center-of-mass overrides whatever might be passed in here. // The displacement is in local coordinates (relative to root prim in linkset oriented coordinates). - public virtual void SetEffectiveCenterOfMassW(Vector3 centerOfMassDisplacement) + public virtual void SetEffectiveCenterOfMassDisplacement(Vector3 centerOfMassDisplacement) { Vector3 comDisp; - if (UserSetCenterOfMass.HasValue) - comDisp = (OMV.Vector3)UserSetCenterOfMass; + if (UserSetCenterOfMassDisplacement.HasValue) + comDisp = (OMV.Vector3)UserSetCenterOfMassDisplacement; else comDisp = centerOfMassDisplacement; + DetailLog("{0},BSPrimDisplaced.SetEffectiveCenterOfMassDisplacement,userSet={1},comDisp={2}", + LocalID, UserSetCenterOfMassDisplacement.HasValue, comDisp); if (comDisp == Vector3.Zero) { // If there is no diplacement. Things get reset. @@ -107,9 +109,15 @@ public class BSPrimDisplaced : BSPrim set { if (PositionDisplacement != OMV.Vector3.Zero) - base.ForcePosition = value - (PositionDisplacement * RawOrientation); + { + OMV.Vector3 displacedPos = value - (PositionDisplacement * RawOrientation); + DetailLog("{0},BSPrimDisplaced.ForcePosition,val={1},disp={2},newPos={3}", LocalID, value, PositionDisplacement, displacedPos); + base.ForcePosition = displacedPos; + } else + { base.ForcePosition = value; + } } } @@ -118,6 +126,7 @@ public class BSPrimDisplaced : BSPrim get { return base.ForceOrientation; } set { + // TODO: base.ForceOrientation = value; } } @@ -143,7 +152,10 @@ public class BSPrimDisplaced : BSPrim { // Correct for any rotation around the center-of-mass // TODO!!! - entprop.Position = entprop.Position + (PositionDisplacement * entprop.Rotation); + + OMV.Vector3 displacedPos = entprop.Position + (PositionDisplacement * entprop.Rotation); + DetailLog("{0},BSPrimDisplaced.ForcePosition,physPos={1},disp={2},newPos={3}", LocalID, entprop.Position, PositionDisplacement, displacedPos); + entprop.Position = displacedPos; // entprop.Rotation = something; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs index f0c9fd5..3faa484 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs @@ -117,7 +117,7 @@ public abstract class BSShape StringBuilder buff = new StringBuilder(); buff.Append(""); @@ -184,21 +189,21 @@ public abstract class BSShape BSPhysObject xprim = prim; Util.FireAndForget(delegate { - physicsScene.DetailLog("{0},BSShape.VerifyMeshCreated,inFireAndForget", xprim.LocalID); + // physicsScene.DetailLog("{0},BSShape.VerifyMeshCreated,inFireAndForget", xprim.LocalID); RequestAssetDelegate assetProvider = physicsScene.RequestAssetMethod; if (assetProvider != null) { BSPhysObject yprim = xprim; // probably not necessary, but, just in case. assetProvider(yprim.BaseShape.SculptTexture, delegate(AssetBase asset) { - physicsScene.DetailLog("{0},BSShape.VerifyMeshCreated,assetProviderCallback", xprim.LocalID); + // physicsScene.DetailLog("{0},BSShape.VerifyMeshCreated,assetProviderCallback", xprim.LocalID); bool assetFound = false; string mismatchIDs = String.Empty; // DEBUG DEBUG if (asset != null && yprim.BaseShape.SculptEntry) { if (yprim.BaseShape.SculptTexture.ToString() == asset.ID) { - yprim.BaseShape.SculptData = (byte[])asset.Data.Clone(); + yprim.BaseShape.SculptData = asset.Data; // This will cause the prim to see that the filler shape is not the right // one and try again to build the object. // No race condition with the normal shape setting since the rebuild is at taint time. @@ -290,7 +295,7 @@ public class BSShapeNative : BSShape { if (physShapeInfo.HasPhysicalShape) { - physicsScene.DetailLog("{0},BSShapeNative.DereferenceShape,deleteNativeShape,shape={1}", BSScene.DetailLogZero, this); + physicsScene.DetailLog("{0},BSShapeNative.Dereference,deleteNativeShape,shape={1}", BSScene.DetailLogZero, this); physicsScene.PE.DeleteCollisionShape(physicsScene.World, physShapeInfo); } physShapeInfo.Clear(); @@ -347,9 +352,8 @@ public class BSShapeMesh : BSShape float lod; System.UInt64 newMeshKey = BSShape.ComputeShapeKey(prim.Size, prim.BaseShape, out lod); - physicsScene.DetailLog("{0},BSShapeMesh,getReference,oldKey={1},newKey={2},size={3},lod={4}", - prim.LocalID, prim.PhysShape.physShapeInfo.shapeKey.ToString("X"), - newMeshKey.ToString("X"), prim.Size, lod); + physicsScene.DetailLog("{0},BSShapeMesh,getReference,newKey={1},size={2},lod={3}", + prim.LocalID, newMeshKey.ToString("X"), prim.Size, lod); BSShapeMesh retMesh = null; lock (Meshes) @@ -389,6 +393,7 @@ public class BSShapeMesh : BSShape lock (Meshes) { this.DecrementReference(); + physicsScene.DetailLog("{0},BSShapeMesh.Dereference,shape={1}", BSScene.DetailLogZero, this); // TODO: schedule aging and destruction of unused meshes. } } @@ -425,6 +430,12 @@ public class BSShapeMesh : BSShape if (meshData != null) { + if (prim.PrimAssetState == BSPhysObject.PrimAssetCondition.Fetched) + { + // Release the fetched asset data once it has been used. + pbs.SculptData = new byte[0]; + prim.PrimAssetState = BSPhysObject.PrimAssetCondition.Unknown; + } int[] indices = meshData.getIndexListAsInt(); int realIndicesIndex = indices.Length; @@ -462,8 +473,8 @@ public class BSShapeMesh : BSShape } } } - physicsScene.DetailLog("{0},BSShapeMesh.CreatePhysicalMesh,origTri={1},realTri={2},numVerts={3}", - BSScene.DetailLogZero, indices.Length / 3, realIndicesIndex / 3, verticesAsFloats.Length / 3); + physicsScene.DetailLog("{0},BSShapeMesh.CreatePhysicalMesh,key={1},origTri={2},realTri={3},numVerts={4}", + BSScene.DetailLogZero, newMeshKey.ToString("X"), indices.Length / 3, realIndicesIndex / 3, verticesAsFloats.Length / 3); if (realIndicesIndex != 0) { @@ -496,8 +507,8 @@ public class BSShapeHull : BSShape float lod; System.UInt64 newHullKey = BSShape.ComputeShapeKey(prim.Size, prim.BaseShape, out lod); - physicsScene.DetailLog("{0},BSShapeHull,getReference,oldKey={1},newKey={2},size={3},lod={4}", - prim.LocalID, prim.PhysShape.physShapeInfo.shapeKey.ToString("X"), newHullKey.ToString("X"), prim.Size, lod); + physicsScene.DetailLog("{0},BSShapeHull,getReference,newKey={1},size={2},lod={3}", + prim.LocalID, newHullKey.ToString("X"), prim.Size, lod); BSShapeHull retHull = null; lock (Hulls) @@ -537,6 +548,7 @@ public class BSShapeHull : BSShape lock (Hulls) { this.DecrementReference(); + physicsScene.DetailLog("{0},BSShapeHull.Dereference,shape={1}", BSScene.DetailLogZero, this); // TODO: schedule aging and destruction of unused meshes. } } @@ -549,6 +561,8 @@ public class BSShapeHull : BSShape if (BSParam.ShouldUseBulletHACD) { + // Build the hull shape from an existing mesh shape. + // The mesh should have already been created in Bullet. physicsScene.DetailLog("{0},BSShapeHull.CreatePhysicalHull,shouldUseBulletHACD,entry", prim.LocalID); BSShape meshShape = BSShapeMesh.GetReference(physicsScene, true, prim); @@ -568,18 +582,26 @@ public class BSShapeHull : BSShape physicsScene.DetailLog("{0},BSShapeHull.CreatePhysicalHull,hullFromMesh,beforeCall", prim.LocalID, newShape.HasPhysicalShape); newShape = physicsScene.PE.BuildHullShapeFromMesh(physicsScene.World, meshShape.physShapeInfo, parms); physicsScene.DetailLog("{0},BSShapeHull.CreatePhysicalHull,hullFromMesh,hasBody={1}", prim.LocalID, newShape.HasPhysicalShape); + + // Now done with the mesh shape. + meshShape.Dereference(physicsScene); } - // Now done with the mesh shape. - meshShape.Dereference(physicsScene); physicsScene.DetailLog("{0},BSShapeHull.CreatePhysicalHull,shouldUseBulletHACD,exit,hasBody={1}", prim.LocalID, newShape.HasPhysicalShape); } if (!newShape.HasPhysicalShape) { - // Build a new hull in the physical world. + // Build a new hull in the physical world using the C# HACD algorigthm. // Pass true for physicalness as this prevents the creation of bounding box which is not needed IMesh meshData = physicsScene.mesher.CreateMesh(prim.PhysObjectName, pbs, size, lod, true /* isPhysical */, false /* shouldCache */); if (meshData != null) { + if (prim.PrimAssetState == BSPhysObject.PrimAssetCondition.Fetched) + { + // Release the fetched asset data once it has been used. + pbs.SculptData = new byte[0]; + prim.PrimAssetState = BSPhysObject.PrimAssetCondition.Unknown; + } + int[] indices = meshData.getIndexListAsInt(); List vertices = meshData.getVertexList(); @@ -740,6 +762,7 @@ public class BSShapeCompound : BSShape lock (physShapeInfo) { this.DecrementReference(); + physicsScene.DetailLog("{0},BSShapeCompound.Dereference,shape={1}", BSScene.DetailLogZero, this); if (referenceCount <= 0) { if (!physicsScene.PE.IsCompound(physShapeInfo)) -- cgit v1.1 From 4042c82a7293c40955a14d04d9e5ae05d35ef7cf Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Thu, 2 May 2013 12:27:30 -0700 Subject: BulletSim: prims with no cuts created with single convex hull shape. Parameter added to enable/disable this feature. --- OpenSim/Region/Physics/BulletSPlugin/BSParam.cs | 5 ++ OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 3 + .../Physics/BulletSPlugin/BSShapeCollection.cs | 19 +++++- OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs | 74 ++++++++++++++++++++++ 4 files changed, 99 insertions(+), 2 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs index 5ebeace..2ac68e3 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs @@ -87,6 +87,7 @@ public static class BSParam public static bool ShouldUseHullsForPhysicalObjects { get; private set; } // 'true' if should create hulls for physical objects public static bool ShouldRemoveZeroWidthTriangles { get; private set; } public static bool ShouldUseBulletHACD { get; set; } + public static bool ShouldUseSingleConvexHullForPrims { get; set; } public static float TerrainImplementation { get; private set; } public static int TerrainMeshMagnification { get; private set; } @@ -342,6 +343,10 @@ public static class BSParam false, (s) => { return ShouldUseBulletHACD; }, (s,v) => { ShouldUseBulletHACD = v; } ), + new ParameterDefn("ShouldUseSingleConvexHullForPrims", "If true, use a single convex hull shape for physical prims", + true, + (s) => { return ShouldUseSingleConvexHullForPrims; }, + (s,v) => { ShouldUseSingleConvexHullForPrims = v; } ), new ParameterDefn("CrossingFailuresBeforeOutOfBounds", "How forgiving we are about getting into adjactent regions", 5, diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index 8e05b58..a4a8794 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -316,7 +316,10 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters break; case "bulletxna": ret = new BSAPIXNA(engineName, this); + // Disable some features that are not implemented in BulletXNA + m_log.InfoFormat("{0} Disabling some physics features not implemented by BulletXNA", LogHeader); BSParam.ShouldUseBulletHACD = false; + BSParam.ShouldUseSingleConvexHullForPrims = false; break; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index 809435d..794857c 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -226,8 +226,23 @@ public sealed class BSShapeCollection : IDisposable // made. Native shapes work in either case. if (prim.IsPhysical && BSParam.ShouldUseHullsForPhysicalObjects) { - // Update prim.BSShape to reference a hull of this shape. - BSShape potentialHull = BSShapeHull.GetReference(m_physicsScene, false /*forceRebuild*/, prim); + // Use a simple, single mesh convex hull shape if the object is simple enough + BSShape potentialHull = null; + + PrimitiveBaseShape pbs = prim.BaseShape; + if (BSParam.ShouldUseSingleConvexHullForPrims + && pbs != null + && !pbs.SculptEntry + && PrimHasNoCuts(pbs) + ) + { + potentialHull = BSShapeConvexHull.GetReference(m_physicsScene, false /* forceRebuild */, prim); + } + else + { + potentialHull = BSShapeHull.GetReference(m_physicsScene, false /*forceRebuild*/, prim); + } + // If the current shape is not what is on the prim at the moment, time to change. if (!prim.PhysShape.HasPhysicalShape || potentialHull.ShapeType != prim.PhysShape.ShapeType diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs index 3346626..9ef2923 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs @@ -832,6 +832,80 @@ public class BSShapeCompound : BSShape } // ============================================================================================================ +public class BSShapeConvexHull : BSShape +{ + private static string LogHeader = "[BULLETSIM SHAPE CONVEX HULL]"; + public static Dictionary ConvexHulls = new Dictionary(); + + public BSShapeConvexHull(BulletShape pShape) : base(pShape) + { + } + public static BSShape GetReference(BSScene physicsScene, bool forceRebuild, BSPhysObject prim) + { + float lod; + System.UInt64 newMeshKey = BSShape.ComputeShapeKey(prim.Size, prim.BaseShape, out lod); + + physicsScene.DetailLog("{0},BSShapeMesh,getReference,newKey={1},size={2},lod={3}", + prim.LocalID, newMeshKey.ToString("X"), prim.Size, lod); + + BSShapeConvexHull retConvexHull = null; + lock (ConvexHulls) + { + if (ConvexHulls.TryGetValue(newMeshKey, out retConvexHull)) + { + // The mesh has already been created. Return a new reference to same. + retConvexHull.IncrementReference(); + } + else + { + retConvexHull = new BSShapeConvexHull(new BulletShape()); + BulletShape convexShape = null; + + // Get a handle to a mesh to build the hull from + BSShape baseMesh = BSShapeMesh.GetReference(physicsScene, false /* forceRebuild */, prim); + if (baseMesh.physShapeInfo.isNativeShape) + { + // We get here if the mesh was not creatable. Could be waiting for an asset from the disk. + // In the short term, we return the native shape and a later ForceBodyShapeRebuild should + // get back to this code with a buildable mesh. + // TODO: not sure the temp native shape is freed when the mesh is rebuilt. When does this get freed? + convexShape = baseMesh.physShapeInfo; + } + else + { + convexShape = physicsScene.PE.BuildConvexHullShapeFromMesh(physicsScene.World, baseMesh.physShapeInfo); + convexShape.shapeKey = newMeshKey; + ConvexHulls.Add(convexShape.shapeKey, retConvexHull); + } + + // Done with the base mesh + baseMesh.Dereference(physicsScene); + + retConvexHull.physShapeInfo = convexShape; + } + } + return retConvexHull; + } + public override BSShape GetReference(BSScene physicsScene, BSPhysObject prim) + { + // Calling this reference means we want another handle to an existing shape + // (usually linksets) so return this copy. + IncrementReference(); + return this; + } + // Dereferencing a compound shape releases the hold on all the child shapes. + public override void Dereference(BSScene physicsScene) + { + lock (ConvexHulls) + { + this.DecrementReference(); + physicsScene.DetailLog("{0},BSShapeConvexHull.Dereference,shape={1}", BSScene.DetailLogZero, this); + // TODO: schedule aging and destruction of unused meshes. + } + } +} + +// ============================================================================================================ public class BSShapeAvatar : BSShape { private static string LogHeader = "[BULLETSIM SHAPE AVATAR]"; -- cgit v1.1 From 5d25bb3084937d266375cba61b3a2c802bd57717 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Fri, 3 May 2013 14:23:53 -0700 Subject: BulletSim: zero vehicle motion when changing vehicle type. Rebuild compound linkset of any child in the linkset changes shape. Comments and better detailed logging messages. --- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 6 +++--- .../Region/Physics/BulletSPlugin/BSLinksetCompound.cs | 16 +++++----------- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 2 +- OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs | 4 ++++ .../Region/Physics/BulletSPlugin/BSShapeCollection.cs | 7 +++---- OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs | 9 ++------- 6 files changed, 18 insertions(+), 26 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index b9bd909..c5bee6d 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -559,9 +559,6 @@ namespace OpenSim.Region.Physics.BulletSPlugin break; } - // Update any physical parameters based on this type. - Refresh(); - m_linearMotor = new BSVMotor("LinearMotor", m_linearMotorTimescale, m_linearMotorDecayTimescale, m_linearFrictionTimescale, 1f); @@ -589,6 +586,9 @@ namespace OpenSim.Region.Physics.BulletSPlugin { RegisterForSceneEvents(); } + + // Update any physical parameters based on this type. + Refresh(); } #endregion // Vehicle parameter setting diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs index 20eb871..1f16cc8 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs @@ -246,7 +246,8 @@ public sealed class BSLinksetCompound : BSLinkset } // Routine called when rebuilding the body of some member of the linkset. - // Since we don't keep in world relationships, do nothing unless it's a child changing. + // If one of the bodies is being changed, the linkset needs rebuilding. + // For instance, a linkset is built and then a mesh asset is read in and the mesh is recreated. // Returns 'true' of something was actually removed and would need restoring // Called at taint-time!! public override bool RemoveDependencies(BSPrimLinkable child) @@ -256,14 +257,7 @@ public sealed class BSLinksetCompound : BSLinkset DetailLog("{0},BSLinksetCompound.RemoveBodyDependencies,refreshIfChild,rID={1},rBody={2},isRoot={3}", child.LocalID, LinksetRoot.LocalID, LinksetRoot.PhysBody, IsRoot(child)); - if (!IsRoot(child)) - { - child.LinksetInfo = null; - } - - // Cannot schedule a refresh/rebuild here because this routine is called when - // the linkset is being rebuilt. - // InternalRefresh(LinksetRoot); + ScheduleRebuild(child); return ret; } @@ -322,7 +316,7 @@ public sealed class BSLinksetCompound : BSLinkset // Constraint linksets are rebuilt every time. // Note that this works for rebuilding just the root after a linkset is taken apart. // Called at taint time!! - private bool UseBulletSimRootOffsetHack = false; + private bool UseBulletSimRootOffsetHack = false; // Attempt to have Bullet track the coords of root compound shape private bool disableCOM = true; // For basic linkset debugging, turn off the center-of-mass setting private void RecomputeLinksetCompound() { @@ -382,7 +376,7 @@ public sealed class BSLinksetCompound : BSLinkset OMV.Quaternion offsetRot = cPrim.RawOrientation * invRootOrientation; m_physicsScene.PE.AddChildShapeToCompoundShape(linksetShape.physShapeInfo, childShape.physShapeInfo, offsetPos, offsetRot); DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,addChild,indx={1},cShape={2},offPos={3},offRot={4}", - LinksetRoot.LocalID, memberIndex, cPrim.PhysShape, offsetPos, offsetRot); + LinksetRoot.LocalID, memberIndex, childShape, offsetPos, offsetRot); // Since we are borrowing the shape of the child, disable the origional child body if (!IsRoot(cPrim)) diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 3d68d7f..d3f3475 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -511,7 +511,7 @@ public class BSPrim : BSPhysObject PhysScene.TaintedObject("setVehicleType", delegate() { - // Vehicle code changes the parameters for this vehicle type. + ZeroMotion(true /* inTaintTime */); VehicleActor.ProcessTypeChange(type); ActivateIfPhysical(false); }); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs index 5236909..235da78 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs @@ -182,6 +182,10 @@ public class BSPrimLinkable : BSPrimDisplaced { return false; } + + // TODO: handle collisions of other objects with with children of linkset. + // This is a problem for LinksetCompound since the children are packed into the root. + return base.Collide(collidingWith, collidee, contactPoint, contactNormal, pentrationDepth); } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index 794857c..64aaa15 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -254,10 +254,10 @@ public sealed class BSShapeCollection : IDisposable } else { + // The current shape on the prim is the correct one. We don't need the potential reference. potentialHull.Dereference(m_physicsScene); } - if (DDetail) DetailLog("{0},BSShapeCollection.CreateGeom,hull,shape={1},key={2}", - prim.LocalID, prim.PhysShape, prim.PhysShape.physShapeInfo.shapeKey.ToString("X")); + if (DDetail) DetailLog("{0},BSShapeCollection.CreateGeom,hull,shape={1}", prim.LocalID, prim.PhysShape); } else { @@ -277,8 +277,7 @@ public sealed class BSShapeCollection : IDisposable // We don't need this reference to the mesh that is already being using. potentialMesh.Dereference(m_physicsScene); } - if (DDetail) DetailLog("{0},BSShapeCollection.CreateGeom,mesh,shape={1},key={2}", - prim.LocalID, prim.PhysShape, prim.PhysShape.physShapeInfo.shapeKey.ToString("X")); + if (DDetail) DetailLog("{0},BSShapeCollection.CreateGeom,mesh,shape={1}", prim.LocalID, prim.PhysShape); } return ret; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs index 9ef2923..3e4ee5a 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs @@ -352,9 +352,6 @@ public class BSShapeMesh : BSShape float lod; System.UInt64 newMeshKey = BSShape.ComputeShapeKey(prim.Size, prim.BaseShape, out lod); - physicsScene.DetailLog("{0},BSShapeMesh,getReference,newKey={1},size={2},lod={3}", - prim.LocalID, newMeshKey.ToString("X"), prim.Size, lod); - BSShapeMesh retMesh = null; lock (Meshes) { @@ -380,6 +377,7 @@ public class BSShapeMesh : BSShape retMesh.physShapeInfo = newShape; } } + physicsScene.DetailLog("{0},BSShapeMesh,getReference,mesh={1},size={2},lod={3}", prim.LocalID, retMesh, prim.Size, lod); return retMesh; } public override BSShape GetReference(BSScene pPhysicsScene, BSPhysObject pPrim) @@ -507,9 +505,6 @@ public class BSShapeHull : BSShape float lod; System.UInt64 newHullKey = BSShape.ComputeShapeKey(prim.Size, prim.BaseShape, out lod); - physicsScene.DetailLog("{0},BSShapeHull,getReference,newKey={1},size={2},lod={3}", - prim.LocalID, newHullKey.ToString("X"), prim.Size, lod); - BSShapeHull retHull = null; lock (Hulls) { @@ -531,10 +526,10 @@ public class BSShapeHull : BSShape // If a mesh was what was created, remember the built shape for later sharing. Hulls.Add(newHullKey, retHull); } - retHull.physShapeInfo = newShape; } } + physicsScene.DetailLog("{0},BSShapeHull,getReference,hull={1},size={2},lod={3}", prim.LocalID, retHull, prim.Size, lod); return retHull; } public override BSShape GetReference(BSScene pPhysicsScene, BSPhysObject pPrim) -- cgit v1.1 From f9fb1484aa00f8bfadead06ce71d004502fb564e Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Fri, 3 May 2013 15:46:35 -0700 Subject: BulletSim: extend BSActorLockAxis to allow locking linear movement in addition to angular movement. Not enabled by anything yet. --- .../Physics/BulletSPlugin/BSActorLockAxis.cs | 25 +++++++++++++++++----- .../Region/Physics/BulletSPlugin/BSPhysObject.cs | 9 +++++--- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 4 ++-- 3 files changed, 28 insertions(+), 10 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSActorLockAxis.cs b/OpenSim/Region/Physics/BulletSPlugin/BSActorLockAxis.cs index 7801d8e..8b0fdeb 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSActorLockAxis.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSActorLockAxis.cs @@ -64,9 +64,9 @@ public class BSActorLockAxis : BSActor public override void Refresh() { m_physicsScene.DetailLog("{0},BSActorLockAxis,refresh,lockedAxis={1},enabled={2},pActive={3}", - m_controllingPrim.LocalID, m_controllingPrim.LockedAxis, Enabled, m_controllingPrim.IsPhysicallyActive); + m_controllingPrim.LocalID, m_controllingPrim.LockedAngularAxis, Enabled, m_controllingPrim.IsPhysicallyActive); // If all the axis are free, we don't need to exist - if (m_controllingPrim.LockedAxis == m_controllingPrim.LockedAxisFree) + if (m_controllingPrim.LockedAngularAxis == m_controllingPrim.LockedAxisFree) { Enabled = false; } @@ -123,23 +123,38 @@ public class BSActorLockAxis : BSActor // Free to move linearly in the region OMV.Vector3 linearLow = OMV.Vector3.Zero; OMV.Vector3 linearHigh = m_physicsScene.TerrainManager.DefaultRegionSize; + if (m_controllingPrim.LockedLinearAxis.X != BSPhysObject.FreeAxis) + { + linearLow.X = m_controllingPrim.RawPosition.X; + linearHigh.X = m_controllingPrim.RawPosition.X; + } + if (m_controllingPrim.LockedLinearAxis.Y != BSPhysObject.FreeAxis) + { + linearLow.Y = m_controllingPrim.RawPosition.Y; + linearHigh.Y = m_controllingPrim.RawPosition.Y; + } + if (m_controllingPrim.LockedLinearAxis.Z != BSPhysObject.FreeAxis) + { + linearLow.Z = m_controllingPrim.RawPosition.Z; + linearHigh.Z = m_controllingPrim.RawPosition.Z; + } axisConstrainer.SetLinearLimits(linearLow, linearHigh); // Angular with some axis locked float fPI = (float)Math.PI; OMV.Vector3 angularLow = new OMV.Vector3(-fPI, -fPI, -fPI); OMV.Vector3 angularHigh = new OMV.Vector3(fPI, fPI, fPI); - if (m_controllingPrim.LockedAxis.X != 1f) + if (m_controllingPrim.LockedAngularAxis.X != BSPhysObject.FreeAxis) { angularLow.X = 0f; angularHigh.X = 0f; } - if (m_controllingPrim.LockedAxis.Y != 1f) + if (m_controllingPrim.LockedAngularAxis.Y != BSPhysObject.FreeAxis) { angularLow.Y = 0f; angularHigh.Y = 0f; } - if (m_controllingPrim.LockedAxis.Z != 1f) + if (m_controllingPrim.LockedAngularAxis.Z != BSPhysObject.FreeAxis) { angularLow.Z = 0f; angularHigh.Z = 0f; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index e796804..cca887a 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -108,7 +108,8 @@ public abstract class BSPhysObject : PhysicsActor CollisionScore = 0; // All axis free. - LockedAxis = LockedAxisFree; + LockedLinearAxis = LockedAxisFree; + LockedAngularAxis = LockedAxisFree; } // Tell the object to clean up. @@ -265,8 +266,10 @@ public abstract class BSPhysObject : PhysicsActor // Note this is a displacement from the root's coordinates. Zero means use the root prim as center-of-mass. public OMV.Vector3? UserSetCenterOfMassDisplacement { get; set; } - public OMV.Vector3 LockedAxis { get; set; } // zero means locked. one means free. - public readonly OMV.Vector3 LockedAxisFree = new OMV.Vector3(1f, 1f, 1f); // All axis are free + public OMV.Vector3 LockedLinearAxis { get; set; } // zero means locked. one means free. + public OMV.Vector3 LockedAngularAxis { get; set; } // zero means locked. one means free. + public const float FreeAxis = 1f; + public readonly OMV.Vector3 LockedAxisFree = new OMV.Vector3(FreeAxis, FreeAxis, FreeAxis); // All axis are free // Enable physical actions. Bullet will keep sleeping non-moving physical objects so // they need waking up when parameters are changed. diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index d3f3475..f5b0361 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -256,9 +256,9 @@ public class BSPrim : BSPhysObject if (axis.X != 1) locking.X = 0f; if (axis.Y != 1) locking.Y = 0f; if (axis.Z != 1) locking.Z = 0f; - LockedAxis = locking; + LockedAngularAxis = locking; - EnableActor(LockedAxis != LockedAxisFree, LockedAxisActorName, delegate() + EnableActor(LockedAngularAxis != LockedAxisFree, LockedAxisActorName, delegate() { return new BSActorLockAxis(PhysScene, this, LockedAxisActorName); }); -- cgit v1.1 From bf318969836bf38dbd0325f24fa3d1bd12f34d77 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Fri, 3 May 2013 17:14:31 -0700 Subject: BulletSim: simplify parameter specification by reducing the number of specifications required for simple properties with defaults. --- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 2 +- OpenSim/Region/Physics/BulletSPlugin/BSParam.cs | 283 +++++++-------------- 2 files changed, 94 insertions(+), 191 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index c5bee6d..0dd2aa5 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -146,7 +146,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin enableAngularVerticalAttraction = true; enableAngularDeflection = false; enableAngularBanking = true; - if (BSParam.VehicleDebuggingEnabled) + if (BSParam.VehicleDebuggingEnable) { enableAngularVerticalAttraction = true; enableAngularDeflection = false; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs index 2ac68e3..3ca7e16 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs @@ -26,6 +26,7 @@ */ using System; using System.Collections.Generic; +using System.Reflection; using System.Text; using OpenSim.Region.Physics.Manager; @@ -144,7 +145,7 @@ public static class BSParam public static Vector3 VehicleAngularFactor { get; private set; } public static float VehicleGroundGravityFudge { get; private set; } public static float VehicleAngularBankingTimescaleFudge { get; private set; } - public static bool VehicleDebuggingEnabled { get; private set; } + public static bool VehicleDebuggingEnable { get; private set; } // Convex Hulls public static int CSHullMaxDepthSplit { get; private set; } @@ -236,17 +237,41 @@ public static class BSParam getter = pGetter; objectSet = pObjSetter; } - /* Wish I could simplify using this definition but CLR doesn't store references so closure around delegates of references won't work - * TODO: Maybe use reflection and the name of the variable to create a reference for the getter/setter. - public ParameterDefn(string pName, string pDesc, T pDefault, ref T loc) + // Simple parameter variable where property name is the same as the INI file name + // and the value is only a simple get and set. + public ParameterDefn(string pName, string pDesc, T pDefault) : base(pName, pDesc) { defaultValue = pDefault; - setter = (s, v) => { loc = v; }; - getter = (s) => { return loc; }; + setter = (s, v) => { SetValueByName(s, name, v); }; + getter = (s) => { return GetValueByName(s, name); }; objectSet = null; } - */ + // Use reflection to find the property named 'pName' in BSParam and assign 'val' to same. + private void SetValueByName(BSScene s, string pName, T val) + { + PropertyInfo prop = typeof(BSParam).GetProperty(pName, BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy); + if (prop == null) + { + // This should only be output when someone adds a new INI parameter and misspells the name. + s.Logger.ErrorFormat("{0} SetValueByName: did not find '{1}'. Verify specified property name is the same as the given INI parameters name.", LogHeader, pName); + } + else + { + prop.SetValue(null, val, null); + } + } + // Use reflection to find the property named 'pName' in BSParam and return the value in same. + private T GetValueByName(BSScene s, string pName) + { + PropertyInfo prop = typeof(BSParam).GetProperty(pName, BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy); + if (prop == null) + { + // This should only be output when someone adds a new INI parameter and misspells the name. + s.Logger.ErrorFormat("{0} GetValueByName: did not find '{1}'. Verify specified property name is the same as the given INI parameter name.", LogHeader, pName); + } + return (T)prop.GetValue(null, null); + } public override void AssignDefault(BSScene s) { setter(s, defaultValue); @@ -336,26 +361,16 @@ public static class BSParam (s) => { return ShouldUseHullsForPhysicalObjects; }, (s,v) => { ShouldUseHullsForPhysicalObjects = v; } ), new ParameterDefn("ShouldRemoveZeroWidthTriangles", "If true, remove degenerate triangles from meshes", - true, - (s) => { return ShouldRemoveZeroWidthTriangles; }, - (s,v) => { ShouldRemoveZeroWidthTriangles = v; } ), + true ), new ParameterDefn("ShouldUseBulletHACD", "If true, use the Bullet version of HACD", - false, - (s) => { return ShouldUseBulletHACD; }, - (s,v) => { ShouldUseBulletHACD = v; } ), + false ), new ParameterDefn("ShouldUseSingleConvexHullForPrims", "If true, use a single convex hull shape for physical prims", - true, - (s) => { return ShouldUseSingleConvexHullForPrims; }, - (s,v) => { ShouldUseSingleConvexHullForPrims = v; } ), + true ), new ParameterDefn("CrossingFailuresBeforeOutOfBounds", "How forgiving we are about getting into adjactent regions", - 5, - (s) => { return CrossingFailuresBeforeOutOfBounds; }, - (s,v) => { CrossingFailuresBeforeOutOfBounds = v; } ), + 5 ), new ParameterDefn("UpdateVelocityChangeThreshold", "Change in updated velocity required before reporting change to simulator", - 0.1f, - (s) => { return UpdateVelocityChangeThreshold; }, - (s,v) => { UpdateVelocityChangeThreshold = v; } ), + 0.1f ), new ParameterDefn("MeshLevelOfDetail", "Level of detail to render meshes (32, 16, 8 or 4. 32=most detailed)", 32f, @@ -422,18 +437,12 @@ public static class BSParam (s,v) => { MaxAddForceMagnitude = v; MaxAddForceMagnitudeSquared = v * v; } ), // Density is passed around as 100kg/m3. This scales that to 1kg/m3. new ParameterDefn("DensityScaleFactor", "Conversion for simulator/viewer density (100kg/m3) to physical density (1kg/m3)", - 0.01f, - (s) => { return DensityScaleFactor; }, - (s,v) => { DensityScaleFactor = v; } ), + 0.01f ), new ParameterDefn("PID_D", "Derivitive factor for motion smoothing", - 2200f, - (s) => { return (float)PID_D; }, - (s,v) => { PID_D = v; } ), + 2200f ), new ParameterDefn("PID_P", "Parameteric factor for motion smoothing", - 900f, - (s) => { return (float)PID_P; }, - (s,v) => { PID_P = v; } ), + 900f ), new ParameterDefn("DefaultFriction", "Friction factor used on new objects", 0.2f, @@ -500,94 +509,50 @@ public static class BSParam (s,o) => { s.PE.SetContactProcessingThreshold(o.PhysBody, ContactProcessingThreshold); } ), new ParameterDefn("TerrainImplementation", "Type of shape to use for terrain (0=heightmap, 1=mesh)", - (float)BSTerrainPhys.TerrainImplementation.Mesh, - (s) => { return TerrainImplementation; }, - (s,v) => { TerrainImplementation = v; } ), + (float)BSTerrainPhys.TerrainImplementation.Mesh ), new ParameterDefn("TerrainMeshMagnification", "Number of times the 256x256 heightmap is multiplied to create the terrain mesh" , - 2, - (s) => { return TerrainMeshMagnification; }, - (s,v) => { TerrainMeshMagnification = v; } ), + 2 ), new ParameterDefn("TerrainFriction", "Factor to reduce movement against terrain surface" , - 0.3f, - (s) => { return TerrainFriction; }, - (s,v) => { TerrainFriction = v; /* TODO: set on real terrain */} ), + 0.3f ), new ParameterDefn("TerrainHitFraction", "Distance to measure hit collisions" , - 0.8f, - (s) => { return TerrainHitFraction; }, - (s,v) => { TerrainHitFraction = v; /* TODO: set on real terrain */ } ), + 0.8f ), new ParameterDefn("TerrainRestitution", "Bouncyness" , - 0f, - (s) => { return TerrainRestitution; }, - (s,v) => { TerrainRestitution = v; /* TODO: set on real terrain */ } ), + 0f ), new ParameterDefn("TerrainContactProcessingThreshold", "Distance from terrain to stop processing collisions" , - 0.0f, - (s) => { return TerrainContactProcessingThreshold; }, - (s,v) => { TerrainContactProcessingThreshold = v; /* TODO: set on real terrain */ } ), + 0.0f ), new ParameterDefn("TerrainCollisionMargin", "Margin where collision checking starts" , - 0.08f, - (s) => { return TerrainCollisionMargin; }, - (s,v) => { TerrainCollisionMargin = v; /* TODO: set on real terrain */ } ), + 0.08f ), new ParameterDefn("AvatarFriction", "Factor to reduce movement against an avatar. Changed on avatar recreation.", - 0.2f, - (s) => { return AvatarFriction; }, - (s,v) => { AvatarFriction = v; } ), + 0.2f ), new ParameterDefn("AvatarStandingFriction", "Avatar friction when standing. Changed on avatar recreation.", - 0.95f, - (s) => { return AvatarStandingFriction; }, - (s,v) => { AvatarStandingFriction = v; } ), + 0.95f ), new ParameterDefn("AvatarAlwaysRunFactor", "Speed multiplier if avatar is set to always run", - 1.3f, - (s) => { return AvatarAlwaysRunFactor; }, - (s,v) => { AvatarAlwaysRunFactor = v; } ), + 1.3f ), new ParameterDefn("AvatarDensity", "Density of an avatar. Changed on avatar recreation.", - 3.5f, - (s) => { return AvatarDensity; }, - (s,v) => { AvatarDensity = v; } ), + 3.5f) , new ParameterDefn("AvatarRestitution", "Bouncyness. Changed on avatar recreation.", - 0f, - (s) => { return AvatarRestitution; }, - (s,v) => { AvatarRestitution = v; } ), + 0f ), new ParameterDefn("AvatarCapsuleWidth", "The distance between the sides of the avatar capsule", - 0.6f, - (s) => { return AvatarCapsuleWidth; }, - (s,v) => { AvatarCapsuleWidth = v; } ), + 0.6f ) , new ParameterDefn("AvatarCapsuleDepth", "The distance between the front and back of the avatar capsule", - 0.45f, - (s) => { return AvatarCapsuleDepth; }, - (s,v) => { AvatarCapsuleDepth = v; } ), + 0.45f ), new ParameterDefn("AvatarCapsuleHeight", "Default height of space around avatar", - 1.5f, - (s) => { return AvatarCapsuleHeight; }, - (s,v) => { AvatarCapsuleHeight = v; } ), + 1.5f ), new ParameterDefn("AvatarContactProcessingThreshold", "Distance from capsule to check for collisions", - 0.1f, - (s) => { return AvatarContactProcessingThreshold; }, - (s,v) => { AvatarContactProcessingThreshold = v; } ), + 0.1f ), new ParameterDefn("AvatarBelowGroundUpCorrectionMeters", "Meters to move avatar up if it seems to be below ground", - 1.0f, - (s) => { return AvatarBelowGroundUpCorrectionMeters; }, - (s,v) => { AvatarBelowGroundUpCorrectionMeters = v; } ), + 1.0f ), new ParameterDefn("AvatarStepHeight", "Height of a step obstacle to consider step correction", - 0.6f, - (s) => { return AvatarStepHeight; }, - (s,v) => { AvatarStepHeight = v; } ), + 0.6f ) , new ParameterDefn("AvatarStepApproachFactor", "Factor to control angle of approach to step (0=straight on)", - 0.6f, - (s) => { return AvatarStepApproachFactor; }, - (s,v) => { AvatarStepApproachFactor = v; } ), + 0.6f ), new ParameterDefn("AvatarStepForceFactor", "Controls the amount of force up applied to step up onto a step", - 1.0f, - (s) => { return AvatarStepForceFactor; }, - (s,v) => { AvatarStepForceFactor = v; } ), + 1.0f ), new ParameterDefn("AvatarStepUpCorrectionFactor", "Multiplied by height of step collision to create up movement at step", - 1.0f, - (s) => { return AvatarStepUpCorrectionFactor; }, - (s,v) => { AvatarStepUpCorrectionFactor = v; } ), + 1.0f ), new ParameterDefn("AvatarStepSmoothingSteps", "Number of frames after a step collision that we continue walking up stairs", - 2, - (s) => { return AvatarStepSmoothingSteps; }, - (s,v) => { AvatarStepSmoothingSteps = v; } ), + 2 ), new ParameterDefn("VehicleMaxLinearVelocity", "Maximum velocity magnitude that can be assigned to a vehicle", 1000.0f, @@ -598,37 +563,21 @@ public static class BSParam (s) => { return (float)VehicleMaxAngularVelocity; }, (s,v) => { VehicleMaxAngularVelocity = v; VehicleMaxAngularVelocitySq = v * v; } ), new ParameterDefn("VehicleAngularDamping", "Factor to damp vehicle angular movement per second (0.0 - 1.0)", - 0.0f, - (s) => { return VehicleAngularDamping; }, - (s,v) => { VehicleAngularDamping = v; } ), + 0.0f ), new ParameterDefn("VehicleLinearFactor", "Fraction of physical linear changes applied to vehicle (<0,0,0> to <1,1,1>)", - new Vector3(1f, 1f, 1f), - (s) => { return VehicleLinearFactor; }, - (s,v) => { VehicleLinearFactor = v; } ), + new Vector3(1f, 1f, 1f) ), new ParameterDefn("VehicleAngularFactor", "Fraction of physical angular changes applied to vehicle (<0,0,0> to <1,1,1>)", - new Vector3(1f, 1f, 1f), - (s) => { return VehicleAngularFactor; }, - (s,v) => { VehicleAngularFactor = v; } ), + new Vector3(1f, 1f, 1f) ), new ParameterDefn("VehicleFriction", "Friction of vehicle on the ground (0.0 - 1.0)", - 0.0f, - (s) => { return VehicleFriction; }, - (s,v) => { VehicleFriction = v; } ), + 0.0f ), new ParameterDefn("VehicleRestitution", "Bouncyness factor for vehicles (0.0 - 1.0)", - 0.0f, - (s) => { return VehicleRestitution; }, - (s,v) => { VehicleRestitution = v; } ), + 0.0f ), new ParameterDefn("VehicleGroundGravityFudge", "Factor to multiply gravity if a ground vehicle is probably on the ground (0.0 - 1.0)", - 0.2f, - (s) => { return VehicleGroundGravityFudge; }, - (s,v) => { VehicleGroundGravityFudge = v; } ), + 0.2f ), new ParameterDefn("VehicleAngularBankingTimescaleFudge", "Factor to multiple angular banking timescale. Tune to increase realism.", - 60.0f, - (s) => { return VehicleAngularBankingTimescaleFudge; }, - (s,v) => { VehicleAngularBankingTimescaleFudge = v; } ), + 60.0f ), new ParameterDefn("VehicleDebuggingEnable", "Turn on/off vehicle debugging", - false, - (s) => { return VehicleDebuggingEnabled; }, - (s,v) => { VehicleDebuggingEnabled = v; } ), + false ), new ParameterDefn("MaxPersistantManifoldPoolSize", "Number of manifolds pooled (0 means default of 4096)", 0f, @@ -673,99 +622,53 @@ public static class BSParam (s,v) => { GlobalContactBreakingThreshold = v; s.UnmanagedParams[0].globalContactBreakingThreshold = v; } ), new ParameterDefn("CSHullMaxDepthSplit", "CS impl: max depth to split for hull. 1-10 but > 7 is iffy", - 7, - (s) => { return CSHullMaxDepthSplit; }, - (s,v) => { CSHullMaxDepthSplit = v; } ), + 7 ), new ParameterDefn("CSHullMaxDepthSplitForSimpleShapes", "CS impl: max depth setting for simple prim shapes", - 2, - (s) => { return CSHullMaxDepthSplitForSimpleShapes; }, - (s,v) => { CSHullMaxDepthSplitForSimpleShapes = v; } ), + 2 ), new ParameterDefn("CSHullConcavityThresholdPercent", "CS impl: concavity threshold percent (0-20)", - 5f, - (s) => { return CSHullConcavityThresholdPercent; }, - (s,v) => { CSHullConcavityThresholdPercent = v; } ), + 5f ), new ParameterDefn("CSHullVolumeConservationThresholdPercent", "percent volume conservation to collapse hulls (0-30)", - 5f, - (s) => { return CSHullVolumeConservationThresholdPercent; }, - (s,v) => { CSHullVolumeConservationThresholdPercent = v; } ), + 5f ), new ParameterDefn("CSHullMaxVertices", "CS impl: maximum number of vertices in output hulls. Keep < 50.", - 32, - (s) => { return CSHullMaxVertices; }, - (s,v) => { CSHullMaxVertices = v; } ), + 32 ), new ParameterDefn("CSHullMaxSkinWidth", "CS impl: skin width to apply to output hulls.", - 0f, - (s) => { return CSHullMaxSkinWidth; }, - (s,v) => { CSHullMaxSkinWidth = v; } ), + 0f ), new ParameterDefn("BHullMaxVerticesPerHull", "Bullet impl: max number of vertices per created hull", - 100f, - (s) => { return BHullMaxVerticesPerHull; }, - (s,v) => { BHullMaxVerticesPerHull = v; } ), + 100f ), new ParameterDefn("BHullMinClusters", "Bullet impl: minimum number of hulls to create per mesh", - 2f, - (s) => { return BHullMinClusters; }, - (s,v) => { BHullMinClusters = v; } ), + 2f ), new ParameterDefn("BHullCompacityWeight", "Bullet impl: weight factor for how compact to make hulls", - 2f, - (s) => { return BHullCompacityWeight; }, - (s,v) => { BHullCompacityWeight = v; } ), + 0.1f ), new ParameterDefn("BHullVolumeWeight", "Bullet impl: weight factor for volume in created hull", - 0.1f, - (s) => { return BHullVolumeWeight; }, - (s,v) => { BHullVolumeWeight = v; } ), + 0f ), new ParameterDefn("BHullConcavity", "Bullet impl: weight factor for how convex a created hull can be", - 100f, - (s) => { return BHullConcavity; }, - (s,v) => { BHullConcavity = v; } ), + 100f ), new ParameterDefn("BHullAddExtraDistPoints", "Bullet impl: whether to add extra vertices for long distance vectors", - false, - (s) => { return BHullAddExtraDistPoints; }, - (s,v) => { BHullAddExtraDistPoints = v; } ), + false ), new ParameterDefn("BHullAddNeighboursDistPoints", "Bullet impl: whether to add extra vertices between neighbor hulls", - false, - (s) => { return BHullAddNeighboursDistPoints; }, - (s,v) => { BHullAddNeighboursDistPoints = v; } ), + false ), new ParameterDefn("BHullAddFacesPoints", "Bullet impl: whether to add extra vertices to break up hull faces", - false, - (s) => { return BHullAddFacesPoints; }, - (s,v) => { BHullAddFacesPoints = v; } ), + false ), new ParameterDefn("BHullShouldAdjustCollisionMargin", "Bullet impl: whether to shrink resulting hulls to account for collision margin", - false, - (s) => { return BHullShouldAdjustCollisionMargin; }, - (s,v) => { BHullShouldAdjustCollisionMargin = v; } ), + false ), new ParameterDefn("LinksetImplementation", "Type of linkset implementation (0=Constraint, 1=Compound, 2=Manual)", - (float)BSLinkset.LinksetImplementation.Compound, - (s) => { return LinksetImplementation; }, - (s,v) => { LinksetImplementation = v; } ), + (float)BSLinkset.LinksetImplementation.Compound ), new ParameterDefn("LinkConstraintUseFrameOffset", "For linksets built with constraints, enable frame offsetFor linksets built with constraints, enable frame offset.", - false, - (s) => { return LinkConstraintUseFrameOffset; }, - (s,v) => { LinkConstraintUseFrameOffset = v; } ), + false ), new ParameterDefn("LinkConstraintEnableTransMotor", "Whether to enable translational motor on linkset constraints", - true, - (s) => { return LinkConstraintEnableTransMotor; }, - (s,v) => { LinkConstraintEnableTransMotor = v; } ), + true ), new ParameterDefn("LinkConstraintTransMotorMaxVel", "Maximum velocity to be applied by translational motor in linkset constraints", - 5.0f, - (s) => { return LinkConstraintTransMotorMaxVel; }, - (s,v) => { LinkConstraintTransMotorMaxVel = v; } ), + 5.0f ), new ParameterDefn("LinkConstraintTransMotorMaxForce", "Maximum force to be applied by translational motor in linkset constraints", - 0.1f, - (s) => { return LinkConstraintTransMotorMaxForce; }, - (s,v) => { LinkConstraintTransMotorMaxForce = v; } ), + 0.1f ), new ParameterDefn("LinkConstraintCFM", "Amount constraint can be violated. 0=no violation, 1=infinite. Default=0.1", - 0.1f, - (s) => { return LinkConstraintCFM; }, - (s,v) => { LinkConstraintCFM = v; } ), + 0.1f ), new ParameterDefn("LinkConstraintERP", "Amount constraint is corrected each tick. 0=none, 1=all. Default = 0.2", - 0.1f, - (s) => { return LinkConstraintERP; }, - (s,v) => { LinkConstraintERP = v; } ), + 0.1f ), new ParameterDefn("LinkConstraintSolverIterations", "Number of solver iterations when computing constraint. (0 = Bullet default)", - 40, - (s) => { return LinkConstraintSolverIterations; }, - (s,v) => { LinkConstraintSolverIterations = v; } ), + 40 ), new ParameterDefn("PhysicsMetricFrames", "Frames between outputting detailed phys metrics. (0 is off)", 0, -- cgit v1.1 From 045aaa838ac0a6e129ff1d8ec65053508df1d51a Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Mon, 6 May 2013 13:29:19 -0700 Subject: BulletSim: remove friction calcuation from BSMotor and move linear and angular friction computation into linear and angular movement code. The friction wasn't being applied properly. This will make it so vehicles don't drift as much and the drift is tunable by changing the friction timescales. --- .../Physics/BulletSPlugin/BSActorAvatarMove.cs | 1 - .../Region/Physics/BulletSPlugin/BSActorHover.cs | 1 - .../Physics/BulletSPlugin/BSActorMoveToTarget.cs | 1 - .../Physics/BulletSPlugin/BSActorSetForce.cs | 2 +- .../Physics/BulletSPlugin/BSActorSetTorque.cs | 2 +- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 44 ++++++++++----- OpenSim/Region/Physics/BulletSPlugin/BSMotors.cs | 63 +++++----------------- 7 files changed, 47 insertions(+), 67 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs b/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs index 4e067b5..ac8c30c 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs @@ -118,7 +118,6 @@ public class BSActorAvatarMove : BSActor m_velocityMotor = new BSVMotor("BSCharacter.Velocity", 0.2f, // time scale BSMotor.Infinite, // decay time scale - BSMotor.InfiniteVector, // friction timescale 1f // efficiency ); // _velocityMotor.PhysicsScene = PhysicsScene; // DEBUG DEBUG so motor will output detail log messages. diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSActorHover.cs b/OpenSim/Region/Physics/BulletSPlugin/BSActorHover.cs index 3630ca8..8a79809 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSActorHover.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSActorHover.cs @@ -102,7 +102,6 @@ public class BSActorHover : BSActor m_hoverMotor = new BSFMotor("BSActorHover", m_controllingPrim.HoverTau, // timeScale BSMotor.Infinite, // decay time scale - BSMotor.Infinite, // friction timescale 1f // efficiency ); m_hoverMotor.SetTarget(ComputeCurrentHoverHeight()); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSActorMoveToTarget.cs b/OpenSim/Region/Physics/BulletSPlugin/BSActorMoveToTarget.cs index 1b598fd..75ff24e 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSActorMoveToTarget.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSActorMoveToTarget.cs @@ -105,7 +105,6 @@ public class BSActorMoveToTarget : BSActor m_targetMotor = new BSVMotor("BSActorMoveToTargget.Activate", m_controllingPrim.MoveToTargetTau, // timeScale BSMotor.Infinite, // decay time scale - BSMotor.InfiniteVector, // friction timescale 1f // efficiency ); m_targetMotor.PhysicsScene = m_physicsScene; // DEBUG DEBUG so motor will output detail log messages. diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSActorSetForce.cs b/OpenSim/Region/Physics/BulletSPlugin/BSActorSetForce.cs index c0f40fd..96fa0b6 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSActorSetForce.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSActorSetForce.cs @@ -101,7 +101,7 @@ public class BSActorSetForce : BSActor if (m_forceMotor == null) { // A fake motor that might be used someday - m_forceMotor = new BSFMotor("setForce", 1f, 1f, 1f, 1f); + m_forceMotor = new BSFMotor("setForce", 1f, 1f, 1f); m_physicsScene.BeforeStep += Mover; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSActorSetTorque.cs b/OpenSim/Region/Physics/BulletSPlugin/BSActorSetTorque.cs index b3806e1..65098e1 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSActorSetTorque.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSActorSetTorque.cs @@ -101,7 +101,7 @@ public class BSActorSetTorque : BSActor if (m_torqueMotor == null) { // A fake motor that might be used someday - m_torqueMotor = new BSFMotor("setTorque", 1f, 1f, 1f, 1f); + m_torqueMotor = new BSFMotor("setTorque", 1f, 1f, 1f); m_physicsScene.BeforeStep += Mover; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index 0dd2aa5..272a162 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -235,7 +235,6 @@ namespace OpenSim.Region.Physics.BulletSPlugin // set all of the components to the same value case Vehicle.ANGULAR_FRICTION_TIMESCALE: m_angularFrictionTimescale = new Vector3(pValue, pValue, pValue); - m_angularMotor.FrictionTimescale = m_angularFrictionTimescale; break; case Vehicle.ANGULAR_MOTOR_DIRECTION: m_angularMotorDirection = new Vector3(pValue, pValue, pValue); @@ -244,7 +243,6 @@ namespace OpenSim.Region.Physics.BulletSPlugin break; case Vehicle.LINEAR_FRICTION_TIMESCALE: m_linearFrictionTimescale = new Vector3(pValue, pValue, pValue); - m_linearMotor.FrictionTimescale = m_linearFrictionTimescale; break; case Vehicle.LINEAR_MOTOR_DIRECTION: m_linearMotorDirection = new Vector3(pValue, pValue, pValue); @@ -265,7 +263,6 @@ namespace OpenSim.Region.Physics.BulletSPlugin { case Vehicle.ANGULAR_FRICTION_TIMESCALE: m_angularFrictionTimescale = new Vector3(pValue.X, pValue.Y, pValue.Z); - m_angularMotor.FrictionTimescale = m_angularFrictionTimescale; break; case Vehicle.ANGULAR_MOTOR_DIRECTION: // Limit requested angular speed to 2 rps= 4 pi rads/sec @@ -278,7 +275,6 @@ namespace OpenSim.Region.Physics.BulletSPlugin break; case Vehicle.LINEAR_FRICTION_TIMESCALE: m_linearFrictionTimescale = new Vector3(pValue.X, pValue.Y, pValue.Z); - m_linearMotor.FrictionTimescale = m_linearFrictionTimescale; break; case Vehicle.LINEAR_MOTOR_DIRECTION: m_linearMotorDirection = new Vector3(pValue.X, pValue.Y, pValue.Z); @@ -559,14 +555,10 @@ namespace OpenSim.Region.Physics.BulletSPlugin break; } - m_linearMotor = new BSVMotor("LinearMotor", m_linearMotorTimescale, - m_linearMotorDecayTimescale, m_linearFrictionTimescale, - 1f); + m_linearMotor = new BSVMotor("LinearMotor", m_linearMotorTimescale, m_linearMotorDecayTimescale, 1f); m_linearMotor.PhysicsScene = m_physicsScene; // DEBUG DEBUG DEBUG (enables detail logging) - m_angularMotor = new BSVMotor("AngularMotor", m_angularMotorTimescale, - m_angularMotorDecayTimescale, m_angularFrictionTimescale, - 1f); + m_angularMotor = new BSVMotor("AngularMotor", m_angularMotorTimescale, m_angularMotorDecayTimescale, 1f); m_angularMotor.PhysicsScene = m_physicsScene; // DEBUG DEBUG DEBUG (enables detail logging) /* Not implemented @@ -574,7 +566,6 @@ namespace OpenSim.Region.Physics.BulletSPlugin BSMotor.Infinite, BSMotor.InfiniteVector, m_verticalAttractionEfficiency); // Z goes away and we keep X and Y - m_verticalAttractionMotor.FrictionTimescale = new Vector3(BSMotor.Infinite, BSMotor.Infinite, 0.1f); m_verticalAttractionMotor.PhysicsScene = PhysicsScene; // DEBUG DEBUG DEBUG (enables detail logging) */ @@ -1050,8 +1041,13 @@ namespace OpenSim.Region.Physics.BulletSPlugin // Add this correction to the velocity to make it faster/slower. VehicleVelocity += linearMotorVelocityW; - VDetailLog("{0}, MoveLinear,velocity,origVelW={1},velV={2},correctV={3},correctW={4},newVelW={5}", - ControllingPrim.LocalID, origVelW, currentVelV, linearMotorCorrectionV, linearMotorVelocityW, VehicleVelocity); + // Friction reduces vehicle motion + Vector3 frictionFactor = ComputeFrictionFactor(m_linearFrictionTimescale, pTimestep); + VehicleVelocity -= (VehicleVelocity * frictionFactor); + + VDetailLog("{0}, MoveLinear,velocity,origVelW={1},velV={2},correctV={3},correctW={4},newVelW={5},fricFact={6}", + ControllingPrim.LocalID, origVelW, currentVelV, linearMotorCorrectionV, + linearMotorVelocityW, VehicleVelocity, frictionFactor); } public void ComputeLinearTerrainHeightCorrection(float pTimestep) @@ -1342,6 +1338,11 @@ namespace OpenSim.Region.Physics.BulletSPlugin // } VehicleRotationalVelocity += angularMotorContributionV * VehicleOrientation; + + // Reduce any velocity by friction. + Vector3 frictionFactor = ComputeFrictionFactor(m_angularFrictionTimescale, pTimestep); + VehicleRotationalVelocity -= (VehicleRotationalVelocity * frictionFactor); + VDetailLog("{0}, MoveAngular,angularTurning,angularMotorContrib={1}", ControllingPrim.LocalID, angularMotorContributionV); } @@ -1629,6 +1630,23 @@ namespace OpenSim.Region.Physics.BulletSPlugin } + // Given a friction vector (reduction in seconds) and a timestep, return the factor to reduce + // some value by to apply this friction. + private Vector3 ComputeFrictionFactor(Vector3 friction, float pTimestep) + { + Vector3 frictionFactor = Vector3.Zero; + if (friction != BSMotor.InfiniteVector) + { + // frictionFactor = (Vector3.One / FrictionTimescale) * timeStep; + // Individual friction components can be 'infinite' so compute each separately. + frictionFactor.X = (friction.X == BSMotor.Infinite) ? 0f : (1f / friction.X); + frictionFactor.Y = (friction.Y == BSMotor.Infinite) ? 0f : (1f / friction.Y); + frictionFactor.Z = (friction.Z == BSMotor.Infinite) ? 0f : (1f / friction.Z); + frictionFactor *= pTimestep; + } + return frictionFactor; + } + private float ClampInRange(float low, float val, float high) { return Math.Max(low, Math.Min(val, high)); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSMotors.cs b/OpenSim/Region/Physics/BulletSPlugin/BSMotors.cs index 0128d8d..ef662b5 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSMotors.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSMotors.cs @@ -65,13 +65,11 @@ public abstract class BSMotor } // Motor which moves CurrentValue to TargetValue over TimeScale seconds. -// The TargetValue decays in TargetValueDecayTimeScale and -// the CurrentValue will be held back by FrictionTimeScale. +// The TargetValue decays in TargetValueDecayTimeScale. // This motor will "zero itself" over time in that the targetValue will // decay to zero and the currentValue will follow it to that zero. // The overall effect is for the returned correction value to go from large -// values (the total difference between current and target minus friction) -// to small and eventually zero values. +// values to small and eventually zero values. // TimeScale and TargetDelayTimeScale may be 'infinite' which means no decay. // For instance, if something is moving at speed X and the desired speed is Y, @@ -88,7 +86,6 @@ public class BSVMotor : BSMotor public virtual float TimeScale { get; set; } public virtual float TargetValueDecayTimeScale { get; set; } - public virtual Vector3 FrictionTimescale { get; set; } public virtual float Efficiency { get; set; } public virtual float ErrorZeroThreshold { get; set; } @@ -111,16 +108,14 @@ public class BSVMotor : BSMotor { TimeScale = TargetValueDecayTimeScale = BSMotor.Infinite; Efficiency = 1f; - FrictionTimescale = BSMotor.InfiniteVector; CurrentValue = TargetValue = Vector3.Zero; ErrorZeroThreshold = 0.001f; } - public BSVMotor(string useName, float timeScale, float decayTimeScale, Vector3 frictionTimeScale, float efficiency) + public BSVMotor(string useName, float timeScale, float decayTimeScale, float efficiency) : this(useName) { TimeScale = timeScale; TargetValueDecayTimeScale = decayTimeScale; - FrictionTimescale = frictionTimeScale; Efficiency = efficiency; CurrentValue = TargetValue = Vector3.Zero; } @@ -165,26 +160,11 @@ public class BSVMotor : BSMotor TargetValue *= (1f - decayFactor); } - // The amount we can correct the error is reduced by the friction - Vector3 frictionFactor = Vector3.Zero; - if (FrictionTimescale != BSMotor.InfiniteVector) - { - // frictionFactor = (Vector3.One / FrictionTimescale) * timeStep; - // Individual friction components can be 'infinite' so compute each separately. - frictionFactor.X = (FrictionTimescale.X == BSMotor.Infinite) ? 0f : (1f / FrictionTimescale.X); - frictionFactor.Y = (FrictionTimescale.Y == BSMotor.Infinite) ? 0f : (1f / FrictionTimescale.Y); - frictionFactor.Z = (FrictionTimescale.Z == BSMotor.Infinite) ? 0f : (1f / FrictionTimescale.Z); - frictionFactor *= timeStep; - CurrentValue *= (Vector3.One - frictionFactor); - } - MDetailLog("{0}, BSVMotor.Step,nonZero,{1},origCurr={2},origTarget={3},timeStep={4},err={5},corr={6}", BSScene.DetailLogZero, UseName, origCurrVal, origTarget, timeStep, error, correction); - MDetailLog("{0}, BSVMotor.Step,nonZero,{1},tgtDecayTS={2},decayFact={3},frictTS={4},frictFact={5},tgt={6},curr={7}", - BSScene.DetailLogZero, UseName, - TargetValueDecayTimeScale, decayFactor, FrictionTimescale, frictionFactor, - TargetValue, CurrentValue); + MDetailLog("{0}, BSVMotor.Step,nonZero,{1},tgtDecayTS={2},decayFact={3},tgt={4},curr={5}", + BSScene.DetailLogZero, UseName, TargetValueDecayTimeScale, decayFactor, TargetValue, CurrentValue); } else { @@ -235,9 +215,9 @@ public class BSVMotor : BSMotor // maximum number of outputs to generate. int maxOutput = 50; MDetailLog("{0},BSVMotor.Test,{1},===================================== BEGIN Test Output", BSScene.DetailLogZero, UseName); - MDetailLog("{0},BSVMotor.Test,{1},timeScale={2},targDlyTS={3},frictTS={4},eff={5},curr={6},tgt={7}", + MDetailLog("{0},BSVMotor.Test,{1},timeScale={2},targDlyTS={3},eff={4},curr={5},tgt={6}", BSScene.DetailLogZero, UseName, - TimeScale, TargetValueDecayTimeScale, FrictionTimescale, Efficiency, + TimeScale, TargetValueDecayTimeScale, Efficiency, CurrentValue, TargetValue); LastError = BSMotor.InfiniteVector; @@ -254,8 +234,8 @@ public class BSVMotor : BSMotor public override string ToString() { - return String.Format("<{0},curr={1},targ={2},lastErr={3},decayTS={4},frictTS={5}>", - UseName, CurrentValue, TargetValue, LastError, TargetValueDecayTimeScale, FrictionTimescale); + return String.Format("<{0},curr={1},targ={2},lastErr={3},decayTS={4}>", + UseName, CurrentValue, TargetValue, LastError, TargetValueDecayTimeScale); } } @@ -265,7 +245,6 @@ public class BSFMotor : BSMotor { public virtual float TimeScale { get; set; } public virtual float TargetValueDecayTimeScale { get; set; } - public virtual float FrictionTimescale { get; set; } public virtual float Efficiency { get; set; } public virtual float ErrorZeroThreshold { get; set; } @@ -283,12 +262,11 @@ public class BSFMotor : BSMotor return (err >= -ErrorZeroThreshold && err <= ErrorZeroThreshold); } - public BSFMotor(string useName, float timeScale, float decayTimescale, float friction, float efficiency) + public BSFMotor(string useName, float timeScale, float decayTimescale, float efficiency) : base(useName) { TimeScale = TargetValueDecayTimeScale = BSMotor.Infinite; Efficiency = 1f; - FrictionTimescale = BSMotor.Infinite; CurrentValue = TargetValue = 0f; ErrorZeroThreshold = 0.01f; } @@ -331,24 +309,11 @@ public class BSFMotor : BSMotor TargetValue *= (1f - decayFactor); } - // The amount we can correct the error is reduced by the friction - float frictionFactor = 0f; - if (FrictionTimescale != BSMotor.Infinite) - { - // frictionFactor = (Vector3.One / FrictionTimescale) * timeStep; - // Individual friction components can be 'infinite' so compute each separately. - frictionFactor = 1f / FrictionTimescale; - frictionFactor *= timeStep; - CurrentValue *= (1f - frictionFactor); - } - MDetailLog("{0}, BSFMotor.Step,nonZero,{1},origCurr={2},origTarget={3},timeStep={4},err={5},corr={6}", BSScene.DetailLogZero, UseName, origCurrVal, origTarget, timeStep, error, correction); - MDetailLog("{0}, BSFMotor.Step,nonZero,{1},tgtDecayTS={2},decayFact={3},frictTS={4},frictFact={5},tgt={6},curr={7}", - BSScene.DetailLogZero, UseName, - TargetValueDecayTimeScale, decayFactor, FrictionTimescale, frictionFactor, - TargetValue, CurrentValue); + MDetailLog("{0}, BSFMotor.Step,nonZero,{1},tgtDecayTS={2},decayFact={3},tgt={4},curr={5}", + BSScene.DetailLogZero, UseName, TargetValueDecayTimeScale, decayFactor, TargetValue, CurrentValue); } else { @@ -390,8 +355,8 @@ public class BSFMotor : BSMotor public override string ToString() { - return String.Format("<{0},curr={1},targ={2},lastErr={3},decayTS={4},frictTS={5}>", - UseName, CurrentValue, TargetValue, LastError, TargetValueDecayTimeScale, FrictionTimescale); + return String.Format("<{0},curr={1},targ={2},lastErr={3},decayTS={4}>", + UseName, CurrentValue, TargetValue, LastError, TargetValueDecayTimeScale); } } -- cgit v1.1 From 93e1986d690cda415c9cce639a2656bc773a9a29 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Mon, 6 May 2013 16:48:01 -0700 Subject: BulletSim: apply linear and angular friction in vehicle coordinates and not world coordinates. --- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index 272a162..04ea289 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -1042,12 +1042,12 @@ namespace OpenSim.Region.Physics.BulletSPlugin VehicleVelocity += linearMotorVelocityW; // Friction reduces vehicle motion - Vector3 frictionFactor = ComputeFrictionFactor(m_linearFrictionTimescale, pTimestep); - VehicleVelocity -= (VehicleVelocity * frictionFactor); + Vector3 frictionFactorW = ComputeFrictionFactor(m_linearFrictionTimescale, pTimestep) * VehicleOrientation; + VehicleVelocity -= (VehicleVelocity * frictionFactorW); VDetailLog("{0}, MoveLinear,velocity,origVelW={1},velV={2},correctV={3},correctW={4},newVelW={5},fricFact={6}", ControllingPrim.LocalID, origVelW, currentVelV, linearMotorCorrectionV, - linearMotorVelocityW, VehicleVelocity, frictionFactor); + linearMotorVelocityW, VehicleVelocity, frictionFactorW); } public void ComputeLinearTerrainHeightCorrection(float pTimestep) @@ -1340,10 +1340,10 @@ namespace OpenSim.Region.Physics.BulletSPlugin VehicleRotationalVelocity += angularMotorContributionV * VehicleOrientation; // Reduce any velocity by friction. - Vector3 frictionFactor = ComputeFrictionFactor(m_angularFrictionTimescale, pTimestep); - VehicleRotationalVelocity -= (VehicleRotationalVelocity * frictionFactor); + Vector3 frictionFactorW = ComputeFrictionFactor(m_angularFrictionTimescale, pTimestep) * VehicleOrientation; + VehicleRotationalVelocity -= (VehicleRotationalVelocity * frictionFactorW); - VDetailLog("{0}, MoveAngular,angularTurning,angularMotorContrib={1}", ControllingPrim.LocalID, angularMotorContributionV); + VDetailLog("{0}, MoveAngular,angularTurning,angContribV={1}", ControllingPrim.LocalID, angularMotorContributionV); } // From http://wiki.secondlife.com/wiki/Linden_Vehicle_Tutorial: -- cgit v1.1 From 84118c5735f49bb38ded2ccc72b1bd7d39c09010 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Mon, 6 May 2013 18:05:37 -0700 Subject: BulletSim: properly free references to simple convex hull shapes. Didn't loose memory since shapes are shared but did mess up usage accounting. --- OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs | 45 +++++++++++++++++++----- 1 file changed, 37 insertions(+), 8 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs index 3e4ee5a..9d47657 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs @@ -117,11 +117,11 @@ public abstract class BSShape StringBuilder buff = new StringBuilder(); if (physShapeInfo == null) { - buff.Append(",noPhys"); + buff.Append(" --- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index 04ea289..e93dbd7 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -1028,6 +1028,10 @@ namespace OpenSim.Region.Physics.BulletSPlugin Vector3 currentVelV = VehicleVelocity * Quaternion.Inverse(VehicleOrientation); Vector3 linearMotorCorrectionV = m_linearMotor.Step(pTimestep, currentVelV); + // Friction reduces vehicle motion + Vector3 frictionFactorW = ComputeFrictionFactor(m_linearFrictionTimescale, pTimestep); + linearMotorCorrectionV -= (currentVelV * frictionFactorW); + // Motor is vehicle coordinates. Rotate it to world coordinates Vector3 linearMotorVelocityW = linearMotorCorrectionV * VehicleOrientation; @@ -1041,9 +1045,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin // Add this correction to the velocity to make it faster/slower. VehicleVelocity += linearMotorVelocityW; - // Friction reduces vehicle motion - Vector3 frictionFactorW = ComputeFrictionFactor(m_linearFrictionTimescale, pTimestep) * VehicleOrientation; - VehicleVelocity -= (VehicleVelocity * frictionFactorW); + VDetailLog("{0}, MoveLinear,velocity,origVelW={1},velV={2},correctV={3},correctW={4},newVelW={5},fricFact={6}", ControllingPrim.LocalID, origVelW, currentVelV, linearMotorCorrectionV, -- cgit v1.1 From ac6dcd35fb77f118fc6c3d72cb029591306c7e99 Mon Sep 17 00:00:00 2001 From: Vegaslon Date: Mon, 6 May 2013 21:19:48 -0400 Subject: Bulletsim: and the rotational friction. Signed-off-by: Robert Adams --- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index e93dbd7..c16b7d3 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -1339,11 +1339,13 @@ namespace OpenSim.Region.Physics.BulletSPlugin // angularMotorContributionV.Y = 0f; // } + // Reduce any velocity by friction. + Vector3 frictionFactorW = ComputeFrictionFactor(m_angularFrictionTimescale, pTimestep); + angularMotorContributionV -= (currentAngularV * frictionFactorW); + VehicleRotationalVelocity += angularMotorContributionV * VehicleOrientation; - // Reduce any velocity by friction. - Vector3 frictionFactorW = ComputeFrictionFactor(m_angularFrictionTimescale, pTimestep) * VehicleOrientation; - VehicleRotationalVelocity -= (VehicleRotationalVelocity * frictionFactorW); + VDetailLog("{0}, MoveAngular,angularTurning,angContribV={1}", ControllingPrim.LocalID, angularMotorContributionV); } -- cgit v1.1 From a42bb799cca27c0dddbecbd2edd2bd5e6d379472 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Fri, 10 May 2013 14:48:52 -0700 Subject: BulletSim: fix CPU loop that occurs when any 'degenerate' sculptie is in a region. This fixes the high CPU usage for regions with nothing else going on. --- OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs index 9d47657..262d734 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs @@ -368,9 +368,10 @@ public class BSShapeMesh : BSShape // Check to see if mesh was created (might require an asset). newShape = VerifyMeshCreated(physicsScene, newShape, prim); - if (!newShape.isNativeShape) + if (!newShape.isNativeShape || prim.PrimAssetState == BSPhysObject.PrimAssetCondition.Failed) { // If a mesh was what was created, remember the built shape for later sharing. + // Also note that if meshing failed we put it in the mesh list as there is nothing else to do about the mesh. Meshes.Add(newMeshKey, retMesh); } @@ -481,8 +482,11 @@ public class BSShapeMesh : BSShape } else { + // Force the asset condition to 'failed' so we won't try to keep fetching and processing this mesh. + prim.PrimAssetState = BSPhysObject.PrimAssetCondition.Failed; physicsScene.Logger.DebugFormat("{0} All mesh triangles degenerate. Prim {1} at {2} in {3}", LogHeader, prim.PhysObjectName, prim.RawPosition, physicsScene.Name); + physicsScene.DetailLog("{0},BSShapeMesh.CreatePhysicalMesh,allDegenerate,key={1}", prim.LocalID, newMeshKey); } } newShape.shapeKey = newMeshKey; @@ -521,7 +525,7 @@ public class BSShapeHull : BSShape // Check to see if hull was created (might require an asset). newShape = VerifyMeshCreated(physicsScene, newShape, prim); - if (!newShape.isNativeShape) + if (!newShape.isNativeShape || prim.PrimAssetState == BSPhysObject.PrimAssetCondition.Failed) { // If a mesh was what was created, remember the built shape for later sharing. Hulls.Add(newHullKey, retHull); -- cgit v1.1 From 45f37e11ad6e9a9917a6ea07ec52dec9058393f0 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Mon, 13 May 2013 08:40:24 -0700 Subject: BulletSim: use heightmap terrain when using BulletXNA. Output messages on features disabled when using BulletXNA. --- OpenSim/Region/Physics/BulletSPlugin/BSParam.cs | 2 +- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs index 3ca7e16..5504478 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs @@ -90,7 +90,7 @@ public static class BSParam public static bool ShouldUseBulletHACD { get; set; } public static bool ShouldUseSingleConvexHullForPrims { get; set; } - public static float TerrainImplementation { get; private set; } + public static float TerrainImplementation { get; set; } public static int TerrainMeshMagnification { get; private set; } public static float TerrainFriction { get; private set; } public static float TerrainHitFraction { get; private set; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index a4a8794..3f407ce 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -318,8 +318,12 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters ret = new BSAPIXNA(engineName, this); // Disable some features that are not implemented in BulletXNA m_log.InfoFormat("{0} Disabling some physics features not implemented by BulletXNA", LogHeader); + m_log.InfoFormat("{0} Disabling ShouldUseBulletHACD", LogHeader); BSParam.ShouldUseBulletHACD = false; + m_log.InfoFormat("{0} Disabling ShouldUseSingleConvexHullForPrims", LogHeader); BSParam.ShouldUseSingleConvexHullForPrims = false; + m_log.InfoFormat("{0} Setting terrain implimentation to Heightmap", LogHeader); + BSParam.TerrainImplementation = (float)BSTerrainPhys.TerrainImplementation.Heightmap; break; } -- cgit v1.1 From 15360cbb6ba83e40f474cca84082c908af49c58e Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Mon, 13 May 2013 13:03:13 -0700 Subject: BulletSim: add adjustment for avatar capsule height scaling. Makes avatar standing on ground view better and enables tuning. --- .../Region/Physics/BulletSPlugin/BSCharacter.cs | 27 ++++++++++++++++++---- OpenSim/Region/Physics/BulletSPlugin/BSParam.cs | 9 ++++++++ 2 files changed, 32 insertions(+), 4 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index 542f732..3671fc2 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -1,4 +1,4 @@ -/* +/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * @@ -649,12 +649,12 @@ public sealed class BSCharacter : BSPhysObject OMV.Vector3 newScale; // Bullet's capsule total height is the "passed height + radius * 2"; - // The base capsule is 1 diameter and 2 height (passed radius=0.5, passed height = 1) + // The base capsule is 1 unit in diameter and 2 units in height (passed radius=0.5, passed height = 1) // The number we pass in for 'scaling' is the multiplier to get that base // shape to be the size desired. // So, when creating the scale for the avatar height, we take the passed height // (size.Z) and remove the caps. - // Another oddity of the Bullet capsule implementation is that it presumes the Y + // An oddity of the Bullet capsule implementation is that it presumes the Y // dimension is the radius of the capsule. Even though some of the code allows // for a asymmetrical capsule, other parts of the code presume it is cylindrical. @@ -662,8 +662,27 @@ public sealed class BSCharacter : BSPhysObject newScale.X = size.X / 2f; newScale.Y = size.Y / 2f; + float heightAdjust = BSParam.AvatarHeightMidFudge; + if (BSParam.AvatarHeightLowFudge != 0f || BSParam.AvatarHeightHighFudge != 0f) + { + // An avatar is between 1.61 and 2.12 meters. Midpoint is 1.87m. + // The "times 4" relies on the fact that the difference from the midpoint to the extremes is exactly 0.25 + float midHeightOffset = size.Z - 1.87f; + if (midHeightOffset < 0f) + { + // Small avatar. Add the adjustment based on the distance from midheight + heightAdjust += -1f * midHeightOffset * 4f * BSParam.AvatarHeightLowFudge; + } + else + { + // Large avatar. Add the adjustment based on the distance from midheight + heightAdjust += midHeightOffset * 4f * BSParam.AvatarHeightHighFudge; + } + } // The total scale height is the central cylindar plus the caps on the two ends. - newScale.Z = (size.Z + (Math.Min(size.X, size.Y) * 2)) / 2f; + newScale.Z = (size.Z + (Math.Min(size.X, size.Y) * 2) + heightAdjust) / 2f; + // m_log.DebugFormat("{0} ComputeAvatarScale: size={1},adj={2},scale={3}", LogHeader, size, heightAdjust, newScale); + // If smaller than the endcaps, just fake like we're almost that small if (newScale.Z < 0) newScale.Z = 0.1f; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs index 5504478..d33292f 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs @@ -125,6 +125,9 @@ public static class BSParam public static float AvatarCapsuleWidth { get; private set; } public static float AvatarCapsuleDepth { get; private set; } public static float AvatarCapsuleHeight { get; private set; } + public static float AvatarHeightLowFudge { get; private set; } + public static float AvatarHeightMidFudge { get; private set; } + public static float AvatarHeightHighFudge { get; private set; } public static float AvatarContactProcessingThreshold { get; private set; } public static float AvatarBelowGroundUpCorrectionMeters { get; private set; } public static float AvatarStepHeight { get; private set; } @@ -539,6 +542,12 @@ public static class BSParam 0.45f ), new ParameterDefn("AvatarCapsuleHeight", "Default height of space around avatar", 1.5f ), + new ParameterDefn("AvatarHeightLowFudge", "A fudge factor to make small avatars stand on the ground", + -0.2f ), + new ParameterDefn("AvatarHeightMidFudge", "A fudge distance to adjust average sized avatars to be standing on ground", + 0.1f ), + new ParameterDefn("AvatarHeightHighFudge", "A fudge factor to make tall avatars stand on the ground", + 0.1f ), new ParameterDefn("AvatarContactProcessingThreshold", "Distance from capsule to check for collisions", 0.1f ), new ParameterDefn("AvatarBelowGroundUpCorrectionMeters", "Meters to move avatar up if it seems to be below ground", -- cgit v1.1 From c86e828dbfed8b9cf72c7e7e8d1dad0c0e9f8940 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Mon, 13 May 2013 13:05:27 -0700 Subject: BulletSim: add a lock to try and catch a native shape creation/destruction race condition. --- OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs index 262d734..72d039b 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs @@ -283,8 +283,13 @@ public class BSShapeNative : BSShape public override BSShape GetReference(BSScene pPhysicsScene, BSPhysObject pPrim) { // Native shapes are not shared so we return a new shape. - return new BSShapeNative(CreatePhysicalNativeShape(pPhysicsScene, pPrim, - physShapeInfo.shapeType, (FixedShapeKey)physShapeInfo.shapeKey) ); + BSShape ret = null; + lock (physShapeInfo) + { + ret = new BSShapeNative(CreatePhysicalNativeShape(pPhysicsScene, pPrim, + physShapeInfo.shapeType, (FixedShapeKey)physShapeInfo.shapeKey)); + } + return ret; } // Make this reference to the physical shape go away since native shapes are not shared. -- cgit v1.1 From b135f1d58a1f3532cb198bf25680864e335d4cb1 Mon Sep 17 00:00:00 2001 From: Vegaslon Date: Thu, 9 May 2013 10:25:44 -0400 Subject: BulletSim: Fix for mantis 6487, also minor adjustment to fix flying while you are running. Signed-off-by: Robert Adams --- OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index 3671fc2..ff5b6ab 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -419,7 +419,7 @@ public sealed class BSCharacter : BSPhysObject DetailLog("{0},BSCharacter.setTargetVelocity,call,vel={1}", LocalID, value); m_targetVelocity = value; OMV.Vector3 targetVel = value; - if (_setAlwaysRun) + if (_setAlwaysRun && !_flying) targetVel *= new OMV.Vector3(BSParam.AvatarAlwaysRunFactor, BSParam.AvatarAlwaysRunFactor, 0f); if (m_moveActor != null) @@ -481,7 +481,10 @@ public sealed class BSCharacter : BSPhysObject _orientation = value; PhysScene.TaintedObject("BSCharacter.setOrientation", delegate() { - ForceOrientation = _orientation; + // Bullet assumes we know what we are doing when forcing orientation + // so it lets us go against all the rules and just compensates for them later. + // This keeps us from flipping the capsule over which the veiwer does not understand. + ForceOrientation = new OMV.Quaternion(0, 0, _orientation.Z,0); }); } } -- cgit v1.1 From 46eb8465a01b7dd923b962035562c953d4eb78e4 Mon Sep 17 00:00:00 2001 From: dahlia Date: Wed, 15 May 2013 17:12:17 -0700 Subject: fall back to using a display mesh for physics proxy if no physics_mesh entry was wound in a mesh asset --- OpenSim/Region/Physics/Meshing/Meshmerizer.cs | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/Meshing/Meshmerizer.cs b/OpenSim/Region/Physics/Meshing/Meshmerizer.cs index 8145d61..2d102de 100644 --- a/OpenSim/Region/Physics/Meshing/Meshmerizer.cs +++ b/OpenSim/Region/Physics/Meshing/Meshmerizer.cs @@ -358,6 +358,10 @@ namespace OpenSim.Region.Physics.Meshing physicsParms = (OSDMap)map["physics_shape"]; // old asset format else if (map.ContainsKey("physics_mesh")) physicsParms = (OSDMap)map["physics_mesh"]; // new asset format + else if (map.ContainsKey("medium_lod")) + physicsParms = (OSDMap)map["medium_lod"]; // if no physics mesh, try to fall back to medium LOD display mesh + else if (map.ContainsKey("high_lod")) + physicsParms = (OSDMap)map["high_lod"]; // if all else fails, use highest LOD display mesh and hope it works :) if (physicsParms == null) { -- cgit v1.1 From 214bae14799c05c12595b067ff2eb0e2e5b4eeb2 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Fri, 17 May 2013 14:43:53 -0700 Subject: BulletSim: fix BulletSim crashing if there is no [BulletSim] section in any INI file. Update TODO list. --- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 6 ++++++ OpenSim/Region/Physics/BulletSPlugin/BulletSimTODO.txt | 14 ++++++-------- 2 files changed, 12 insertions(+), 8 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index 3f407ce..9ed2d06 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -268,6 +268,12 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters // Do any replacements in the parameters m_physicsLoggingPrefix = m_physicsLoggingPrefix.Replace("%REGIONNAME%", RegionName); } + else + { + BulletEngineName = "BulletUnmanaged"; + m_physicsLoggingEnabled = false; + VehicleLoggingEnabled = false; + } // The material characteristics. BSMaterials.InitializeFromDefaults(Params); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimTODO.txt b/OpenSim/Region/Physics/BulletSPlugin/BulletSimTODO.txt index 5792ae6..df1da63 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimTODO.txt +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimTODO.txt @@ -1,16 +1,12 @@ -PROBLEMS TO LOOK INTO +CURRENT PROBLEMS TO FIX AND/OR LOOK AT ================================================= -Nebadon vehicle ride, get up, ride again. Second time vehicle does not act correctly. +Script changing rotation of child prim while vehicle moving (eg turning wheel) causes + the wheel to appear to jump back. Looks like sending position from previous update. +Vehicle ride, get up, ride again. Second time vehicle does not act correctly. Have to rez new vehicle and delete the old to fix situation. Hitting RESET on Nebadon's vehicle while riding causes vehicle to get into odd position state where it will not settle onto ground properly, etc Two of Nebadon vehicles in a sim max the CPU. This is new. -A sitting, active vehicle bobs up and down a small amount. - -CURRENT PRIORITIES -================================================= -Use the HACD convex hull routine in Bullet rather than the C# version. - Speed up hullifying large meshes. Enable vehicle border crossings (at least as poorly as ODE) Terrain skirts Avatar created in previous region and not new region when crossing border @@ -361,4 +357,6 @@ Angular motion around Z moves the vehicle in world Z and not vehicle Z in ODE. Nebadon vehicles turning funny in arena (DONE) Lock axis (DONE 20130401) Terrain detail: double terrain mesh detail (DONE) +Use the HACD convex hull routine in Bullet rather than the C# version. + Speed up hullifying large meshes. (DONE) -- cgit v1.1 From fa8f5bafb225624fe4a0df88acf1f4c227632fe0 Mon Sep 17 00:00:00 2001 From: dahlia Date: Sat, 18 May 2013 01:23:09 -0700 Subject: add prototype code to decode convex hulls from mesh assets. Please do not use yet; the interface will be defined in a later commit. --- OpenSim/Region/Physics/Meshing/Meshmerizer.cs | 131 +++++++++++++++++++++----- 1 file changed, 110 insertions(+), 21 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/Meshing/Meshmerizer.cs b/OpenSim/Region/Physics/Meshing/Meshmerizer.cs index 2d102de..825e622 100644 --- a/OpenSim/Region/Physics/Meshing/Meshmerizer.cs +++ b/OpenSim/Region/Physics/Meshing/Meshmerizer.cs @@ -79,6 +79,8 @@ namespace OpenSim.Region.Physics.Meshing private float minSizeForComplexMesh = 0.2f; // prims with all dimensions smaller than this will have a bounding box mesh + private List> mConvexHulls = null; + private Dictionary m_uniqueMeshes = new Dictionary(); public Meshmerizer(IConfigSource config) @@ -363,6 +365,57 @@ namespace OpenSim.Region.Physics.Meshing else if (map.ContainsKey("high_lod")) physicsParms = (OSDMap)map["high_lod"]; // if all else fails, use highest LOD display mesh and hope it works :) + if (map.ContainsKey("physics_convex")) + { // pull this out also in case physics engine can use it + try + { + OSDMap convexBlock = (OSDMap)map["physics_convex"]; + if (convexBlock.ContainsKey("HullList")) + { + byte[] hullList = convexBlock["HullList"].AsBinary(); + Vector3 min = new Vector3(-0.5f, -0.5f, -0.5f); + if (convexBlock.ContainsKey("Min")) min = convexBlock["Min"].AsVector3(); + Vector3 max = new Vector3(0.5f, 0.5f, 0.5f); + if (convexBlock.ContainsKey("Max")) max = convexBlock["Max"].AsVector3(); + + // decompress and decode hull points + byte[] posBytes = DecompressOsd(convexBlock["Positions"].AsBinary()).AsBinary(); + + List> hulls = new List>(); + int posNdx = 0; + + foreach (byte cnt in hullList) + { + int count = cnt == 0 ? 256 : cnt; + List hull = new List(); + + for (int i = 0; i < cnt; i++) + { + ushort uX = Utils.BytesToUInt16(posBytes, posNdx); posNdx += 2; + ushort uY = Utils.BytesToUInt16(posBytes, posNdx); posNdx += 2; + ushort uZ = Utils.BytesToUInt16(posBytes, posNdx); posNdx += 2; + + Vector3 pos = new Vector3( + Utils.UInt16ToFloat(uX, min.X, max.X) * size.X, + Utils.UInt16ToFloat(uY, min.Y, max.Y) * size.Y, + Utils.UInt16ToFloat(uZ, min.Z, max.Z) * size.Z + ); + + hull.Add(pos); + } + + hulls.Add(hull); + } + + mConvexHulls = hulls; + } + } + catch (Exception e) + { + m_log.WarnFormat("[MESH]: exception decoding convex block: {0}", e.Message); + } + } + if (physicsParms == null) { m_log.WarnFormat("[MESH]: No recognized physics mesh found in mesh asset for {0}", primName); @@ -381,27 +434,7 @@ namespace OpenSim.Region.Physics.Meshing // byte[] decompressed = new byte[physSize * 5]; try { - using (MemoryStream inMs = new MemoryStream(meshBytes)) - { - using (MemoryStream outMs = new MemoryStream()) - { - using (ZOutputStream zOut = new ZOutputStream(outMs)) - { - byte[] readBuffer = new byte[2048]; - int readLen = 0; - while ((readLen = inMs.Read(readBuffer, 0, readBuffer.Length)) > 0) - { - zOut.Write(readBuffer, 0, readLen); - } - zOut.Flush(); - outMs.Seek(0, SeekOrigin.Begin); - - byte[] decompressedBuf = outMs.GetBuffer(); - - decodedMeshOsd = OSDParser.DeserializeLLSDBinary(decompressedBuf); - } - } - } + decodedMeshOsd = DecompressOsd(meshBytes); } catch (Exception e) { @@ -428,6 +461,41 @@ namespace OpenSim.Region.Physics.Meshing return true; } + + /// + /// decompresses a gzipped OSD object + /// + /// the OSD object + /// + /// + private static OSD DecompressOsd(byte[] meshBytes) + { + OSD decodedOsd = null; + + using (MemoryStream inMs = new MemoryStream(meshBytes)) + { + using (MemoryStream outMs = new MemoryStream()) + { + using (ZOutputStream zOut = new ZOutputStream(outMs)) + { + byte[] readBuffer = new byte[2048]; + int readLen = 0; + while ((readLen = inMs.Read(readBuffer, 0, readBuffer.Length)) > 0) + { + zOut.Write(readBuffer, 0, readLen); + } + zOut.Flush(); + outMs.Seek(0, SeekOrigin.Begin); + + byte[] decompressedBuf = outMs.GetBuffer(); + + decodedOsd = OSDParser.DeserializeLLSDBinary(decompressedBuf); + } + } + } + return decodedOsd; + } + /// /// Generate the co-ords and faces necessary to construct a mesh from the sculpt data the accompanies a prim. /// @@ -704,6 +772,27 @@ namespace OpenSim.Region.Physics.Meshing return true; } + /// + /// temporary prototype code - please do not use until the interface has been finalized! + /// + /// value to scale the hull points by + /// a list of hulls if they exist and have been successfully decoded, otherwise null + public List> GetConvexHulls(Vector3 size) + { + if (mConvexHulls == null) + return null; + + List> hulls = new List>(); + foreach (var hull in mConvexHulls) + { + List verts = new List(); + foreach (var vert in hull) + verts.Add(vert * size); + } + + return hulls; + } + public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, Vector3 size, float lod) { return CreateMesh(primName, primShape, size, lod, false, true); -- cgit v1.1 From 477bee6468f35ca9264fc8f752a9124e32503901 Mon Sep 17 00:00:00 2001 From: dahlia Date: Sat, 18 May 2013 11:15:05 -0700 Subject: remove duplicate hull scaling --- OpenSim/Region/Physics/Meshing/Meshmerizer.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/Meshing/Meshmerizer.cs b/OpenSim/Region/Physics/Meshing/Meshmerizer.cs index 825e622..a57146c 100644 --- a/OpenSim/Region/Physics/Meshing/Meshmerizer.cs +++ b/OpenSim/Region/Physics/Meshing/Meshmerizer.cs @@ -396,9 +396,9 @@ namespace OpenSim.Region.Physics.Meshing ushort uZ = Utils.BytesToUInt16(posBytes, posNdx); posNdx += 2; Vector3 pos = new Vector3( - Utils.UInt16ToFloat(uX, min.X, max.X) * size.X, - Utils.UInt16ToFloat(uY, min.Y, max.Y) * size.Y, - Utils.UInt16ToFloat(uZ, min.Z, max.Z) * size.Z + Utils.UInt16ToFloat(uX, min.X, max.X), + Utils.UInt16ToFloat(uY, min.Y, max.Y), + Utils.UInt16ToFloat(uZ, min.Z, max.Z) ); hull.Add(pos); -- cgit v1.1 From e65d1e459eb875cb2d0d5f9aa6042c640daa19fd Mon Sep 17 00:00:00 2001 From: dahlia Date: Sat, 18 May 2013 13:11:22 -0700 Subject: fix error in hull point indexing --- OpenSim/Region/Physics/Meshing/Meshmerizer.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/Meshing/Meshmerizer.cs b/OpenSim/Region/Physics/Meshing/Meshmerizer.cs index a57146c..79edc12 100644 --- a/OpenSim/Region/Physics/Meshing/Meshmerizer.cs +++ b/OpenSim/Region/Physics/Meshing/Meshmerizer.cs @@ -389,7 +389,7 @@ namespace OpenSim.Region.Physics.Meshing int count = cnt == 0 ? 256 : cnt; List hull = new List(); - for (int i = 0; i < cnt; i++) + for (int i = 0; i < count; i++) { ushort uX = Utils.BytesToUInt16(posBytes, posNdx); posNdx += 2; ushort uY = Utils.BytesToUInt16(posBytes, posNdx); posNdx += 2; -- cgit v1.1 From 9de3979f5b91ae4bf9b05b89ec59999c43514f90 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Fri, 17 May 2013 21:17:54 -0700 Subject: BulletSim: add gImpact shape type. Add logic to use gImpact shape for prims that have cuts or holes. Default logic to 'off' as it needs debugging. --- OpenSim/Region/Physics/BulletSPlugin/BSAPIUnman.cs | 15 +++ OpenSim/Region/Physics/BulletSPlugin/BSAPIXNA.cs | 11 +- .../Region/Physics/BulletSPlugin/BSApiTemplate.cs | 5 + OpenSim/Region/Physics/BulletSPlugin/BSParam.cs | 3 + OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 2 + .../Physics/BulletSPlugin/BSShapeCollection.cs | 15 ++- OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs | 130 +++++++++++++++++++-- 7 files changed, 167 insertions(+), 14 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSAPIUnman.cs b/OpenSim/Region/Physics/BulletSPlugin/BSAPIUnman.cs index 231f0f8..12a0c17 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSAPIUnman.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSAPIUnman.cs @@ -251,6 +251,16 @@ public override BulletShape CreateMeshShape(BulletWorld world, BSPhysicsShapeType.SHAPE_MESH); } +public override BulletShape CreateGImpactShape(BulletWorld world, + int indicesCount, int[] indices, + int verticesCount, float[] vertices) +{ + BulletWorldUnman worldu = world as BulletWorldUnman; + return new BulletShapeUnman( + BSAPICPP.CreateGImpactShape2(worldu.ptr, indicesCount, indices, verticesCount, vertices), + BSPhysicsShapeType.SHAPE_GIMPACT); +} + public override BulletShape CreateHullShape(BulletWorld world, int hullCount, float[] hulls) { BulletWorldUnman worldu = world as BulletWorldUnman; @@ -1426,6 +1436,11 @@ public static extern IntPtr CreateMeshShape2(IntPtr world, int verticesCount, [MarshalAs(UnmanagedType.LPArray)] float[] vertices ); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern IntPtr CreateGImpactShape2(IntPtr world, + int indicesCount, [MarshalAs(UnmanagedType.LPArray)] int[] indices, + int verticesCount, [MarshalAs(UnmanagedType.LPArray)] float[] vertices ); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern IntPtr CreateHullShape2(IntPtr world, int hullCount, [MarshalAs(UnmanagedType.LPArray)] float[] hulls); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSAPIXNA.cs b/OpenSim/Region/Physics/BulletSPlugin/BSAPIXNA.cs index 59780ae..6db5f5e 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSAPIXNA.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSAPIXNA.cs @@ -1475,7 +1475,7 @@ private sealed class BulletConstraintXNA : BulletConstraint ret = BSPhysicsShapeType.SHAPE_UNKNOWN; break; case BroadphaseNativeTypes.CONVEX_TRIANGLEMESH_SHAPE_PROXYTYPE: - ret = BSPhysicsShapeType.SHAPE_MESH; + ret = BSPhysicsShapeType.SHAPE_CONVEXHULL; break; case BroadphaseNativeTypes.CONVEX_HULL_SHAPE_PROXYTYPE: ret = BSPhysicsShapeType.SHAPE_HULL; @@ -1503,7 +1503,7 @@ private sealed class BulletConstraintXNA : BulletConstraint ret = BSPhysicsShapeType.SHAPE_CONE; break; case BroadphaseNativeTypes.CONVEX_SHAPE_PROXYTYPE: - ret = BSPhysicsShapeType.SHAPE_UNKNOWN; + ret = BSPhysicsShapeType.SHAPE_CONVEXHULL; break; case BroadphaseNativeTypes.CYLINDER_SHAPE_PROXYTYPE: ret = BSPhysicsShapeType.SHAPE_CYLINDER; @@ -1547,7 +1547,7 @@ private sealed class BulletConstraintXNA : BulletConstraint break; ///Used for GIMPACT Trimesh integration case BroadphaseNativeTypes.GIMPACT_SHAPE_PROXYTYPE: - ret = BSPhysicsShapeType.SHAPE_MESH; + ret = BSPhysicsShapeType.SHAPE_GIMPACT; break; ///Multimaterial mesh case BroadphaseNativeTypes.MULTIMATERIAL_TRIANGLE_MESH_PROXYTYPE: @@ -1820,6 +1820,11 @@ private sealed class BulletConstraintXNA : BulletConstraint return new BulletShapeXNA(meshShape, BSPhysicsShapeType.SHAPE_MESH); } + public override BulletShape CreateGImpactShape(BulletWorld pWorld, int pIndicesCount, int[] indices, int pVerticesCount, float[] verticesAsFloats) + { + // TODO: + return null; + } public static void DumpRaw(ObjectArrayindices, ObjectArray vertices, int pIndicesCount,int pVerticesCount ) { diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSApiTemplate.cs b/OpenSim/Region/Physics/BulletSPlugin/BSApiTemplate.cs index 3378c93..6cdc112 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSApiTemplate.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSApiTemplate.cs @@ -71,6 +71,7 @@ public enum BSPhysicsShapeType SHAPE_HEIGHTMAP = 23, SHAPE_AVATAR = 24, SHAPE_CONVEXHULL= 25, + SHAPE_GIMPACT = 26, }; // The native shapes have predefined shape hash keys @@ -321,6 +322,10 @@ public abstract BulletShape CreateMeshShape(BulletWorld world, int indicesCount, int[] indices, int verticesCount, float[] vertices ); +public abstract BulletShape CreateGImpactShape(BulletWorld world, + int indicesCount, int[] indices, + int verticesCount, float[] vertices ); + public abstract BulletShape CreateHullShape(BulletWorld world, int hullCount, float[] hulls); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs index d33292f..9a9e527 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs @@ -89,6 +89,7 @@ public static class BSParam public static bool ShouldRemoveZeroWidthTriangles { get; private set; } public static bool ShouldUseBulletHACD { get; set; } public static bool ShouldUseSingleConvexHullForPrims { get; set; } + public static bool ShouldUseGImpactShapeForPrims { get; set; } public static float TerrainImplementation { get; set; } public static int TerrainMeshMagnification { get; private set; } @@ -369,6 +370,8 @@ public static class BSParam false ), new ParameterDefn("ShouldUseSingleConvexHullForPrims", "If true, use a single convex hull shape for physical prims", true ), + new ParameterDefn("ShouldUseGImpactShapeForPrims", "If true, use a GImpact shape for prims with cuts and twists", + false ), new ParameterDefn("CrossingFailuresBeforeOutOfBounds", "How forgiving we are about getting into adjactent regions", 5 ), diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index 9ed2d06..39f5b0a 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -328,6 +328,8 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters BSParam.ShouldUseBulletHACD = false; m_log.InfoFormat("{0} Disabling ShouldUseSingleConvexHullForPrims", LogHeader); BSParam.ShouldUseSingleConvexHullForPrims = false; + m_log.InfoFormat("{0} Disabling ShouldUseGImpactShapeForPrims", LogHeader); + BSParam.ShouldUseGImpactShapeForPrims = false; m_log.InfoFormat("{0} Setting terrain implimentation to Heightmap", LogHeader); BSParam.TerrainImplementation = (float)BSTerrainPhys.TerrainImplementation.Heightmap; break; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index 64aaa15..32bbc8f 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -230,6 +230,7 @@ public sealed class BSShapeCollection : IDisposable BSShape potentialHull = null; PrimitiveBaseShape pbs = prim.BaseShape; + // Use a simple, one section convex shape for prims that are probably convex (no cuts or twists) if (BSParam.ShouldUseSingleConvexHullForPrims && pbs != null && !pbs.SculptEntry @@ -238,7 +239,17 @@ public sealed class BSShapeCollection : IDisposable { potentialHull = BSShapeConvexHull.GetReference(m_physicsScene, false /* forceRebuild */, prim); } - else + // Use the GImpact shape if it is a prim that has some concaveness + if (potentialHull == null + && BSParam.ShouldUseGImpactShapeForPrims + && pbs != null + && !pbs.SculptEntry + ) + { + potentialHull = BSShapeGImpact.GetReference(m_physicsScene, false /* forceRebuild */, prim); + } + // If not any of the simple cases, just make a hull + if (potentialHull == null) { potentialHull = BSShapeHull.GetReference(m_physicsScene, false /*forceRebuild*/, prim); } @@ -261,7 +272,7 @@ public sealed class BSShapeCollection : IDisposable } else { - // Update prim.BSShape to reference a mesh of this shape. + // Non-physical objects should be just meshes. BSShape potentialMesh = BSShapeMesh.GetReference(m_physicsScene, false /*forceRebuild*/, prim); // If the current shape is not what is on the prim at the moment, time to change. if (!prim.PhysShape.HasPhysicalShape diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs index 72d039b..0152233 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs @@ -422,9 +422,22 @@ public class BSShapeMesh : BSShape outMesh = foundDesc; return ret; } + + public delegate BulletShape CreateShapeCall(BulletWorld world, int indicesCount, int[] indices, int verticesCount, float[] vertices ); private BulletShape CreatePhysicalMesh(BSScene physicsScene, BSPhysObject prim, System.UInt64 newMeshKey, PrimitiveBaseShape pbs, OMV.Vector3 size, float lod) { + return BSShapeMesh.CreatePhysicalMeshShape(physicsScene, prim, newMeshKey, pbs, size, lod, + (w, iC, i, vC, v) => physicsScene.PE.CreateMeshShape(w, iC, i, vC, v) ); + } + + // Code that uses the mesher to create the index/vertices info for a trimesh shape. + // This is used by the passed 'makeShape' call to create the Bullet mesh shape. + // The actual build call is passed so this logic can be used by several of the shapes that use a + // simple mesh as their base shape. + public static BulletShape CreatePhysicalMeshShape(BSScene physicsScene, BSPhysObject prim, System.UInt64 newMeshKey, + PrimitiveBaseShape pbs, OMV.Vector3 size, float lod, CreateShapeCall makeShape) + { BulletShape newShape = new BulletShape(); IMesh meshData = physicsScene.mesher.CreateMesh(prim.PhysObjectName, pbs, size, lod, @@ -482,8 +495,7 @@ public class BSShapeMesh : BSShape if (realIndicesIndex != 0) { - newShape = physicsScene.PE.CreateMeshShape(physicsScene.World, - realIndicesIndex, indices, verticesAsFloats.Length / 3, verticesAsFloats); + newShape = makeShape(physicsScene.World, realIndicesIndex, indices, verticesAsFloats.Length / 3, verticesAsFloats); } else { @@ -803,6 +815,7 @@ public class BSShapeCompound : BSShape // Called at taint-time. private void DereferenceAnonCollisionShape(BSScene physicsScene, BulletShape pShape) { + // TODO: figure a better way to go through all the shape types and find a possible instance. BSShapeMesh meshDesc; if (BSShapeMesh.TryGetMeshByPtr(pShape, out meshDesc)) { @@ -824,17 +837,25 @@ public class BSShapeCompound : BSShape } else { - if (physicsScene.PE.IsCompound(pShape)) + BSShapeGImpact gImpactDesc; + if (BSShapeGImpact.TryGetGImpactByPtr(pShape, out gImpactDesc)) { - BSShapeCompound recursiveCompound = new BSShapeCompound(pShape); - recursiveCompound.Dereference(physicsScene); + gImpactDesc.Dereference(physicsScene); } else { - if (physicsScene.PE.IsNativeShape(pShape)) + if (physicsScene.PE.IsCompound(pShape)) + { + BSShapeCompound recursiveCompound = new BSShapeCompound(pShape); + recursiveCompound.Dereference(physicsScene); + } + else { - BSShapeNative nativeShape = new BSShapeNative(pShape); - nativeShape.Dereference(physicsScene); + if (physicsScene.PE.IsNativeShape(pShape)) + { + BSShapeNative nativeShape = new BSShapeNative(pShape); + nativeShape.Dereference(physicsScene); + } } } } @@ -857,7 +878,7 @@ public class BSShapeConvexHull : BSShape float lod; System.UInt64 newMeshKey = BSShape.ComputeShapeKey(prim.Size, prim.BaseShape, out lod); - physicsScene.DetailLog("{0},BSShapeMesh,getReference,newKey={1},size={2},lod={3}", + physicsScene.DetailLog("{0},BSShapeConvexHull,getReference,newKey={1},size={2},lod={3}", prim.LocalID, newMeshKey.ToString("X"), prim.Size, lod); BSShapeConvexHull retConvexHull = null; @@ -937,6 +958,97 @@ public class BSShapeConvexHull : BSShape return ret; } } +// ============================================================================================================ +public class BSShapeGImpact : BSShape +{ + private static string LogHeader = "[BULLETSIM SHAPE GIMPACT]"; + public static Dictionary GImpacts = new Dictionary(); + + public BSShapeGImpact(BulletShape pShape) : base(pShape) + { + } + public static BSShape GetReference(BSScene physicsScene, bool forceRebuild, BSPhysObject prim) + { + float lod; + System.UInt64 newMeshKey = BSShape.ComputeShapeKey(prim.Size, prim.BaseShape, out lod); + + physicsScene.DetailLog("{0},BSShapeGImpact,getReference,newKey={1},size={2},lod={3}", + prim.LocalID, newMeshKey.ToString("X"), prim.Size, lod); + + BSShapeGImpact retGImpact = null; + lock (GImpacts) + { + if (GImpacts.TryGetValue(newMeshKey, out retGImpact)) + { + // The mesh has already been created. Return a new reference to same. + retGImpact.IncrementReference(); + } + else + { + retGImpact = new BSShapeGImpact(new BulletShape()); + BulletShape newShape = retGImpact.CreatePhysicalGImpact(physicsScene, prim, newMeshKey, prim.BaseShape, prim.Size, lod); + + // Check to see if mesh was created (might require an asset). + newShape = VerifyMeshCreated(physicsScene, newShape, prim); + if (!newShape.isNativeShape || prim.PrimAssetState == BSPhysObject.PrimAssetCondition.Failed) + { + // If a mesh was what was created, remember the built shape for later sharing. + // Also note that if meshing failed we put it in the mesh list as there is nothing else to do about the mesh. + GImpacts.Add(newMeshKey, retGImpact); + } + + retGImpact.physShapeInfo = newShape; + } + } + return retGImpact; + } + + private BulletShape CreatePhysicalGImpact(BSScene physicsScene, BSPhysObject prim, System.UInt64 newMeshKey, + PrimitiveBaseShape pbs, OMV.Vector3 size, float lod) + { + return BSShapeMesh.CreatePhysicalMeshShape(physicsScene, prim, newMeshKey, pbs, size, lod, + (w, iC, i, vC, v) => physicsScene.PE.CreateGImpactShape(w, iC, i, vC, v) ); + } + + public override BSShape GetReference(BSScene physicsScene, BSPhysObject prim) + { + // Calling this reference means we want another handle to an existing shape + // (usually linksets) so return this copy. + IncrementReference(); + return this; + } + // Dereferencing a compound shape releases the hold on all the child shapes. + public override void Dereference(BSScene physicsScene) + { + lock (GImpacts) + { + this.DecrementReference(); + physicsScene.DetailLog("{0},BSShapeGImpact.Dereference,shape={1}", BSScene.DetailLogZero, this); + // TODO: schedule aging and destruction of unused meshes. + } + } + // Loop through all the known hulls and return the description based on the physical address. + public static bool TryGetGImpactByPtr(BulletShape pShape, out BSShapeGImpact outHull) + { + bool ret = false; + BSShapeGImpact foundDesc = null; + lock (GImpacts) + { + foreach (BSShapeGImpact sh in GImpacts.Values) + { + if (sh.physShapeInfo.ReferenceSame(pShape)) + { + foundDesc = sh; + ret = true; + break; + } + + } + } + outHull = foundDesc; + return ret; + } +} // ============================================================================================================ public class BSShapeAvatar : BSShape -- cgit v1.1 From 2fd8819a043269f9308cb46c71893e6eb35a426e Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 21 May 2013 21:32:30 -0700 Subject: BulletSim: add code to experimentally use asset hull data. Default to 'off' as it needs debugging. --- OpenSim/Region/Physics/BulletSPlugin/BSParam.cs | 3 ++ OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs | 55 ++++++++++++++++++++++-- 2 files changed, 54 insertions(+), 4 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs index 9a9e527..5cff668 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs @@ -90,6 +90,7 @@ public static class BSParam public static bool ShouldUseBulletHACD { get; set; } public static bool ShouldUseSingleConvexHullForPrims { get; set; } public static bool ShouldUseGImpactShapeForPrims { get; set; } + public static bool ShouldUseAssetHulls { get; set; } public static float TerrainImplementation { get; set; } public static int TerrainMeshMagnification { get; private set; } @@ -372,6 +373,8 @@ public static class BSParam true ), new ParameterDefn("ShouldUseGImpactShapeForPrims", "If true, use a GImpact shape for prims with cuts and twists", false ), + new ParameterDefn("UseAssetHulls", "If true, use hull if specified in the mesh asset info", + false ), new ParameterDefn("CrossingFailuresBeforeOutOfBounds", "How forgiving we are about getting into adjactent regions", 5 ), diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs index 0152233..b7f7e6c 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs @@ -31,6 +31,7 @@ using System.Text; using OpenSim.Framework; using OpenSim.Region.Physics.Manager; +using OpenSim.Region.Physics.Meshing; using OpenSim.Region.Physics.ConvexDecompositionDotNet; using OMV = OpenMetaverse; @@ -573,9 +574,56 @@ public class BSShapeHull : BSShape PrimitiveBaseShape pbs, OMV.Vector3 size, float lod) { BulletShape newShape = new BulletShape(); - IntPtr hullPtr = IntPtr.Zero; + newShape.shapeKey = newHullKey; - if (BSParam.ShouldUseBulletHACD) + // Pass true for physicalness as this prevents the creation of bounding box which is not needed + IMesh meshData = physicsScene.mesher.CreateMesh(prim.PhysObjectName, pbs, size, lod, true /* isPhysical */, false /* shouldCache */); + + // If there is hull data in the mesh asset, build the hull from that + if (meshData != null && BSParam.ShouldUseAssetHulls) + { + Meshmerizer realMesher = physicsScene.mesher as Meshmerizer; + if (realMesher != null) + { + List> allHulls = realMesher.GetConvexHulls(size); + if (allHulls != null) + { + int hullCount = allHulls.Count; + int totalVertices = 1; // include one for the count of the hulls + // Using the structure described for HACD hulls, create the memory sturcture + // to pass the hull data to the creater. + foreach (List hullVerts in allHulls) + { + totalVertices += 4; // add four for the vertex count and centroid + totalVertices += hullVerts.Count * 3; // one vertex is three dimensions + } + float[] convHulls = new float[totalVertices]; + + convHulls[0] = (float)hullCount; + int jj = 1; + foreach (List hullVerts in allHulls) + { + convHulls[jj + 0] = hullVerts.Count; + convHulls[jj + 1] = 0f; // centroid x,y,z + convHulls[jj + 2] = 0f; + convHulls[jj + 3] = 0f; + jj += 4; + foreach (OMV.Vector3 oneVert in hullVerts) + { + convHulls[jj + 0] = oneVert.X; + convHulls[jj + 1] = oneVert.Y; + convHulls[jj + 2] = oneVert.Z; + jj += 3; + } + } + + // create the hull data structure in Bullet + newShape = physicsScene.PE.CreateHullShape(physicsScene.World, hullCount, convHulls); + } + } + } + // If no hull specified in the asset and we should use Bullet's HACD approximation... + if (!newShape.HasPhysicalShape && BSParam.ShouldUseBulletHACD) { // Build the hull shape from an existing mesh shape. // The mesh should have already been created in Bullet. @@ -604,11 +652,10 @@ public class BSShapeHull : BSShape } physicsScene.DetailLog("{0},BSShapeHull.CreatePhysicalHull,shouldUseBulletHACD,exit,hasBody={1}", prim.LocalID, newShape.HasPhysicalShape); } + // If no hull specified, use our HACD hull approximation. if (!newShape.HasPhysicalShape) { // Build a new hull in the physical world using the C# HACD algorigthm. - // Pass true for physicalness as this prevents the creation of bounding box which is not needed - IMesh meshData = physicsScene.mesher.CreateMesh(prim.PhysObjectName, pbs, size, lod, true /* isPhysical */, false /* shouldCache */); if (meshData != null) { if (prim.PrimAssetState == BSPhysObject.PrimAssetCondition.Fetched) -- cgit v1.1 From 6596a1de806d1ec509f3a570a0944ab9aff5947c Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 21 May 2013 22:16:18 -0700 Subject: Revert "BulletSim: add code to experimentally use asset hull data." This reverts commit 2fd8819a043269f9308cb46c71893e6eb35a426e. Remove this code until I can figure out why the references that are clearly in prebuild.xml doesn't work for the 'using OpenSim.Region.Physics.Meshing' in BSShape.cs. --- OpenSim/Region/Physics/BulletSPlugin/BSParam.cs | 3 -- OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs | 55 ++---------------------- 2 files changed, 4 insertions(+), 54 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs index 5cff668..9a9e527 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs @@ -90,7 +90,6 @@ public static class BSParam public static bool ShouldUseBulletHACD { get; set; } public static bool ShouldUseSingleConvexHullForPrims { get; set; } public static bool ShouldUseGImpactShapeForPrims { get; set; } - public static bool ShouldUseAssetHulls { get; set; } public static float TerrainImplementation { get; set; } public static int TerrainMeshMagnification { get; private set; } @@ -373,8 +372,6 @@ public static class BSParam true ), new ParameterDefn("ShouldUseGImpactShapeForPrims", "If true, use a GImpact shape for prims with cuts and twists", false ), - new ParameterDefn("UseAssetHulls", "If true, use hull if specified in the mesh asset info", - false ), new ParameterDefn("CrossingFailuresBeforeOutOfBounds", "How forgiving we are about getting into adjactent regions", 5 ), diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs index b7f7e6c..0152233 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs @@ -31,7 +31,6 @@ using System.Text; using OpenSim.Framework; using OpenSim.Region.Physics.Manager; -using OpenSim.Region.Physics.Meshing; using OpenSim.Region.Physics.ConvexDecompositionDotNet; using OMV = OpenMetaverse; @@ -574,56 +573,9 @@ public class BSShapeHull : BSShape PrimitiveBaseShape pbs, OMV.Vector3 size, float lod) { BulletShape newShape = new BulletShape(); - newShape.shapeKey = newHullKey; + IntPtr hullPtr = IntPtr.Zero; - // Pass true for physicalness as this prevents the creation of bounding box which is not needed - IMesh meshData = physicsScene.mesher.CreateMesh(prim.PhysObjectName, pbs, size, lod, true /* isPhysical */, false /* shouldCache */); - - // If there is hull data in the mesh asset, build the hull from that - if (meshData != null && BSParam.ShouldUseAssetHulls) - { - Meshmerizer realMesher = physicsScene.mesher as Meshmerizer; - if (realMesher != null) - { - List> allHulls = realMesher.GetConvexHulls(size); - if (allHulls != null) - { - int hullCount = allHulls.Count; - int totalVertices = 1; // include one for the count of the hulls - // Using the structure described for HACD hulls, create the memory sturcture - // to pass the hull data to the creater. - foreach (List hullVerts in allHulls) - { - totalVertices += 4; // add four for the vertex count and centroid - totalVertices += hullVerts.Count * 3; // one vertex is three dimensions - } - float[] convHulls = new float[totalVertices]; - - convHulls[0] = (float)hullCount; - int jj = 1; - foreach (List hullVerts in allHulls) - { - convHulls[jj + 0] = hullVerts.Count; - convHulls[jj + 1] = 0f; // centroid x,y,z - convHulls[jj + 2] = 0f; - convHulls[jj + 3] = 0f; - jj += 4; - foreach (OMV.Vector3 oneVert in hullVerts) - { - convHulls[jj + 0] = oneVert.X; - convHulls[jj + 1] = oneVert.Y; - convHulls[jj + 2] = oneVert.Z; - jj += 3; - } - } - - // create the hull data structure in Bullet - newShape = physicsScene.PE.CreateHullShape(physicsScene.World, hullCount, convHulls); - } - } - } - // If no hull specified in the asset and we should use Bullet's HACD approximation... - if (!newShape.HasPhysicalShape && BSParam.ShouldUseBulletHACD) + if (BSParam.ShouldUseBulletHACD) { // Build the hull shape from an existing mesh shape. // The mesh should have already been created in Bullet. @@ -652,10 +604,11 @@ public class BSShapeHull : BSShape } physicsScene.DetailLog("{0},BSShapeHull.CreatePhysicalHull,shouldUseBulletHACD,exit,hasBody={1}", prim.LocalID, newShape.HasPhysicalShape); } - // If no hull specified, use our HACD hull approximation. if (!newShape.HasPhysicalShape) { // Build a new hull in the physical world using the C# HACD algorigthm. + // Pass true for physicalness as this prevents the creation of bounding box which is not needed + IMesh meshData = physicsScene.mesher.CreateMesh(prim.PhysObjectName, pbs, size, lod, true /* isPhysical */, false /* shouldCache */); if (meshData != null) { if (prim.PrimAssetState == BSPhysObject.PrimAssetCondition.Fetched) -- cgit v1.1 From 61cdf9390d8dc124b0ef3afabb5bcb63328686eb Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Wed, 22 May 2013 16:06:06 -0700 Subject: BulletSim: fix problem with walking up stairs that are oriented in certain directions. The problem was really that the avatar capsule orientation was being set incorrectly. --- OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index ff5b6ab..48f842e 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -483,8 +483,15 @@ public sealed class BSCharacter : BSPhysObject { // Bullet assumes we know what we are doing when forcing orientation // so it lets us go against all the rules and just compensates for them later. - // This keeps us from flipping the capsule over which the veiwer does not understand. - ForceOrientation = new OMV.Quaternion(0, 0, _orientation.Z,0); + // This forces rotation to be only around the Z axis and doesn't change any of the other axis. + // This keeps us from flipping the capsule over which the veiwer does not understand. + float oRoll, oPitch, oYaw; + _orientation.GetEulerAngles(out oRoll, out oPitch, out oYaw); + OMV.Quaternion trimmedOrientation = OMV.Quaternion.CreateFromEulers(0f, 0f, oYaw); + // DetailLog("{0},BSCharacter.setOrientation,taint,val={1},valDir={2},conv={3},convDir={4}", + // LocalID, _orientation, OMV.Vector3.UnitX * _orientation, + // trimmedOrientation, OMV.Vector3.UnitX * trimmedOrientation); + ForceOrientation = trimmedOrientation; }); } } -- cgit v1.1 From ffc9b3dda766c15e053b9296d15356533f7e99f8 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 21 May 2013 21:32:30 -0700 Subject: BulletSim: add code to experimentally use asset hull data. Default to 'off' as it needs debugging. --- OpenSim/Region/Physics/BulletSPlugin/BSParam.cs | 3 ++ OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs | 55 ++++++++++++++++++++++-- 2 files changed, 54 insertions(+), 4 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs index 9a9e527..5cff668 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs @@ -90,6 +90,7 @@ public static class BSParam public static bool ShouldUseBulletHACD { get; set; } public static bool ShouldUseSingleConvexHullForPrims { get; set; } public static bool ShouldUseGImpactShapeForPrims { get; set; } + public static bool ShouldUseAssetHulls { get; set; } public static float TerrainImplementation { get; set; } public static int TerrainMeshMagnification { get; private set; } @@ -372,6 +373,8 @@ public static class BSParam true ), new ParameterDefn("ShouldUseGImpactShapeForPrims", "If true, use a GImpact shape for prims with cuts and twists", false ), + new ParameterDefn("UseAssetHulls", "If true, use hull if specified in the mesh asset info", + false ), new ParameterDefn("CrossingFailuresBeforeOutOfBounds", "How forgiving we are about getting into adjactent regions", 5 ), diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs index 0152233..b7f7e6c 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs @@ -31,6 +31,7 @@ using System.Text; using OpenSim.Framework; using OpenSim.Region.Physics.Manager; +using OpenSim.Region.Physics.Meshing; using OpenSim.Region.Physics.ConvexDecompositionDotNet; using OMV = OpenMetaverse; @@ -573,9 +574,56 @@ public class BSShapeHull : BSShape PrimitiveBaseShape pbs, OMV.Vector3 size, float lod) { BulletShape newShape = new BulletShape(); - IntPtr hullPtr = IntPtr.Zero; + newShape.shapeKey = newHullKey; - if (BSParam.ShouldUseBulletHACD) + // Pass true for physicalness as this prevents the creation of bounding box which is not needed + IMesh meshData = physicsScene.mesher.CreateMesh(prim.PhysObjectName, pbs, size, lod, true /* isPhysical */, false /* shouldCache */); + + // If there is hull data in the mesh asset, build the hull from that + if (meshData != null && BSParam.ShouldUseAssetHulls) + { + Meshmerizer realMesher = physicsScene.mesher as Meshmerizer; + if (realMesher != null) + { + List> allHulls = realMesher.GetConvexHulls(size); + if (allHulls != null) + { + int hullCount = allHulls.Count; + int totalVertices = 1; // include one for the count of the hulls + // Using the structure described for HACD hulls, create the memory sturcture + // to pass the hull data to the creater. + foreach (List hullVerts in allHulls) + { + totalVertices += 4; // add four for the vertex count and centroid + totalVertices += hullVerts.Count * 3; // one vertex is three dimensions + } + float[] convHulls = new float[totalVertices]; + + convHulls[0] = (float)hullCount; + int jj = 1; + foreach (List hullVerts in allHulls) + { + convHulls[jj + 0] = hullVerts.Count; + convHulls[jj + 1] = 0f; // centroid x,y,z + convHulls[jj + 2] = 0f; + convHulls[jj + 3] = 0f; + jj += 4; + foreach (OMV.Vector3 oneVert in hullVerts) + { + convHulls[jj + 0] = oneVert.X; + convHulls[jj + 1] = oneVert.Y; + convHulls[jj + 2] = oneVert.Z; + jj += 3; + } + } + + // create the hull data structure in Bullet + newShape = physicsScene.PE.CreateHullShape(physicsScene.World, hullCount, convHulls); + } + } + } + // If no hull specified in the asset and we should use Bullet's HACD approximation... + if (!newShape.HasPhysicalShape && BSParam.ShouldUseBulletHACD) { // Build the hull shape from an existing mesh shape. // The mesh should have already been created in Bullet. @@ -604,11 +652,10 @@ public class BSShapeHull : BSShape } physicsScene.DetailLog("{0},BSShapeHull.CreatePhysicalHull,shouldUseBulletHACD,exit,hasBody={1}", prim.LocalID, newShape.HasPhysicalShape); } + // If no hull specified, use our HACD hull approximation. if (!newShape.HasPhysicalShape) { // Build a new hull in the physical world using the C# HACD algorigthm. - // Pass true for physicalness as this prevents the creation of bounding box which is not needed - IMesh meshData = physicsScene.mesher.CreateMesh(prim.PhysObjectName, pbs, size, lod, true /* isPhysical */, false /* shouldCache */); if (meshData != null) { if (prim.PrimAssetState == BSPhysObject.PrimAssetCondition.Fetched) -- cgit v1.1 From 5efce21abc92fa1005fa8651a5622fe72cf83ff3 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Wed, 22 May 2013 21:57:07 -0700 Subject: BulletSim: correct errors caused by misspelled INI parameter spec. Add debugging messages for hull asset use. --- OpenSim/Region/Physics/BulletSPlugin/BSParam.cs | 2 +- OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs | 9 ++++++--- 2 files changed, 7 insertions(+), 4 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs index 5cff668..c19eda1 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs @@ -373,7 +373,7 @@ public static class BSParam true ), new ParameterDefn("ShouldUseGImpactShapeForPrims", "If true, use a GImpact shape for prims with cuts and twists", false ), - new ParameterDefn("UseAssetHulls", "If true, use hull if specified in the mesh asset info", + new ParameterDefn("ShouldUseAssetHulls", "If true, use hull if specified in the mesh asset info", false ), new ParameterDefn("CrossingFailuresBeforeOutOfBounds", "How forgiving we are about getting into adjactent regions", diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs index b7f7e6c..6729d6b 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs @@ -619,6 +619,9 @@ public class BSShapeHull : BSShape // create the hull data structure in Bullet newShape = physicsScene.PE.CreateHullShape(physicsScene.World, hullCount, convHulls); + + physicsScene.DetailLog("{0},BSShapeHull.CreatePhysicalHull,assetHulls,hulls={1},totVert={2},shape={3}", + prim.LocalID, hullCount, totalVertices, newShape); } } } @@ -627,7 +630,7 @@ public class BSShapeHull : BSShape { // Build the hull shape from an existing mesh shape. // The mesh should have already been created in Bullet. - physicsScene.DetailLog("{0},BSShapeHull.CreatePhysicalHull,shouldUseBulletHACD,entry", prim.LocalID); + physicsScene.DetailLog("{0},BSShapeHull.CreatePhysicalHull,bulletHACD,entry", prim.LocalID); BSShape meshShape = BSShapeMesh.GetReference(physicsScene, true, prim); if (meshShape.physShapeInfo.HasPhysicalShape) @@ -645,12 +648,12 @@ public class BSShapeHull : BSShape physicsScene.DetailLog("{0},BSShapeHull.CreatePhysicalHull,hullFromMesh,beforeCall", prim.LocalID, newShape.HasPhysicalShape); newShape = physicsScene.PE.BuildHullShapeFromMesh(physicsScene.World, meshShape.physShapeInfo, parms); - physicsScene.DetailLog("{0},BSShapeHull.CreatePhysicalHull,hullFromMesh,hasBody={1}", prim.LocalID, newShape.HasPhysicalShape); + physicsScene.DetailLog("{0},BSShapeHull.CreatePhysicalHull,hullFromMesh,shape={1}", prim.LocalID, newShape); // Now done with the mesh shape. meshShape.Dereference(physicsScene); } - physicsScene.DetailLog("{0},BSShapeHull.CreatePhysicalHull,shouldUseBulletHACD,exit,hasBody={1}", prim.LocalID, newShape.HasPhysicalShape); + physicsScene.DetailLog("{0},BSShapeHull.CreatePhysicalHull,bulletHACD,exit,hasBody={1}", prim.LocalID, newShape.HasPhysicalShape); } // If no hull specified, use our HACD hull approximation. if (!newShape.HasPhysicalShape) -- cgit v1.1 From 29b3b44fab46a44f911e582ab284025086cf3692 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Thu, 23 May 2013 14:40:16 -0700 Subject: BulletSim: add locking around Meshmerizer use to eliminate possible race condition when extracting the convex hulls. --- OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs | 302 ++++++++++++----------- 1 file changed, 157 insertions(+), 145 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs index 6729d6b..48f1394 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs @@ -441,10 +441,14 @@ public class BSShapeMesh : BSShape { BulletShape newShape = new BulletShape(); - IMesh meshData = physicsScene.mesher.CreateMesh(prim.PhysObjectName, pbs, size, lod, - false, // say it is not physical so a bounding box is not built - false // do not cache the mesh and do not use previously built versions - ); + IMesh meshData = null; + lock (physicsScene.mesher) + { + meshData = physicsScene.mesher.CreateMesh(prim.PhysObjectName, pbs, size, lod, + false, // say it is not physical so a bounding box is not built + false // do not cache the mesh and do not use previously built versions + ); + } if (meshData != null) { @@ -576,55 +580,67 @@ public class BSShapeHull : BSShape BulletShape newShape = new BulletShape(); newShape.shapeKey = newHullKey; - // Pass true for physicalness as this prevents the creation of bounding box which is not needed - IMesh meshData = physicsScene.mesher.CreateMesh(prim.PhysObjectName, pbs, size, lod, true /* isPhysical */, false /* shouldCache */); - - // If there is hull data in the mesh asset, build the hull from that - if (meshData != null && BSParam.ShouldUseAssetHulls) + IMesh meshData = null; + List> allHulls = null; + lock (physicsScene.mesher) { - Meshmerizer realMesher = physicsScene.mesher as Meshmerizer; - if (realMesher != null) + // Pass true for physicalness as this prevents the creation of bounding box which is not needed + meshData = physicsScene.mesher.CreateMesh(prim.PhysObjectName, pbs, size, lod, true /* isPhysical */, false /* shouldCache */); + + // If we should use the asset's hull info, fetch it out of the locked mesher + if (meshData != null && BSParam.ShouldUseAssetHulls) { - List> allHulls = realMesher.GetConvexHulls(size); - if (allHulls != null) + Meshmerizer realMesher = physicsScene.mesher as Meshmerizer; + if (realMesher != null) { - int hullCount = allHulls.Count; - int totalVertices = 1; // include one for the count of the hulls - // Using the structure described for HACD hulls, create the memory sturcture - // to pass the hull data to the creater. - foreach (List hullVerts in allHulls) - { - totalVertices += 4; // add four for the vertex count and centroid - totalVertices += hullVerts.Count * 3; // one vertex is three dimensions - } - float[] convHulls = new float[totalVertices]; - - convHulls[0] = (float)hullCount; - int jj = 1; - foreach (List hullVerts in allHulls) - { - convHulls[jj + 0] = hullVerts.Count; - convHulls[jj + 1] = 0f; // centroid x,y,z - convHulls[jj + 2] = 0f; - convHulls[jj + 3] = 0f; - jj += 4; - foreach (OMV.Vector3 oneVert in hullVerts) - { - convHulls[jj + 0] = oneVert.X; - convHulls[jj + 1] = oneVert.Y; - convHulls[jj + 2] = oneVert.Z; - jj += 3; - } - } + allHulls = realMesher.GetConvexHulls(size); + } + if (allHulls == null) + { + physicsScene.DetailLog("{0},BSShapeHull.CreatePhysicalHull,assetHulls,noAssetHull", prim.LocalID); + } + } + } - // create the hull data structure in Bullet - newShape = physicsScene.PE.CreateHullShape(physicsScene.World, hullCount, convHulls); + // If there is hull data in the mesh asset, build the hull from that + if (allHulls != null && BSParam.ShouldUseAssetHulls) + { + int hullCount = allHulls.Count; + int totalVertices = 1; // include one for the count of the hulls + // Using the structure described for HACD hulls, create the memory sturcture + // to pass the hull data to the creater. + foreach (List hullVerts in allHulls) + { + totalVertices += 4; // add four for the vertex count and centroid + totalVertices += hullVerts.Count * 3; // one vertex is three dimensions + } + float[] convHulls = new float[totalVertices]; - physicsScene.DetailLog("{0},BSShapeHull.CreatePhysicalHull,assetHulls,hulls={1},totVert={2},shape={3}", - prim.LocalID, hullCount, totalVertices, newShape); + convHulls[0] = (float)hullCount; + int jj = 1; + foreach (List hullVerts in allHulls) + { + convHulls[jj + 0] = hullVerts.Count; + convHulls[jj + 1] = 0f; // centroid x,y,z + convHulls[jj + 2] = 0f; + convHulls[jj + 3] = 0f; + jj += 4; + foreach (OMV.Vector3 oneVert in hullVerts) + { + convHulls[jj + 0] = oneVert.X; + convHulls[jj + 1] = oneVert.Y; + convHulls[jj + 2] = oneVert.Z; + jj += 3; } } + + // create the hull data structure in Bullet + newShape = physicsScene.PE.CreateHullShape(physicsScene.World, hullCount, convHulls); + + physicsScene.DetailLog("{0},BSShapeHull.CreatePhysicalHull,assetHulls,hulls={1},totVert={2},shape={3}", + prim.LocalID, hullCount, totalVertices, newShape); } + // If no hull specified in the asset and we should use Bullet's HACD approximation... if (!newShape.HasPhysicalShape && BSParam.ShouldUseBulletHACD) { @@ -655,120 +671,116 @@ public class BSShapeHull : BSShape } physicsScene.DetailLog("{0},BSShapeHull.CreatePhysicalHull,bulletHACD,exit,hasBody={1}", prim.LocalID, newShape.HasPhysicalShape); } - // If no hull specified, use our HACD hull approximation. - if (!newShape.HasPhysicalShape) + + // If no other hull specifications, use our HACD hull approximation. + if (!newShape.HasPhysicalShape && meshData != null) { - // Build a new hull in the physical world using the C# HACD algorigthm. - if (meshData != null) + if (prim.PrimAssetState == BSPhysObject.PrimAssetCondition.Fetched) { - if (prim.PrimAssetState == BSPhysObject.PrimAssetCondition.Fetched) - { - // Release the fetched asset data once it has been used. - pbs.SculptData = new byte[0]; - prim.PrimAssetState = BSPhysObject.PrimAssetCondition.Unknown; - } + // Release the fetched asset data once it has been used. + pbs.SculptData = new byte[0]; + prim.PrimAssetState = BSPhysObject.PrimAssetCondition.Unknown; + } - int[] indices = meshData.getIndexListAsInt(); - List vertices = meshData.getVertexList(); + int[] indices = meshData.getIndexListAsInt(); + List vertices = meshData.getVertexList(); - //format conversion from IMesh format to DecompDesc format - List convIndices = new List(); - List convVertices = new List(); - for (int ii = 0; ii < indices.GetLength(0); ii++) - { - convIndices.Add(indices[ii]); - } - foreach (OMV.Vector3 vv in vertices) - { - convVertices.Add(new float3(vv.X, vv.Y, vv.Z)); - } + //format conversion from IMesh format to DecompDesc format + List convIndices = new List(); + List convVertices = new List(); + for (int ii = 0; ii < indices.GetLength(0); ii++) + { + convIndices.Add(indices[ii]); + } + foreach (OMV.Vector3 vv in vertices) + { + convVertices.Add(new float3(vv.X, vv.Y, vv.Z)); + } - uint maxDepthSplit = (uint)BSParam.CSHullMaxDepthSplit; - if (BSParam.CSHullMaxDepthSplit != BSParam.CSHullMaxDepthSplitForSimpleShapes) + uint maxDepthSplit = (uint)BSParam.CSHullMaxDepthSplit; + if (BSParam.CSHullMaxDepthSplit != BSParam.CSHullMaxDepthSplitForSimpleShapes) + { + // Simple primitive shapes we know are convex so they are better implemented with + // fewer hulls. + // Check for simple shape (prim without cuts) and reduce split parameter if so. + if (BSShapeCollection.PrimHasNoCuts(pbs)) { - // Simple primitive shapes we know are convex so they are better implemented with - // fewer hulls. - // Check for simple shape (prim without cuts) and reduce split parameter if so. - if (BSShapeCollection.PrimHasNoCuts(pbs)) - { - maxDepthSplit = (uint)BSParam.CSHullMaxDepthSplitForSimpleShapes; - } + maxDepthSplit = (uint)BSParam.CSHullMaxDepthSplitForSimpleShapes; } + } + + // setup and do convex hull conversion + m_hulls = new List(); + DecompDesc dcomp = new DecompDesc(); + dcomp.mIndices = convIndices; + dcomp.mVertices = convVertices; + dcomp.mDepth = maxDepthSplit; + dcomp.mCpercent = BSParam.CSHullConcavityThresholdPercent; + dcomp.mPpercent = BSParam.CSHullVolumeConservationThresholdPercent; + dcomp.mMaxVertices = (uint)BSParam.CSHullMaxVertices; + dcomp.mSkinWidth = BSParam.CSHullMaxSkinWidth; + ConvexBuilder convexBuilder = new ConvexBuilder(HullReturn); + // create the hull into the _hulls variable + convexBuilder.process(dcomp); + + physicsScene.DetailLog("{0},BSShapeCollection.CreatePhysicalHull,key={1},inVert={2},inInd={3},split={4},hulls={5}", + BSScene.DetailLogZero, newHullKey, indices.GetLength(0), vertices.Count, maxDepthSplit, m_hulls.Count); + + // Convert the vertices and indices for passing to unmanaged. + // The hull information is passed as a large floating point array. + // The format is: + // convHulls[0] = number of hulls + // convHulls[1] = number of vertices in first hull + // convHulls[2] = hull centroid X coordinate + // convHulls[3] = hull centroid Y coordinate + // convHulls[4] = hull centroid Z coordinate + // convHulls[5] = first hull vertex X + // convHulls[6] = first hull vertex Y + // convHulls[7] = first hull vertex Z + // convHulls[8] = second hull vertex X + // ... + // convHulls[n] = number of vertices in second hull + // convHulls[n+1] = second hull centroid X coordinate + // ... + // + // TODO: is is very inefficient. Someday change the convex hull generator to return + // data structures that do not need to be converted in order to pass to Bullet. + // And maybe put the values directly into pinned memory rather than marshaling. + int hullCount = m_hulls.Count; + int totalVertices = 1; // include one for the count of the hulls + foreach (ConvexResult cr in m_hulls) + { + totalVertices += 4; // add four for the vertex count and centroid + totalVertices += cr.HullIndices.Count * 3; // we pass just triangles + } + float[] convHulls = new float[totalVertices]; - // setup and do convex hull conversion - m_hulls = new List(); - DecompDesc dcomp = new DecompDesc(); - dcomp.mIndices = convIndices; - dcomp.mVertices = convVertices; - dcomp.mDepth = maxDepthSplit; - dcomp.mCpercent = BSParam.CSHullConcavityThresholdPercent; - dcomp.mPpercent = BSParam.CSHullVolumeConservationThresholdPercent; - dcomp.mMaxVertices = (uint)BSParam.CSHullMaxVertices; - dcomp.mSkinWidth = BSParam.CSHullMaxSkinWidth; - ConvexBuilder convexBuilder = new ConvexBuilder(HullReturn); - // create the hull into the _hulls variable - convexBuilder.process(dcomp); - - physicsScene.DetailLog("{0},BSShapeCollection.CreatePhysicalHull,key={1},inVert={2},inInd={3},split={4},hulls={5}", - BSScene.DetailLogZero, newHullKey, indices.GetLength(0), vertices.Count, maxDepthSplit, m_hulls.Count); - - // Convert the vertices and indices for passing to unmanaged. - // The hull information is passed as a large floating point array. - // The format is: - // convHulls[0] = number of hulls - // convHulls[1] = number of vertices in first hull - // convHulls[2] = hull centroid X coordinate - // convHulls[3] = hull centroid Y coordinate - // convHulls[4] = hull centroid Z coordinate - // convHulls[5] = first hull vertex X - // convHulls[6] = first hull vertex Y - // convHulls[7] = first hull vertex Z - // convHulls[8] = second hull vertex X - // ... - // convHulls[n] = number of vertices in second hull - // convHulls[n+1] = second hull centroid X coordinate - // ... - // - // TODO: is is very inefficient. Someday change the convex hull generator to return - // data structures that do not need to be converted in order to pass to Bullet. - // And maybe put the values directly into pinned memory rather than marshaling. - int hullCount = m_hulls.Count; - int totalVertices = 1; // include one for the count of the hulls - foreach (ConvexResult cr in m_hulls) + convHulls[0] = (float)hullCount; + int jj = 1; + foreach (ConvexResult cr in m_hulls) + { + // copy vertices for index access + float3[] verts = new float3[cr.HullVertices.Count]; + int kk = 0; + foreach (float3 ff in cr.HullVertices) { - totalVertices += 4; // add four for the vertex count and centroid - totalVertices += cr.HullIndices.Count * 3; // we pass just triangles + verts[kk++] = ff; } - float[] convHulls = new float[totalVertices]; - convHulls[0] = (float)hullCount; - int jj = 1; - foreach (ConvexResult cr in m_hulls) + // add to the array one hull's worth of data + convHulls[jj++] = cr.HullIndices.Count; + convHulls[jj++] = 0f; // centroid x,y,z + convHulls[jj++] = 0f; + convHulls[jj++] = 0f; + foreach (int ind in cr.HullIndices) { - // copy vertices for index access - float3[] verts = new float3[cr.HullVertices.Count]; - int kk = 0; - foreach (float3 ff in cr.HullVertices) - { - verts[kk++] = ff; - } - - // add to the array one hull's worth of data - convHulls[jj++] = cr.HullIndices.Count; - convHulls[jj++] = 0f; // centroid x,y,z - convHulls[jj++] = 0f; - convHulls[jj++] = 0f; - foreach (int ind in cr.HullIndices) - { - convHulls[jj++] = verts[ind].x; - convHulls[jj++] = verts[ind].y; - convHulls[jj++] = verts[ind].z; - } + convHulls[jj++] = verts[ind].x; + convHulls[jj++] = verts[ind].y; + convHulls[jj++] = verts[ind].z; } - // create the hull data structure in Bullet - newShape = physicsScene.PE.CreateHullShape(physicsScene.World, hullCount, convHulls); } - newShape.shapeKey = newHullKey; + // create the hull data structure in Bullet + newShape = physicsScene.PE.CreateHullShape(physicsScene.World, hullCount, convHulls); } return newShape; } -- cgit v1.1 From 0e002e369339719204f26c07157713bfc40fecca Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Thu, 23 May 2013 14:41:05 -0700 Subject: Add DEBUG level logging in Meshmerizer for mesh parsing. There is a compile time variable to turn this logging off if it is too spammy. --- OpenSim/Region/Physics/Meshing/Meshmerizer.cs | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/Meshing/Meshmerizer.cs b/OpenSim/Region/Physics/Meshing/Meshmerizer.cs index 79edc12..adc0dc9 100644 --- a/OpenSim/Region/Physics/Meshing/Meshmerizer.cs +++ b/OpenSim/Region/Physics/Meshing/Meshmerizer.cs @@ -64,6 +64,7 @@ namespace OpenSim.Region.Physics.Meshing public class Meshmerizer : IMesher { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + private static string LogHeader = "[MESH]"; // Setting baseDir to a path will enable the dumping of raw files // raw files can be imported by blender so a visual inspection of the results can be done @@ -72,6 +73,8 @@ namespace OpenSim.Region.Physics.Meshing #else private const string baseDir = null; //"rawFiles"; #endif + // If 'true', lots of DEBUG logging of asset parsing details + private bool debugDetail = true; private bool cacheSculptMaps = true; private string decodedSculptMapPath = null; @@ -357,13 +360,25 @@ namespace OpenSim.Region.Physics.Meshing OSDMap physicsParms = null; OSDMap map = (OSDMap)meshOsd; if (map.ContainsKey("physics_shape")) + { physicsParms = (OSDMap)map["physics_shape"]; // old asset format + if (debugDetail) m_log.DebugFormat("{0} prim='{1}': using 'physics_shape' mesh data", LogHeader, primName); + } else if (map.ContainsKey("physics_mesh")) + { physicsParms = (OSDMap)map["physics_mesh"]; // new asset format + if (debugDetail) m_log.DebugFormat("{0} prim='{1}':using 'physics_mesh' mesh data", LogHeader, primName); + } else if (map.ContainsKey("medium_lod")) + { physicsParms = (OSDMap)map["medium_lod"]; // if no physics mesh, try to fall back to medium LOD display mesh + if (debugDetail) m_log.DebugFormat("{0} prim='{1}':using 'medium_lod' mesh data", LogHeader, primName); + } else if (map.ContainsKey("high_lod")) + { physicsParms = (OSDMap)map["high_lod"]; // if all else fails, use highest LOD display mesh and hope it works :) + if (debugDetail) m_log.DebugFormat("{0} prim='{1}':using 'high_lod' mesh data", LogHeader, primName); + } if (map.ContainsKey("physics_convex")) { // pull this out also in case physics engine can use it @@ -408,11 +423,16 @@ namespace OpenSim.Region.Physics.Meshing } mConvexHulls = hulls; + if (debugDetail) m_log.DebugFormat("{0} prim='{1}': parsed hulls. nHulls={2}", LogHeader, primName, mConvexHulls.Count); + } + else + { + if (debugDetail) m_log.DebugFormat("{0} prim='{1}' has physics_convex but no HullList", LogHeader, primName); } } catch (Exception e) { - m_log.WarnFormat("[MESH]: exception decoding convex block: {0}", e.Message); + m_log.WarnFormat("{0} exception decoding convex block: {1}", LogHeader, e); } } @@ -438,7 +458,7 @@ namespace OpenSim.Region.Physics.Meshing } catch (Exception e) { - m_log.Error("[MESH]: exception decoding physical mesh: " + e.ToString()); + m_log.ErrorFormat("{0} prim='{1}': exception decoding physical mesh: {2}", LogHeader, primName, e); return false; } @@ -455,6 +475,9 @@ namespace OpenSim.Region.Physics.Meshing if (subMeshOsd is OSDMap) AddSubMesh(subMeshOsd as OSDMap, size, coords, faces); } + if (debugDetail) + m_log.DebugFormat("{0} {1}: mesh decoded. offset={2}, size={3}, nCoords={4}, nFaces={5}", + LogHeader, primName, physOffset, physSize, coords.Count, faces.Count); } } -- cgit v1.1 From c5549d27306c71cd5ed96e7cba68bd28d5e6d9b0 Mon Sep 17 00:00:00 2001 From: dahlia Date: Thu, 23 May 2013 15:47:47 -0700 Subject: add decoder for bounding convex hull --- OpenSim/Region/Physics/Meshing/Meshmerizer.cs | 57 +++++++++++++++++++++++++-- 1 file changed, 53 insertions(+), 4 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/Meshing/Meshmerizer.cs b/OpenSim/Region/Physics/Meshing/Meshmerizer.cs index adc0dc9..fd45efe 100644 --- a/OpenSim/Region/Physics/Meshing/Meshmerizer.cs +++ b/OpenSim/Region/Physics/Meshing/Meshmerizer.cs @@ -83,6 +83,7 @@ namespace OpenSim.Region.Physics.Meshing private float minSizeForComplexMesh = 0.2f; // prims with all dimensions smaller than this will have a bounding box mesh private List> mConvexHulls = null; + private List mBoundingHull = null; private Dictionary m_uniqueMeshes = new Dictionary(); @@ -324,6 +325,9 @@ namespace OpenSim.Region.Physics.Meshing faces = new List(); OSD meshOsd = null; + mConvexHulls = null; + mBoundingHull = null; + if (primShape.SculptData.Length <= 0) { // XXX: At the moment we can not log here since ODEPrim, for instance, ends up triggering this @@ -385,13 +389,41 @@ namespace OpenSim.Region.Physics.Meshing try { OSDMap convexBlock = (OSDMap)map["physics_convex"]; + + Vector3 min = new Vector3(-0.5f, -0.5f, -0.5f); + if (convexBlock.ContainsKey("Min")) min = convexBlock["Min"].AsVector3(); + Vector3 max = new Vector3(0.5f, 0.5f, 0.5f); + if (convexBlock.ContainsKey("Max")) max = convexBlock["Max"].AsVector3(); + + List boundingHull = null; + + if (convexBlock.ContainsKey("BoundingVerts")) + { + // decompress and decode bounding hull points + byte[] boundingVertsBytes = DecompressOsd(convexBlock["BoundingVerts"].AsBinary()).AsBinary(); + boundingHull = new List(); + for (int i = 0; i < boundingVertsBytes.Length;) + { + ushort uX = Utils.BytesToUInt16(boundingVertsBytes, i); i += 2; + ushort uY = Utils.BytesToUInt16(boundingVertsBytes, i); i += 2; + ushort uZ = Utils.BytesToUInt16(boundingVertsBytes, i); i += 2; + + Vector3 pos = new Vector3( + Utils.UInt16ToFloat(uX, min.X, max.X), + Utils.UInt16ToFloat(uY, min.Y, max.Y), + Utils.UInt16ToFloat(uZ, min.Z, max.Z) + ); + + boundingHull.Add(pos); + } + + mBoundingHull = boundingHull; + if (debugDetail) m_log.DebugFormat("{0} prim='{1}': parsed bounding hull. nHulls={2}", LogHeader, primName, mBoundingHull.Count); + } + if (convexBlock.ContainsKey("HullList")) { byte[] hullList = convexBlock["HullList"].AsBinary(); - Vector3 min = new Vector3(-0.5f, -0.5f, -0.5f); - if (convexBlock.ContainsKey("Min")) min = convexBlock["Min"].AsVector3(); - Vector3 max = new Vector3(0.5f, 0.5f, 0.5f); - if (convexBlock.ContainsKey("Max")) max = convexBlock["Max"].AsVector3(); // decompress and decode hull points byte[] posBytes = DecompressOsd(convexBlock["Positions"].AsBinary()).AsBinary(); @@ -799,6 +831,23 @@ namespace OpenSim.Region.Physics.Meshing /// temporary prototype code - please do not use until the interface has been finalized! /// /// value to scale the hull points by + /// a list of vertices in the bounding hull if it exists and has been successfully decoded, otherwise null + public List GetBoundingHull(Vector3 size) + { + if (mBoundingHull == null) + return null; + + List verts = new List(); + foreach (var vert in mBoundingHull) + verts.Add(vert * size); + + return verts; + } + + /// + /// temporary prototype code - please do not use until the interface has been finalized! + /// + /// value to scale the hull points by /// a list of hulls if they exist and have been successfully decoded, otherwise null public List> GetConvexHulls(Vector3 size) { -- cgit v1.1 From 0cdea5c2f302ece2d37357b7e7b8c1d3f6ed8f94 Mon Sep 17 00:00:00 2001 From: dahlia Date: Fri, 24 May 2013 01:53:37 -0700 Subject: correct some errors in decoding of mesh asset convex decomposition data --- OpenSim/Region/Physics/Meshing/Meshmerizer.cs | 136 ++++++++++++++++---------- 1 file changed, 83 insertions(+), 53 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/Meshing/Meshmerizer.cs b/OpenSim/Region/Physics/Meshing/Meshmerizer.cs index fd45efe..3e2b663 100644 --- a/OpenSim/Region/Physics/Meshing/Meshmerizer.cs +++ b/OpenSim/Region/Physics/Meshing/Meshmerizer.cs @@ -386,61 +386,57 @@ namespace OpenSim.Region.Physics.Meshing if (map.ContainsKey("physics_convex")) { // pull this out also in case physics engine can use it + OSD convexBlockOsd = null; try { OSDMap convexBlock = (OSDMap)map["physics_convex"]; - - Vector3 min = new Vector3(-0.5f, -0.5f, -0.5f); - if (convexBlock.ContainsKey("Min")) min = convexBlock["Min"].AsVector3(); - Vector3 max = new Vector3(0.5f, 0.5f, 0.5f); - if (convexBlock.ContainsKey("Max")) max = convexBlock["Max"].AsVector3(); - - List boundingHull = null; - - if (convexBlock.ContainsKey("BoundingVerts")) { - // decompress and decode bounding hull points - byte[] boundingVertsBytes = DecompressOsd(convexBlock["BoundingVerts"].AsBinary()).AsBinary(); - boundingHull = new List(); - for (int i = 0; i < boundingVertsBytes.Length;) - { - ushort uX = Utils.BytesToUInt16(boundingVertsBytes, i); i += 2; - ushort uY = Utils.BytesToUInt16(boundingVertsBytes, i); i += 2; - ushort uZ = Utils.BytesToUInt16(boundingVertsBytes, i); i += 2; - - Vector3 pos = new Vector3( - Utils.UInt16ToFloat(uX, min.X, max.X), - Utils.UInt16ToFloat(uY, min.Y, max.Y), - Utils.UInt16ToFloat(uZ, min.Z, max.Z) - ); + int convexOffset = convexBlock["offset"].AsInteger() + (int)start; + int convexSize = convexBlock["size"].AsInteger(); - boundingHull.Add(pos); + byte[] convexBytes = new byte[convexSize]; + + System.Buffer.BlockCopy(primShape.SculptData, convexOffset, convexBytes, 0, convexSize); + + try + { + convexBlockOsd = DecompressOsd(convexBytes); + } + catch (Exception e) + { + m_log.ErrorFormat("{0} prim='{1}': exception decoding convex block: {2}", LogHeader, primName, e); + //return false; } - - mBoundingHull = boundingHull; - if (debugDetail) m_log.DebugFormat("{0} prim='{1}': parsed bounding hull. nHulls={2}", LogHeader, primName, mBoundingHull.Count); } - - if (convexBlock.ContainsKey("HullList")) + + if (convexBlockOsd != null && convexBlockOsd is OSDMap) { - byte[] hullList = convexBlock["HullList"].AsBinary(); + convexBlock = convexBlockOsd as OSDMap; - // decompress and decode hull points - byte[] posBytes = DecompressOsd(convexBlock["Positions"].AsBinary()).AsBinary(); - - List> hulls = new List>(); - int posNdx = 0; + if (debugDetail) + { + string keys = "[MESH]: keys found in convexBlock: "; + foreach (KeyValuePair kvp in convexBlock) + keys += "'" + kvp.Key + "' "; + m_log.Info(keys); + } + + Vector3 min = new Vector3(-0.5f, -0.5f, -0.5f); + if (convexBlock.ContainsKey("Min")) min = convexBlock["Min"].AsVector3(); + Vector3 max = new Vector3(0.5f, 0.5f, 0.5f); + if (convexBlock.ContainsKey("Max")) max = convexBlock["Max"].AsVector3(); + + List boundingHull = null; - foreach (byte cnt in hullList) + if (convexBlock.ContainsKey("BoundingVerts")) { - int count = cnt == 0 ? 256 : cnt; - List hull = new List(); - - for (int i = 0; i < count; i++) + byte[] boundingVertsBytes = convexBlock["BoundingVerts"].AsBinary(); + boundingHull = new List(); + for (int i = 0; i < boundingVertsBytes.Length; ) { - ushort uX = Utils.BytesToUInt16(posBytes, posNdx); posNdx += 2; - ushort uY = Utils.BytesToUInt16(posBytes, posNdx); posNdx += 2; - ushort uZ = Utils.BytesToUInt16(posBytes, posNdx); posNdx += 2; + ushort uX = Utils.BytesToUInt16(boundingVertsBytes, i); i += 2; + ushort uY = Utils.BytesToUInt16(boundingVertsBytes, i); i += 2; + ushort uZ = Utils.BytesToUInt16(boundingVertsBytes, i); i += 2; Vector3 pos = new Vector3( Utils.UInt16ToFloat(uX, min.X, max.X), @@ -448,18 +444,52 @@ namespace OpenSim.Region.Physics.Meshing Utils.UInt16ToFloat(uZ, min.Z, max.Z) ); - hull.Add(pos); + boundingHull.Add(pos); } - hulls.Add(hull); + mBoundingHull = boundingHull; + if (debugDetail) m_log.DebugFormat("{0} prim='{1}': parsed bounding hull. nVerts={2}", LogHeader, primName, mBoundingHull.Count); } - mConvexHulls = hulls; - if (debugDetail) m_log.DebugFormat("{0} prim='{1}': parsed hulls. nHulls={2}", LogHeader, primName, mConvexHulls.Count); - } - else - { - if (debugDetail) m_log.DebugFormat("{0} prim='{1}' has physics_convex but no HullList", LogHeader, primName); + if (convexBlock.ContainsKey("HullList")) + { + byte[] hullList = convexBlock["HullList"].AsBinary(); + + byte[] posBytes = convexBlock["Positions"].AsBinary(); + + List> hulls = new List>(); + int posNdx = 0; + + foreach (byte cnt in hullList) + { + int count = cnt == 0 ? 256 : cnt; + List hull = new List(); + + for (int i = 0; i < count; i++) + { + ushort uX = Utils.BytesToUInt16(posBytes, posNdx); posNdx += 2; + ushort uY = Utils.BytesToUInt16(posBytes, posNdx); posNdx += 2; + ushort uZ = Utils.BytesToUInt16(posBytes, posNdx); posNdx += 2; + + Vector3 pos = new Vector3( + Utils.UInt16ToFloat(uX, min.X, max.X), + Utils.UInt16ToFloat(uY, min.Y, max.Y), + Utils.UInt16ToFloat(uZ, min.Z, max.Z) + ); + + hull.Add(pos); + } + + hulls.Add(hull); + } + + mConvexHulls = hulls; + if (debugDetail) m_log.DebugFormat("{0} prim='{1}': parsed hulls. nHulls={2}", LogHeader, primName, mConvexHulls.Count); + } + else + { + if (debugDetail) m_log.DebugFormat("{0} prim='{1}' has physics_convex but no HullList", LogHeader, primName); + } } } catch (Exception e) @@ -483,7 +513,7 @@ namespace OpenSim.Region.Physics.Meshing OSD decodedMeshOsd = new OSD(); byte[] meshBytes = new byte[physSize]; System.Buffer.BlockCopy(primShape.SculptData, physOffset, meshBytes, 0, physSize); -// byte[] decompressed = new byte[physSize * 5]; + // byte[] decompressed = new byte[physSize * 5]; try { decodedMeshOsd = DecompressOsd(meshBytes); @@ -499,7 +529,7 @@ namespace OpenSim.Region.Physics.Meshing // physics_shape is an array of OSDMaps, one for each submesh if (decodedMeshOsd is OSDArray) { -// Console.WriteLine("decodedMeshOsd for {0} - {1}", primName, Util.GetFormattedXml(decodedMeshOsd)); + // Console.WriteLine("decodedMeshOsd for {0} - {1}", primName, Util.GetFormattedXml(decodedMeshOsd)); decodedMeshOsdArray = (OSDArray)decodedMeshOsd; foreach (OSD subMeshOsd in decodedMeshOsdArray) -- cgit v1.1 From 440905ad14d4261df9da0fd2ce7e20a350982af1 Mon Sep 17 00:00:00 2001 From: dahlia Date: Fri, 24 May 2013 10:31:14 -0700 Subject: change a hull debugging message to Debug instead of Info --- OpenSim/Region/Physics/Meshing/Meshmerizer.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/Meshing/Meshmerizer.cs b/OpenSim/Region/Physics/Meshing/Meshmerizer.cs index 3e2b663..2c10568 100644 --- a/OpenSim/Region/Physics/Meshing/Meshmerizer.cs +++ b/OpenSim/Region/Physics/Meshing/Meshmerizer.cs @@ -418,7 +418,7 @@ namespace OpenSim.Region.Physics.Meshing string keys = "[MESH]: keys found in convexBlock: "; foreach (KeyValuePair kvp in convexBlock) keys += "'" + kvp.Key + "' "; - m_log.Info(keys); + m_log.Debug(keys); } Vector3 min = new Vector3(-0.5f, -0.5f, -0.5f); -- cgit v1.1 From 81a6c397811c587cd97b5bb0f186fe6e799f865b Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Fri, 24 May 2013 16:20:26 -0700 Subject: Meshmerizer: add INI parameter to enable DEBUG mesh detail logging. Default to off. To turn mesh parsing DEBUG detail logging on, add [Mesh] LogMeshDetail=true to the INI file. --- OpenSim/Region/Physics/Meshing/Meshmerizer.cs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/Meshing/Meshmerizer.cs b/OpenSim/Region/Physics/Meshing/Meshmerizer.cs index 2c10568..1b499d0 100644 --- a/OpenSim/Region/Physics/Meshing/Meshmerizer.cs +++ b/OpenSim/Region/Physics/Meshing/Meshmerizer.cs @@ -74,7 +74,7 @@ namespace OpenSim.Region.Physics.Meshing private const string baseDir = null; //"rawFiles"; #endif // If 'true', lots of DEBUG logging of asset parsing details - private bool debugDetail = true; + private bool debugDetail = false; private bool cacheSculptMaps = true; private string decodedSculptMapPath = null; @@ -94,8 +94,11 @@ namespace OpenSim.Region.Physics.Meshing decodedSculptMapPath = start_config.GetString("DecodedSculptMapPath","j2kDecodeCache"); cacheSculptMaps = start_config.GetBoolean("CacheSculptMaps", cacheSculptMaps); - if(mesh_config != null) + if (mesh_config != null) + { useMeshiesPhysicsMesh = mesh_config.GetBoolean("UseMeshiesPhysicsMesh", useMeshiesPhysicsMesh); + debugDetail = mesh_config.GetBoolean("LogMeshDetails", debugDetail); + } try { @@ -415,7 +418,7 @@ namespace OpenSim.Region.Physics.Meshing if (debugDetail) { - string keys = "[MESH]: keys found in convexBlock: "; + string keys = LogHeader + " keys found in convexBlock: "; foreach (KeyValuePair kvp in convexBlock) keys += "'" + kvp.Key + "' "; m_log.Debug(keys); -- cgit v1.1 From 4979940def5561015cb56bc660c6ec721722b9fc Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Fri, 24 May 2013 16:23:10 -0700 Subject: BulletSim: properly set mesh hash key in use tracking structure. Shouldn't see any functional difference. --- OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs index 48f1394..81edc12 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs @@ -578,7 +578,6 @@ public class BSShapeHull : BSShape PrimitiveBaseShape pbs, OMV.Vector3 size, float lod) { BulletShape newShape = new BulletShape(); - newShape.shapeKey = newHullKey; IMesh meshData = null; List> allHulls = null; @@ -782,6 +781,7 @@ public class BSShapeHull : BSShape // create the hull data structure in Bullet newShape = physicsScene.PE.CreateHullShape(physicsScene.World, hullCount, convHulls); } + newShape.shapeKey = newHullKey; return newShape; } // Callback from convex hull creater with a newly created hull. @@ -906,6 +906,7 @@ public class BSShapeCompound : BSShape } else { + // Didn't find it in the lists of specific types. It could be compound. if (physicsScene.PE.IsCompound(pShape)) { BSShapeCompound recursiveCompound = new BSShapeCompound(pShape); @@ -913,6 +914,7 @@ public class BSShapeCompound : BSShape } else { + // If none of the above, maybe it is a simple native shape. if (physicsScene.PE.IsNativeShape(pShape)) { BSShapeNative nativeShape = new BSShapeNative(pShape); @@ -1052,6 +1054,7 @@ public class BSShapeGImpact : BSShape // Check to see if mesh was created (might require an asset). newShape = VerifyMeshCreated(physicsScene, newShape, prim); + newShape.shapeKey = newMeshKey; if (!newShape.isNativeShape || prim.PrimAssetState == BSPhysObject.PrimAssetCondition.Failed) { // If a mesh was what was created, remember the built shape for later sharing. -- cgit v1.1 From 5f1f5ea5ab5badf5944471fefe0a45f7b4f41b91 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Fri, 24 May 2013 16:24:16 -0700 Subject: BulletSim: add VehicleInertiaFactor to allow modifying inertia. Another parameter for vehicle operation tuning. Default to <1,1,1> which means nothing is different under normal use. --- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 3 ++- OpenSim/Region/Physics/BulletSPlugin/BSParam.cs | 3 +++ 2 files changed, 5 insertions(+), 1 deletion(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index c16b7d3..311cf4f 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -617,7 +617,8 @@ namespace OpenSim.Region.Physics.BulletSPlugin // Vehicles report collision events so we know when it's on the ground m_physicsScene.PE.AddToCollisionFlags(ControllingPrim.PhysBody, CollisionFlags.BS_VEHICLE_COLLISIONS); - ControllingPrim.Inertia = m_physicsScene.PE.CalculateLocalInertia(ControllingPrim.PhysShape.physShapeInfo, m_vehicleMass); + Vector3 inertia = m_physicsScene.PE.CalculateLocalInertia(ControllingPrim.PhysShape.physShapeInfo, m_vehicleMass); + ControllingPrim.Inertia = inertia * BSParam.VehicleInertiaFactor; m_physicsScene.PE.SetMassProps(ControllingPrim.PhysBody, m_vehicleMass, ControllingPrim.Inertia); m_physicsScene.PE.UpdateInertiaTensor(ControllingPrim.PhysBody); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs index c19eda1..e98a7fb 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs @@ -148,6 +148,7 @@ public static class BSParam public static float VehicleRestitution { get; private set; } public static Vector3 VehicleLinearFactor { get; private set; } public static Vector3 VehicleAngularFactor { get; private set; } + public static Vector3 VehicleInertiaFactor { get; private set; } public static float VehicleGroundGravityFudge { get; private set; } public static float VehicleAngularBankingTimescaleFudge { get; private set; } public static bool VehicleDebuggingEnable { get; private set; } @@ -583,6 +584,8 @@ public static class BSParam new Vector3(1f, 1f, 1f) ), new ParameterDefn("VehicleAngularFactor", "Fraction of physical angular changes applied to vehicle (<0,0,0> to <1,1,1>)", new Vector3(1f, 1f, 1f) ), + new ParameterDefn("VehicleInertiaFactor", "Fraction of physical inertia applied (<0,0,0> to <1,1,1>)", + new Vector3(1f, 1f, 1f) ), new ParameterDefn("VehicleFriction", "Friction of vehicle on the ground (0.0 - 1.0)", 0.0f ), new ParameterDefn("VehicleRestitution", "Bouncyness factor for vehicles (0.0 - 1.0)", -- cgit v1.1 From 182137263412fb23f9bdb250afbe1b1509280aac Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Fri, 24 May 2013 16:32:19 -0700 Subject: Meshmerizer: remember to add the copied hull verts to the list of hulls. --- OpenSim/Region/Physics/Meshing/Meshmerizer.cs | 1 + 1 file changed, 1 insertion(+) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/Meshing/Meshmerizer.cs b/OpenSim/Region/Physics/Meshing/Meshmerizer.cs index 1b499d0..fc679e7 100644 --- a/OpenSim/Region/Physics/Meshing/Meshmerizer.cs +++ b/OpenSim/Region/Physics/Meshing/Meshmerizer.cs @@ -893,6 +893,7 @@ namespace OpenSim.Region.Physics.Meshing List verts = new List(); foreach (var vert in hull) verts.Add(vert * size); + hulls.Add(verts); } return hulls; -- cgit v1.1 From 0c35d28933ddb2cae7b4f095b35ed4e386a1b71b Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Sun, 26 May 2013 17:35:12 -0700 Subject: BulletSim: enable GImpact shape for prims with cuts. Include DLLs and SOs which recompute GImpact shape bounding box after creation as Bullet doesn't do that itself (something it does for nearly every other shape). Now, physical prims without cuts become single mesh convex meshes. Physical prims with cuts become GImpact meshes. Meshes become a set of convex hulls approximated from the mesh unless the hulls are specified in the mesh asset data. The use of GImpact shapes should make some mechanical physics more stable. --- OpenSim/Region/Physics/BulletSPlugin/BSParam.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs index e98a7fb..0f0a494 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs @@ -373,7 +373,7 @@ public static class BSParam new ParameterDefn("ShouldUseSingleConvexHullForPrims", "If true, use a single convex hull shape for physical prims", true ), new ParameterDefn("ShouldUseGImpactShapeForPrims", "If true, use a GImpact shape for prims with cuts and twists", - false ), + true ), new ParameterDefn("ShouldUseAssetHulls", "If true, use hull if specified in the mesh asset info", false ), -- cgit v1.1 From 7c3a46cceaf9dac694b1c387f37adc2c51c6ee40 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Mon, 27 May 2013 14:38:59 -0700 Subject: BulletSim: default using mesh asset hulls to 'true'. This means that, if the mesh asset specifies physics hulls, BulletSim will fetch and use same rather than approximating the hulls. If physics hulls are not specified, the representation will fall back to the regular physics mesh. --- OpenSim/Region/Physics/BulletSPlugin/BSParam.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs index 0f0a494..2651e3b 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs @@ -373,9 +373,9 @@ public static class BSParam new ParameterDefn("ShouldUseSingleConvexHullForPrims", "If true, use a single convex hull shape for physical prims", true ), new ParameterDefn("ShouldUseGImpactShapeForPrims", "If true, use a GImpact shape for prims with cuts and twists", - true ), - new ParameterDefn("ShouldUseAssetHulls", "If true, use hull if specified in the mesh asset info", false ), + new ParameterDefn("ShouldUseAssetHulls", "If true, use hull if specified in the mesh asset info", + true ), new ParameterDefn("CrossingFailuresBeforeOutOfBounds", "How forgiving we are about getting into adjactent regions", 5 ), -- cgit v1.1 From ae0d6ab28a03ec23c91eaf6a8ac94b890916a1ca Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 28 May 2013 09:19:08 -0700 Subject: BulletSim: don't zero motion when changing vehicle type. Some vehicle scripts change type on the fly as an easy way of setting all the parameters (like a plane changing to a car when on the ground). --- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index f5b0361..e11e365 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -511,7 +511,10 @@ public class BSPrim : BSPhysObject PhysScene.TaintedObject("setVehicleType", delegate() { - ZeroMotion(true /* inTaintTime */); + // Some vehicle scripts change vehicle type on the fly as an easy way to + // change all the parameters. Like a plane changing to CAR when on the + // ground. In this case, don't want to zero motion. + // ZeroMotion(true /* inTaintTime */); VehicleActor.ProcessTypeChange(type); ActivateIfPhysical(false); }); -- cgit v1.1 From 07058b044be59b6e07efedeca36b2b464e984195 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Sat, 1 Jun 2013 14:52:44 -0700 Subject: BulletSim: experimental movement of physics execution off of heartbeat thread. Off by default until more testing. Setting "[BulletSim]UseSeparatePhysicsThread=true" causes the physics engine to be called on its own thread and the heartbeat thread only handles the reporting of property updates and collisions. Physics frame rate is about right but physics execution time goes to zero as accounted by the heartbeat loop. --- OpenSim/Region/Physics/BulletSPlugin/BSParam.cs | 8 + OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 3 +- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 271 +++++++++++++++++------- 3 files changed, 209 insertions(+), 73 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs index 2651e3b..afd547a 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs @@ -54,6 +54,9 @@ public static class BSParam // =================== // From: + public static bool UseSeparatePhysicsThread { get; private set; } + public static float PhysicsTimeStep { get; private set; } + // Level of Detail values kept as float because that's what the Meshmerizer wants public static float MeshLOD { get; private set; } public static float MeshCircularLOD { get; private set; } @@ -354,6 +357,11 @@ public static class BSParam // v = value (appropriate type) private static ParameterDefnBase[] ParameterDefinitions = { + new ParameterDefn("UseSeparatePhysicsThread", "If 'true', the physics engine runs independent from the simulator heartbeat", + false ), + new ParameterDefn("PhysicsTimeStep", "If separate thread, seconds to simulate each interval", + 0.1f ), + new ParameterDefn("MeshSculptedPrim", "Whether to create meshes for sculpties", true, (s) => { return ShouldMeshSculptedPrim; }, diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index e11e365..95bdc7b 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -1513,7 +1513,8 @@ public class BSPrim : BSPhysObject CurrentEntityProperties = entprop; // Note that BSPrim can be overloaded by BSPrimLinkable which controls updates from root and children prims. - base.RequestPhysicsterseUpdate(); + + PhysScene.PostUpdate(this); } } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index 39f5b0a..423c389 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -56,12 +56,23 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters public string BulletEngineName { get; private set; } public BSAPITemplate PE; + // If the physics engine is running on a separate thread + public Thread m_physicsThread; + public Dictionary PhysObjects; public BSShapeCollection Shapes; // Keeping track of the objects with collisions so we can report begin and end of a collision public HashSet ObjectsWithCollisions = new HashSet(); public HashSet ObjectsWithNoMoreCollisions = new HashSet(); + + // All the collision processing is protected with this lock object + public Object CollisionLock = new Object(); + + // Properties are updated here + public Object UpdateLock = new Object(); + public HashSet ObjectsWithUpdates = new HashSet(); + // Keep track of all the avatars so we can send them a collision event // every tick so OpenSim will update its animation. private HashSet m_avatars = new HashSet(); @@ -77,12 +88,19 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters public BSConstraintCollection Constraints { get; private set; } // Simulation parameters + internal float m_physicsStepTime; // if running independently, the interval simulated by default + internal int m_maxSubSteps; internal float m_fixedTimeStep; - internal long m_simulationStep = 0; - internal float NominalFrameRate { get; set; } + + internal float m_simulatedTime; // the time simulated previously. Used for physics framerate calc. + + internal long m_simulationStep = 0; // The current simulation step. public long SimulationStep { get { return m_simulationStep; } } - internal float LastTimeStep { get; private set; } + + internal float LastTimeStep { get; private set; } // The simulation time from the last invocation of Simulate() + + internal float NominalFrameRate { get; set; } // Parameterized ideal frame rate that simulation is scaled to // Physical objects can register for prestep or poststep events public delegate void PreStepAction(float timeStep); @@ -90,7 +108,7 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters public event PreStepAction BeforeStep; public event PostStepAction AfterStep; - // A value of the time now so all the collision and update routines do not have to get their own + // A value of the time 'now' so all the collision and update routines do not have to get their own // Set to 'now' just before all the prims and actors are called for collisions and updates public int SimulationNowTime { get; private set; } @@ -188,6 +206,9 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters PhysObjects = new Dictionary(); Shapes = new BSShapeCollection(this); + m_simulatedTime = 0f; + LastTimeStep = 0.1f; + // Allocate pinned memory to pass parameters. UnmanagedParams = new ConfigurationParameters[1]; @@ -227,10 +248,20 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters TerrainManager = new BSTerrainManager(this); TerrainManager.CreateInitialGroundPlaneAndTerrain(); + // Put some informational messages into the log file. m_log.WarnFormat("{0} Linksets implemented with {1}", LogHeader, (BSLinkset.LinksetImplementation)BSParam.LinksetImplementation); InTaintTime = false; m_initialized = true; + + // If the physics engine runs on its own thread, start same. + if (BSParam.UseSeparatePhysicsThread) + { + // The physics simulation should happen independently of the heartbeat loop + m_physicsThread = new Thread(BulletSPluginPhysicsThread); + m_physicsThread.Name = BulletEngineName; + m_physicsThread.Start(); + } } // All default parameter values are set here. There should be no values set in the @@ -270,6 +301,7 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters } else { + // Nothing in the configuration INI file so assume unmanaged and other defaults. BulletEngineName = "BulletUnmanaged"; m_physicsLoggingEnabled = false; VehicleLoggingEnabled = false; @@ -317,6 +349,7 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters switch (selectionName) { + case "bullet": case "bulletunmanaged": ret = new BSAPIUnman(engineName, this); break; @@ -494,25 +527,41 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters #endregion // Prim and Avatar addition and removal #region Simulation - // Simulate one timestep + + // Call from the simulator to send physics information to the simulator objects. + // This pushes all the collision and property update events into the objects in + // the simulator and, since it is on the heartbeat thread, there is an implicit + // locking of those data structures from other heartbeat events. + // If the physics engine is running on a separate thread, the update information + // will be in the ObjectsWithCollions and ObjectsWithUpdates structures. public override float Simulate(float timeStep) { + if (!BSParam.UseSeparatePhysicsThread) + { + DoPhysicsStep(timeStep); + } + return SendUpdatesToSimulator(timeStep); + } + + // Call the physics engine to do one 'timeStep' and collect collisions and updates + // into ObjectsWithCollisions and ObjectsWithUpdates data structures. + private void DoPhysicsStep(float timeStep) + { // prevent simulation until we've been initialized - if (!m_initialized) return 5.0f; + if (!m_initialized) return; LastTimeStep = timeStep; int updatedEntityCount = 0; int collidersCount = 0; - int beforeTime = 0; + int beforeTime = Util.EnvironmentTickCount(); int simTime = 0; - // update the prim states while we know the physics engine is not busy int numTaints = _taintOperations.Count; - InTaintTime = true; // Only used for debugging so locking is not necessary. + // update the prim states while we know the physics engine is not busy ProcessTaints(); // Some of the physical objects requre individual, pre-step calls @@ -535,18 +584,8 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters int numSubSteps = 0; try { - if (PhysicsLogging.Enabled) - beforeTime = Util.EnvironmentTickCount(); - numSubSteps = PE.PhysicsStep(World, timeStep, m_maxSubSteps, m_fixedTimeStep, out updatedEntityCount, out collidersCount); - if (PhysicsLogging.Enabled) - { - simTime = Util.EnvironmentTickCountSubtract(beforeTime); - DetailLog("{0},Simulate,call, frame={1}, nTaints={2}, simTime={3}, substeps={4}, updates={5}, colliders={6}, objWColl={7}", - DetailLogZero, m_simulationStep, numTaints, simTime, numSubSteps, - updatedEntityCount, collidersCount, ObjectsWithCollisions.Count); - } } catch (Exception e) { @@ -558,77 +597,62 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters collidersCount = 0; } + // Make the physics engine dump useful statistics periodically if (PhysicsMetricDumpFrames != 0 && ((m_simulationStep % PhysicsMetricDumpFrames) == 0)) PE.DumpPhysicsStatistics(World); // Get a value for 'now' so all the collision and update routines don't have to get their own. SimulationNowTime = Util.EnvironmentTickCount(); - // If there were collisions, process them by sending the event to the prim. - // Collisions must be processed before updates. - if (collidersCount > 0) + // Send collision information to the colliding objects. The objects decide if the collision + // is 'real' (like linksets don't collide with themselves) and the individual objects + // know if the simulator has subscribed to collisions. + lock (CollisionLock) { - for (int ii = 0; ii < collidersCount; ii++) + if (collidersCount > 0) { - uint cA = m_collisionArray[ii].aID; - uint cB = m_collisionArray[ii].bID; - Vector3 point = m_collisionArray[ii].point; - Vector3 normal = m_collisionArray[ii].normal; - float penetration = m_collisionArray[ii].penetration; - SendCollision(cA, cB, point, normal, penetration); - SendCollision(cB, cA, point, -normal, penetration); - } - } - - // The above SendCollision's batch up the collisions on the objects. - // Now push the collisions into the simulator. - if (ObjectsWithCollisions.Count > 0) - { - foreach (BSPhysObject bsp in ObjectsWithCollisions) - if (!bsp.SendCollisions()) + for (int ii = 0; ii < collidersCount; ii++) { - // If the object is done colliding, see that it's removed from the colliding list - ObjectsWithNoMoreCollisions.Add(bsp); + uint cA = m_collisionArray[ii].aID; + uint cB = m_collisionArray[ii].bID; + Vector3 point = m_collisionArray[ii].point; + Vector3 normal = m_collisionArray[ii].normal; + float penetration = m_collisionArray[ii].penetration; + SendCollision(cA, cB, point, normal, penetration); + SendCollision(cB, cA, point, -normal, penetration); } + } } - // This is a kludge to get avatar movement updates. - // The simulator expects collisions for avatars even if there are have been no collisions. - // The event updates avatar animations and stuff. - // If you fix avatar animation updates, remove this overhead and let normal collision processing happen. - foreach (BSPhysObject bsp in m_avatars) - if (!ObjectsWithCollisions.Contains(bsp)) // don't call avatars twice - bsp.SendCollisions(); - - // Objects that are done colliding are removed from the ObjectsWithCollisions list. - // Not done above because it is inside an iteration of ObjectWithCollisions. - // This complex collision processing is required to create an empty collision - // event call after all real collisions have happened on an object. This enables - // the simulator to generate the 'collision end' event. - if (ObjectsWithNoMoreCollisions.Count > 0) - { - foreach (BSPhysObject po in ObjectsWithNoMoreCollisions) - ObjectsWithCollisions.Remove(po); - ObjectsWithNoMoreCollisions.Clear(); - } - // Done with collisions. - - // If any of the objects had updated properties, tell the object it has been changed by the physics engine - if (updatedEntityCount > 0) + // If any of the objects had updated properties, tell the managed objects about the update + // and remember that there was a change so it will be passed to the simulator. + lock (UpdateLock) { - for (int ii = 0; ii < updatedEntityCount; ii++) + if (updatedEntityCount > 0) { - EntityProperties entprop = m_updateArray[ii]; - BSPhysObject pobj; - if (PhysObjects.TryGetValue(entprop.ID, out pobj)) + for (int ii = 0; ii < updatedEntityCount; ii++) { - pobj.UpdateProperties(entprop); + EntityProperties entprop = m_updateArray[ii]; + BSPhysObject pobj; + if (PhysObjects.TryGetValue(entprop.ID, out pobj)) + { + pobj.UpdateProperties(entprop); + } } } } + // Some actors want to know when the simulation step is complete. TriggerPostStepEvent(timeStep); + simTime = Util.EnvironmentTickCountSubtract(beforeTime); + if (PhysicsLogging.Enabled) + { + DetailLog("{0},DoPhysicsStep,call, frame={1}, nTaints={2}, simTime={3}, substeps={4}, updates={5}, colliders={6}, objWColl={7}", + DetailLogZero, m_simulationStep, numTaints, simTime, numSubSteps, + updatedEntityCount, collidersCount, ObjectsWithCollisions.Count); + } + // The following causes the unmanaged code to output ALL the values found in ALL the objects in the world. // Only enable this in a limited test world with few objects. if (m_physicsPhysicalDumpEnabled) @@ -637,7 +661,84 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters // The physics engine returns the number of milliseconds it simulated this call. // These are summed and normalized to one second and divided by 1000 to give the reported physics FPS. // Multiply by a fixed nominal frame rate to give a rate similar to the simulator (usually 55). - return (float)numSubSteps * m_fixedTimeStep * 1000f * NominalFrameRate; + m_simulatedTime += (float)numSubSteps * m_fixedTimeStep * 1000f * NominalFrameRate; + } + + // Called by a BSPhysObject to note that it has changed properties and this information + // should be passed up to the simulator at the proper time. + // Note: this is called by the BSPhysObject from invocation via DoPhysicsStep() above so + // this is is under UpdateLock. + public void PostUpdate(BSPhysObject updatee) + { + ObjectsWithUpdates.Add(updatee); + } + + // The simulator thinks it is physics time so return all the collisions and position + // updates that were collected in actual physics simulation. + private float SendUpdatesToSimulator(float timeStep) + { + if (!m_initialized) return 5.0f; + + DetailLog("{0},SendUpdatesToSimulator,collisions={1},updates={2},simedTime={3}", + BSScene.DetailLogZero, ObjectsWithCollisions.Count, ObjectsWithUpdates.Count, m_simulatedTime); + // Push the collisions into the simulator. + lock (CollisionLock) + { + if (ObjectsWithCollisions.Count > 0) + { + foreach (BSPhysObject bsp in ObjectsWithCollisions) + if (!bsp.SendCollisions()) + { + // If the object is done colliding, see that it's removed from the colliding list + ObjectsWithNoMoreCollisions.Add(bsp); + } + } + + // This is a kludge to get avatar movement updates. + // The simulator expects collisions for avatars even if there are have been no collisions. + // The event updates avatar animations and stuff. + // If you fix avatar animation updates, remove this overhead and let normal collision processing happen. + foreach (BSPhysObject bsp in m_avatars) + if (!ObjectsWithCollisions.Contains(bsp)) // don't call avatars twice + bsp.SendCollisions(); + + // Objects that are done colliding are removed from the ObjectsWithCollisions list. + // Not done above because it is inside an iteration of ObjectWithCollisions. + // This complex collision processing is required to create an empty collision + // event call after all real collisions have happened on an object. This allows + // the simulator to generate the 'collision end' event. + if (ObjectsWithNoMoreCollisions.Count > 0) + { + foreach (BSPhysObject po in ObjectsWithNoMoreCollisions) + ObjectsWithCollisions.Remove(po); + ObjectsWithNoMoreCollisions.Clear(); + } + } + + // Call the simulator for each object that has physics property updates. + HashSet updatedObjects = null; + lock (UpdateLock) + { + if (ObjectsWithUpdates.Count > 0) + { + updatedObjects = ObjectsWithUpdates; + ObjectsWithUpdates = new HashSet(); + } + } + if (updatedObjects != null) + { + foreach (BSPhysObject obj in updatedObjects) + { + obj.RequestPhysicsterseUpdate(); + } + updatedObjects.Clear(); + } + + // Return the framerate simulated to give the above returned results. + // (Race condition here but this is just bookkeeping so rare mistakes do not merit a lock). + float simTime = m_simulatedTime; + m_simulatedTime = 0f; + return simTime; } // Something has collided @@ -656,7 +757,7 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters return; } - // The terrain is not in the physical object list so 'collidee' can be null when Collide() is called. + // Note: the terrain is not in the physical object list so 'collidee' can be null when Collide() is called. BSPhysObject collidee = null; PhysObjects.TryGetValue(collidingWith, out collidee); @@ -664,13 +765,39 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters if (collider.Collide(collidingWith, collidee, collidePoint, collideNormal, penetration)) { - // If a collision was posted, remember to send it to the simulator + // If a collision was 'good', remember to send it to the simulator ObjectsWithCollisions.Add(collider); } return; } + public void BulletSPluginPhysicsThread() + { + while (m_initialized) + { + int beginSimulationRealtimeMS = Util.EnvironmentTickCount(); + DoPhysicsStep(BSParam.PhysicsTimeStep); + int simulationRealtimeMS = Util.EnvironmentTickCountSubtract(beginSimulationRealtimeMS); + int simulationTimeVsRealtimeDifferenceMS = ((int)(BSParam.PhysicsTimeStep*1000f)) - simulationRealtimeMS; + + if (simulationTimeVsRealtimeDifferenceMS > 0) + { + // The simulation of the time interval took less than realtime. + // Do a sleep for the rest of realtime. + DetailLog("{0},BulletSPluginPhysicsThread,sleeping={1}", BSScene.DetailLogZero, simulationTimeVsRealtimeDifferenceMS); + Thread.Sleep(simulationTimeVsRealtimeDifferenceMS); + } + else + { + // The simulation took longer than realtime. + // Do some scaling of simulation time. + // TODO. + DetailLog("{0},BulletSPluginPhysicsThread,longerThanRealtime={1}", BSScene.DetailLogZero, simulationTimeVsRealtimeDifferenceMS); + } + } + } + #endregion // Simulation public override void GetResults() { } -- cgit v1.1 From 0c971d148cbee691136a8e6f6c0b3dd40ba4e78a Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Wed, 5 Jun 2013 07:09:43 -0700 Subject: BulletSim: fix corner case when rebuilding a compound linkset while a mesh/hull while a mesh or hull is being rebuilt when its asset is fetched. This fixes a 'pure virtual function' crash when changing physical state of complex linksets that include many meshes. --- OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs | 57 +++++++++++++++++++----- 1 file changed, 46 insertions(+), 11 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs index 81edc12..867d2ab 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs @@ -389,9 +389,21 @@ public class BSShapeMesh : BSShape } public override BSShape GetReference(BSScene pPhysicsScene, BSPhysObject pPrim) { - // Another reference to this shape is just counted. - IncrementReference(); - return this; + BSShape ret = null; + // If the underlying shape is native, the actual shape has not been build (waiting for asset) + // and we must create a copy of the native shape since they are never shared. + if (physShapeInfo.HasPhysicalShape && physShapeInfo.isNativeShape) + { + // TODO: decide when the native shapes should be freed. Check in Dereference? + ret = BSShapeNative.GetReference(pPhysicsScene, pPrim, BSPhysicsShapeType.SHAPE_BOX, FixedShapeKey.KEY_BOX); + } + else + { + // Another reference to this shape is just counted. + IncrementReference(); + ret = this; + } + return ret; } public override void Dereference(BSScene physicsScene) { @@ -560,9 +572,21 @@ public class BSShapeHull : BSShape } public override BSShape GetReference(BSScene pPhysicsScene, BSPhysObject pPrim) { - // Another reference to this shape is just counted. - IncrementReference(); - return this; + BSShape ret = null; + // If the underlying shape is native, the actual shape has not been build (waiting for asset) + // and we must create a copy of the native shape since they are never shared. + if (physShapeInfo.HasPhysicalShape && physShapeInfo.isNativeShape) + { + // TODO: decide when the native shapes should be freed. Check in Dereference? + ret = BSShapeNative.GetReference(pPhysicsScene, pPrim, BSPhysicsShapeType.SHAPE_BOX, FixedShapeKey.KEY_BOX); + } + else + { + // Another reference to this shape is just counted. + IncrementReference(); + ret = this; + } + return ret; } public override void Dereference(BSScene physicsScene) { @@ -1075,12 +1099,23 @@ public class BSShapeGImpact : BSShape (w, iC, i, vC, v) => physicsScene.PE.CreateGImpactShape(w, iC, i, vC, v) ); } - public override BSShape GetReference(BSScene physicsScene, BSPhysObject prim) + public override BSShape GetReference(BSScene pPhysicsScene, BSPhysObject pPrim) { - // Calling this reference means we want another handle to an existing shape - // (usually linksets) so return this copy. - IncrementReference(); - return this; + BSShape ret = null; + // If the underlying shape is native, the actual shape has not been build (waiting for asset) + // and we must create a copy of the native shape since they are never shared. + if (physShapeInfo.HasPhysicalShape && physShapeInfo.isNativeShape) + { + // TODO: decide when the native shapes should be freed. Check in Dereference? + ret = BSShapeNative.GetReference(pPhysicsScene, pPrim, BSPhysicsShapeType.SHAPE_BOX, FixedShapeKey.KEY_BOX); + } + else + { + // Another reference to this shape is just counted. + IncrementReference(); + ret = this; + } + return ret; } // Dereferencing a compound shape releases the hold on all the child shapes. public override void Dereference(BSScene physicsScene) -- cgit v1.1 From b5d0ac4c42629812523f5af4384f61dee00ef495 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Wed, 5 Jun 2013 07:12:14 -0700 Subject: BulletSim: default PhysicsTimeStep to same as the simulator's heartbeat timestep when running the physics engine on a separate thread. This reduces the occurance of heartbeats that happen when there is no physics step which is seen as vehicle jerkyness. --- OpenSim/Region/Physics/BulletSPlugin/BSParam.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs index afd547a..aad1108 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs @@ -360,7 +360,7 @@ public static class BSParam new ParameterDefn("UseSeparatePhysicsThread", "If 'true', the physics engine runs independent from the simulator heartbeat", false ), new ParameterDefn("PhysicsTimeStep", "If separate thread, seconds to simulate each interval", - 0.1f ), + 0.089f ), new ParameterDefn("MeshSculptedPrim", "Whether to create meshes for sculpties", true, -- cgit v1.1 From 795acaa6aa8e32ad0281226208a6b1bbc2292bf5 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Mon, 10 Jun 2013 14:12:45 -0700 Subject: BulletSim: add failure flag for meshing failure vs asset fetch failure so error messages make more sense. Change some BulletSim status log messages from WARN to INFO. Update TODO list. --- .../Region/Physics/BulletSPlugin/BSPhysObject.cs | 2 +- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 4 +- OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs | 35 ++++++++++++----- .../Region/Physics/BulletSPlugin/BulletSimTODO.txt | 44 +++++++++++----------- 4 files changed, 51 insertions(+), 34 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index cca887a..a4c5e08 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -148,7 +148,7 @@ public abstract class BSPhysObject : PhysicsActor // The asset state is first 'Unknown' then 'Waiting' then either 'Failed' or 'Fetched'. public enum PrimAssetCondition { - Unknown, Waiting, Failed, Fetched + Unknown, Waiting, FailedAssetFetch, FailedMeshing, Fetched } public PrimAssetCondition PrimAssetState { get; set; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index 423c389..dec6b6f 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -249,7 +249,7 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters TerrainManager.CreateInitialGroundPlaneAndTerrain(); // Put some informational messages into the log file. - m_log.WarnFormat("{0} Linksets implemented with {1}", LogHeader, (BSLinkset.LinksetImplementation)BSParam.LinksetImplementation); + m_log.InfoFormat("{0} Linksets implemented with {1}", LogHeader, (BSLinkset.LinksetImplementation)BSParam.LinksetImplementation); InTaintTime = false; m_initialized = true; @@ -374,7 +374,7 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters } else { - m_log.WarnFormat("{0} Selected bullet engine {1} -> {2}/{3}", LogHeader, engineName, ret.BulletEngineName, ret.BulletEngineVersion); + m_log.InfoFormat("{0} Selected bullet engine {1} -> {2}/{3}", LogHeader, engineName, ret.BulletEngineName, ret.BulletEngineVersion); } return ret; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs index 867d2ab..202a4ce 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs @@ -167,7 +167,7 @@ public abstract class BSShape // Prevent trying to keep fetching the mesh by declaring failure. if (prim.PrimAssetState == BSPhysObject.PrimAssetCondition.Fetched) { - prim.PrimAssetState = BSPhysObject.PrimAssetCondition.Failed; + prim.PrimAssetState = BSPhysObject.PrimAssetCondition.FailedMeshing; physicsScene.Logger.WarnFormat("{0} Fetched asset would not mesh. {1}, texture={2}", LogHeader, prim.PhysObjectName, prim.BaseShape.SculptTexture); physicsScene.DetailLog("{0},BSShape.VerifyMeshCreated,setFailed,objNam={1},tex={2}", @@ -177,7 +177,8 @@ public abstract class BSShape { // If this mesh has an underlying asset and we have not failed getting it before, fetch the asset if (prim.BaseShape.SculptEntry - && prim.PrimAssetState != BSPhysObject.PrimAssetCondition.Failed + && prim.PrimAssetState != BSPhysObject.PrimAssetCondition.FailedAssetFetch + && prim.PrimAssetState != BSPhysObject.PrimAssetCondition.FailedMeshing && prim.PrimAssetState != BSPhysObject.PrimAssetCondition.Waiting && prim.BaseShape.SculptTexture != OMV.UUID.Zero ) @@ -219,7 +220,7 @@ public abstract class BSShape } if (!assetFound) { - yprim.PrimAssetState = BSPhysObject.PrimAssetCondition.Failed; + yprim.PrimAssetState = BSPhysObject.PrimAssetCondition.FailedAssetFetch; } physicsScene.DetailLog("{0},BSShape.VerifyMeshCreated,fetchAssetCallback,found={1},isSculpt={2},ids={3}", yprim.LocalID, assetFound, yprim.BaseShape.SculptEntry, mismatchIDs ); @@ -227,7 +228,7 @@ public abstract class BSShape } else { - xprim.PrimAssetState = BSPhysObject.PrimAssetCondition.Failed; + xprim.PrimAssetState = BSPhysObject.PrimAssetCondition.FailedAssetFetch; physicsScene.Logger.ErrorFormat("{0} Physical object requires asset but no asset provider. Name={1}", LogHeader, physicsScene.Name); } @@ -235,13 +236,20 @@ public abstract class BSShape } else { - if (prim.PrimAssetState == BSPhysObject.PrimAssetCondition.Failed) + if (prim.PrimAssetState == BSPhysObject.PrimAssetCondition.FailedAssetFetch) { physicsScene.Logger.WarnFormat("{0} Mesh failed to fetch asset. obj={1}, texture={2}", LogHeader, prim.PhysObjectName, prim.BaseShape.SculptTexture); physicsScene.DetailLog("{0},BSShape.VerifyMeshCreated,wasFailed,objNam={1},tex={2}", prim.LocalID, prim.PhysObjectName, prim.BaseShape.SculptTexture); } + if (prim.PrimAssetState == BSPhysObject.PrimAssetCondition.FailedMeshing) + { + physicsScene.Logger.WarnFormat("{0} Mesh asset would not mesh. obj={1}, texture={2}", + LogHeader, prim.PhysObjectName, prim.BaseShape.SculptTexture); + physicsScene.DetailLog("{0},BSShape.VerifyMeshCreated,wasFailedMeshing,objNam={1},tex={2}", + prim.LocalID, prim.PhysObjectName, prim.BaseShape.SculptTexture); + } } } @@ -374,7 +382,9 @@ public class BSShapeMesh : BSShape // Check to see if mesh was created (might require an asset). newShape = VerifyMeshCreated(physicsScene, newShape, prim); - if (!newShape.isNativeShape || prim.PrimAssetState == BSPhysObject.PrimAssetCondition.Failed) + if (!newShape.isNativeShape + || prim.PrimAssetState == BSPhysObject.PrimAssetCondition.FailedMeshing + || prim.PrimAssetState == BSPhysObject.PrimAssetCondition.FailedAssetFetch) { // If a mesh was what was created, remember the built shape for later sharing. // Also note that if meshing failed we put it in the mesh list as there is nothing else to do about the mesh. @@ -517,7 +527,7 @@ public class BSShapeMesh : BSShape else { // Force the asset condition to 'failed' so we won't try to keep fetching and processing this mesh. - prim.PrimAssetState = BSPhysObject.PrimAssetCondition.Failed; + prim.PrimAssetState = BSPhysObject.PrimAssetCondition.FailedMeshing; physicsScene.Logger.DebugFormat("{0} All mesh triangles degenerate. Prim {1} at {2} in {3}", LogHeader, prim.PhysObjectName, prim.RawPosition, physicsScene.Name); physicsScene.DetailLog("{0},BSShapeMesh.CreatePhysicalMesh,allDegenerate,key={1}", prim.LocalID, newMeshKey); @@ -559,7 +569,9 @@ public class BSShapeHull : BSShape // Check to see if hull was created (might require an asset). newShape = VerifyMeshCreated(physicsScene, newShape, prim); - if (!newShape.isNativeShape || prim.PrimAssetState == BSPhysObject.PrimAssetCondition.Failed) + if (!newShape.isNativeShape + || prim.PrimAssetState == BSPhysObject.PrimAssetCondition.FailedMeshing + || prim.PrimAssetState == BSPhysObject.PrimAssetCondition.FailedAssetFetch) { // If a mesh was what was created, remember the built shape for later sharing. Hulls.Add(newHullKey, retHull); @@ -1079,10 +1091,13 @@ public class BSShapeGImpact : BSShape // Check to see if mesh was created (might require an asset). newShape = VerifyMeshCreated(physicsScene, newShape, prim); newShape.shapeKey = newMeshKey; - if (!newShape.isNativeShape || prim.PrimAssetState == BSPhysObject.PrimAssetCondition.Failed) + if (!newShape.isNativeShape + || prim.PrimAssetState == BSPhysObject.PrimAssetCondition.FailedMeshing + || prim.PrimAssetState == BSPhysObject.PrimAssetCondition.FailedAssetFetch) { // If a mesh was what was created, remember the built shape for later sharing. - // Also note that if meshing failed we put it in the mesh list as there is nothing else to do about the mesh. + // Also note that if meshing failed we put it in the mesh list as there is nothing + // else to do about the mesh. GImpacts.Add(newMeshKey, retGImpact); } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimTODO.txt b/OpenSim/Region/Physics/BulletSPlugin/BulletSimTODO.txt index df1da63..1e01526 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimTODO.txt +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimTODO.txt @@ -2,11 +2,6 @@ CURRENT PROBLEMS TO FIX AND/OR LOOK AT ================================================= Script changing rotation of child prim while vehicle moving (eg turning wheel) causes the wheel to appear to jump back. Looks like sending position from previous update. -Vehicle ride, get up, ride again. Second time vehicle does not act correctly. - Have to rez new vehicle and delete the old to fix situation. -Hitting RESET on Nebadon's vehicle while riding causes vehicle to get into odd - position state where it will not settle onto ground properly, etc -Two of Nebadon vehicles in a sim max the CPU. This is new. Enable vehicle border crossings (at least as poorly as ODE) Terrain skirts Avatar created in previous region and not new region when crossing border @@ -23,24 +18,17 @@ vehicle angular banking Center-of-gravity Vehicle angular deflection Preferred orientation angular correction fix -when should angular and linear motor targets be zeroed? when selected? - Need a vehicle.clear()? Or an 'else' in prestep if not physical. Teravus llMoveToTarget script debug Mixing of hover, buoyancy/gravity, moveToTarget, into one force Setting hover height to zero disables hover even if hover flags are on (from SL wiki) limitMotorUp calibration (more down?) llRotLookAt llLookAt -Avatars walking up stairs (HALF DONE) -Avatar movement - flying into a wall doesn't stop avatar who keeps appearing to move through the obstacle (DONE) - walking up stairs is not calibrated correctly (stairs out of Kepler cabin) (DONE) - avatar capsule rotation completed (NOT DONE - Bullet's capsule shape is not the solution) +Convert to avatar mesh capsule. Include rotation of capsule. Vehicle script tuning/debugging Avanti speed script Weapon shooter script Move material definitions (friction, ...) into simulator. -Add material densities to the material types. One sided meshes? Should terrain be built into a closed shape? When meshes get partially wedged into the terrain, they cannot push themselves out. It is possible that Bullet processes collisions whether entering or leaving a mesh. @@ -53,12 +41,8 @@ LINEAR_MOTOR_DIRECTION values should be clamped to reasonable numbers. Same for other velocity settings. UBit improvements to remove rubber-banding of avatars sitting on vehicle child prims: https://github.com/UbitUmarov/Ubit-opensim -Border crossing with linked vehicle causes crash - 20121129.1411: editting/moving phys object across region boundries causes crash - getPos-> btRigidBody::upcast -> getBodyType -> BOOM Vehicles (Move smoothly) Some vehicles should not be able to turn if no speed or off ground. -What to do if vehicle and prim buoyancy differ? Cannot edit/move a vehicle being ridden: it jumps back to the origional position. Neb car jiggling left and right Happens on terrain and any other mesh object. Flat cubes are much smoother. @@ -68,8 +52,6 @@ For limitMotorUp, use raycast down to find if vehicle is in the air. Verify llGetVel() is returning a smooth and good value for vehicle movement. llGetVel() should return the root's velocity if requested in a child prim. Implement function efficiency for lineaar and angular motion. -After getting off a vehicle, the root prim is phantom (can be walked through) - Need to force a position update for the root prim after compound shape destruction Linkset explosion after three "rides" on Nebadon lite vehicle (LinksetConstraint) Remove vehicle angular velocity zeroing in BSPrim.UpdateProperties(). A kludge that isn't fixing the real problem of Bullet adding extra motion. @@ -78,11 +60,10 @@ Incorporate inter-relationship of angular corrections. For instance, angularDefl creates over-correction and over-shoot and wabbling. Vehicle attributes are not restored when a vehicle is rezzed on region creation Create vehicle, setup vehicle properties, restart region, vehicle is not reinitialized. +What to do if vehicle and prim buoyancy differ? GENERAL TODO LIST: ================================================= -Explore btGImpactMeshShape as alternative to convex hulls for simplified physical objects. - Regular triangle meshes don't do physical collisions. Resitution of a prim works on another prim but not on terrain. The dropped prim doesn't bounce properly on the terrain. Add a sanity check for PIDTarget location. @@ -359,4 +340,25 @@ Lock axis (DONE 20130401) Terrain detail: double terrain mesh detail (DONE) Use the HACD convex hull routine in Bullet rather than the C# version. Speed up hullifying large meshes. (DONE) +Vehicle ride, get up, ride again. Second time vehicle does not act correctly. + Have to rez new vehicle and delete the old to fix situation. + (DONE 20130520: normalize rotations) +Hitting RESET on Nebadon's vehicle while riding causes vehicle to get into odd + position state where it will not settle onto ground properly, etc + (DONE 20130520: normalize rotations) +Two of Nebadon vehicles in a sim max the CPU. This is new. + (DONE 20130520: two problems: if asset failed to mesh, constantly refetched + asset; vehicle was sending too many messages to all linkset members) +Add material densities to the material types. (WILL NOT BE DONE: not how it is done) +Avatars walking up stairs (DONE) +Avatar movement + flying into a wall doesn't stop avatar who keeps appearing to move through the obstacle (DONE) + walking up stairs is not calibrated correctly (stairs out of Kepler cabin) (DONE) + avatar capsule rotation completed (NOT DONE - Bullet's capsule shape is not the solution) +After getting off a vehicle, the root prim is phantom (can be walked through) + Need to force a position update for the root prim after compound shape destruction + (DONE) +Explore btGImpactMeshShape as alternative to convex hulls for simplified physical objects. + Regular triangle meshes don't do physical collisions. + (DONE: discovered GImpact is VERY CPU intensive) -- cgit v1.1 From 3cb65f0d3166f976713a7c095eb37e6de05061d0 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 11 Jun 2013 17:58:08 -0700 Subject: BulletSim: when meshing or asset fetching fails, include position and region with the offending object's name in the error message. --- OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs | 40 ++++++++++++++-------- .../Region/Physics/BulletSPlugin/BulletSimTODO.txt | 4 +++ 2 files changed, 30 insertions(+), 14 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs index 202a4ce..006a9c1 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs @@ -168,10 +168,10 @@ public abstract class BSShape if (prim.PrimAssetState == BSPhysObject.PrimAssetCondition.Fetched) { prim.PrimAssetState = BSPhysObject.PrimAssetCondition.FailedMeshing; - physicsScene.Logger.WarnFormat("{0} Fetched asset would not mesh. {1}, texture={2}", - LogHeader, prim.PhysObjectName, prim.BaseShape.SculptTexture); - physicsScene.DetailLog("{0},BSShape.VerifyMeshCreated,setFailed,objNam={1},tex={2}", - prim.LocalID, prim.PhysObjectName, prim.BaseShape.SculptTexture); + physicsScene.Logger.WarnFormat("{0} Fetched asset would not mesh. prim={1}, texture={2}", + LogHeader, UsefulPrimInfo(physicsScene, prim), prim.BaseShape.SculptTexture); + physicsScene.DetailLog("{0},BSShape.VerifyMeshCreated,setFailed,prim={1},tex={2}", + prim.LocalID, UsefulPrimInfo(physicsScene, prim), prim.BaseShape.SculptTexture); } else { @@ -238,17 +238,17 @@ public abstract class BSShape { if (prim.PrimAssetState == BSPhysObject.PrimAssetCondition.FailedAssetFetch) { - physicsScene.Logger.WarnFormat("{0} Mesh failed to fetch asset. obj={1}, texture={2}", - LogHeader, prim.PhysObjectName, prim.BaseShape.SculptTexture); - physicsScene.DetailLog("{0},BSShape.VerifyMeshCreated,wasFailed,objNam={1},tex={2}", - prim.LocalID, prim.PhysObjectName, prim.BaseShape.SculptTexture); + physicsScene.Logger.WarnFormat("{0} Mesh failed to fetch asset. prim={1}, texture={2}", + LogHeader, UsefulPrimInfo(physicsScene, prim), prim.BaseShape.SculptTexture); + physicsScene.DetailLog("{0},BSShape.VerifyMeshCreated,wasFailed,prim={1},tex={2}", + prim.LocalID, UsefulPrimInfo(physicsScene, prim), prim.BaseShape.SculptTexture); } if (prim.PrimAssetState == BSPhysObject.PrimAssetCondition.FailedMeshing) { - physicsScene.Logger.WarnFormat("{0} Mesh asset would not mesh. obj={1}, texture={2}", - LogHeader, prim.PhysObjectName, prim.BaseShape.SculptTexture); - physicsScene.DetailLog("{0},BSShape.VerifyMeshCreated,wasFailedMeshing,objNam={1},tex={2}", - prim.LocalID, prim.PhysObjectName, prim.BaseShape.SculptTexture); + physicsScene.Logger.WarnFormat("{0} Mesh asset would not mesh. prim={1}, texture={2}", + LogHeader, UsefulPrimInfo(physicsScene, prim), prim.BaseShape.SculptTexture); + physicsScene.DetailLog("{0},BSShape.VerifyMeshCreated,wasFailedMeshing,prim={1},tex={2}", + prim.LocalID, UsefulPrimInfo(physicsScene, prim), prim.BaseShape.SculptTexture); } } } @@ -260,6 +260,19 @@ public abstract class BSShape return fillShape.physShapeInfo; } + public static String UsefulPrimInfo(BSScene pScene, BSPhysObject prim) + { + StringBuilder buff = new StringBuilder(prim.PhysObjectName); + buff.Append("/pos="); + buff.Append(prim.RawPosition.ToString()); + if (pScene != null) + { + buff.Append("/rgn="); + buff.Append(pScene.Name); + } + return buff.ToString(); + } + #endregion // Common shape routines } @@ -528,8 +541,7 @@ public class BSShapeMesh : BSShape { // Force the asset condition to 'failed' so we won't try to keep fetching and processing this mesh. prim.PrimAssetState = BSPhysObject.PrimAssetCondition.FailedMeshing; - physicsScene.Logger.DebugFormat("{0} All mesh triangles degenerate. Prim {1} at {2} in {3}", - LogHeader, prim.PhysObjectName, prim.RawPosition, physicsScene.Name); + physicsScene.Logger.DebugFormat("{0} All mesh triangles degenerate. Prim={1}", LogHeader, UsefulPrimInfo(physicsScene, prim) ); physicsScene.DetailLog("{0},BSShapeMesh.CreatePhysicalMesh,allDegenerate,key={1}", prim.LocalID, newMeshKey); } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimTODO.txt b/OpenSim/Region/Physics/BulletSPlugin/BulletSimTODO.txt index 1e01526..4357ef1 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimTODO.txt +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimTODO.txt @@ -1,5 +1,9 @@ CURRENT PROBLEMS TO FIX AND/OR LOOK AT ================================================= +Vehicle buoyancy. Computed correctly? Possibly creating very large effective mass. + Interaction of llSetBuoyancy and vehicle buoyancy. Should be additive? + Negative buoyancy computed correctly +Computation of mesh mass. How done? How should it be done? Script changing rotation of child prim while vehicle moving (eg turning wheel) causes the wheel to appear to jump back. Looks like sending position from previous update. Enable vehicle border crossings (at least as poorly as ODE) -- cgit v1.1 From bbeff4b8ca34a4567f2215ed5e90637a00d8c81e Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Thu, 20 Jun 2013 09:55:40 -0700 Subject: BulletSim: rework velocity updating when not colliding and not flying to prevent infinite jumps. Now jumps last only AvatarJumpFrames long (default 4) which is about as high as in SL. TODO: jumping should only depend on standing (collision with feet) rather than collision anywhere on the avatar. --- .../Physics/BulletSPlugin/BSActorAvatarMove.cs | 44 +++++++++++++++++++--- OpenSim/Region/Physics/BulletSPlugin/BSParam.cs | 3 ++ 2 files changed, 42 insertions(+), 5 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs b/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs index ac8c30c..928b350 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs @@ -43,8 +43,14 @@ public class BSActorAvatarMove : BSActor // Set to true if we think we're going up stairs. // This state is remembered because collisions will turn on and off as we go up stairs. int m_walkingUpStairs; + // The amount the step up is applying. Used to smooth stair walking. float m_lastStepUp; + // Jumping happens over several frames. If use applies up force while colliding, start the + // jump and allow the jump to continue for this number of frames. + int m_jumpFrames = 0; + float m_jumpVelocity = 0f; + public BSActorAvatarMove(BSScene physicsScene, BSPhysObject pObj, string actorName) : base(physicsScene, pObj, actorName) { @@ -206,17 +212,45 @@ public class BSActorAvatarMove : BSActor if (m_controllingPrim.Friction != BSParam.AvatarFriction) { - // Probably starting up walking. Set friction to moving friction. + // Probably starting to walk. Set friction to moving friction. m_controllingPrim.Friction = BSParam.AvatarFriction; m_physicsScene.PE.SetFriction(m_controllingPrim.PhysBody, m_controllingPrim.Friction); } - // If falling, we keep the world's downward vector no matter what the other axis specify. - // The check for RawVelocity.Z < 0 makes jumping work (temporary upward force). if (!m_controllingPrim.Flying && !m_controllingPrim.IsColliding) { - if (m_controllingPrim.RawVelocity.Z < 0) + stepVelocity.Z = m_controllingPrim.RawVelocity.Z; + } + + + // Colliding and not flying with an upward force. The avatar must be trying to jump. + if (!m_controllingPrim.Flying && m_controllingPrim.IsColliding && stepVelocity.Z > 0) + { + // We allow the upward force to happen for this many frames. + m_jumpFrames = BSParam.AvatarJumpFrames; + m_jumpVelocity = stepVelocity.Z; + } + + // The case where the avatar is not colliding and is not flying is special. + // The avatar is either falling or jumping and the user can be applying force to the avatar + // (force in some direction or force up or down). + // If the avatar has negative Z velocity and is not colliding, presume we're falling and keep the velocity. + // If the user is trying to apply upward force but we're not colliding, assume the avatar + // is trying to jump and don't apply the upward force if not touching the ground any more. + if (!m_controllingPrim.Flying && !m_controllingPrim.IsColliding) + { + // If upward velocity is being applied, this must be a jump and only allow that to go on so long + if (m_jumpFrames > 0) + { + // Since not touching the ground, only apply upward force for so long. + m_jumpFrames--; + stepVelocity.Z = m_jumpVelocity; + } + else + { + // Since we're not affected by anything, whatever vertical motion the avatar has, continue that. stepVelocity.Z = m_controllingPrim.RawVelocity.Z; + } // DetailLog("{0},BSCharacter.MoveMotor,taint,overrideStepZWithWorldZ,stepVel={1}", LocalID, stepVelocity); } @@ -241,7 +275,7 @@ public class BSActorAvatarMove : BSActor m_physicsScene.DetailLog("{0},BSCharacter.WalkUpStairs,IsColliding={1},flying={2},targSpeed={3},collisions={4},avHeight={5}", m_controllingPrim.LocalID, m_controllingPrim.IsColliding, m_controllingPrim.Flying, m_controllingPrim.TargetVelocitySpeed, m_controllingPrim.CollisionsLastTick.Count, m_controllingPrim.Size.Z); - // This test is done if moving forward, not flying and is colliding with something. + // Check for stairs climbing if colliding, not flying and moving forward if ( m_controllingPrim.IsColliding && !m_controllingPrim.Flying diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs index aad1108..6437b04 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs @@ -134,6 +134,7 @@ public static class BSParam public static float AvatarHeightMidFudge { get; private set; } public static float AvatarHeightHighFudge { get; private set; } public static float AvatarContactProcessingThreshold { get; private set; } + public static int AvatarJumpFrames { get; private set; } public static float AvatarBelowGroundUpCorrectionMeters { get; private set; } public static float AvatarStepHeight { get; private set; } public static float AvatarStepApproachFactor { get; private set; } @@ -567,6 +568,8 @@ public static class BSParam 0.1f ), new ParameterDefn("AvatarBelowGroundUpCorrectionMeters", "Meters to move avatar up if it seems to be below ground", 1.0f ), + new ParameterDefn("AvatarJumpFrames", "Number of frames to allow jump forces. Changes jump height.", + 4 ), new ParameterDefn("AvatarStepHeight", "Height of a step obstacle to consider step correction", 0.6f ) , new ParameterDefn("AvatarStepApproachFactor", "Factor to control angle of approach to step (0=straight on)", -- cgit v1.1 From a5de4f692bd0de5faccdcf32a923a72949bb3cca Mon Sep 17 00:00:00 2001 From: Vegaslon Date: Sat, 15 Jun 2013 17:23:43 -0400 Subject: BulletSim: Implementation of Linear Deflection, it is a partial help for the vehicle tuning diffrence between Opensim and Second life. Signed-off-by: Robert Adams --- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 38 +++++++++++++++++++--- 1 file changed, 33 insertions(+), 5 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index 311cf4f..51207f1 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -209,7 +209,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin m_VhoverTimescale = Math.Max(pValue, 0.01f); break; case Vehicle.LINEAR_DEFLECTION_EFFICIENCY: - m_linearDeflectionEfficiency = Math.Max(pValue, 0.01f); + m_linearDeflectionEfficiency = ClampInRange(0f, pValue, 1f); break; case Vehicle.LINEAR_DEFLECTION_TIMESCALE: m_linearDeflectionTimescale = Math.Max(pValue, 0.01f); @@ -1029,9 +1029,13 @@ namespace OpenSim.Region.Physics.BulletSPlugin Vector3 currentVelV = VehicleVelocity * Quaternion.Inverse(VehicleOrientation); Vector3 linearMotorCorrectionV = m_linearMotor.Step(pTimestep, currentVelV); + //Compute Linear deflection. + Vector3 linearDeflectionFactorV = ComputeLinearDeflection(m_linearDeflectionEfficiency, currentVelV, pTimestep); + linearMotorCorrectionV += linearDeflectionFactorV; + // Friction reduces vehicle motion - Vector3 frictionFactorW = ComputeFrictionFactor(m_linearFrictionTimescale, pTimestep); - linearMotorCorrectionV -= (currentVelV * frictionFactorW); + Vector3 frictionFactorV = ComputeFrictionFactor(m_linearFrictionTimescale, pTimestep); + linearMotorCorrectionV -= (currentVelV * frictionFactorV); // Motor is vehicle coordinates. Rotate it to world coordinates Vector3 linearMotorVelocityW = linearMotorCorrectionV * VehicleOrientation; @@ -1048,9 +1052,9 @@ namespace OpenSim.Region.Physics.BulletSPlugin - VDetailLog("{0}, MoveLinear,velocity,origVelW={1},velV={2},correctV={3},correctW={4},newVelW={5},fricFact={6}", + VDetailLog("{0}, MoveLinear,velocity,origVelW={1},velV={2},correctV={3},correctW={4},newVelW={5},fricFact={6},LinearDeflec={7}", ControllingPrim.LocalID, origVelW, currentVelV, linearMotorCorrectionV, - linearMotorVelocityW, VehicleVelocity, frictionFactorW); + linearMotorVelocityW, VehicleVelocity, frictionFactorV, linearDeflectionFactorV); } public void ComputeLinearTerrainHeightCorrection(float pTimestep) @@ -1651,6 +1655,30 @@ namespace OpenSim.Region.Physics.BulletSPlugin } return frictionFactor; } + //Given a Deflection Effiency and a Velocity, Returns a Velocity that is Partially Deflected onto the X Axis + //Clamped so that a DeflectionTimescale of less then 1 does not increase force over original velocity + private Vector3 ComputeLinearDeflection(float DeflectionEfficiency,Vector3 Velocity,float pTimestep) + { + Vector3 LinearDeflection = Vector3.Zero; + LinearDeflection.Y = SortedClampInRange(0, (Velocity.Y * DeflectionEfficiency) / m_linearDeflectionTimescale, Velocity.Y); + LinearDeflection.Z = SortedClampInRange(0, (Velocity.Z * DeflectionEfficiency) / m_linearDeflectionTimescale, Velocity.Z); + LinearDeflection.X += Math.Abs(LinearDeflection.Y); + LinearDeflection.X += Math.Abs(LinearDeflection.Z); + LinearDeflection *= pTimestep; + return LinearDeflection*=new Vector3(1,-1,-1); + + } + private float SortedClampInRange(float clampa, float val, float clampb) + { + if (clampa > clampb) + { + float temp = clampa; + clampa = clampb; + clampb = temp; + } + return ClampInRange(clampa, val, clampb); + + } private float ClampInRange(float low, float val, float high) { -- cgit v1.1 From 74539659f6f9be557dbd07fdefa1adae1c59ce87 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Fri, 21 Jun 2013 10:46:21 -0700 Subject: BulletSim: move new linear deflection code to own routine. Remove VehicleForwardVelocity changed storage since the value will be modified as movement is processed. --- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 64 ++++++++++++---------- 1 file changed, 35 insertions(+), 29 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index 51207f1..07e87d1 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -707,7 +707,6 @@ namespace OpenSim.Region.Physics.BulletSPlugin private Vector3 m_knownRotationalVelocity; private Vector3 m_knownRotationalForce; private Vector3 m_knownRotationalImpulse; - private Vector3 m_knownForwardVelocity; // vehicle relative forward speed private const int m_knownChangedPosition = 1 << 0; private const int m_knownChangedVelocity = 1 << 1; @@ -719,7 +718,6 @@ namespace OpenSim.Region.Physics.BulletSPlugin private const int m_knownChangedRotationalImpulse = 1 << 7; private const int m_knownChangedTerrainHeight = 1 << 8; private const int m_knownChangedWaterLevel = 1 << 9; - private const int m_knownChangedForwardVelocity = 1 <<10; public void ForgetKnownVehicleProperties() { @@ -923,12 +921,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin { get { - if ((m_knownHas & m_knownChangedForwardVelocity) == 0) - { - m_knownForwardVelocity = VehicleVelocity * Quaternion.Inverse(Quaternion.Normalize(VehicleOrientation)); - m_knownHas |= m_knownChangedForwardVelocity; - } - return m_knownForwardVelocity; + return VehicleVelocity * Quaternion.Inverse(Quaternion.Normalize(VehicleOrientation)); } } private float VehicleForwardSpeed @@ -981,6 +974,8 @@ namespace OpenSim.Region.Physics.BulletSPlugin { ComputeLinearVelocity(pTimestep); + ComputeLinearDeflection(pTimestep); + ComputeLinearTerrainHeightCorrection(pTimestep); ComputeLinearHover(pTimestep); @@ -1026,14 +1021,10 @@ namespace OpenSim.Region.Physics.BulletSPlugin { // Step the motor from the current value. Get the correction needed this step. Vector3 origVelW = VehicleVelocity; // DEBUG - Vector3 currentVelV = VehicleVelocity * Quaternion.Inverse(VehicleOrientation); + Vector3 currentVelV = VehicleForwardVelocity; Vector3 linearMotorCorrectionV = m_linearMotor.Step(pTimestep, currentVelV); - //Compute Linear deflection. - Vector3 linearDeflectionFactorV = ComputeLinearDeflection(m_linearDeflectionEfficiency, currentVelV, pTimestep); - linearMotorCorrectionV += linearDeflectionFactorV; - - // Friction reduces vehicle motion + // Friction reduces vehicle motion based on absolute speed. Slow vehicle down by friction. Vector3 frictionFactorV = ComputeFrictionFactor(m_linearFrictionTimescale, pTimestep); linearMotorCorrectionV -= (currentVelV * frictionFactorV); @@ -1050,11 +1041,38 @@ namespace OpenSim.Region.Physics.BulletSPlugin // Add this correction to the velocity to make it faster/slower. VehicleVelocity += linearMotorVelocityW; + VDetailLog("{0}, MoveLinear,velocity,origVelW={1},velV={2},correctV={3},correctW={4},newVelW={5},fricFact={6}", + ControllingPrim.LocalID, origVelW, currentVelV, linearMotorCorrectionV, + linearMotorVelocityW, VehicleVelocity, frictionFactorV); + } + //Given a Deflection Effiency and a Velocity, Returns a Velocity that is Partially Deflected onto the X Axis + //Clamped so that a DeflectionTimescale of less then 1 does not increase force over original velocity + private void ComputeLinearDeflection(float pTimestep) + { + Vector3 linearDeflectionV = Vector3.Zero; + Vector3 velocityV = VehicleForwardVelocity; - VDetailLog("{0}, MoveLinear,velocity,origVelW={1},velV={2},correctV={3},correctW={4},newVelW={5},fricFact={6},LinearDeflec={7}", - ControllingPrim.LocalID, origVelW, currentVelV, linearMotorCorrectionV, - linearMotorVelocityW, VehicleVelocity, frictionFactorV, linearDeflectionFactorV); + // Velocity in Y and Z dimensions is movement to the side or turning. + // Compute deflection factor from the to the side and rotational velocity + linearDeflectionV.Y = SortedClampInRange(0, (velocityV.Y * m_linearDeflectionEfficiency) / m_linearDeflectionTimescale, velocityV.Y); + linearDeflectionV.Z = SortedClampInRange(0, (velocityV.Z * m_linearDeflectionEfficiency) / m_linearDeflectionTimescale, velocityV.Z); + + // Velocity to the side and around is corrected and moved into the forward direction + linearDeflectionV.X += Math.Abs(linearDeflectionV.Y); + linearDeflectionV.X += Math.Abs(linearDeflectionV.Z); + + // Scale the deflection to the fractional simulation time + linearDeflectionV *= pTimestep; + + // Subtract the sideways and rotational velocity deflection factors while adding the correction forward + linearDeflectionV *= new Vector3(1,-1,-1); + + // Correciont is vehicle relative. Convert to world coordinates and add to the velocity + VehicleVelocity += linearDeflectionV * VehicleOrientation; + + VDetailLog("{0}, MoveLinear,LinearDeflection,linDefEff={1},linDefTS={2},linDeflectionV={3}", + ControllingPrim.LocalID, m_linearDeflectionEfficiency, m_linearDeflectionTimescale, linearDeflectionV); } public void ComputeLinearTerrainHeightCorrection(float pTimestep) @@ -1655,19 +1673,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin } return frictionFactor; } - //Given a Deflection Effiency and a Velocity, Returns a Velocity that is Partially Deflected onto the X Axis - //Clamped so that a DeflectionTimescale of less then 1 does not increase force over original velocity - private Vector3 ComputeLinearDeflection(float DeflectionEfficiency,Vector3 Velocity,float pTimestep) - { - Vector3 LinearDeflection = Vector3.Zero; - LinearDeflection.Y = SortedClampInRange(0, (Velocity.Y * DeflectionEfficiency) / m_linearDeflectionTimescale, Velocity.Y); - LinearDeflection.Z = SortedClampInRange(0, (Velocity.Z * DeflectionEfficiency) / m_linearDeflectionTimescale, Velocity.Z); - LinearDeflection.X += Math.Abs(LinearDeflection.Y); - LinearDeflection.X += Math.Abs(LinearDeflection.Z); - LinearDeflection *= pTimestep; - return LinearDeflection*=new Vector3(1,-1,-1); - } private float SortedClampInRange(float clampa, float val, float clampb) { if (clampa > clampb) -- cgit v1.1 From 2f4a729d408acfd311c8b7bc53d2cbff9d2ddfad Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Sat, 29 Jun 2013 06:42:38 -0700 Subject: BulletSim: add inTaintTime parameter to collision cache clear function. --- OpenSim/Region/Physics/BulletSPlugin/BSParam.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs index 6437b04..d17c8e7 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs @@ -706,7 +706,7 @@ public static class BSParam new ParameterDefn("ResetBroadphasePool", "Setting this is any value resets the broadphase collision pool", 0f, (s) => { return 0f; }, - (s,v) => { BSParam.ResetBroadphasePoolTainted(s, v); } ), + (s,v) => { BSParam.ResetBroadphasePoolTainted(s, v, false /* inTaintTime */); } ), new ParameterDefn("ResetConstraintSolver", "Setting this is any value resets the constraint solver", 0f, (s) => { return 0f; }, @@ -792,10 +792,10 @@ public static class BSParam // ===================================================================== // There are parameters that, when set, cause things to happen in the physics engine. // This causes the broadphase collision cache to be cleared. - private static void ResetBroadphasePoolTainted(BSScene pPhysScene, float v) + private static void ResetBroadphasePoolTainted(BSScene pPhysScene, float v, bool inTaintTime) { BSScene physScene = pPhysScene; - physScene.TaintedObject("BSParam.ResetBroadphasePoolTainted", delegate() + physScene.TaintedObject(inTaintTime, "BSParam.ResetBroadphasePoolTainted", delegate() { physScene.PE.ResetBroadphasePool(physScene.World); }); -- cgit v1.1 From 23516717e48095011c1c06d64785ef7d91754ff2 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Sun, 30 Jun 2013 13:39:58 -0700 Subject: BulletSim: a better version of llMoveToTarget that doesn't go crazy. There is still some overshoot but mostly fixes Mantis 6693. Fix bug where moveToTarget was active for non-physical objects and while selected. Fix bug where move target was not getting changed if the script changed the target during a move. --- .../Physics/BulletSPlugin/BSActorMoveToTarget.cs | 80 +++++++++++++++++++--- .../Region/Physics/BulletSPlugin/BSCharacter.cs | 2 +- OpenSim/Region/Physics/BulletSPlugin/BSMotors.cs | 15 ++-- .../Region/Physics/BulletSPlugin/BSPhysObject.cs | 1 + OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 19 ++++- 5 files changed, 98 insertions(+), 19 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSActorMoveToTarget.cs b/OpenSim/Region/Physics/BulletSPlugin/BSActorMoveToTarget.cs index 75ff24e..bdf4bc0 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSActorMoveToTarget.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSActorMoveToTarget.cs @@ -50,7 +50,8 @@ public class BSActorMoveToTarget : BSActor // BSActor.isActive public override bool isActive { - get { return Enabled; } + // MoveToTarget only works on physical prims + get { return Enabled && m_controllingPrim.IsPhysicallyActive; } } // Release any connections and resources used by the actor. @@ -102,16 +103,28 @@ public class BSActorMoveToTarget : BSActor // We're taking over after this. m_controllingPrim.ZeroMotion(true); - m_targetMotor = new BSVMotor("BSActorMoveToTargget.Activate", - m_controllingPrim.MoveToTargetTau, // timeScale - BSMotor.Infinite, // decay time scale - 1f // efficiency + /* Someday use the PID controller + m_targetMotor = new BSPIDVMotor("BSActorMoveToTarget-" + m_controllingPrim.LocalID.ToString()); + m_targetMotor.TimeScale = m_controllingPrim.MoveToTargetTau; + m_targetMotor.Efficiency = 1f; + */ + m_targetMotor = new BSVMotor("BSActorMoveToTarget-" + m_controllingPrim.LocalID.ToString(), + m_controllingPrim.MoveToTargetTau, // timeScale + BSMotor.Infinite, // decay time scale + 1f // efficiency ); m_targetMotor.PhysicsScene = m_physicsScene; // DEBUG DEBUG so motor will output detail log messages. m_targetMotor.SetTarget(m_controllingPrim.MoveToTargetTarget); m_targetMotor.SetCurrent(m_controllingPrim.RawPosition); - m_physicsScene.BeforeStep += Mover; + // m_physicsScene.BeforeStep += Mover; + m_physicsScene.BeforeStep += Mover2; + } + else + { + // If already allocated, make sure the target and other paramters are current + m_targetMotor.SetTarget(m_controllingPrim.MoveToTargetTarget); + m_targetMotor.SetCurrent(m_controllingPrim.RawPosition); } } @@ -119,12 +132,16 @@ public class BSActorMoveToTarget : BSActor { if (m_targetMotor != null) { - m_physicsScene.BeforeStep -= Mover; + // m_physicsScene.BeforeStep -= Mover; + m_physicsScene.BeforeStep -= Mover2; m_targetMotor = null; } } - // Called just before the simulation step. Update the vertical position for hoverness. + // Origional mover that set the objects position to move to the target. + // The problem was that gravity would keep trying to push the object down so + // the overall downward velocity would increase to infinity. + // Called just before the simulation step. private void Mover(float timeStep) { // Don't do hovering while the object is selected. @@ -142,6 +159,7 @@ public class BSActorMoveToTarget : BSActor m_physicsScene.DetailLog("{0},BSActorMoveToTarget.Mover,zeroMovement,movePos={1},pos={2},mass={3}", m_controllingPrim.LocalID, movePosition, m_controllingPrim.RawPosition, m_controllingPrim.Mass); m_controllingPrim.ForcePosition = m_targetMotor.TargetValue; + m_controllingPrim.ForceVelocity = OMV.Vector3.Zero; // Setting the position does not cause the physics engine to generate a property update. Force it. m_physicsScene.PE.PushUpdate(m_controllingPrim.PhysBody); } @@ -151,7 +169,51 @@ public class BSActorMoveToTarget : BSActor // Setting the position does not cause the physics engine to generate a property update. Force it. m_physicsScene.PE.PushUpdate(m_controllingPrim.PhysBody); } - m_physicsScene.DetailLog("{0},BSActorMoveToTarget.Mover,move,fromPos={1},movePos={2}", m_controllingPrim.LocalID, origPosition, movePosition); + m_physicsScene.DetailLog("{0},BSActorMoveToTarget.Mover,move,fromPos={1},movePos={2}", + m_controllingPrim.LocalID, origPosition, movePosition); + } + + // Version of mover that applies forces to move the physical object to the target. + // Also overcomes gravity so the object doesn't just drop to the ground. + // Called just before the simulation step. + private void Mover2(float timeStep) + { + // Don't do hovering while the object is selected. + if (!isActive) + return; + + OMV.Vector3 origPosition = m_controllingPrim.RawPosition; // DEBUG DEBUG (for printout below) + OMV.Vector3 addedForce = OMV.Vector3.Zero; + + // CorrectionVector is the movement vector required this step + OMV.Vector3 correctionVector = m_targetMotor.Step(timeStep, m_controllingPrim.RawPosition); + + // If we are very close to our target, turn off the movement motor. + if (m_targetMotor.ErrorIsZero()) + { + m_physicsScene.DetailLog("{0},BSActorMoveToTarget.Mover3,zeroMovement,pos={1},mass={2}", + m_controllingPrim.LocalID, m_controllingPrim.RawPosition, m_controllingPrim.Mass); + m_controllingPrim.ForcePosition = m_targetMotor.TargetValue; + m_controllingPrim.ForceVelocity = OMV.Vector3.Zero; + // Setting the position does not cause the physics engine to generate a property update. Force it. + m_physicsScene.PE.PushUpdate(m_controllingPrim.PhysBody); + } + else + { + // First force to move us there -- the motor return a timestep scaled value. + addedForce = correctionVector / timeStep; + // Remove the existing velocity (only the moveToTarget force counts) + addedForce -= m_controllingPrim.RawVelocity; + // Overcome gravity. + addedForce -= m_controllingPrim.Gravity; + + // Add enough force to overcome the mass of the object + addedForce *= m_controllingPrim.Mass; + + m_controllingPrim.AddForce(addedForce, false /* pushForce */, true /* inTaintTime */); + } + m_physicsScene.DetailLog("{0},BSActorMoveToTarget.Mover3,move,fromPos={1},addedForce={2}", + m_controllingPrim.LocalID, origPosition, addedForce); } } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index 48f842e..5ef6992 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -626,7 +626,7 @@ public sealed class BSCharacter : BSPhysObject OMV.Vector3 addForce = force / PhysScene.LastTimeStep; AddForce(addForce, pushforce, false); } - private void AddForce(OMV.Vector3 force, bool pushforce, bool inTaintTime) { + public override void AddForce(OMV.Vector3 force, bool pushforce, bool inTaintTime) { if (force.IsFinite()) { OMV.Vector3 addForce = Util.ClampV(force, BSParam.MaxAddForceMagnitude); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSMotors.cs b/OpenSim/Region/Physics/BulletSPlugin/BSMotors.cs index ef662b5..1214703 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSMotors.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSMotors.cs @@ -144,7 +144,6 @@ public class BSVMotor : BSMotor Vector3 correction = Vector3.Zero; Vector3 error = TargetValue - CurrentValue; - LastError = error; if (!ErrorIsZero(error)) { correction = StepError(timeStep, error); @@ -179,6 +178,7 @@ public class BSVMotor : BSMotor MDetailLog("{0}, BSVMotor.Step,zero,{1},origTgt={2},origCurr={3},currTgt={4},currCurr={5}", BSScene.DetailLogZero, UseName, origCurrVal, origTarget, TargetValue, CurrentValue); } + LastError = error; return correction; } @@ -293,7 +293,6 @@ public class BSFMotor : BSMotor float correction = 0f; float error = TargetValue - CurrentValue; - LastError = error; if (!ErrorIsZero(error)) { correction = StepError(timeStep, error); @@ -328,6 +327,7 @@ public class BSFMotor : BSMotor MDetailLog("{0}, BSFMotor.Step,zero,{1},origTgt={2},origCurr={3},ret={4}", BSScene.DetailLogZero, UseName, origCurrVal, origTarget, CurrentValue); } + LastError = error; return CurrentValue; } @@ -363,7 +363,7 @@ public class BSFMotor : BSMotor // ============================================================================ // ============================================================================ -// Proportional, Integral, Derivitive Motor +// Proportional, Integral, Derivitive ("PID") Motor // Good description at http://www.answers.com/topic/pid-controller . Includes processes for choosing p, i and d factors. public class BSPIDVMotor : BSVMotor { @@ -434,15 +434,14 @@ public class BSPIDVMotor : BSVMotor // A simple derivitive is the rate of change from the last error. Vector3 derivitive = (error - LastError) * timeStep; - LastError = error; // Correction = (proportionOfPresentError + accumulationOfPastError + rateOfChangeOfError) - Vector3 ret = error * timeStep * proportionFactor * FactorMix.X - + RunningIntegration * integralFactor * FactorMix.Y - + derivitive * derivFactor * FactorMix.Z + Vector3 ret = error / TimeScale * timeStep * proportionFactor * FactorMix.X + + RunningIntegration / TimeScale * integralFactor * FactorMix.Y + + derivitive / TimeScale * derivFactor * FactorMix.Z ; - MDetailLog("{0},BSPIDVMotor.step,ts={1},err={2},runnInt={3},deriv={4},ret={5}", + MDetailLog("{0}, BSPIDVMotor.step,ts={1},err={2},runnInt={3},deriv={4},ret={5}", BSScene.DetailLogZero, timeStep, error, RunningIntegration, derivitive, ret); return ret; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index a4c5e08..a0d5c42 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -210,6 +210,7 @@ public abstract class BSPhysObject : PhysicsActor AddAngularForce(force, pushforce, false); } public abstract void AddAngularForce(OMV.Vector3 force, bool pushforce, bool inTaintTime); + public abstract void AddForce(OMV.Vector3 force, bool pushforce, bool inTaintTime); public abstract OMV.Vector3 ForceRotationalVelocity { get; set; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 95bdc7b..90f74df 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -450,6 +450,9 @@ public class BSPrim : BSPhysObject Gravity = ComputeGravity(Buoyancy); PhysScene.PE.SetGravity(PhysBody, Gravity); + OMV.Vector3 currentScale = PhysScene.PE.GetLocalScaling(PhysShape.physShapeInfo); // DEBUG DEBUG + DetailLog("{0},BSPrim.UpdateMassProperties,currentScale{1},shape={2}", LocalID, currentScale, PhysShape.physShapeInfo); // DEBUG DEBUG + Inertia = PhysScene.PE.CalculateLocalInertia(PhysShape.physShapeInfo, physMass); PhysScene.PE.SetMassProps(PhysBody, physMass, Inertia); PhysScene.PE.UpdateInertiaTensor(PhysBody); @@ -1040,6 +1043,20 @@ public class BSPrim : BSPhysObject } } + public override OMV.Vector3 PIDTarget + { + set + { + base.PIDTarget = value; + BSActor actor; + if (PhysicalActors.TryGetActor(MoveToTargetActorName, out actor)) + { + // if the actor exists, tell it to refresh its values. + actor.Refresh(); + } + + } + } // Used for llSetHoverHeight and maybe vehicle height // Hover Height will override MoveTo target's Z public override bool PIDHoverActive { @@ -1063,7 +1080,7 @@ public class BSPrim : BSPhysObject // Applying a force just adds this to the total force on the object. // This added force will only last the next simulation tick. - public void AddForce(OMV.Vector3 force, bool pushforce, bool inTaintTime) { + public override void AddForce(OMV.Vector3 force, bool pushforce, bool inTaintTime) { // for an object, doesn't matter if force is a pushforce or not if (IsPhysicallyActive) { -- cgit v1.1 From 425d2a2a972de34c1853c6049727d4c0eea38af4 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Sun, 30 Jun 2013 13:48:27 -0700 Subject: BulletSim: set linkset type to be prim specific rather than a simulator wide default. This allows individual prims to differ in the underlying linkset implementation. --- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 16 ++++------------ .../Region/Physics/BulletSPlugin/BSLinksetCompound.cs | 2 -- OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs | 5 ++++- 3 files changed, 8 insertions(+), 15 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index 76c2187..ad8e10f 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -33,14 +33,6 @@ using OMV = OpenMetaverse; namespace OpenSim.Region.Physics.BulletSPlugin { -// A BSPrim can get individual information about its linkedness attached -// to it through an instance of a subclass of LinksetInfo. -// Each type of linkset will define the information needed for its type. -public abstract class BSLinksetInfo -{ - public virtual void Clear() { } -} - public abstract class BSLinkset { // private static string LogHeader = "[BULLETSIM LINKSET]"; @@ -56,15 +48,15 @@ public abstract class BSLinkset { BSLinkset ret = null; - switch ((int)BSParam.LinksetImplementation) + switch (parent.LinksetType) { - case (int)LinksetImplementation.Constraint: + case LinksetImplementation.Constraint: ret = new BSLinksetConstraints(physScene, parent); break; - case (int)LinksetImplementation.Compound: + case LinksetImplementation.Compound: ret = new BSLinksetCompound(physScene, parent); break; - case (int)LinksetImplementation.Manual: + case LinksetImplementation.Manual: // ret = new BSLinksetManual(physScene, parent); break; default: diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs index 350a5d1..308cf13 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs @@ -238,7 +238,6 @@ public sealed class BSLinksetCompound : BSLinkset // there will already be a rebuild scheduled. DetailLog("{0},BSLinksetCompound.UpdateProperties,couldNotUpdateChild.schedulingRebuild,whichUpdated={1}", updated.LocalID, whichUpdated); - updated.LinksetInfo = null; // setting to 'null' causes relative position to be recomputed. ScheduleRebuild(updated); } } @@ -294,7 +293,6 @@ public sealed class BSLinksetCompound : BSLinkset child.LocalID, child.PhysBody.AddrString); // Cause the child's body to be rebuilt and thus restored to normal operation - child.LinksetInfo = null; child.ForceBodyShapeRebuild(false); if (!HasAnyChildren) diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs index 235da78..87eed98 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs @@ -41,12 +41,15 @@ public class BSPrimLinkable : BSPrimDisplaced // The index of this child prim. public int LinksetChildIndex { get; set; } - public BSLinksetInfo LinksetInfo { get; set; } + public BSLinkset.LinksetImplementation LinksetType { get; set; } public BSPrimLinkable(uint localID, String primName, BSScene parent_scene, OMV.Vector3 pos, OMV.Vector3 size, OMV.Quaternion rotation, PrimitiveBaseShape pbs, bool pisPhysical) : base(localID, primName, parent_scene, pos, size, rotation, pbs, pisPhysical) { + // Default linkset implementation for this prim + LinksetType = (BSLinkset.LinksetImplementation)BSParam.LinksetImplementation; + Linkset = BSLinkset.Factory(PhysScene, this); PhysScene.TaintedObject("BSPrimLinksetCompound.Refresh", delegate() -- cgit v1.1 From 9d5ae759504f01dceac5d3f859da1e43e28797ad Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Sun, 30 Jun 2013 17:06:27 -0700 Subject: BulletSim: remove the handle to the vehicle actor and cause routines that need it to look it up. --- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 70 ++++++++++++++++------ .../Physics/BulletSPlugin/Tests/BasicVehicles.cs | 32 +++++----- 2 files changed, 70 insertions(+), 32 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 90f74df..b2947c6 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -70,18 +70,17 @@ public class BSPrim : BSPhysObject private int CrossingFailures { get; set; } // Keep a handle to the vehicle actor so it is easy to set parameters on same. - public BSDynamics VehicleActor; public const string VehicleActorName = "BasicVehicle"; // Parameters for the hover actor - public const string HoverActorName = "HoverActor"; + public const string HoverActorName = "BSPrim.HoverActor"; // Parameters for the axis lock actor public const String LockedAxisActorName = "BSPrim.LockedAxis"; // Parameters for the move to target actor - public const string MoveToTargetActorName = "MoveToTargetActor"; + public const string MoveToTargetActorName = "BSPrim.MoveToTargetActor"; // Parameters for the setForce and setTorque actors - public const string SetForceActorName = "SetForceActor"; - public const string SetTorqueActorName = "SetTorqueActor"; + public const string SetForceActorName = "BSPrim.SetForceActor"; + public const string SetTorqueActorName = "BSPrim.SetTorqueActor"; public BSPrim(uint localID, String primName, BSScene parent_scene, OMV.Vector3 pos, OMV.Vector3 size, OMV.Quaternion rotation, PrimitiveBaseShape pbs, bool pisPhysical) @@ -100,9 +99,8 @@ public class BSPrim : BSPhysObject _isPhysical = pisPhysical; _isVolumeDetect = false; - // We keep a handle to the vehicle actor so we can set vehicle parameters later. - VehicleActor = new BSDynamics(PhysScene, this, VehicleActorName); - PhysicalActors.Add(VehicleActorName, VehicleActor); + // Add a dynamic vehicle to our set of actors that can move this prim. + PhysicalActors.Add(VehicleActorName, new BSDynamics(PhysScene, this, VehicleActorName)); _mass = CalculateMass(); @@ -505,9 +503,25 @@ public class BSPrim : BSPhysObject } } + // Find and return a handle to the current vehicle actor. + // Return 'null' if there is no vehicle actor. + public BSDynamics GetVehicleActor() + { + BSDynamics ret = null; + BSActor actor; + if (PhysicalActors.TryGetActor(VehicleActorName, out actor)) + { + ret = actor as BSDynamics; + } + return ret; + } public override int VehicleType { get { - return (int)VehicleActor.Type; + int ret = (int)Vehicle.TYPE_NONE; + BSDynamics vehicleActor = GetVehicleActor(); + if (vehicleActor != null) + ret = (int)vehicleActor.Type; + return ret; } set { Vehicle type = (Vehicle)value; @@ -518,8 +532,12 @@ public class BSPrim : BSPhysObject // change all the parameters. Like a plane changing to CAR when on the // ground. In this case, don't want to zero motion. // ZeroMotion(true /* inTaintTime */); - VehicleActor.ProcessTypeChange(type); - ActivateIfPhysical(false); + BSDynamics vehicleActor = GetVehicleActor(); + if (vehicleActor != null) + { + vehicleActor.ProcessTypeChange(type); + ActivateIfPhysical(false); + } }); } } @@ -527,31 +545,47 @@ public class BSPrim : BSPhysObject { PhysScene.TaintedObject("BSPrim.VehicleFloatParam", delegate() { - VehicleActor.ProcessFloatVehicleParam((Vehicle)param, value); - ActivateIfPhysical(false); + BSDynamics vehicleActor = GetVehicleActor(); + if (vehicleActor != null) + { + vehicleActor.ProcessFloatVehicleParam((Vehicle)param, value); + ActivateIfPhysical(false); + } }); } public override void VehicleVectorParam(int param, OMV.Vector3 value) { PhysScene.TaintedObject("BSPrim.VehicleVectorParam", delegate() { - VehicleActor.ProcessVectorVehicleParam((Vehicle)param, value); - ActivateIfPhysical(false); + BSDynamics vehicleActor = GetVehicleActor(); + if (vehicleActor != null) + { + vehicleActor.ProcessVectorVehicleParam((Vehicle)param, value); + ActivateIfPhysical(false); + } }); } public override void VehicleRotationParam(int param, OMV.Quaternion rotation) { PhysScene.TaintedObject("BSPrim.VehicleRotationParam", delegate() { - VehicleActor.ProcessRotationVehicleParam((Vehicle)param, rotation); - ActivateIfPhysical(false); + BSDynamics vehicleActor = GetVehicleActor(); + if (vehicleActor != null) + { + vehicleActor.ProcessRotationVehicleParam((Vehicle)param, rotation); + ActivateIfPhysical(false); + } }); } public override void VehicleFlags(int param, bool remove) { PhysScene.TaintedObject("BSPrim.VehicleFlags", delegate() { - VehicleActor.ProcessVehicleFlags(param, remove); + BSDynamics vehicleActor = GetVehicleActor(); + if (vehicleActor != null) + { + vehicleActor.ProcessVehicleFlags(param, remove); + } }); } diff --git a/OpenSim/Region/Physics/BulletSPlugin/Tests/BasicVehicles.cs b/OpenSim/Region/Physics/BulletSPlugin/Tests/BasicVehicles.cs index b040e21..583c436 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/Tests/BasicVehicles.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/Tests/BasicVehicles.cs @@ -114,21 +114,25 @@ public class BasicVehicles : OpenSimTestCase // Instead the appropriate values are set and calls are made just the parts of the // controller we want to exercise. Stepping the physics engine then applies // the actions of that one feature. - TestVehicle.VehicleActor.ProcessFloatVehicleParam(Vehicle.VERTICAL_ATTRACTION_EFFICIENCY, efficiency); - TestVehicle.VehicleActor.ProcessFloatVehicleParam(Vehicle.VERTICAL_ATTRACTION_TIMESCALE, timeScale); - TestVehicle.VehicleActor.enableAngularVerticalAttraction = true; - - TestVehicle.IsPhysical = true; - PhysicsScene.ProcessTaints(); - - // Step the simulator a bunch of times and vertical attraction should orient the vehicle up - for (int ii = 0; ii < simSteps; ii++) + BSDynamics vehicleActor = TestVehicle.GetVehicleActor(); + if (vehicleActor != null) { - TestVehicle.VehicleActor.ForgetKnownVehicleProperties(); - TestVehicle.VehicleActor.ComputeAngularVerticalAttraction(); - TestVehicle.VehicleActor.PushKnownChanged(); - - PhysicsScene.Simulate(simulationTimeStep); + vehicleActor.ProcessFloatVehicleParam(Vehicle.VERTICAL_ATTRACTION_EFFICIENCY, efficiency); + vehicleActor.ProcessFloatVehicleParam(Vehicle.VERTICAL_ATTRACTION_TIMESCALE, timeScale); + vehicleActor.enableAngularVerticalAttraction = true; + + TestVehicle.IsPhysical = true; + PhysicsScene.ProcessTaints(); + + // Step the simulator a bunch of times and vertical attraction should orient the vehicle up + for (int ii = 0; ii < simSteps; ii++) + { + vehicleActor.ForgetKnownVehicleProperties(); + vehicleActor.ComputeAngularVerticalAttraction(); + vehicleActor.PushKnownChanged(); + + PhysicsScene.Simulate(simulationTimeStep); + } } TestVehicle.IsPhysical = false; -- cgit v1.1 From c24c99f4bab0ef2e926ebc46235ffed25fdd9add Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Sun, 30 Jun 2013 19:08:15 -0700 Subject: BulletSim: fix an occasional crash with flushing log files. --- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index dec6b6f..155d143 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -223,8 +223,8 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters // can be left in and every call doesn't have to check for null. if (m_physicsLoggingEnabled) { - PhysicsLogging = new Logging.LogWriter(m_physicsLoggingDir, m_physicsLoggingPrefix, m_physicsLoggingFileMinutes); - PhysicsLogging.ErrorLogger = m_log; // for DEBUG. Let's the logger output error messages. + PhysicsLogging = new Logging.LogWriter(m_physicsLoggingDir, m_physicsLoggingPrefix, m_physicsLoggingFileMinutes, m_physicsLoggingDoFlush); + PhysicsLogging.ErrorLogger = m_log; // for DEBUG. Let's the logger output its own error messages. } else { @@ -1106,8 +1106,6 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters public void DetailLog(string msg, params Object[] args) { PhysicsLogging.Write(msg, args); - // Add the Flush() if debugging crashes. Gets all the messages written out. - if (m_physicsLoggingDoFlush) PhysicsLogging.Flush(); } // Used to fill in the LocalID when there isn't one. It's the correct number of characters. public const string DetailLogZero = "0000000000"; -- cgit v1.1 From 8eb86c9ec91ee41699ab455fc5e788a4bff53071 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Sun, 30 Jun 2013 19:22:43 -0700 Subject: BulletSim: add the reset of the last commit for flush log file problems. Fix small typo in one log message. --- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 2 +- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index 07e87d1..aa247dd 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -1276,7 +1276,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin VehicleAddForce(appliedGravity); - VDetailLog("{0}, MoveLinear,applyGravity,vehGrav={1},collid={2},fudge={3},mass={4},appliedForce={3}", + VDetailLog("{0}, MoveLinear,applyGravity,vehGrav={1},collid={2},fudge={3},mass={4},appliedForce={5}", ControllingPrim.LocalID, m_VehicleGravity, ControllingPrim.IsColliding, BSParam.VehicleGroundGravityFudge, m_vehicleMass, appliedGravity); } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index 155d143..1645c98 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -223,7 +223,7 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters // can be left in and every call doesn't have to check for null. if (m_physicsLoggingEnabled) { - PhysicsLogging = new Logging.LogWriter(m_physicsLoggingDir, m_physicsLoggingPrefix, m_physicsLoggingFileMinutes, m_physicsLoggingDoFlush); + PhysicsLogging = new Logging.LogWriter(m_physicsLoggingDir, m_physicsLoggingPrefix, m_physicsLoggingFileMinutes, m_physicsLoggingDoFlush); PhysicsLogging.ErrorLogger = m_log; // for DEBUG. Let's the logger output its own error messages. } else -- cgit v1.1 From 5f97c6f8f06f0b90ab815a1d44358dc256ec5a50 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Thu, 4 Jul 2013 12:16:33 -0700 Subject: BulletSim: non-functional updates. Comments and formatting. Update TODO list. --- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 14 +++- OpenSim/Region/Physics/BulletSPlugin/BSMotors.cs | 15 +++-- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 6 +- .../Region/Physics/BulletSPlugin/BulletSimTODO.txt | 75 +++++++++++++--------- 4 files changed, 67 insertions(+), 43 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index aa247dd..c27d3f0 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -774,7 +774,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin // Since the computation of terrain height can be a little involved, this routine // is used to fetch the height only once for each vehicle simulation step. - Vector3 lastRememberedHeightPos; + Vector3 lastRememberedHeightPos = new Vector3(-1, -1, -1); private float GetTerrainHeight(Vector3 pos) { if ((m_knownHas & m_knownChangedTerrainHeight) == 0 || pos != lastRememberedHeightPos) @@ -788,14 +788,16 @@ namespace OpenSim.Region.Physics.BulletSPlugin // Since the computation of water level can be a little involved, this routine // is used ot fetch the level only once for each vehicle simulation step. + Vector3 lastRememberedWaterHeightPos = new Vector3(-1, -1, -1); private float GetWaterLevel(Vector3 pos) { - if ((m_knownHas & m_knownChangedWaterLevel) == 0) + if ((m_knownHas & m_knownChangedWaterLevel) == 0 || pos != lastRememberedWaterHeightPos) { + lastRememberedWaterHeightPos = pos; m_knownWaterLevel = ControllingPrim.PhysScene.TerrainManager.GetWaterLevelAtXYZ(pos); m_knownHas |= m_knownChangedWaterLevel; } - return (float)m_knownWaterLevel; + return m_knownWaterLevel; } private Vector3 VehiclePosition @@ -991,11 +993,17 @@ namespace OpenSim.Region.Physics.BulletSPlugin { Vector3 vel = VehicleVelocity; if ((m_flags & (VehicleFlag.NO_X)) != 0) + { vel.X = 0; + } if ((m_flags & (VehicleFlag.NO_Y)) != 0) + { vel.Y = 0; + } if ((m_flags & (VehicleFlag.NO_Z)) != 0) + { vel.Z = 0; + } VehicleVelocity = vel; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSMotors.cs b/OpenSim/Region/Physics/BulletSPlugin/BSMotors.cs index 1214703..7693195 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSMotors.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSMotors.cs @@ -188,6 +188,8 @@ public class BSVMotor : BSMotor CurrentValue = current; return Step(timeStep); } + // Given and error, computer a correction for this step. + // Simple scaling of the error by the timestep. public virtual Vector3 StepError(float timeStep, Vector3 error) { if (!Enabled) return Vector3.Zero; @@ -221,7 +223,7 @@ public class BSVMotor : BSMotor CurrentValue, TargetValue); LastError = BSMotor.InfiniteVector; - while (maxOutput-- > 0 && !LastError.ApproxEquals(Vector3.Zero, ErrorZeroThreshold)) + while (maxOutput-- > 0 && !ErrorIsZero()) { Vector3 lastStep = Step(timeStep); MDetailLog("{0},BSVMotor.Test,{1},cur={2},tgt={3},lastError={4},lastStep={5}", @@ -375,7 +377,6 @@ public class BSPIDVMotor : BSVMotor // The factors are vectors for the three dimensions. This is the proportional of each // that is applied. This could be multiplied through the actual factors but it // is sometimes easier to manipulate the factors and their mix separately. - // to public Vector3 FactorMix; // Arbritrary factor range. @@ -413,14 +414,14 @@ public class BSPIDVMotor : BSVMotor // If efficiency is high (1f), use a factor value that moves the error value to zero with little overshoot. // If efficiency is low (0f), use a factor value that overcorrects. // TODO: might want to vary contribution of different factor depending on efficiency. - float factor = ((1f - this.Efficiency) * EfficiencyHigh + EfficiencyLow) / 3f; - // float factor = (1f - this.Efficiency) * EfficiencyHigh + EfficiencyLow; + // float factor = ((1f - this.Efficiency) * EfficiencyHigh + EfficiencyLow) / 3f; + float factor = (1f - this.Efficiency) * EfficiencyHigh + EfficiencyLow; proportionFactor = new Vector3(factor, factor, factor); integralFactor = new Vector3(factor, factor, factor); derivFactor = new Vector3(factor, factor, factor); - MDetailLog("{0},BSPIDVMotor.setEfficiency,eff={1},factor={2}", BSScene.DetailLogZero, Efficiency, factor); + MDetailLog("{0}, BSPIDVMotor.setEfficiency,eff={1},factor={2}", BSScene.DetailLogZero, Efficiency, factor); } } @@ -441,8 +442,8 @@ public class BSPIDVMotor : BSVMotor + derivitive / TimeScale * derivFactor * FactorMix.Z ; - MDetailLog("{0}, BSPIDVMotor.step,ts={1},err={2},runnInt={3},deriv={4},ret={5}", - BSScene.DetailLogZero, timeStep, error, RunningIntegration, derivitive, ret); + MDetailLog("{0}, BSPIDVMotor.step,ts={1},err={2},lerr={3},runnInt={4},deriv={5},ret={6}", + BSScene.DetailLogZero, timeStep, error, LastError, RunningIntegration, derivitive, ret); return ret; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index b2947c6..f0858ca 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -1125,7 +1125,9 @@ public class BSPrim : BSPhysObject OMV.Vector3 addForce = force; PhysScene.TaintedObject(inTaintTime, "BSPrim.AddForce", delegate() { - // Bullet adds this central force to the total force for this tick + // Bullet adds this central force to the total force for this tick. + // Deep down in Bullet: + // linearVelocity += totalForce / mass * timeStep; DetailLog("{0},BSPrim.addForce,taint,force={1}", LocalID, addForce); if (PhysBody.HasPhysicalBody) { @@ -1493,6 +1495,8 @@ public class BSPrim : BSPhysObject returnMass = Util.Clamp(returnMass, BSParam.MinimumObjectMass, BSParam.MaximumObjectMass); // DetailLog("{0},BSPrim.CalculateMass,den={1},vol={2},mass={3}", LocalID, Density, volume, returnMass); + DetailLog("{0},BSPrim.CalculateMass,den={1},vol={2},mass={3},pathB={4},pathE={5},profB={6},profE={7},siz={8}", + LocalID, Density, volume, returnMass, pathBegin, pathEnd, profileBegin, profileEnd, _size); return returnMass; }// end CalculateMass diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimTODO.txt b/OpenSim/Region/Physics/BulletSPlugin/BulletSimTODO.txt index 4357ef1..0453376 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimTODO.txt +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimTODO.txt @@ -3,25 +3,21 @@ CURRENT PROBLEMS TO FIX AND/OR LOOK AT Vehicle buoyancy. Computed correctly? Possibly creating very large effective mass. Interaction of llSetBuoyancy and vehicle buoyancy. Should be additive? Negative buoyancy computed correctly +Center-of-gravity Computation of mesh mass. How done? How should it be done? -Script changing rotation of child prim while vehicle moving (eg turning wheel) causes - the wheel to appear to jump back. Looks like sending position from previous update. Enable vehicle border crossings (at least as poorly as ODE) Terrain skirts Avatar created in previous region and not new region when crossing border Vehicle recreated in new sim at small Z value (offset from root value?) (DONE) +User settable terrain mesh + Allow specifying as convex or concave and use different getHeight functions depending +Boats, when turning nose down into the water + Acts like rotation around Z is also effecting rotation around X and Y Deleting a linkset while standing on the root will leave the physical shape of the root behind. Not sure if it is because standing on it. Done with large prim linksets. Linkset child rotations. Nebadon spiral tube has middle sections which are rotated wrong. Select linked spiral tube. Delink and note where the middle section ends up. -Refarb compound linkset creation to create a pseudo-root for center-of-mass - Let children change their shape to physical indendently and just add shapes to compound -Vehicle angular vertical attraction -vehicle angular banking -Center-of-gravity -Vehicle angular deflection - Preferred orientation angular correction fix Teravus llMoveToTarget script debug Mixing of hover, buoyancy/gravity, moveToTarget, into one force Setting hover height to zero disables hover even if hover flags are on (from SL wiki) @@ -33,10 +29,16 @@ Vehicle script tuning/debugging Avanti speed script Weapon shooter script Move material definitions (friction, ...) into simulator. +osGetPhysicsEngineVerion() and create a version code for the C++ DLL One sided meshes? Should terrain be built into a closed shape? When meshes get partially wedged into the terrain, they cannot push themselves out. It is possible that Bullet processes collisions whether entering or leaving a mesh. Ref: http://bulletphysics.org/Bullet/phpBB3/viewtopic.php?t=4869 +Small physical objects do not interact correctly + Create chain of .5x.5x.1 torui and make all but top physical so to hang. + The chain will fall apart and pairs will dance around on ground + Chains of 1x1x.2 will stay connected but will dance. + Chains above 2x2x.4 are more stable and get stablier as torui get larger. VEHICLES TODO LIST: ================================================= @@ -45,14 +47,12 @@ LINEAR_MOTOR_DIRECTION values should be clamped to reasonable numbers. Same for other velocity settings. UBit improvements to remove rubber-banding of avatars sitting on vehicle child prims: https://github.com/UbitUmarov/Ubit-opensim -Vehicles (Move smoothly) Some vehicles should not be able to turn if no speed or off ground. Cannot edit/move a vehicle being ridden: it jumps back to the origional position. Neb car jiggling left and right Happens on terrain and any other mesh object. Flat cubes are much smoother. This has been reduced but not eliminated. Implement referenceFrame for all the motion routines. -For limitMotorUp, use raycast down to find if vehicle is in the air. Verify llGetVel() is returning a smooth and good value for vehicle movement. llGetVel() should return the root's velocity if requested in a child prim. Implement function efficiency for lineaar and angular motion. @@ -93,29 +93,15 @@ Revisit CollisionMargin. Builders notice the 0.04 spacing between prims. Duplicating a physical prim causes old prim to jump away Dup a phys prim and the original become unselected and thus interacts w/ selected prim. Scenes with hundred of thousands of static objects take a lot of physics CPU time. -BSPrim.Force should set a continious force on the prim. The force should be - applied each tick. Some limits? Gun sending shooter flying. Collision margin (gap between physical objects lying on each other) Boundry checking (crashes related to crossing boundry) Add check for border edge position for avatars and objects. Verify the events are created for border crossings. -Avatar rotation (check out changes to ScenePresence for physical rotation) -Avatar running (what does phys engine need to do?) -Small physical objects do not interact correctly - Create chain of .5x.5x.1 torui and make all but top physical so to hang. - The chain will fall apart and pairs will dance around on ground - Chains of 1x1x.2 will stay connected but will dance. - Chains above 2x2x.4 are more stable and get stablier as torui get larger. -Add PID motor for avatar movement (slow to stop, ...) -setForce should set a constant force. Different than AddImpulse. -Implement raycast. Implement ShapeCollection.Dispose() -Implement water as a plain so raycasting and collisions can happen with same. +Implement water as a plain or mesh so raycasting and collisions can happen with same. Add collision penetration return Add field passed back by BulletSim.dll and fill with info in ManifoldConstact.GetDistance() -Add osGetPhysicsEngineName() so scripters can tell whether BulletSim or ODE - Also osGetPhysicsEngineVerion() maybe. Linkset.Position and Linkset.Orientation requre rewrite to properly return child position. LinksetConstraint acts like it's at taint time!! Implement LockAngularMotion -- implements llSetStatus(ROTATE_AXIS_*, T/F) @@ -127,9 +113,6 @@ Selecting and deselecting physical objects causes CPU processing time to jump Re-implement buoyancy as a separate force on the object rather than diddling gravity. Register a pre-step event to add the force. More efficient memory usage when passing hull information from BSPrim to BulletSim -Avatar movement motor check for zero or small movement. Somehow suppress small movements - when avatar has stopped and is just standing. Simple test for near zero has - the problem of preventing starting up (increase from zero) especially when falling. Physical and phantom will drop through the terrain @@ -172,7 +155,6 @@ Do we need to do convex hulls all the time? Can complex meshes be left meshes? There is some problem with meshes and collisions Hulls are not as detailed as meshes. Hulled vehicles insides are different shape. Debounce avatar contact so legs don't keep folding up when standing. -Implement LSL physics controls. Like STATUS_ROTATE_X. Add border extensions to terrain to help region crossings and objects leaving region. Use a different capsule shape for avatar when sitting LL uses a pyrimidal shape scaled by the avatar's bounding box @@ -205,8 +187,6 @@ Keep avatar scaling correct. http://pennycow.blogspot.fr/2011/07/matter-of-scale INTERNAL IMPROVEMENT/CLEANUP ================================================= -Can the 'inTaintTime' flag be cleaned up and used? For instance, a call to - BSScene.TaintedObject() could immediately execute the callback if already in taint time. Create the physical wrapper classes (BulletBody, BulletShape) by methods on BSAPITemplate and make their actual implementation Bullet engine specific. For the short term, just call the existing functions in ShapeCollection. @@ -365,4 +345,35 @@ After getting off a vehicle, the root prim is phantom (can be walked through) Explore btGImpactMeshShape as alternative to convex hulls for simplified physical objects. Regular triangle meshes don't do physical collisions. (DONE: discovered GImpact is VERY CPU intensive) +Script changing rotation of child prim while vehicle moving (eg turning wheel) causes + the wheel to appear to jump back. Looks like sending position from previous update. + (DONE: redo of compound linksets fixed problem) +Refarb compound linkset creation to create a pseudo-root for center-of-mass + Let children change their shape to physical indendently and just add shapes to compound + (DONE: redo of compound linkset fixed problem) +Vehicle angular vertical attraction (DONE: vegaslon code) +vehicle angular banking (DONE: vegaslon code) +Vehicle angular deflection (DONE: vegaslon code) + Preferred orientation angular correction fix +Vehicles (Move smoothly) +For limitMotorUp, use raycast down to find if vehicle is in the air. + (WILL NOT BE DONE: gravity does the job well enough) +BSPrim.Force should set a continious force on the prim. The force should be + applied each tick. Some limits? + (DONE: added physical actors. Implemented SetForce, SetTorque, ...) +Implement LSL physics controls. Like STATUS_ROTATE_X. (DONE) +Add osGetPhysicsEngineName() so scripters can tell whether BulletSim or ODE +Avatar rotation (check out changes to ScenePresence for physical rotation) (DONE) +Avatar running (what does phys engine need to do?) (DONE: multiplies run factor by walking force) +setForce should set a constant force. Different than AddImpulse. (DONE) +Add PID motor for avatar movement (slow to stop, ...) (WNBD: current works ok) +Avatar movement motor check for zero or small movement. Somehow suppress small movements + when avatar has stopped and is just standing. Simple test for near zero has + the problem of preventing starting up (increase from zero) especially when falling. + (DONE: avatar movement actor knows if standing on stationary object and zeros motion) +Can the 'inTaintTime' flag be cleaned up and used? For instance, a call to + BSScene.TaintedObject() could immediately execute the callback if already in taint time. + (DONE) + + -- cgit v1.1 From 03268d85c41c94e7b35802b9dea1ce08299e5426 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Sun, 2 Jun 2013 10:04:15 -0700 Subject: BulletSim: comments and non-functional changes working toward the center-of-gravity implementation. --- .../Physics/BulletSPlugin/BSLinksetCompound.cs | 11 +++++---- OpenSim/Region/Physics/BulletSPlugin/BSParam.cs | 3 +++ .../Physics/BulletSPlugin/BSPrimDisplaced.cs | 26 +++++++++++++--------- .../Region/Physics/BulletSPlugin/BSPrimLinkable.cs | 19 ++++++++++++---- 4 files changed, 39 insertions(+), 20 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs index 308cf13..30f6c8c 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs @@ -315,7 +315,6 @@ public sealed class BSLinksetCompound : BSLinkset // Note that this works for rebuilding just the root after a linkset is taken apart. // Called at taint time!! private bool UseBulletSimRootOffsetHack = false; // Attempt to have Bullet track the coords of root compound shape - private bool disableCOM = true; // For basic linkset debugging, turn off the center-of-mass setting private void RecomputeLinksetCompound() { try @@ -331,9 +330,7 @@ public sealed class BSLinksetCompound : BSLinkset // There is no reason to build all this physical stuff for a non-physical linkset. if (!LinksetRoot.IsPhysicallyActive) { - // Clean up any old linkset shape and make sure the root shape is set to the root object. DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,notPhysical", LinksetRoot.LocalID); - return; // Note the 'finally' clause at the botton which will get executed. } @@ -347,9 +344,9 @@ public sealed class BSLinksetCompound : BSLinkset OMV.Quaternion invRootOrientation = OMV.Quaternion.Normalize(OMV.Quaternion.Inverse(LinksetRoot.RawOrientation)); - // 'centerDisplacement' is the value to subtract from children to give physical offset position + // 'centerDisplacementV' is the value to subtract from children to give physical offset position OMV.Vector3 centerDisplacementV = (centerOfMassW - LinksetRoot.RawPosition) * invRootOrientation; - if (UseBulletSimRootOffsetHack || disableCOM) + if (UseBulletSimRootOffsetHack || !BSParam.LinksetOffsetCenterOfMass) { centerDisplacementV = OMV.Vector3.Zero; LinksetRoot.ClearDisplacement(); @@ -357,6 +354,8 @@ public sealed class BSLinksetCompound : BSLinkset else { LinksetRoot.SetEffectiveCenterOfMassDisplacement(centerDisplacementV); + // The actual center-of-mass could have been set by the user. + centerDisplacementV = LinksetRoot.PositionDisplacement; } DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,COM,rootPos={1},com={2},comDisp={3}", LinksetRoot.LocalID, LinksetRoot.RawPosition, centerOfMassW, centerDisplacementV); @@ -409,7 +408,7 @@ public sealed class BSLinksetCompound : BSLinkset { // Enable the physical position updator to return the position and rotation of the root shape. // This enables a feature in the C++ code to return the world coordinates of the first shape in the - // compound shape. This eleviates the need to offset the returned physical position by the + // compound shape. This aleviates the need to offset the returned physical position by the // center-of-mass offset. m_physicsScene.PE.AddToCollisionFlags(LinksetRoot.PhysBody, CollisionFlags.BS_RETURN_ROOT_COMPOUND_SHAPE); } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs index d17c8e7..0f84bf7 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs @@ -176,6 +176,7 @@ public static class BSParam // Linkset implementation parameters public static float LinksetImplementation { get; private set; } + public static bool LinksetOffsetCenterOfMass { get; private set; } public static bool LinkConstraintUseFrameOffset { get; private set; } public static bool LinkConstraintEnableTransMotor { get; private set; } public static float LinkConstraintTransMotorMaxVel { get; private set; } @@ -684,6 +685,8 @@ public static class BSParam new ParameterDefn("LinksetImplementation", "Type of linkset implementation (0=Constraint, 1=Compound, 2=Manual)", (float)BSLinkset.LinksetImplementation.Compound ), + new ParameterDefn("LinksetOffsetCenterOfMass", "If 'true', compute linkset center-of-mass and offset linkset position to account for same", + false ), new ParameterDefn("LinkConstraintUseFrameOffset", "For linksets built with constraints, enable frame offsetFor linksets built with constraints, enable frame offset.", false ), new ParameterDefn("LinkConstraintEnableTransMotor", "Whether to enable translational motor on linkset constraints", diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrimDisplaced.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrimDisplaced.cs index f5ee671..9a05349 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrimDisplaced.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrimDisplaced.cs @@ -44,12 +44,12 @@ namespace OpenSim.Region.Physics.BulletSPlugin { public class BSPrimDisplaced : BSPrim { - // The purpose of this module is to do any mapping between what the simulator thinks + // The purpose of this subclass is to do any mapping between what the simulator thinks // the prim position and orientation is and what the physical position/orientation. // This difference happens because Bullet assumes the center-of-mass is the <0,0,0> - // of the prim/linkset. The simulator tracks the location of the prim/linkset by - // the location of the root prim. So, if center-of-mass is anywhere but the origin - // of the root prim, the physical origin is displaced from the simulator origin. + // of the prim/linkset. The simulator, on the other hand, tracks the location of + // the prim/linkset by the location of the root prim. So, if center-of-mass is anywhere + // but the origin of the root prim, the physical origin is displaced from the simulator origin. // // This routine works by capturing the Force* setting of position/orientation/... and // adjusting the simulator values (being set) into the physical values. @@ -61,6 +61,7 @@ public class BSPrimDisplaced : BSPrim public virtual OMV.Vector3 PositionDisplacement { get; set; } public virtual OMV.Quaternion OrientationDisplacement { get; set; } + public virtual OMV.Quaternion OrientationDisplacementOrigInv { get; set; } public BSPrimDisplaced(uint localID, String primName, BSScene parent_scene, OMV.Vector3 pos, OMV.Vector3 size, OMV.Quaternion rotation, PrimitiveBaseShape pbs, bool pisPhysical) @@ -99,7 +100,8 @@ public class BSPrimDisplaced : BSPrim // Remember the displacement from root as well as the origional rotation of the // new center-of-mass. PositionDisplacement = comDisp; - OrientationDisplacement = OMV.Quaternion.Identity; + OrientationDisplacement = Quaternion.Normalize(RawOrientation); + OrientationDisplacementOrigInv = Quaternion.Inverse(OrientationDisplacement); } } @@ -110,7 +112,7 @@ public class BSPrimDisplaced : BSPrim { if (PositionDisplacement != OMV.Vector3.Zero) { - OMV.Vector3 displacedPos = value - (PositionDisplacement * RawOrientation); + OMV.Vector3 displacedPos = value - (PositionDisplacement * (OrientationDisplacementOrigInv * RawOrientation)); DetailLog("{0},BSPrimDisplaced.ForcePosition,val={1},disp={2},newPos={3}", LocalID, value, PositionDisplacement, displacedPos); base.ForcePosition = displacedPos; } @@ -126,7 +128,8 @@ public class BSPrimDisplaced : BSPrim get { return base.ForceOrientation; } set { - // TODO: + // Changing orientation also changes the position of the center-of-mass since + // the orientation passed is for a rotation around the root prim's center. base.ForceOrientation = value; } } @@ -150,10 +153,13 @@ public class BSPrimDisplaced : BSPrim // Undo any center-of-mass displacement that might have been done. if (PositionDisplacement != OMV.Vector3.Zero || OrientationDisplacement != OMV.Quaternion.Identity) { - // Correct for any rotation around the center-of-mass - // TODO!!! + // The origional shape was offset from 'zero' by PositionDisplacement and rotated by OrientationDisplacement. + // These physical locations and rotation must be back converted to be centered around the displaced + // root shape. + + // The root position is the reported position displaced by the rotated displacement. + OMV.Vector3 displacedPos = entprop.Position + (PositionDisplacement * (entprop.Rotation * OrientationDisplacementOrigInv)); - OMV.Vector3 displacedPos = entprop.Position + (PositionDisplacement * entprop.Rotation); DetailLog("{0},BSPrimDisplaced.ForcePosition,physPos={1},disp={2},newPos={3}", LocalID, entprop.Position, PositionDisplacement, displacedPos); entprop.Position = displacedPos; // entprop.Rotation = something; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs index 87eed98..6d7de35 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs @@ -37,6 +37,12 @@ namespace OpenSim.Region.Physics.BulletSPlugin { public class BSPrimLinkable : BSPrimDisplaced { + // The purpose of this subclass is to add linkset functionality to the prim. This overrides + // operations necessary for keeping the linkset created and, additionally, this + // calls the linkset implementation for its creation and management. + + // This adds the overrides for link() and delink() so the prim is linkable. + public BSLinkset Linkset { get; set; } // The index of this child prim. public int LinksetChildIndex { get; set; } @@ -69,8 +75,8 @@ public class BSPrimLinkable : BSPrimDisplaced BSPrimLinkable parent = obj as BSPrimLinkable; if (parent != null) { - BSPhysObject parentBefore = Linkset.LinksetRoot; - int childrenBefore = Linkset.NumberOfChildren; + BSPhysObject parentBefore = Linkset.LinksetRoot; // DEBUG + int childrenBefore = Linkset.NumberOfChildren; // DEBUG Linkset = parent.Linkset.AddMeToLinkset(this); @@ -85,8 +91,8 @@ public class BSPrimLinkable : BSPrimDisplaced // TODO: decide if this parent checking needs to happen at taint time // Race condition here: if link() and delink() in same simulation tick, the delink will not happen - BSPhysObject parentBefore = Linkset.LinksetRoot; - int childrenBefore = Linkset.NumberOfChildren; + BSPhysObject parentBefore = Linkset.LinksetRoot; // DEBUG + int childrenBefore = Linkset.NumberOfChildren; // DEBUG Linkset = Linkset.RemoveMeFromLinkset(this); @@ -128,6 +134,7 @@ public class BSPrimLinkable : BSPrimDisplaced get { return Linkset.LinksetMass; } } + // Refresh the linkset structure and parameters when the prim's physical parameters are changed. public override void UpdatePhysicalParameters() { base.UpdatePhysicalParameters(); @@ -139,6 +146,7 @@ public class BSPrimLinkable : BSPrimDisplaced Linkset.Refresh(this); } + // When the prim is made dynamic or static, the linkset needs to change. protected override void MakeDynamic(bool makeStatic) { base.MakeDynamic(makeStatic); @@ -155,6 +163,8 @@ public class BSPrimLinkable : BSPrimDisplaced base.RemoveDependencies(); } + // Called after a simulation step for the changes in physical object properties. + // Do any filtering/modification needed for linksets. public override void UpdateProperties(EntityProperties entprop) { if (Linkset.IsRoot(this)) @@ -176,6 +186,7 @@ public class BSPrimLinkable : BSPrimDisplaced Linkset.UpdateProperties(UpdatedProperties.EntPropUpdates, this); } + // Called after a simulation step to post a collision with this object. public override bool Collide(uint collidingWith, BSPhysObject collidee, OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth) { -- cgit v1.1 From 97698ae3119e01ecd2c98f7a17ad37204b9bfd9c Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Mon, 10 Jun 2013 06:40:07 -0700 Subject: BulletSim: More tweaking on center-of-mass. Almost there. Changes have no effect if LinksetOffsetCenterOfMass=false (the default). --- .../Physics/BulletSPlugin/BSLinksetCompound.cs | 78 +++++----------------- .../Physics/BulletSPlugin/BSPrimDisplaced.cs | 63 +++++++---------- .../Region/Physics/BulletSPlugin/BSPrimLinkable.cs | 10 +++ OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 1 - 4 files changed, 51 insertions(+), 101 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs index 30f6c8c..96626ca 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs @@ -35,62 +35,6 @@ using OMV = OpenMetaverse; namespace OpenSim.Region.Physics.BulletSPlugin { - /* -// When a child is linked, the relationship position of the child to the parent -// is remembered so the child's world position can be recomputed when it is -// removed from the linkset. -sealed class BSLinksetCompoundInfo : BSLinksetInfo -{ - public int Index; - public OMV.Vector3 OffsetFromRoot; - public OMV.Vector3 OffsetFromCenterOfMass; - public OMV.Quaternion OffsetRot; - public BSLinksetCompoundInfo(int indx, OMV.Vector3 p, OMV.Quaternion r) - { - Index = indx; - OffsetFromRoot = p; - OffsetFromCenterOfMass = p; - OffsetRot = r; - } - // 'centerDisplacement' is the distance from the root the the center-of-mass (Bullet 'zero' of the shape) - public BSLinksetCompoundInfo(int indx, BSPrimLinkable root, BSPrimLinkable child, OMV.Vector3 centerDisplacement) - { - // Each child position and rotation is given relative to the center-of-mass. - OMV.Quaternion invRootOrientation = OMV.Quaternion.Inverse(root.RawOrientation); - OMV.Vector3 displacementFromRoot = (child.RawPosition - root.RawPosition) * invRootOrientation; - OMV.Vector3 displacementFromCOM = displacementFromRoot - centerDisplacement; - OMV.Quaternion displacementRot = child.RawOrientation * invRootOrientation; - - // Save relative position for recomputing child's world position after moving linkset. - Index = indx; - OffsetFromRoot = displacementFromRoot; - OffsetFromCenterOfMass = displacementFromCOM; - OffsetRot = displacementRot; - } - public override void Clear() - { - Index = 0; - OffsetFromRoot = OMV.Vector3.Zero; - OffsetFromCenterOfMass = OMV.Vector3.Zero; - OffsetRot = OMV.Quaternion.Identity; - } - public override string ToString() - { - StringBuilder buff = new StringBuilder(); - buff.Append(""); - return buff.ToString(); - } -}; - */ - public sealed class BSLinksetCompound : BSLinkset { private static string LogHeader = "[BULLETSIM LINKSET COMPOUND]"; @@ -151,7 +95,9 @@ public sealed class BSLinksetCompound : BSLinkset public override bool MakeStatic(BSPrimLinkable child) { bool ret = false; + DetailLog("{0},BSLinksetCompound.MakeStatic,call,IsRoot={1}", child.LocalID, IsRoot(child)); + child.ClearDisplacement(); if (IsRoot(child)) { // Schedule a rebuild to verify that the root shape is set to the real shape. @@ -364,16 +310,28 @@ public sealed class BSLinksetCompound : BSLinkset int memberIndex = 1; ForEachMember(delegate(BSPrimLinkable cPrim) { - // Root shape is always index zero. - cPrim.LinksetChildIndex = IsRoot(cPrim) ? 0 : memberIndex; + if (IsRoot(cPrim)) + { + // Root shape is always index zero. + cPrim.LinksetChildIndex = 0; + } + else + { + cPrim.LinksetChildIndex = memberIndex; + memberIndex++; + } // Get a reference to the shape of the child and add that shape to the linkset compound shape BSShape childShape = cPrim.PhysShape.GetReference(m_physicsScene, cPrim); + + // Offset the child shape from the center-of-mass and rotate it to vehicle relative OMV.Vector3 offsetPos = (cPrim.RawPosition - LinksetRoot.RawPosition) * invRootOrientation - centerDisplacementV; OMV.Quaternion offsetRot = OMV.Quaternion.Normalize(cPrim.RawOrientation) * invRootOrientation; + + // Add the child shape to the compound shape being built m_physicsScene.PE.AddChildShapeToCompoundShape(linksetShape.physShapeInfo, childShape.physShapeInfo, offsetPos, offsetRot); DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,addChild,indx={1},cShape={2},offPos={3},offRot={4}", - LinksetRoot.LocalID, memberIndex, childShape, offsetPos, offsetRot); + LinksetRoot.LocalID, cPrim.LinksetChildIndex, childShape, offsetPos, offsetRot); // Since we are borrowing the shape of the child, disable the origional child body if (!IsRoot(cPrim)) @@ -385,8 +343,6 @@ public sealed class BSLinksetCompound : BSLinkset cPrim.PhysBody.collisionType = CollisionType.LinksetChild; } - memberIndex++; - return false; // 'false' says to move onto the next child in the list }); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrimDisplaced.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrimDisplaced.cs index 9a05349..a11bca0 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrimDisplaced.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrimDisplaced.cs @@ -51,7 +51,7 @@ public class BSPrimDisplaced : BSPrim // the prim/linkset by the location of the root prim. So, if center-of-mass is anywhere // but the origin of the root prim, the physical origin is displaced from the simulator origin. // - // This routine works by capturing the Force* setting of position/orientation/... and + // This routine works by capturing ForcePosition and // adjusting the simulator values (being set) into the physical values. // The conversion is also done in the opposite direction (physical origin -> simulator origin). // @@ -60,8 +60,6 @@ public class BSPrimDisplaced : BSPrim // class. public virtual OMV.Vector3 PositionDisplacement { get; set; } - public virtual OMV.Quaternion OrientationDisplacement { get; set; } - public virtual OMV.Quaternion OrientationDisplacementOrigInv { get; set; } public BSPrimDisplaced(uint localID, String primName, BSScene parent_scene, OMV.Vector3 pos, OMV.Vector3 size, OMV.Quaternion rotation, PrimitiveBaseShape pbs, bool pisPhysical) @@ -70,15 +68,17 @@ public class BSPrimDisplaced : BSPrim ClearDisplacement(); } + // Clears any center-of-mass displacement introduced by linksets, etc. + // Does not clear the displacement set by the user. public void ClearDisplacement() { - PositionDisplacement = OMV.Vector3.Zero; - OrientationDisplacement = OMV.Quaternion.Identity; + SetEffectiveCenterOfMassDisplacement(OMV.Vector3.Zero); } // Set this sets and computes the displacement from the passed prim to the center-of-mass. // A user set value for center-of-mass overrides whatever might be passed in here. // The displacement is in local coordinates (relative to root prim in linkset oriented coordinates). + // Called at taint time. public virtual void SetEffectiveCenterOfMassDisplacement(Vector3 centerOfMassDisplacement) { Vector3 comDisp; @@ -87,21 +87,17 @@ public class BSPrimDisplaced : BSPrim else comDisp = centerOfMassDisplacement; + if (comDisp.ApproxEquals(Vector3.Zero, 0.01f) ) + comDisp = Vector3.Zero; + DetailLog("{0},BSPrimDisplaced.SetEffectiveCenterOfMassDisplacement,userSet={1},comDisp={2}", LocalID, UserSetCenterOfMassDisplacement.HasValue, comDisp); - if (comDisp == Vector3.Zero) + if ( comDisp != PositionDisplacement ) { - // If there is no diplacement. Things get reset. - PositionDisplacement = OMV.Vector3.Zero; - OrientationDisplacement = OMV.Quaternion.Identity; - } - else - { - // Remember the displacement from root as well as the origional rotation of the - // new center-of-mass. + // Displacement setting is changing. + // The relationship between the physical object and simulated object must be aligned. PositionDisplacement = comDisp; - OrientationDisplacement = Quaternion.Normalize(RawOrientation); - OrientationDisplacementOrigInv = Quaternion.Inverse(OrientationDisplacement); + this.ForcePosition = RawPosition; } } @@ -112,7 +108,11 @@ public class BSPrimDisplaced : BSPrim { if (PositionDisplacement != OMV.Vector3.Zero) { - OMV.Vector3 displacedPos = value - (PositionDisplacement * (OrientationDisplacementOrigInv * RawOrientation)); + // The displacement is always relative to the vehicle so, when setting position, + // the caller means to set the position of the root prim. + // This offsets the setting value to the center-of-mass and sends that to the + // physics engine. + OMV.Vector3 displacedPos = value - (PositionDisplacement * RawOrientation); DetailLog("{0},BSPrimDisplaced.ForcePosition,val={1},disp={2},newPos={3}", LocalID, value, PositionDisplacement, displacedPos); base.ForcePosition = displacedPos; } @@ -123,26 +123,12 @@ public class BSPrimDisplaced : BSPrim } } - public override Quaternion ForceOrientation - { - get { return base.ForceOrientation; } - set - { - // Changing orientation also changes the position of the center-of-mass since - // the orientation passed is for a rotation around the root prim's center. - base.ForceOrientation = value; - } - } - - // TODO: decide if this is the right place for these variables. - // Somehow incorporate the optional settability by the user. - // Is this used? + // These are also overridden by BSPrimLinkable if the prim can be part of a linkset public override OMV.Vector3 CenterOfMass { get { return RawPosition; } } - // Is this used? public override OMV.Vector3 GeometricCenter { get { return RawPosition; } @@ -151,18 +137,17 @@ public class BSPrimDisplaced : BSPrim public override void UpdateProperties(EntityProperties entprop) { // Undo any center-of-mass displacement that might have been done. - if (PositionDisplacement != OMV.Vector3.Zero || OrientationDisplacement != OMV.Quaternion.Identity) + if (PositionDisplacement != OMV.Vector3.Zero) { - // The origional shape was offset from 'zero' by PositionDisplacement and rotated by OrientationDisplacement. - // These physical locations and rotation must be back converted to be centered around the displaced + // The origional shape was offset from 'zero' by PositionDisplacement. + // These physical location must be back converted to be centered around the displaced // root shape. // The root position is the reported position displaced by the rotated displacement. - OMV.Vector3 displacedPos = entprop.Position + (PositionDisplacement * (entprop.Rotation * OrientationDisplacementOrigInv)); - - DetailLog("{0},BSPrimDisplaced.ForcePosition,physPos={1},disp={2},newPos={3}", LocalID, entprop.Position, PositionDisplacement, displacedPos); + OMV.Vector3 displacedPos = entprop.Position + (PositionDisplacement * entprop.Rotation); + DetailLog("{0},BSPrimDisplaced.UpdateProperties,physPos={1},disp={2},newPos={3}", + LocalID, entprop.Position, PositionDisplacement, displacedPos); entprop.Position = displacedPos; - // entprop.Rotation = something; } base.UpdateProperties(entprop); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs index 6d7de35..7058646 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs @@ -134,6 +134,16 @@ public class BSPrimLinkable : BSPrimDisplaced get { return Linkset.LinksetMass; } } + public override OMV.Vector3 CenterOfMass + { + get { return Linkset.CenterOfMass; } + } + + public override OMV.Vector3 GeometricCenter + { + get { return Linkset.GeometricCenter; } + } + // Refresh the linkset structure and parameters when the prim's physical parameters are changed. public override void UpdatePhysicalParameters() { diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index 1645c98..e56a6f6 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -785,7 +785,6 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters { // The simulation of the time interval took less than realtime. // Do a sleep for the rest of realtime. - DetailLog("{0},BulletSPluginPhysicsThread,sleeping={1}", BSScene.DetailLogZero, simulationTimeVsRealtimeDifferenceMS); Thread.Sleep(simulationTimeVsRealtimeDifferenceMS); } else -- cgit v1.1 From a65cec3986431f5a2f4f9eb2424157def0d035c8 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Sat, 6 Jul 2013 08:22:59 -0700 Subject: BulletSim: implementation of linkset center-of-mass. Default off, for the moment, until more testing. Add separate thread and center-of-mass flags to OpenSimDefaults.ini. Clean up comments in OpenSimDefaults.ini. --- .../Physics/BulletSPlugin/BSLinksetCompound.cs | 20 +++++--- .../Region/Physics/BulletSPlugin/BSPhysObject.cs | 3 ++ OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 5 +- .../Physics/BulletSPlugin/BSPrimDisplaced.cs | 60 ++++++++++++++++------ .../Region/Physics/BulletSPlugin/BSPrimLinkable.cs | 11 ++-- 5 files changed, 70 insertions(+), 29 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs index 96626ca..1d94142 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs @@ -271,6 +271,8 @@ public sealed class BSLinksetCompound : BSLinkset // to what they should be as if the root was not in a linkset. // Not that bad since we only get into this routine if there are children in the linkset and // something has been updated/changed. + // Have to do the rebuild before checking for physical because this might be a linkset + // being destructed and going non-physical. LinksetRoot.ForceBodyShapeRebuild(true); // There is no reason to build all this physical stuff for a non-physical linkset. @@ -283,28 +285,29 @@ public sealed class BSLinksetCompound : BSLinkset // Get a new compound shape to build the linkset shape in. BSShape linksetShape = BSShapeCompound.GetReference(m_physicsScene); - // The center of mass for the linkset is the geometric center of the group. // Compute a displacement for each component so it is relative to the center-of-mass. // Bullet presumes an object's origin (relative <0,0,0>) is its center-of-mass OMV.Vector3 centerOfMassW = ComputeLinksetCenterOfMass(); OMV.Quaternion invRootOrientation = OMV.Quaternion.Normalize(OMV.Quaternion.Inverse(LinksetRoot.RawOrientation)); + OMV.Vector3 origRootPosition = LinksetRoot.RawPosition; - // 'centerDisplacementV' is the value to subtract from children to give physical offset position + // 'centerDisplacementV' is the vehicle relative distance from the simulator root position to the center-of-mass OMV.Vector3 centerDisplacementV = (centerOfMassW - LinksetRoot.RawPosition) * invRootOrientation; if (UseBulletSimRootOffsetHack || !BSParam.LinksetOffsetCenterOfMass) { + // Zero everything if center-of-mass displacement is not being done. centerDisplacementV = OMV.Vector3.Zero; LinksetRoot.ClearDisplacement(); } else { - LinksetRoot.SetEffectiveCenterOfMassDisplacement(centerDisplacementV); // The actual center-of-mass could have been set by the user. - centerDisplacementV = LinksetRoot.PositionDisplacement; + centerDisplacementV = LinksetRoot.SetEffectiveCenterOfMassDisplacement(centerDisplacementV); } + DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,COM,rootPos={1},com={2},comDisp={3}", - LinksetRoot.LocalID, LinksetRoot.RawPosition, centerOfMassW, centerDisplacementV); + LinksetRoot.LocalID, origRootPosition, centerOfMassW, centerDisplacementV); // Add the shapes of all the components of the linkset int memberIndex = 1; @@ -321,11 +324,11 @@ public sealed class BSLinksetCompound : BSLinkset memberIndex++; } - // Get a reference to the shape of the child and add that shape to the linkset compound shape + // Get a reference to the shape of the child for adding of that shape to the linkset compound shape BSShape childShape = cPrim.PhysShape.GetReference(m_physicsScene, cPrim); - // Offset the child shape from the center-of-mass and rotate it to vehicle relative - OMV.Vector3 offsetPos = (cPrim.RawPosition - LinksetRoot.RawPosition) * invRootOrientation - centerDisplacementV; + // Offset the child shape from the center-of-mass and rotate it to vehicle relative. + OMV.Vector3 offsetPos = (cPrim.RawPosition - origRootPosition) * invRootOrientation - centerDisplacementV; OMV.Quaternion offsetRot = OMV.Quaternion.Normalize(cPrim.RawOrientation) * invRootOrientation; // Add the child shape to the compound shape being built @@ -366,6 +369,7 @@ public sealed class BSLinksetCompound : BSLinkset // This enables a feature in the C++ code to return the world coordinates of the first shape in the // compound shape. This aleviates the need to offset the returned physical position by the // center-of-mass offset. + // TODO: either debug this feature or remove it. m_physicsScene.PE.AddToCollisionFlags(LinksetRoot.PhysBody, CollisionFlags.BS_RETURN_ROOT_COMPOUND_SHAPE); } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index a0d5c42..738e2d0 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -90,6 +90,8 @@ public abstract class BSPhysObject : PhysicsActor PhysBody = new BulletBody(localID); PhysShape = new BSShapeNull(); + UserSetCenterOfMassDisplacement = null; + PrimAssetState = PrimAssetCondition.Unknown; // Default material type. Also sets Friction, Restitution and Density. @@ -180,6 +182,7 @@ public abstract class BSPhysObject : PhysicsActor Material = (MaterialAttributes.Material)material; // Setting the material sets the material attributes also. + // TODO: decide if this is necessary -- the simulator does this. MaterialAttributes matAttrib = BSMaterials.GetAttributes(Material, false); Friction = matAttrib.friction; Restitution = matAttrib.restitution; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index f0858ca..ce4c3da 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -802,6 +802,7 @@ public class BSPrim : BSPhysObject // isSolid: other objects bounce off of this object // isVolumeDetect: other objects pass through but can generate collisions // collisionEvents: whether this object returns collision events + // NOTE: overloaded by BSPrimLinkable to also update linkset physical parameters. public virtual void UpdatePhysicalParameters() { if (!PhysBody.HasPhysicalBody) @@ -1532,6 +1533,8 @@ public class BSPrim : BSPhysObject // The physics engine says that properties have updated. Update same and inform // the world that things have changed. + // NOTE: BSPrim.UpdateProperties is overloaded by BSPrimLinkable which modifies updates from root and children prims. + // NOTE: BSPrim.UpdateProperties is overloaded by BSPrimDisplaced which handles mapping physical position to simulator position. public override void UpdateProperties(EntityProperties entprop) { // Let anyone (like the actors) modify the updated properties before they are pushed into the object and the simulator. @@ -1567,8 +1570,6 @@ public class BSPrim : BSPhysObject LastEntityProperties = CurrentEntityProperties; CurrentEntityProperties = entprop; - // Note that BSPrim can be overloaded by BSPrimLinkable which controls updates from root and children prims. - PhysScene.PostUpdate(this); } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrimDisplaced.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrimDisplaced.cs index a11bca0..35d5a08 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrimDisplaced.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrimDisplaced.cs @@ -59,6 +59,7 @@ public class BSPrimDisplaced : BSPrim // are converted into simulator origin values before being passed to the base // class. + // PositionDisplacement is the vehicle relative distance from the root prim position to the center-of-mass. public virtual OMV.Vector3 PositionDisplacement { get; set; } public BSPrimDisplaced(uint localID, String primName, BSScene parent_scene, OMV.Vector3 pos, OMV.Vector3 size, @@ -72,49 +73,77 @@ public class BSPrimDisplaced : BSPrim // Does not clear the displacement set by the user. public void ClearDisplacement() { - SetEffectiveCenterOfMassDisplacement(OMV.Vector3.Zero); + if (UserSetCenterOfMassDisplacement.HasValue) + PositionDisplacement = (OMV.Vector3)UserSetCenterOfMassDisplacement; + else + PositionDisplacement = OMV.Vector3.Zero; } // Set this sets and computes the displacement from the passed prim to the center-of-mass. // A user set value for center-of-mass overrides whatever might be passed in here. // The displacement is in local coordinates (relative to root prim in linkset oriented coordinates). + // Returns the relative offset from the root position to the center-of-mass. // Called at taint time. - public virtual void SetEffectiveCenterOfMassDisplacement(Vector3 centerOfMassDisplacement) + public virtual Vector3 SetEffectiveCenterOfMassDisplacement(Vector3 centerOfMassDisplacement) { + PhysScene.AssertInTaintTime("BSPrimDisplaced.SetEffectiveCenterOfMassDisplacement"); Vector3 comDisp; if (UserSetCenterOfMassDisplacement.HasValue) comDisp = (OMV.Vector3)UserSetCenterOfMassDisplacement; else comDisp = centerOfMassDisplacement; + // Eliminate any jitter caused be very slight differences in masses and positions if (comDisp.ApproxEquals(Vector3.Zero, 0.01f) ) comDisp = Vector3.Zero; DetailLog("{0},BSPrimDisplaced.SetEffectiveCenterOfMassDisplacement,userSet={1},comDisp={2}", LocalID, UserSetCenterOfMassDisplacement.HasValue, comDisp); - if ( comDisp != PositionDisplacement ) + if ( !comDisp.ApproxEquals(PositionDisplacement, 0.01f) ) { // Displacement setting is changing. // The relationship between the physical object and simulated object must be aligned. PositionDisplacement = comDisp; this.ForcePosition = RawPosition; } + + return PositionDisplacement; } + // 'ForcePosition' is the one way to set the physical position of the body in the physics engine. + // Displace the simulator idea of position (center of root prim) to the physical position. public override Vector3 ForcePosition { - get { return base.ForcePosition; } + get { + OMV.Vector3 physPosition = base.ForcePosition; + if (PositionDisplacement != OMV.Vector3.Zero) + { + // If there is some displacement, return the physical position (center-of-mass) + // location minus the displacement to give the center of the root prim. + OMV.Vector3 displacement = PositionDisplacement * ForceOrientation; + DetailLog("{0},BSPrimDisplaced.ForcePosition,get,physPos={1},disp={2},simPos={3}", + LocalID, physPosition, displacement, physPosition - displacement); + physPosition -= displacement; + } + return physPosition; + } set { if (PositionDisplacement != OMV.Vector3.Zero) { - // The displacement is always relative to the vehicle so, when setting position, - // the caller means to set the position of the root prim. - // This offsets the setting value to the center-of-mass and sends that to the - // physics engine. - OMV.Vector3 displacedPos = value - (PositionDisplacement * RawOrientation); - DetailLog("{0},BSPrimDisplaced.ForcePosition,val={1},disp={2},newPos={3}", LocalID, value, PositionDisplacement, displacedPos); - base.ForcePosition = displacedPos; + // This value is the simulator's idea of where the prim is: the center of the root prim + RawPosition = value; + + // Move the passed root prim postion to the center-of-mass position and set in the physics engine. + OMV.Vector3 displacement = PositionDisplacement * RawOrientation; + OMV.Vector3 displacedPos = RawPosition + displacement; + DetailLog("{0},BSPrimDisplaced.ForcePosition,set,simPos={1},disp={2},physPos={3}", + LocalID, RawPosition, displacement, displacedPos); + if (PhysBody.HasPhysicalBody) + { + PhysScene.PE.SetTranslation(PhysBody, displacedPos, RawOrientation); + ActivateIfPhysical(false); + } } else { @@ -143,10 +172,11 @@ public class BSPrimDisplaced : BSPrim // These physical location must be back converted to be centered around the displaced // root shape. - // The root position is the reported position displaced by the rotated displacement. - OMV.Vector3 displacedPos = entprop.Position + (PositionDisplacement * entprop.Rotation); - DetailLog("{0},BSPrimDisplaced.UpdateProperties,physPos={1},disp={2},newPos={3}", - LocalID, entprop.Position, PositionDisplacement, displacedPos); + // Move the returned center-of-mass location to the root prim location. + OMV.Vector3 displacement = PositionDisplacement * entprop.Rotation; + OMV.Vector3 displacedPos = entprop.Position - displacement; + DetailLog("{0},BSPrimDisplaced.UpdateProperties,physPos={1},disp={2},simPos={3}", + LocalID, entprop.Position, displacement, displacedPos); entprop.Position = displacedPos; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs index 7058646..1fbcfcc 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs @@ -160,10 +160,13 @@ public class BSPrimLinkable : BSPrimDisplaced protected override void MakeDynamic(bool makeStatic) { base.MakeDynamic(makeStatic); - if (makeStatic) - Linkset.MakeStatic(this); - else - Linkset.MakeDynamic(this); + if (Linkset != null) // null can happen during initialization + { + if (makeStatic) + Linkset.MakeStatic(this); + else + Linkset.MakeDynamic(this); + } } // Body is being taken apart. Remove physical dependencies and schedule a rebuild. -- cgit v1.1 From 70d24a654b8eb0257ca927327d51bd0e47f85259 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Sun, 7 Jul 2013 05:46:24 -0700 Subject: BulletSim: rename position and orientation variables to remove the inconsistant use of Raw* and _* conventions. --- .../Region/Physics/BulletSPlugin/BSCharacter.cs | 78 +++++++++----------- .../Region/Physics/BulletSPlugin/BSPhysObject.cs | 4 +- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 84 ++++++++++------------ 3 files changed, 71 insertions(+), 95 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index 5ef6992..c9e3ca0 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -43,12 +43,10 @@ public sealed class BSCharacter : BSPhysObject private OMV.Vector3 _size; private bool _grabbed; private bool _selected; - private OMV.Vector3 _position; private float _mass; private float _avatarVolume; private float _collisionScore; private OMV.Vector3 _acceleration; - private OMV.Quaternion _orientation; private int _physicsActorType; private bool _isPhysical; private bool _flying; @@ -70,10 +68,10 @@ public sealed class BSCharacter : BSPhysObject : base(parent_scene, localID, avName, "BSCharacter") { _physicsActorType = (int)ActorTypes.Agent; - _position = pos; + RawPosition = pos; _flying = isFlying; - _orientation = OMV.Quaternion.Identity; + RawOrientation = OMV.Quaternion.Identity; RawVelocity = OMV.Vector3.Zero; _buoyancy = ComputeBuoyancyFromFlying(isFlying); Friction = BSParam.AvatarStandingFriction; @@ -133,7 +131,7 @@ public sealed class BSCharacter : BSPhysObject PhysScene.PE.RemoveObjectFromWorld(PhysScene.World, PhysBody); ZeroMotion(true); - ForcePosition = _position; + ForcePosition = RawPosition; // Set the velocity if (m_moveActor != null) @@ -272,38 +270,33 @@ public sealed class BSCharacter : BSPhysObject public override void LockAngularMotion(OMV.Vector3 axis) { return; } - public override OMV.Vector3 RawPosition - { - get { return _position; } - set { _position = value; } - } public override OMV.Vector3 Position { get { // Don't refetch the position because this function is called a zillion times - // _position = PhysicsScene.PE.GetObjectPosition(Scene.World, LocalID); - return _position; + // RawPosition = PhysicsScene.PE.GetObjectPosition(Scene.World, LocalID); + return RawPosition; } set { - _position = value; + RawPosition = value; PhysScene.TaintedObject("BSCharacter.setPosition", delegate() { - DetailLog("{0},BSCharacter.SetPosition,taint,pos={1},orient={2}", LocalID, _position, _orientation); + DetailLog("{0},BSCharacter.SetPosition,taint,pos={1},orient={2}", LocalID, RawPosition, RawOrientation); PositionSanityCheck(); - ForcePosition = _position; + ForcePosition = RawPosition; }); } } public override OMV.Vector3 ForcePosition { get { - _position = PhysScene.PE.GetPosition(PhysBody); - return _position; + RawPosition = PhysScene.PE.GetPosition(PhysBody); + return RawPosition; } set { - _position = value; + RawPosition = value; if (PhysBody.HasPhysicalBody) { - PhysScene.PE.SetTranslation(PhysBody, _position, _orientation); + PhysScene.PE.SetTranslation(PhysBody, RawPosition, RawOrientation); } } } @@ -331,16 +324,16 @@ public sealed class BSCharacter : BSPhysObject float terrainHeight = PhysScene.TerrainManager.GetTerrainHeightAtXYZ(RawPosition); if (Position.Z < terrainHeight) { - DetailLog("{0},BSCharacter.PositionSanityCheck,adjustForUnderGround,pos={1},terrain={2}", LocalID, _position, terrainHeight); - _position.Z = terrainHeight + BSParam.AvatarBelowGroundUpCorrectionMeters; + DetailLog("{0},BSCharacter.PositionSanityCheck,adjustForUnderGround,pos={1},terrain={2}", LocalID, RawPosition, terrainHeight); + RawPosition = new OMV.Vector3(RawPosition.X, RawPosition.Y, terrainHeight + BSParam.AvatarBelowGroundUpCorrectionMeters); ret = true; } if ((CurrentCollisionFlags & CollisionFlags.BS_FLOATS_ON_WATER) != 0) { - float waterHeight = PhysScene.TerrainManager.GetWaterLevelAtXYZ(_position); + float waterHeight = PhysScene.TerrainManager.GetWaterLevelAtXYZ(RawPosition); if (Position.Z < waterHeight) { - _position.Z = waterHeight; + RawPosition = new OMV.Vector3(RawPosition.X, RawPosition.Y, waterHeight); ret = true; } } @@ -360,8 +353,8 @@ public sealed class BSCharacter : BSPhysObject // just assign to "Position" because of potential call loops. PhysScene.TaintedObject(inTaintTime, "BSCharacter.PositionSanityCheck", delegate() { - DetailLog("{0},BSCharacter.PositionSanityCheck,taint,pos={1},orient={2}", LocalID, _position, _orientation); - ForcePosition = _position; + DetailLog("{0},BSCharacter.PositionSanityCheck,taint,pos={1},orient={2}", LocalID, RawPosition, RawOrientation); + ForcePosition = RawPosition; }); ret = true; } @@ -466,19 +459,14 @@ public sealed class BSCharacter : BSPhysObject get { return _acceleration; } set { _acceleration = value; } } - public override OMV.Quaternion RawOrientation - { - get { return _orientation; } - set { _orientation = value; } - } public override OMV.Quaternion Orientation { - get { return _orientation; } + get { return RawOrientation; } set { // Orientation is set zillions of times when an avatar is walking. It's like // the viewer doesn't trust us. - if (_orientation != value) + if (RawOrientation != value) { - _orientation = value; + RawOrientation = value; PhysScene.TaintedObject("BSCharacter.setOrientation", delegate() { // Bullet assumes we know what we are doing when forcing orientation @@ -486,10 +474,10 @@ public sealed class BSCharacter : BSPhysObject // This forces rotation to be only around the Z axis and doesn't change any of the other axis. // This keeps us from flipping the capsule over which the veiwer does not understand. float oRoll, oPitch, oYaw; - _orientation.GetEulerAngles(out oRoll, out oPitch, out oYaw); + RawOrientation.GetEulerAngles(out oRoll, out oPitch, out oYaw); OMV.Quaternion trimmedOrientation = OMV.Quaternion.CreateFromEulers(0f, 0f, oYaw); // DetailLog("{0},BSCharacter.setOrientation,taint,val={1},valDir={2},conv={3},convDir={4}", - // LocalID, _orientation, OMV.Vector3.UnitX * _orientation, + // LocalID, RawOrientation, OMV.Vector3.UnitX * RawOrientation, // trimmedOrientation, OMV.Vector3.UnitX * trimmedOrientation); ForceOrientation = trimmedOrientation; }); @@ -501,16 +489,16 @@ public sealed class BSCharacter : BSPhysObject { get { - _orientation = PhysScene.PE.GetOrientation(PhysBody); - return _orientation; + RawOrientation = PhysScene.PE.GetOrientation(PhysBody); + return RawOrientation; } set { - _orientation = value; + RawOrientation = value; if (PhysBody.HasPhysicalBody) { - // _position = PhysicsScene.PE.GetPosition(BSBody); - PhysScene.PE.SetTranslation(PhysBody, _position, _orientation); + // RawPosition = PhysicsScene.PE.GetPosition(BSBody); + PhysScene.PE.SetTranslation(PhysBody, RawPosition, RawOrientation); } } } @@ -723,9 +711,9 @@ public sealed class BSCharacter : BSPhysObject { // Don't change position if standing on a stationary object. if (!IsStationary) - _position = entprop.Position; + RawPosition = entprop.Position; - _orientation = entprop.Rotation; + RawOrientation = entprop.Rotation; // Smooth velocity. OpenSimulator is VERY sensitive to changes in velocity of the avatar // and will send agent updates to the clients if velocity changes by more than @@ -740,8 +728,8 @@ public sealed class BSCharacter : BSPhysObject // Do some sanity checking for the avatar. Make sure it's above ground and inbounds. if (PositionSanityCheck(true)) { - DetailLog("{0},BSCharacter.UpdateProperties,updatePosForSanity,pos={1}", LocalID, _position); - entprop.Position = _position; + DetailLog("{0},BSCharacter.UpdateProperties,updatePosForSanity,pos={1}", LocalID, RawPosition); + entprop.Position = RawPosition; } // remember the current and last set values @@ -755,7 +743,7 @@ public sealed class BSCharacter : BSPhysObject // base.RequestPhysicsterseUpdate(); DetailLog("{0},BSCharacter.UpdateProperties,call,pos={1},orient={2},vel={3},accel={4},rotVel={5}", - LocalID, _position, _orientation, RawVelocity, _acceleration, _rotationalVelocity); + LocalID, RawPosition, RawOrientation, RawVelocity, _acceleration, _rotationalVelocity); } } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index 738e2d0..a41eaf8 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -197,10 +197,10 @@ public abstract class BSPhysObject : PhysicsActor // Update the physical location and motion of the object. Called with data from Bullet. public abstract void UpdateProperties(EntityProperties entprop); - public abstract OMV.Vector3 RawPosition { get; set; } + public virtual OMV.Vector3 RawPosition { get; set; } public abstract OMV.Vector3 ForcePosition { get; set; } - public abstract OMV.Quaternion RawOrientation { get; set; } + public virtual OMV.Quaternion RawOrientation { get; set; } public abstract OMV.Quaternion ForceOrientation { get; set; } public OMV.Vector3 RawVelocity { get; set; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index ce4c3da..d43448e 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -51,12 +51,8 @@ public class BSPrim : BSPhysObject private bool _isSelected; private bool _isVolumeDetect; - // _position is what the simulator thinks the positions of the prim is. - private OMV.Vector3 _position; - private float _mass; // the mass of this object private OMV.Vector3 _acceleration; - private OMV.Quaternion _orientation; private int _physicsActorType; private bool _isPhysical; private bool _flying; @@ -88,10 +84,10 @@ public class BSPrim : BSPhysObject { // m_log.DebugFormat("{0}: BSPrim creation of {1}, id={2}", LogHeader, primName, localID); _physicsActorType = (int)ActorTypes.Prim; - _position = pos; + RawPosition = pos; _size = size; Scale = size; // prims are the size the user wants them to be (different for BSCharactes). - _orientation = rotation; + RawOrientation = rotation; _buoyancy = 0f; RawVelocity = OMV.Vector3.Zero; _rotationalVelocity = OMV.Vector3.Zero; @@ -270,46 +266,42 @@ public class BSPrim : BSPhysObject return; } - public override OMV.Vector3 RawPosition - { - get { return _position; } - set { _position = value; } - } public override OMV.Vector3 Position { get { // don't do the GetObjectPosition for root elements because this function is called a zillion times. - // _position = ForcePosition; - return _position; + // RawPosition = ForcePosition; + return RawPosition; } set { // If the position must be forced into the physics engine, use ForcePosition. // All positions are given in world positions. - if (_position == value) + if (RawPosition == value) { - DetailLog("{0},BSPrim.setPosition,call,positionNotChanging,pos={1},orient={2}", LocalID, _position, _orientation); + DetailLog("{0},BSPrim.setPosition,call,positionNotChanging,pos={1},orient={2}", LocalID, RawPosition, RawOrientation); return; } - _position = value; + RawPosition = value; PositionSanityCheck(false); PhysScene.TaintedObject("BSPrim.setPosition", delegate() { - DetailLog("{0},BSPrim.SetPosition,taint,pos={1},orient={2}", LocalID, _position, _orientation); - ForcePosition = _position; + DetailLog("{0},BSPrim.SetPosition,taint,pos={1},orient={2}", LocalID, RawPosition, RawOrientation); + ForcePosition = RawPosition; }); } } + // NOTE: overloaded by BSPrimDisplaced to handle offset for center-of-gravity. public override OMV.Vector3 ForcePosition { get { - _position = PhysScene.PE.GetPosition(PhysBody); - return _position; + RawPosition = PhysScene.PE.GetPosition(PhysBody); + return RawPosition; } set { - _position = value; + RawPosition = value; if (PhysBody.HasPhysicalBody) { - PhysScene.PE.SetTranslation(PhysBody, _position, _orientation); + PhysScene.PE.SetTranslation(PhysBody, RawPosition, RawOrientation); ActivateIfPhysical(false); } } @@ -343,10 +335,10 @@ public class BSPrim : BSPhysObject float targetHeight = terrainHeight + (Size.Z / 2f); // If the object is below ground it just has to be moved up because pushing will // not get it through the terrain - _position.Z = targetHeight; + RawPosition = new OMV.Vector3(RawPosition.X, RawPosition.Y, targetHeight); if (inTaintTime) { - ForcePosition = _position; + ForcePosition = RawPosition; } // If we are throwing the object around, zero its other forces ZeroMotion(inTaintTime); @@ -355,7 +347,7 @@ public class BSPrim : BSPhysObject if ((CurrentCollisionFlags & CollisionFlags.BS_FLOATS_ON_WATER) != 0) { - float waterHeight = PhysScene.TerrainManager.GetWaterLevelAtXYZ(_position); + float waterHeight = PhysScene.TerrainManager.GetWaterLevelAtXYZ(RawPosition); // TODO: a floating motor so object will bob in the water if (Math.Abs(RawPosition.Z - waterHeight) > 0.1f) { @@ -364,7 +356,7 @@ public class BSPrim : BSPhysObject // Apply upforce and overcome gravity. OMV.Vector3 correctionForce = upForce - PhysScene.DefaultGravity; - DetailLog("{0},BSPrim.PositionSanityCheck,applyForce,pos={1},upForce={2},correctionForce={3}", LocalID, _position, upForce, correctionForce); + DetailLog("{0},BSPrim.PositionSanityCheck,applyForce,pos={1},upForce={2},correctionForce={3}", LocalID, RawPosition, upForce, correctionForce); AddForce(correctionForce, false, inTaintTime); ret = true; } @@ -383,11 +375,11 @@ public class BSPrim : BSPhysObject uint wayOutThere = Constants.RegionSize * Constants.RegionSize; // There have been instances of objects getting thrown way out of bounds and crashing // the border crossing code. - if ( _position.X < -Constants.RegionSize || _position.X > wayOutThere - || _position.Y < -Constants.RegionSize || _position.Y > wayOutThere - || _position.Z < -Constants.RegionSize || _position.Z > wayOutThere) + if ( RawPosition.X < -Constants.RegionSize || RawPosition.X > wayOutThere + || RawPosition.Y < -Constants.RegionSize || RawPosition.Y > wayOutThere + || RawPosition.Z < -Constants.RegionSize || RawPosition.Z > wayOutThere) { - _position = new OMV.Vector3(10, 10, 50); + RawPosition = new OMV.Vector3(10, 10, 50); ZeroMotion(inTaintTime); ret = true; } @@ -713,23 +705,19 @@ public class BSPrim : BSPhysObject get { return _acceleration; } set { _acceleration = value; } } - public override OMV.Quaternion RawOrientation - { - get { return _orientation; } - set { _orientation = value; } - } + public override OMV.Quaternion Orientation { get { - return _orientation; + return RawOrientation; } set { - if (_orientation == value) + if (RawOrientation == value) return; - _orientation = value; + RawOrientation = value; PhysScene.TaintedObject("BSPrim.setOrientation", delegate() { - ForceOrientation = _orientation; + ForceOrientation = RawOrientation; }); } } @@ -738,14 +726,14 @@ public class BSPrim : BSPhysObject { get { - _orientation = PhysScene.PE.GetOrientation(PhysBody); - return _orientation; + RawOrientation = PhysScene.PE.GetOrientation(PhysBody); + return RawOrientation; } set { - _orientation = value; + RawOrientation = value; if (PhysBody.HasPhysicalBody) - PhysScene.PE.SetTranslation(PhysBody, _position, _orientation); + PhysScene.PE.SetTranslation(PhysBody, RawPosition, RawOrientation); } } public override int PhysicsActorType { @@ -889,7 +877,7 @@ public class BSPrim : BSPhysObject // PhysicsScene.PE.ClearAllForces(BSBody); // For good measure, make sure the transform is set through to the motion state - ForcePosition = _position; + ForcePosition = RawPosition; ForceVelocity = RawVelocity; ForceRotationalVelocity = _rotationalVelocity; @@ -1543,8 +1531,8 @@ public class BSPrim : BSPhysObject // DetailLog("{0},BSPrim.UpdateProperties,entry,entprop={1}", LocalID, entprop); // DEBUG DEBUG // Assign directly to the local variables so the normal set actions do not happen - _position = entprop.Position; - _orientation = entprop.Rotation; + RawPosition = entprop.Position; + RawOrientation = entprop.Rotation; // DEBUG DEBUG DEBUG -- smooth velocity changes a bit. The simulator seems to be // very sensitive to velocity changes. if (entprop.Velocity == OMV.Vector3.Zero || !entprop.Velocity.ApproxEquals(RawVelocity, BSParam.UpdateVelocityChangeThreshold)) @@ -1557,13 +1545,13 @@ public class BSPrim : BSPhysObject // The sanity check can change the velocity and/or position. if (PositionSanityCheck(true /* inTaintTime */ )) { - entprop.Position = _position; + entprop.Position = RawPosition; entprop.Velocity = RawVelocity; entprop.RotationalVelocity = _rotationalVelocity; entprop.Acceleration = _acceleration; } - OMV.Vector3 direction = OMV.Vector3.UnitX * _orientation; // DEBUG DEBUG DEBUG + OMV.Vector3 direction = OMV.Vector3.UnitX * RawOrientation; // DEBUG DEBUG DEBUG DetailLog("{0},BSPrim.UpdateProperties,call,entProp={1},dir={2}", LocalID, entprop, direction); // remember the current and last set values -- cgit v1.1 From 6026759406f20cb89cbc62fcfc3af324c61c5ab0 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Sun, 7 Jul 2013 05:47:41 -0700 Subject: BulletSim: fix jumping up and down of linksets when center-of-mass was enabled. Didn't effect the physical position but the viewer saw the linkset jumping between its simulator center and its physical center. --- OpenSim/Region/Physics/BulletSPlugin/BSPrimDisplaced.cs | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrimDisplaced.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrimDisplaced.cs index 35d5a08..2eb1440 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrimDisplaced.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrimDisplaced.cs @@ -23,11 +23,6 @@ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * The quotations from http://wiki.secondlife.com/wiki/Linden_Vehicle_Tutorial - * are Copyright (c) 2009 Linden Research, Inc and are used under their license - * of Creative Commons Attribution-Share Alike 3.0 - * (http://creativecommons.org/licenses/by-sa/3.0/). */ using System; @@ -115,7 +110,7 @@ public class BSPrimDisplaced : BSPrim public override Vector3 ForcePosition { get { - OMV.Vector3 physPosition = base.ForcePosition; + OMV.Vector3 physPosition = PhysScene.PE.GetPosition(PhysBody); if (PositionDisplacement != OMV.Vector3.Zero) { // If there is some displacement, return the physical position (center-of-mass) @@ -125,6 +120,7 @@ public class BSPrimDisplaced : BSPrim LocalID, physPosition, displacement, physPosition - displacement); physPosition -= displacement; } + RawPosition = physPosition; return physPosition; } set -- cgit v1.1 From bbc40fab620dd61e500d8f74fa1b0d64ecc7c3b6 Mon Sep 17 00:00:00 2001 From: Vegaslon Date: Sat, 6 Jul 2013 12:53:20 -0400 Subject: BulletSim: Different Implementation of Angular Deflection for vehicles, Activates it again and fixes problem with fighting with vertical attractor removing wobble of forward axis. Comments on testing welcome, May require adjustments of this force or other forces after this commit, exact tweaking to come after testing on other hardware. Signed-off-by: Robert Adams --- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 31 +++++++++++----------- 1 file changed, 16 insertions(+), 15 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index c27d3f0..82fe267 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -144,7 +144,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin public void SetupVehicleDebugging() { enableAngularVerticalAttraction = true; - enableAngularDeflection = false; + enableAngularDeflection = true; enableAngularBanking = true; if (BSParam.VehicleDebuggingEnable) { @@ -173,7 +173,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin switch (pParam) { case Vehicle.ANGULAR_DEFLECTION_EFFICIENCY: - m_angularDeflectionEfficiency = Math.Max(pValue, 0.01f); + m_angularDeflectionEfficiency = ClampInRange(0f, pValue, 1f); break; case Vehicle.ANGULAR_DEFLECTION_TIMESCALE: m_angularDeflectionTimescale = Math.Max(pValue, 0.01f); @@ -1512,11 +1512,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin // in that direction. // TODO: implement reference frame. public void ComputeAngularDeflection() - { - // Since angularMotorUp and angularDeflection are computed independently, they will calculate - // approximately the same X or Y correction. When added together (when contributions are combined) - // this creates an over-correction and then wabbling as the target is overshot. - // TODO: rethink how the different correction computations inter-relate. + { if (enableAngularDeflection && m_angularDeflectionEfficiency != 0 && VehicleForwardSpeed > 0.2) { @@ -1531,10 +1527,14 @@ namespace OpenSim.Region.Physics.BulletSPlugin // The direction the vehicle is pointing Vector3 pointingDirection = Vector3.UnitX * VehicleOrientation; - pointingDirection.Normalize(); + //Predict where the Vehicle will be pointing after AngularVelocity change is applied. This will keep + // from overshooting and allow this correction to merge with the Vertical Attraction peacefully. + Vector3 predictedPointingDirection = pointingDirection * Quaternion.CreateFromAxisAngle(VehicleRotationalVelocity, 0f); + predictedPointingDirection.Normalize(); // The difference between what is and what should be. - Vector3 deflectionError = movingDirection - pointingDirection; + // Vector3 deflectionError = movingDirection - predictedPointingDirection; + Vector3 deflectionError = Vector3.Cross(movingDirection, predictedPointingDirection); // Don't try to correct very large errors (not our job) // if (Math.Abs(deflectionError.X) > PIOverFour) deflectionError.X = PIOverTwo * Math.Sign(deflectionError.X); @@ -1547,15 +1547,16 @@ namespace OpenSim.Region.Physics.BulletSPlugin // ret = m_angularDeflectionCorrectionMotor(1f, deflectionError); // Scale the correction by recovery timescale and efficiency - deflectContributionV = (-deflectionError) * m_angularDeflectionEfficiency; - deflectContributionV /= m_angularDeflectionTimescale; - - VehicleRotationalVelocity += deflectContributionV * VehicleOrientation; + // Not modeling a spring so clamp the scale to no more then the arc + deflectContributionV = (-deflectionError) * ClampInRange(0, m_angularDeflectionEfficiency/m_angularDeflectionTimescale,1f); + //deflectContributionV /= m_angularDeflectionTimescale; + // VehicleRotationalVelocity += deflectContributionV * VehicleOrientation; + VehicleRotationalVelocity += deflectContributionV; VDetailLog("{0}, MoveAngular,Deflection,movingDir={1},pointingDir={2},deflectError={3},ret={4}", ControllingPrim.LocalID, movingDirection, pointingDirection, deflectionError, deflectContributionV); - VDetailLog("{0}, MoveAngular,Deflection,fwdSpd={1},defEff={2},defTS={3}", - ControllingPrim.LocalID, VehicleForwardSpeed, m_angularDeflectionEfficiency, m_angularDeflectionTimescale); + VDetailLog("{0}, MoveAngular,Deflection,fwdSpd={1},defEff={2},defTS={3},PredictedPointingDir={4}", + ControllingPrim.LocalID, VehicleForwardSpeed, m_angularDeflectionEfficiency, m_angularDeflectionTimescale, predictedPointingDirection); } } -- cgit v1.1 From 047ef9c2a5cb573c0a506fecd0f2a7e8dc85c023 Mon Sep 17 00:00:00 2001 From: Justin Clark-Casey (justincc) Date: Mon, 8 Jul 2013 23:36:57 +0100 Subject: minor: remove some mono compiler warnings in OdePlugin --- OpenSim/Region/Physics/OdePlugin/ODEPrim.cs | 1 - OpenSim/Region/Physics/OdePlugin/OdePlugin.cs | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs b/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs index 0d66496..13c69d6 100644 --- a/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs +++ b/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs @@ -108,7 +108,6 @@ namespace OpenSim.Region.Physics.OdePlugin private Vector3 m_taintAngularLock = Vector3.One; private IntPtr Amotor = IntPtr.Zero; - private object m_assetsLock = new object(); private bool m_assetFailed = false; private Vector3 m_PIDTarget; diff --git a/OpenSim/Region/Physics/OdePlugin/OdePlugin.cs b/OpenSim/Region/Physics/OdePlugin/OdePlugin.cs index 07663b3..7e652fc 100644 --- a/OpenSim/Region/Physics/OdePlugin/OdePlugin.cs +++ b/OpenSim/Region/Physics/OdePlugin/OdePlugin.cs @@ -46,7 +46,7 @@ namespace OpenSim.Region.Physics.OdePlugin /// public class OdePlugin : IPhysicsPlugin { - private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); +// private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private OdeScene m_scene; -- cgit v1.1 From fad4241e4ea898b0dca0176cc9b428d03ba44d1c Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Mon, 8 Jul 2013 16:21:10 -0700 Subject: BulletSim: make all the different angularVerticalAttraction algorithms selectable from configuration paramters. Changed default algorithm to "1" from previous default as it seems to handle Y axis correction a little better. Add config file independent enablement of vehicle angular forces to make debugging easier (independent testing of forces). --- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 261 ++++++++++----------- OpenSim/Region/Physics/BulletSPlugin/BSParam.cs | 15 +- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 4 +- .../Physics/BulletSPlugin/Tests/BasicVehicles.cs | 4 +- 4 files changed, 146 insertions(+), 138 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index 82fe267..a5f2e98 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -125,33 +125,12 @@ namespace OpenSim.Region.Physics.BulletSPlugin static readonly float PIOverFour = ((float)Math.PI) / 4f; static readonly float PIOverTwo = ((float)Math.PI) / 2f; - // For debugging, flags to turn on and off individual corrections. - public bool enableAngularVerticalAttraction; - public bool enableAngularDeflection; - public bool enableAngularBanking; - public BSDynamics(BSScene myScene, BSPrim myPrim, string actorName) : base(myScene, myPrim, actorName) { ControllingPrim = myPrim; Type = Vehicle.TYPE_NONE; m_haveRegisteredForSceneEvents = false; - SetupVehicleDebugging(); - } - - // Stopgap debugging enablement. Allows source level debugging but still checking - // in changes by making enablement of debugging flags from INI file. - public void SetupVehicleDebugging() - { - enableAngularVerticalAttraction = true; - enableAngularDeflection = true; - enableAngularBanking = true; - if (BSParam.VehicleDebuggingEnable) - { - enableAngularVerticalAttraction = true; - enableAngularDeflection = false; - enableAngularBanking = false; - } } // Return 'true' if this vehicle is doing vehicle things @@ -556,10 +535,10 @@ namespace OpenSim.Region.Physics.BulletSPlugin } m_linearMotor = new BSVMotor("LinearMotor", m_linearMotorTimescale, m_linearMotorDecayTimescale, 1f); - m_linearMotor.PhysicsScene = m_physicsScene; // DEBUG DEBUG DEBUG (enables detail logging) + // m_linearMotor.PhysicsScene = m_physicsScene; // DEBUG DEBUG DEBUG (enables detail logging) m_angularMotor = new BSVMotor("AngularMotor", m_angularMotorTimescale, m_angularMotorDecayTimescale, 1f); - m_angularMotor.PhysicsScene = m_physicsScene; // DEBUG DEBUG DEBUG (enables detail logging) + // m_angularMotor.PhysicsScene = m_physicsScene; // DEBUG DEBUG DEBUG (enables detail logging) /* Not implemented m_verticalAttractionMotor = new BSVMotor("VerticalAttraction", m_verticalAttractionTimescale, @@ -1393,116 +1372,134 @@ namespace OpenSim.Region.Physics.BulletSPlugin { // If vertical attaction timescale is reasonable - if (enableAngularVerticalAttraction && m_verticalAttractionTimescale < m_verticalAttractionCutoff) + if (BSParam.VehicleEnableAngularVerticalAttraction && m_verticalAttractionTimescale < m_verticalAttractionCutoff) { - //Another formula to try got from : - //http://answers.unity3d.com/questions/10425/how-to-stabilize-angular-motion-alignment-of-hover.html - - Vector3 VehicleUpAxis = Vector3.UnitZ * VehicleOrientation; - - // Flipping what was originally a timescale into a speed variable and then multiplying it by 2 - // since only computing half the distance between the angles. - float VerticalAttractionSpeed = (1 / m_verticalAttractionTimescale) * 2.0f; - - // Make a prediction of where the up axis will be when this is applied rather then where it is now as - // this makes for a smoother adjustment and less fighting between the various forces. - Vector3 predictedUp = VehicleUpAxis * Quaternion.CreateFromAxisAngle(VehicleRotationalVelocity, 0f); - - // This is only half the distance to the target so it will take 2 seconds to complete the turn. - Vector3 torqueVector = Vector3.Cross(predictedUp, Vector3.UnitZ); - - // Scale vector by our timescale since it is an acceleration it is r/s^2 or radians a timescale squared - Vector3 vertContributionV = torqueVector * VerticalAttractionSpeed * VerticalAttractionSpeed; - - VehicleRotationalVelocity += vertContributionV; - - VDetailLog("{0}, MoveAngular,verticalAttraction,UpAxis={1},PredictedUp={2},torqueVector={3},contrib={4}", - ControllingPrim.LocalID, - VehicleUpAxis, - predictedUp, - torqueVector, - vertContributionV); - //===================================================================== - /* - // Possible solution derived from a discussion at: - // http://stackoverflow.com/questions/14939657/computing-vector-from-quaternion-works-computing-quaternion-from-vector-does-no - - // Create a rotation that is only the vehicle's rotation around Z - Vector3 currentEuler = Vector3.Zero; - VehicleOrientation.GetEulerAngles(out currentEuler.X, out currentEuler.Y, out currentEuler.Z); - Quaternion justZOrientation = Quaternion.CreateFromAxisAngle(Vector3.UnitZ, currentEuler.Z); - - // Create the axis that is perpendicular to the up vector and the rotated up vector. - Vector3 differenceAxis = Vector3.Cross(Vector3.UnitZ * justZOrientation, Vector3.UnitZ * VehicleOrientation); - // Compute the angle between those to vectors. - double differenceAngle = Math.Acos((double)Vector3.Dot(Vector3.UnitZ, Vector3.Normalize(Vector3.UnitZ * VehicleOrientation))); - // 'differenceAngle' is the angle to rotate and 'differenceAxis' is the plane to rotate in to get the vehicle vertical - - // Reduce the change by the time period it is to change in. Timestep is handled when velocity is applied. - // TODO: add 'efficiency'. - differenceAngle /= m_verticalAttractionTimescale; - - // Create the quaterian representing the correction angle - Quaternion correctionRotation = Quaternion.CreateFromAxisAngle(differenceAxis, (float)differenceAngle); - - // Turn that quaternion into Euler values to make it into velocities to apply. - Vector3 vertContributionV = Vector3.Zero; - correctionRotation.GetEulerAngles(out vertContributionV.X, out vertContributionV.Y, out vertContributionV.Z); - vertContributionV *= -1f; - - VehicleRotationalVelocity += vertContributionV; - - VDetailLog("{0}, MoveAngular,verticalAttraction,diffAxis={1},diffAng={2},corrRot={3},contrib={4}", - ControllingPrim.LocalID, - differenceAxis, - differenceAngle, - correctionRotation, - vertContributionV); - */ - - // =================================================================== - /* - Vector3 vertContributionV = Vector3.Zero; - Vector3 origRotVelW = VehicleRotationalVelocity; // DEBUG DEBUG - - // Take a vector pointing up and convert it from world to vehicle relative coords. - Vector3 verticalError = Vector3.Normalize(Vector3.UnitZ * VehicleOrientation); - - // If vertical attraction correction is needed, the vector that was pointing up (UnitZ) - // is now: - // leaning to one side: rotated around the X axis with the Y value going - // from zero (nearly straight up) to one (completely to the side)) or - // leaning front-to-back: rotated around the Y axis with the value of X being between - // zero and one. - // The value of Z is how far the rotation is off with 1 meaning none and 0 being 90 degrees. - - // Y error means needed rotation around X axis and visa versa. - // Since the error goes from zero to one, the asin is the corresponding angle. - vertContributionV.X = (float)Math.Asin(verticalError.Y); - // (Tilt forward (positive X) needs to tilt back (rotate negative) around Y axis.) - vertContributionV.Y = -(float)Math.Asin(verticalError.X); - - // If verticalError.Z is negative, the vehicle is upside down. Add additional push. - if (verticalError.Z < 0f) + Vector3 vehicleUpAxis = Vector3.UnitZ * VehicleOrientation; + switch (BSParam.VehicleAngularVerticalAttractionAlgorithm) { - vertContributionV.X += Math.Sign(vertContributionV.X) * PIOverFour; - // vertContribution.Y -= PIOverFour; + case 0: + { + //Another formula to try got from : + //http://answers.unity3d.com/questions/10425/how-to-stabilize-angular-motion-alignment-of-hover.html + + // Flipping what was originally a timescale into a speed variable and then multiplying it by 2 + // since only computing half the distance between the angles. + float VerticalAttractionSpeed = (1 / m_verticalAttractionTimescale) * 2.0f; + + // Make a prediction of where the up axis will be when this is applied rather then where it is now as + // this makes for a smoother adjustment and less fighting between the various forces. + Vector3 predictedUp = vehicleUpAxis * Quaternion.CreateFromAxisAngle(VehicleRotationalVelocity, 0f); + + // This is only half the distance to the target so it will take 2 seconds to complete the turn. + Vector3 torqueVector = Vector3.Cross(predictedUp, Vector3.UnitZ); + + // Scale vector by our timescale since it is an acceleration it is r/s^2 or radians a timescale squared + Vector3 vertContributionV = torqueVector * VerticalAttractionSpeed * VerticalAttractionSpeed; + + VehicleRotationalVelocity += vertContributionV; + + VDetailLog("{0}, MoveAngular,verticalAttraction,upAxis={1},PredictedUp={2},torqueVector={3},contrib={4}", + ControllingPrim.LocalID, + vehicleUpAxis, + predictedUp, + torqueVector, + vertContributionV); + break; + } + case 1: + { + // Possible solution derived from a discussion at: + // http://stackoverflow.com/questions/14939657/computing-vector-from-quaternion-works-computing-quaternion-from-vector-does-no + + // Create a rotation that is only the vehicle's rotation around Z + Vector3 currentEuler = Vector3.Zero; + VehicleOrientation.GetEulerAngles(out currentEuler.X, out currentEuler.Y, out currentEuler.Z); + Quaternion justZOrientation = Quaternion.CreateFromAxisAngle(Vector3.UnitZ, currentEuler.Z); + + // Create the axis that is perpendicular to the up vector and the rotated up vector. + Vector3 differenceAxis = Vector3.Cross(Vector3.UnitZ * justZOrientation, Vector3.UnitZ * VehicleOrientation); + // Compute the angle between those to vectors. + double differenceAngle = Math.Acos((double)Vector3.Dot(Vector3.UnitZ, Vector3.Normalize(Vector3.UnitZ * VehicleOrientation))); + // 'differenceAngle' is the angle to rotate and 'differenceAxis' is the plane to rotate in to get the vehicle vertical + + // Reduce the change by the time period it is to change in. Timestep is handled when velocity is applied. + // TODO: add 'efficiency'. + differenceAngle /= m_verticalAttractionTimescale; + + // Create the quaterian representing the correction angle + Quaternion correctionRotation = Quaternion.CreateFromAxisAngle(differenceAxis, (float)differenceAngle); + + // Turn that quaternion into Euler values to make it into velocities to apply. + Vector3 vertContributionV = Vector3.Zero; + correctionRotation.GetEulerAngles(out vertContributionV.X, out vertContributionV.Y, out vertContributionV.Z); + vertContributionV *= -1f; + + VehicleRotationalVelocity += vertContributionV; + + VDetailLog("{0}, MoveAngular,verticalAttraction,upAxis={1},diffAxis={2},diffAng={3},corrRot={4},contrib={5}", + ControllingPrim.LocalID, + vehicleUpAxis, + differenceAxis, + differenceAngle, + correctionRotation, + vertContributionV); + break; + } + case 2: + { + Vector3 vertContributionV = Vector3.Zero; + Vector3 origRotVelW = VehicleRotationalVelocity; // DEBUG DEBUG + + // Take a vector pointing up and convert it from world to vehicle relative coords. + Vector3 verticalError = Vector3.Normalize(Vector3.UnitZ * VehicleOrientation); + + // If vertical attraction correction is needed, the vector that was pointing up (UnitZ) + // is now: + // leaning to one side: rotated around the X axis with the Y value going + // from zero (nearly straight up) to one (completely to the side)) or + // leaning front-to-back: rotated around the Y axis with the value of X being between + // zero and one. + // The value of Z is how far the rotation is off with 1 meaning none and 0 being 90 degrees. + + // Y error means needed rotation around X axis and visa versa. + // Since the error goes from zero to one, the asin is the corresponding angle. + vertContributionV.X = (float)Math.Asin(verticalError.Y); + // (Tilt forward (positive X) needs to tilt back (rotate negative) around Y axis.) + vertContributionV.Y = -(float)Math.Asin(verticalError.X); + + // If verticalError.Z is negative, the vehicle is upside down. Add additional push. + if (verticalError.Z < 0f) + { + vertContributionV.X += Math.Sign(vertContributionV.X) * PIOverFour; + // vertContribution.Y -= PIOverFour; + } + + // 'vertContrbution' is now the necessary angular correction to correct tilt in one second. + // Correction happens over a number of seconds. + Vector3 unscaledContribVerticalErrorV = vertContributionV; // DEBUG DEBUG + + // The correction happens over the user's time period + vertContributionV /= m_verticalAttractionTimescale; + + // Rotate the vehicle rotation to the world coordinates. + VehicleRotationalVelocity += (vertContributionV * VehicleOrientation); + + VDetailLog("{0}, MoveAngular,verticalAttraction,,upAxis={1},origRotVW={2},vertError={3},unscaledV={4},eff={5},ts={6},vertContribV={7}", + ControllingPrim.LocalID, + vehicleUpAxis, + origRotVelW, + verticalError, + unscaledContribVerticalErrorV, + m_verticalAttractionEfficiency, + m_verticalAttractionTimescale, + vertContributionV); + break; + } + default: + { + break; + } } - - // 'vertContrbution' is now the necessary angular correction to correct tilt in one second. - // Correction happens over a number of seconds. - Vector3 unscaledContribVerticalErrorV = vertContributionV; // DEBUG DEBUG - - // The correction happens over the user's time period - vertContributionV /= m_verticalAttractionTimescale; - - // Rotate the vehicle rotation to the world coordinates. - VehicleRotationalVelocity += (vertContributionV * VehicleOrientation); - - VDetailLog("{0}, MoveAngular,verticalAttraction,,origRotVW={1},vertError={2},unscaledV={3},eff={4},ts={5},vertContribV={6}", - Prim.LocalID, origRotVelW, verticalError, unscaledContribVerticalErrorV, - m_verticalAttractionEfficiency, m_verticalAttractionTimescale, vertContributionV); - */ } } @@ -1514,7 +1511,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin public void ComputeAngularDeflection() { - if (enableAngularDeflection && m_angularDeflectionEfficiency != 0 && VehicleForwardSpeed > 0.2) + if (BSParam.VehicleEnableAngularDeflection && m_angularDeflectionEfficiency != 0 && VehicleForwardSpeed > 0.2) { Vector3 deflectContributionV = Vector3.Zero; @@ -1593,7 +1590,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin // make a sluggish vehicle by giving it a timescale of several seconds. public void ComputeAngularBanking() { - if (enableAngularBanking && m_bankingEfficiency != 0 && m_verticalAttractionTimescale < m_verticalAttractionCutoff) + if (BSParam.VehicleEnableAngularBanking && m_bankingEfficiency != 0 && m_verticalAttractionTimescale < m_verticalAttractionCutoff) { Vector3 bankingContributionV = Vector3.Zero; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs index 0f84bf7..75c3399 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs @@ -155,7 +155,10 @@ public static class BSParam public static Vector3 VehicleInertiaFactor { get; private set; } public static float VehicleGroundGravityFudge { get; private set; } public static float VehicleAngularBankingTimescaleFudge { get; private set; } - public static bool VehicleDebuggingEnable { get; private set; } + public static bool VehicleEnableAngularVerticalAttraction { get; private set; } + public static int VehicleAngularVerticalAttractionAlgorithm { get; private set; } + public static bool VehicleEnableAngularDeflection { get; private set; } + public static bool VehicleEnableAngularBanking { get; private set; } // Convex Hulls public static int CSHullMaxDepthSplit { get; private set; } @@ -606,8 +609,14 @@ public static class BSParam 0.2f ), new ParameterDefn("VehicleAngularBankingTimescaleFudge", "Factor to multiple angular banking timescale. Tune to increase realism.", 60.0f ), - new ParameterDefn("VehicleDebuggingEnable", "Turn on/off vehicle debugging", - false ), + new ParameterDefn("VehicleEnableAngularVerticalAttraction", "Turn on/off vehicle angular vertical attraction effect", + true ), + new ParameterDefn("VehicleAngularVerticalAttractionAlgorithm", "Select vertical attraction algo. You need to look at the source.", + 1 ), + new ParameterDefn("VehicleEnableAngularDeflection", "Turn on/off vehicle angular deflection effect", + true ), + new ParameterDefn("VehicleEnableAngularBanking", "Turn on/off vehicle angular banking effect", + true ), new ParameterDefn("MaxPersistantManifoldPoolSize", "Number of manifolds pooled (0 means default of 4096)", 0f, diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index e56a6f6..214271b 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -1,4 +1,4 @@ -/* +/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * @@ -648,7 +648,7 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters simTime = Util.EnvironmentTickCountSubtract(beforeTime); if (PhysicsLogging.Enabled) { - DetailLog("{0},DoPhysicsStep,call, frame={1}, nTaints={2}, simTime={3}, substeps={4}, updates={5}, colliders={6}, objWColl={7}", + DetailLog("{0},DoPhysicsStep,complete,frame={1}, nTaints={2}, simTime={3}, substeps={4}, updates={5}, colliders={6}, objWColl={7}", DetailLogZero, m_simulationStep, numTaints, simTime, numSubSteps, updatedEntityCount, collidersCount, ObjectsWithCollisions.Count); } diff --git a/OpenSim/Region/Physics/BulletSPlugin/Tests/BasicVehicles.cs b/OpenSim/Region/Physics/BulletSPlugin/Tests/BasicVehicles.cs index 583c436..48d3742 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/Tests/BasicVehicles.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/Tests/BasicVehicles.cs @@ -57,6 +57,8 @@ public class BasicVehicles : OpenSimTestCase public void Init() { Dictionary engineParams = new Dictionary(); + engineParams.Add("VehicleEnableAngularVerticalAttraction", "true"); + engineParams.Add("VehicleAngularVerticalAttractionAlgorithm", "1"); PhysicsScene = BulletSimTestsUtil.CreateBasicPhysicsEngine(engineParams); PrimitiveBaseShape pbs = PrimitiveBaseShape.CreateSphere(); @@ -119,7 +121,7 @@ public class BasicVehicles : OpenSimTestCase { vehicleActor.ProcessFloatVehicleParam(Vehicle.VERTICAL_ATTRACTION_EFFICIENCY, efficiency); vehicleActor.ProcessFloatVehicleParam(Vehicle.VERTICAL_ATTRACTION_TIMESCALE, timeScale); - vehicleActor.enableAngularVerticalAttraction = true; + // vehicleActor.enableAngularVerticalAttraction = true; TestVehicle.IsPhysical = true; PhysicsScene.ProcessTaints(); -- cgit v1.1 From 2c761cef192670a6f54fe10bb5b5894b5371ea7c Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 9 Jul 2013 09:33:46 -0700 Subject: BulletSim: add parameter to optionally disable vehicle linear deflection. Add parameter to not apply vehicle linear deflection Z forces if vehicle is not colliding. This defaults to 'true' so vehicles will fall even if there is some linear deflection to apply. --- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 42 ++++++++++++++-------- OpenSim/Region/Physics/BulletSPlugin/BSParam.cs | 8 ++++- 2 files changed, 34 insertions(+), 16 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index a5f2e98..0204967 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -905,6 +905,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin return VehicleVelocity * Quaternion.Inverse(Quaternion.Normalize(VehicleOrientation)); } } + private float VehicleForwardSpeed { get @@ -1040,26 +1041,37 @@ namespace OpenSim.Region.Physics.BulletSPlugin Vector3 linearDeflectionV = Vector3.Zero; Vector3 velocityV = VehicleForwardVelocity; - // Velocity in Y and Z dimensions is movement to the side or turning. - // Compute deflection factor from the to the side and rotational velocity - linearDeflectionV.Y = SortedClampInRange(0, (velocityV.Y * m_linearDeflectionEfficiency) / m_linearDeflectionTimescale, velocityV.Y); - linearDeflectionV.Z = SortedClampInRange(0, (velocityV.Z * m_linearDeflectionEfficiency) / m_linearDeflectionTimescale, velocityV.Z); + if (BSParam.VehicleEnableLinearDeflection) + { + // Velocity in Y and Z dimensions is movement to the side or turning. + // Compute deflection factor from the to the side and rotational velocity + linearDeflectionV.Y = SortedClampInRange(0, (velocityV.Y * m_linearDeflectionEfficiency) / m_linearDeflectionTimescale, velocityV.Y); + linearDeflectionV.Z = SortedClampInRange(0, (velocityV.Z * m_linearDeflectionEfficiency) / m_linearDeflectionTimescale, velocityV.Z); - // Velocity to the side and around is corrected and moved into the forward direction - linearDeflectionV.X += Math.Abs(linearDeflectionV.Y); - linearDeflectionV.X += Math.Abs(linearDeflectionV.Z); + // Velocity to the side and around is corrected and moved into the forward direction + linearDeflectionV.X += Math.Abs(linearDeflectionV.Y); + linearDeflectionV.X += Math.Abs(linearDeflectionV.Z); - // Scale the deflection to the fractional simulation time - linearDeflectionV *= pTimestep; + // Scale the deflection to the fractional simulation time + linearDeflectionV *= pTimestep; - // Subtract the sideways and rotational velocity deflection factors while adding the correction forward - linearDeflectionV *= new Vector3(1,-1,-1); + // Subtract the sideways and rotational velocity deflection factors while adding the correction forward + linearDeflectionV *= new Vector3(1, -1, -1); - // Correciont is vehicle relative. Convert to world coordinates and add to the velocity - VehicleVelocity += linearDeflectionV * VehicleOrientation; + // Correction is vehicle relative. Convert to world coordinates. + Vector3 linearDeflectionW = linearDeflectionV * VehicleOrientation; - VDetailLog("{0}, MoveLinear,LinearDeflection,linDefEff={1},linDefTS={2},linDeflectionV={3}", - ControllingPrim.LocalID, m_linearDeflectionEfficiency, m_linearDeflectionTimescale, linearDeflectionV); + // Optionally, if not colliding, don't effect world downward velocity. Let falling things fall. + if (BSParam.VehicleLinearDeflectionNotCollidingNoZ && !m_controllingPrim.IsColliding) + { + linearDeflectionW.Z = 0f; + } + + VehicleVelocity += linearDeflectionW; + + VDetailLog("{0}, MoveLinear,LinearDeflection,linDefEff={1},linDefTS={2},linDeflectionV={3}", + ControllingPrim.LocalID, m_linearDeflectionEfficiency, m_linearDeflectionTimescale, linearDeflectionV); + } } public void ComputeLinearTerrainHeightCorrection(float pTimestep) diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs index 75c3399..dcf1e83 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs @@ -155,6 +155,8 @@ public static class BSParam public static Vector3 VehicleInertiaFactor { get; private set; } public static float VehicleGroundGravityFudge { get; private set; } public static float VehicleAngularBankingTimescaleFudge { get; private set; } + public static bool VehicleEnableLinearDeflection { get; private set; } + public static bool VehicleLinearDeflectionNotCollidingNoZ { get; private set; } public static bool VehicleEnableAngularVerticalAttraction { get; private set; } public static int VehicleAngularVerticalAttractionAlgorithm { get; private set; } public static bool VehicleEnableAngularDeflection { get; private set; } @@ -609,10 +611,14 @@ public static class BSParam 0.2f ), new ParameterDefn("VehicleAngularBankingTimescaleFudge", "Factor to multiple angular banking timescale. Tune to increase realism.", 60.0f ), + new ParameterDefn("VehicleEnableLinearDeflection", "Turn on/off vehicle linear deflection effect", + true ), + new ParameterDefn("VehicleLinearDeflectionNotCollidingNoZ", "Turn on/off linear deflection Z effect on non-colliding vehicles", + true ), new ParameterDefn("VehicleEnableAngularVerticalAttraction", "Turn on/off vehicle angular vertical attraction effect", true ), new ParameterDefn("VehicleAngularVerticalAttractionAlgorithm", "Select vertical attraction algo. You need to look at the source.", - 1 ), + 0 ), new ParameterDefn("VehicleEnableAngularDeflection", "Turn on/off vehicle angular deflection effect", true ), new ParameterDefn("VehicleEnableAngularBanking", "Turn on/off vehicle angular banking effect", -- cgit v1.1 From 2c8bf4aaa66a4cc9fc8fd9f89825e7cd1b43f3d6 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Wed, 17 Jul 2013 10:19:44 -0700 Subject: BulletSim: fix small bug where everything looked like it was colliding before the first simulator step. --- OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs | 13 +++++++------ OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 3 +++ 2 files changed, 10 insertions(+), 6 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index a41eaf8..fc4545f 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -103,9 +103,10 @@ public abstract class BSPhysObject : PhysicsActor CollisionsLastTickStep = -1; SubscribedEventsMs = 0; - CollidingStep = 0; - CollidingGroundStep = 0; - CollisionAccumulation = 0; + // Crazy values that will never be true + CollidingStep = BSScene.NotASimulationStep; + CollidingGroundStep = BSScene.NotASimulationStep; + CollisionAccumulation = BSScene.NotASimulationStep; ColliderIsMoving = false; CollisionScore = 0; @@ -349,7 +350,7 @@ public abstract class BSPhysObject : PhysicsActor if (value) CollidingStep = PhysScene.SimulationStep; else - CollidingStep = 0; + CollidingStep = BSScene.NotASimulationStep; } } public override bool CollidingGround { @@ -359,7 +360,7 @@ public abstract class BSPhysObject : PhysicsActor if (value) CollidingGroundStep = PhysScene.SimulationStep; else - CollidingGroundStep = 0; + CollidingGroundStep = BSScene.NotASimulationStep; } } public override bool CollidingObj { @@ -368,7 +369,7 @@ public abstract class BSPhysObject : PhysicsActor if (value) CollidingObjectStep = PhysScene.SimulationStep; else - CollidingObjectStep = 0; + CollidingObjectStep = BSScene.NotASimulationStep; } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index 214271b..41aca3b 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -97,6 +97,9 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters internal long m_simulationStep = 0; // The current simulation step. public long SimulationStep { get { return m_simulationStep; } } + // A number to use for SimulationStep that is probably not any step value + // Used by the collision code (which remembers the step when a collision happens) to remember not any simulation step. + public static long NotASimulationStep = -1234; internal float LastTimeStep { get; private set; } // The simulation time from the last invocation of Simulate() -- cgit v1.1 From 1d65b0d80296a672c8023293aee7d0a01bad4066 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Thu, 18 Jul 2013 19:09:55 -0700 Subject: BulletSim: add position resetting for stationary avatars so they don't move around when standing on a stationary object. Create proper linkage between BSCharacter and its actor by generating a UpdatedProperties event the same way BSPrim does. --- .../Region/Physics/BulletSPlugin/BSActorAvatarMove.cs | 17 ++++++++++++++++- OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs | 8 ++++---- 2 files changed, 20 insertions(+), 5 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs b/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs index 928b350..0f11c4a 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs @@ -130,6 +130,7 @@ public class BSActorAvatarMove : BSActor SetVelocityAndTarget(m_controllingPrim.RawVelocity, m_controllingPrim.TargetVelocity, true /* inTaintTime */); m_physicsScene.BeforeStep += Mover; + m_controllingPrim.OnPreUpdateProperty += Process_OnPreUpdateProperty; m_walkingUpStairs = 0; } @@ -139,6 +140,7 @@ public class BSActorAvatarMove : BSActor { if (m_velocityMotor != null) { + m_controllingPrim.OnPreUpdateProperty -= Process_OnPreUpdateProperty; m_physicsScene.BeforeStep -= Mover; m_velocityMotor = null; } @@ -197,7 +199,7 @@ public class BSActorAvatarMove : BSActor { if (m_controllingPrim.Flying) { - // Flying and not collising and velocity nearly zero. + // Flying and not colliding and velocity nearly zero. m_controllingPrim.ZeroMotion(true /* inTaintTime */); } } @@ -266,6 +268,19 @@ public class BSActorAvatarMove : BSActor } } + // Called just as the property update is received from the physics engine. + // Do any mode necessary for avatar movement. + private void Process_OnPreUpdateProperty(ref EntityProperties entprop) + { + // Don't change position if standing on a stationary object. + if (m_controllingPrim.IsStationary) + { + entprop.Position = m_controllingPrim.RawPosition; + m_physicsScene.PE.SetTranslation(m_controllingPrim.PhysBody, entprop.Position, entprop.Rotation); + } + + } + // Decide if the character is colliding with a low object and compute a force to pop the // avatar up so it can walk up and over the low objects. private OMV.Vector3 WalkUpStairs() diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index c9e3ca0..59e7f5f 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -709,10 +709,10 @@ public sealed class BSCharacter : BSPhysObject // the world that things have changed. public override void UpdateProperties(EntityProperties entprop) { - // Don't change position if standing on a stationary object. - if (!IsStationary) - RawPosition = entprop.Position; + // Let anyone (like the actors) modify the updated properties before they are pushed into the object and the simulator. + TriggerPreUpdatePropertyAction(ref entprop); + RawPosition = entprop.Position; RawOrientation = entprop.Rotation; // Smooth velocity. OpenSimulator is VERY sensitive to changes in velocity of the avatar @@ -740,7 +740,7 @@ public sealed class BSCharacter : BSPhysObject // Linkset.UpdateProperties(UpdatedProperties.EntPropUpdates, this); // Avatars don't report their changes the usual way. Changes are checked for in the heartbeat loop. - // base.RequestPhysicsterseUpdate(); + // PhysScene.PostUpdate(this); DetailLog("{0},BSCharacter.UpdateProperties,call,pos={1},orient={2},vel={3},accel={4},rotVel={5}", LocalID, RawPosition, RawOrientation, RawVelocity, _acceleration, _rotationalVelocity); -- cgit v1.1 From 803632f8f32d91bb4aec678d8b45a8430c2703e1 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 9 Jul 2013 16:26:17 -0700 Subject: BulletSim: freshen up the code for constraint based linksets. --- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 4 +- .../Physics/BulletSPlugin/BSLinksetCompound.cs | 1 + .../Physics/BulletSPlugin/BSLinksetConstraints.cs | 82 ++++++++++++++++------ 3 files changed, 64 insertions(+), 23 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index 0204967..4c2c1c1 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -1029,8 +1029,8 @@ namespace OpenSim.Region.Physics.BulletSPlugin // Add this correction to the velocity to make it faster/slower. VehicleVelocity += linearMotorVelocityW; - VDetailLog("{0}, MoveLinear,velocity,origVelW={1},velV={2},correctV={3},correctW={4},newVelW={5},fricFact={6}", - ControllingPrim.LocalID, origVelW, currentVelV, linearMotorCorrectionV, + VDetailLog("{0}, MoveLinear,velocity,origVelW={1},velV={2},tgt={3},correctV={4},correctW={5},newVelW={6},fricFact={7}", + ControllingPrim.LocalID, origVelW, currentVelV, m_linearMotor.TargetValue, linearMotorCorrectionV, linearMotorVelocityW, VehicleVelocity, frictionFactorV); } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs index 1d94142..3668456 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs @@ -59,6 +59,7 @@ public sealed class BSLinksetCompound : BSLinkset { DetailLog("{0},BSLinksetCompound.ScheduleRebuild,,rebuilding={1},hasChildren={2},actuallyScheduling={3}", requestor.LocalID, Rebuilding, HasAnyChildren, (!Rebuilding && HasAnyChildren)); + // When rebuilding, it is possible to set properties that would normally require a rebuild. // If already rebuilding, don't request another rebuild. // If a linkset with just a root prim (simple non-linked prim) don't bother rebuilding. diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs index a06a44d..f17d698 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs @@ -48,12 +48,22 @@ public sealed class BSLinksetConstraints : BSLinkset { base.Refresh(requestor); - if (HasAnyChildren && IsRoot(requestor)) + } + + private void ScheduleRebuild(BSPrimLinkable requestor) + { + DetailLog("{0},BSLinksetConstraint.ScheduleRebuild,,rebuilding={1},hasChildren={2},actuallyScheduling={3}", + requestor.LocalID, Rebuilding, HasAnyChildren, (!Rebuilding && HasAnyChildren)); + + // When rebuilding, it is possible to set properties that would normally require a rebuild. + // If already rebuilding, don't request another rebuild. + // If a linkset with just a root prim (simple non-linked prim) don't bother rebuilding. + if (!Rebuilding && HasAnyChildren) { // Queue to happen after all the other taint processing m_physicsScene.PostTaintObject("BSLinksetContraints.Refresh", requestor.LocalID, delegate() { - if (HasAnyChildren && IsRoot(requestor)) + if (HasAnyChildren) RecomputeLinksetConstraints(); }); } @@ -67,8 +77,14 @@ public sealed class BSLinksetConstraints : BSLinkset // Called at taint-time! public override bool MakeDynamic(BSPrimLinkable child) { - // What is done for each object in BSPrim is what we want. - return false; + bool ret = false; + DetailLog("{0},BSLinksetConstraints.MakeDynamic,call,IsRoot={1}", child.LocalID, IsRoot(child)); + if (IsRoot(child)) + { + // The root is going dynamic. Rebuild the linkset so parts and mass get computed properly. + ScheduleRebuild(LinksetRoot); + } + return ret; } // The object is going static (non-physical). Do any setup necessary for a static linkset. @@ -78,8 +94,16 @@ public sealed class BSLinksetConstraints : BSLinkset // Called at taint-time! public override bool MakeStatic(BSPrimLinkable child) { - // What is done for each object in BSPrim is what we want. - return false; + bool ret = false; + + DetailLog("{0},BSLinksetConstraint.MakeStatic,call,IsRoot={1}", child.LocalID, IsRoot(child)); + child.ClearDisplacement(); + if (IsRoot(child)) + { + // Schedule a rebuild to verify that the root shape is set to the real shape. + ScheduleRebuild(LinksetRoot); + } + return ret; } // Called at taint-time!! @@ -105,7 +129,7 @@ public sealed class BSLinksetConstraints : BSLinkset // Just undo all the constraints for this linkset. Rebuild at the end of the step. ret = PhysicallyUnlinkAllChildrenFromRoot(LinksetRoot); // Cause the constraints, et al to be rebuilt before the next simulation step. - Refresh(LinksetRoot); + ScheduleRebuild(LinksetRoot); } return ret; } @@ -123,7 +147,7 @@ public sealed class BSLinksetConstraints : BSLinkset DetailLog("{0},BSLinksetConstraints.AddChildToLinkset,call,child={1}", LinksetRoot.LocalID, child.LocalID); // Cause constraints and assorted properties to be recomputed before the next simulation step. - Refresh(LinksetRoot); + ScheduleRebuild(LinksetRoot); } return; } @@ -147,7 +171,7 @@ public sealed class BSLinksetConstraints : BSLinkset PhysicallyUnlinkAChildFromRoot(rootx, childx); }); // See that the linkset parameters are recomputed at the end of the taint time. - Refresh(LinksetRoot); + ScheduleRebuild(LinksetRoot); } else { @@ -165,6 +189,7 @@ public sealed class BSLinksetConstraints : BSLinkset Refresh(rootPrim); } + // Create a static constraint between the two passed objects private BSConstraint BuildConstraint(BSPrimLinkable rootPrim, BSPrimLinkable childPrim) { // Zero motion for children so they don't interpolate @@ -281,24 +306,39 @@ public sealed class BSLinksetConstraints : BSLinkset DetailLog("{0},BSLinksetConstraint.RecomputeLinksetConstraints,set,rBody={1},linksetMass={2}", LinksetRoot.LocalID, LinksetRoot.PhysBody.AddrString, linksetMass); - foreach (BSPrimLinkable child in m_children) + try { - // A child in the linkset physically shows the mass of the whole linkset. - // This allows Bullet to apply enough force on the child to move the whole linkset. - // (Also do the mass stuff before recomputing the constraint so mass is not zero.) - child.UpdatePhysicalMassProperties(linksetMass, true); + Rebuilding = true; - BSConstraint constrain; - if (!m_physicsScene.Constraints.TryGetConstraint(LinksetRoot.PhysBody, child.PhysBody, out constrain)) + // There is no reason to build all this physical stuff for a non-physical linkset. + if (!LinksetRoot.IsPhysicallyActive) { - // If constraint doesn't exist yet, create it. - constrain = BuildConstraint(LinksetRoot, child); + DetailLog("{0},BSLinksetConstraint.RecomputeLinksetCompound,notPhysical", LinksetRoot.LocalID); + return; // Note the 'finally' clause at the botton which will get executed. } - constrain.RecomputeConstraintVariables(linksetMass); - // PhysicsScene.PE.DumpConstraint(PhysicsScene.World, constrain.Constraint); // DEBUG DEBUG - } + foreach (BSPrimLinkable child in m_children) + { + // A child in the linkset physically shows the mass of the whole linkset. + // This allows Bullet to apply enough force on the child to move the whole linkset. + // (Also do the mass stuff before recomputing the constraint so mass is not zero.) + child.UpdatePhysicalMassProperties(linksetMass, true); + + BSConstraint constrain; + if (!m_physicsScene.Constraints.TryGetConstraint(LinksetRoot.PhysBody, child.PhysBody, out constrain)) + { + // If constraint doesn't exist yet, create it. + constrain = BuildConstraint(LinksetRoot, child); + } + constrain.RecomputeConstraintVariables(linksetMass); + // PhysicsScene.PE.DumpConstraint(PhysicsScene.World, constrain.Constraint); // DEBUG DEBUG + } + } + finally + { + Rebuilding = false; + } } } } -- cgit v1.1 From 13a4a80b3893af13ab748c177b731fed813974ca Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Wed, 10 Jul 2013 09:32:26 -0700 Subject: Add experimental stubs for an extension function interface on both PhysicsScene and PhysicsActor. --- OpenSim/Region/Physics/Manager/PhysicsActor.cs | 6 ++++++ OpenSim/Region/Physics/Manager/PhysicsScene.cs | 9 +++++++++ 2 files changed, 15 insertions(+) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/Manager/PhysicsActor.cs b/OpenSim/Region/Physics/Manager/PhysicsActor.cs index bd806eb..2500f27 100644 --- a/OpenSim/Region/Physics/Manager/PhysicsActor.cs +++ b/OpenSim/Region/Physics/Manager/PhysicsActor.cs @@ -313,6 +313,12 @@ namespace OpenSim.Region.Physics.Manager public abstract void SubscribeEvents(int ms); public abstract void UnSubscribeEvents(); public abstract bool SubscribedEvents(); + + // Extendable interface for new, physics engine specific operations + public virtual object Extension(string pFunct, params object[] pParams) + { + throw new NotImplementedException(); + } } public class NullPhysicsActor : PhysicsActor diff --git a/OpenSim/Region/Physics/Manager/PhysicsScene.cs b/OpenSim/Region/Physics/Manager/PhysicsScene.cs index 290b72e..07a1d36 100644 --- a/OpenSim/Region/Physics/Manager/PhysicsScene.cs +++ b/OpenSim/Region/Physics/Manager/PhysicsScene.cs @@ -25,10 +25,13 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +using System; using System.Collections.Generic; using System.Reflection; + using log4net; using Nini.Config; + using OpenSim.Framework; using OpenMetaverse; @@ -331,5 +334,11 @@ namespace OpenSim.Region.Physics.Manager { return false; } + + // Extendable interface for new, physics engine specific operations + public virtual object Extension(string pFunct, params object[] pParams) + { + throw new NotImplementedException(); + } } } -- cgit v1.1 From b4c3a791aa55390bff071b3fe4bbe70c1d252703 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Thu, 11 Jul 2013 14:33:03 -0700 Subject: BulletSim: move collision processing for linksets from BSPrimLinkable into the linkset implementation classes. Add HasSomeCollision attribute that remembers of any component of a linkset has a collision. Update vehicle code (BSDynamic) to use the HasSomeCollision in place of IsColliding to make constraint based linksets properly notice the ground. Add linkset functions to change physical attributes of all the members of a linkset. --- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 16 ++--- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 75 +++++++++++++++++++++- .../Region/Physics/BulletSPlugin/BSPhysObject.cs | 11 ++++ OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 5 +- .../Region/Physics/BulletSPlugin/BSPrimLinkable.cs | 32 +++++++-- 5 files changed, 121 insertions(+), 18 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index 4c2c1c1..1540df1 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -1001,7 +1001,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin else if (newVelocityLengthSq < 0.001f) VehicleVelocity = Vector3.Zero; - VDetailLog("{0}, MoveLinear,done,isColl={1},newVel={2}", ControllingPrim.LocalID, ControllingPrim.IsColliding, VehicleVelocity ); + VDetailLog("{0}, MoveLinear,done,isColl={1},newVel={2}", ControllingPrim.LocalID, ControllingPrim.HasSomeCollision, VehicleVelocity ); } // end MoveLinear() @@ -1062,7 +1062,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin Vector3 linearDeflectionW = linearDeflectionV * VehicleOrientation; // Optionally, if not colliding, don't effect world downward velocity. Let falling things fall. - if (BSParam.VehicleLinearDeflectionNotCollidingNoZ && !m_controllingPrim.IsColliding) + if (BSParam.VehicleLinearDeflectionNotCollidingNoZ && !m_controllingPrim.HasSomeCollision) { linearDeflectionW.Z = 0f; } @@ -1222,7 +1222,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin float targetHeight = Type == Vehicle.TYPE_BOAT ? GetWaterLevel(VehiclePosition) : GetTerrainHeight(VehiclePosition); distanceAboveGround = VehiclePosition.Z - targetHeight; // Not colliding if the vehicle is off the ground - if (!Prim.IsColliding) + if (!Prim.HasSomeCollision) { // downForce = new Vector3(0, 0, -distanceAboveGround / m_bankingTimescale); VehicleVelocity += new Vector3(0, 0, -distanceAboveGround); @@ -1233,12 +1233,12 @@ namespace OpenSim.Region.Physics.BulletSPlugin // be computed with a motor. // TODO: add interaction with banking. VDetailLog("{0}, MoveLinear,limitMotorUp,distAbove={1},colliding={2},ret={3}", - Prim.LocalID, distanceAboveGround, Prim.IsColliding, ret); + Prim.LocalID, distanceAboveGround, Prim.HasSomeCollision, ret); */ // Another approach is to measure if we're going up. If going up and not colliding, // the vehicle is in the air. Fix that by pushing down. - if (!ControllingPrim.IsColliding && VehicleVelocity.Z > 0.1) + if (!ControllingPrim.HasSomeCollision && VehicleVelocity.Z > 0.1) { // Get rid of any of the velocity vector that is pushing us up. float upVelocity = VehicleVelocity.Z; @@ -1260,7 +1260,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin } */ VDetailLog("{0}, MoveLinear,limitMotorUp,collide={1},upVel={2},newVel={3}", - ControllingPrim.LocalID, ControllingPrim.IsColliding, upVelocity, VehicleVelocity); + ControllingPrim.LocalID, ControllingPrim.HasSomeCollision, upVelocity, VehicleVelocity); } } } @@ -1270,14 +1270,14 @@ namespace OpenSim.Region.Physics.BulletSPlugin Vector3 appliedGravity = m_VehicleGravity * m_vehicleMass; // Hack to reduce downward force if the vehicle is probably sitting on the ground - if (ControllingPrim.IsColliding && IsGroundVehicle) + if (ControllingPrim.HasSomeCollision && IsGroundVehicle) appliedGravity *= BSParam.VehicleGroundGravityFudge; VehicleAddForce(appliedGravity); VDetailLog("{0}, MoveLinear,applyGravity,vehGrav={1},collid={2},fudge={3},mass={4},appliedForce={5}", ControllingPrim.LocalID, m_VehicleGravity, - ControllingPrim.IsColliding, BSParam.VehicleGroundGravityFudge, m_vehicleMass, appliedGravity); + ControllingPrim.HasSomeCollision, BSParam.VehicleGroundGravityFudge, m_vehicleMass, appliedGravity); } // ======================================================================= diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index ad8e10f..78c0af7 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -203,6 +203,33 @@ public abstract class BSLinkset return ret; } + // Called after a simulation step to post a collision with this object. + // Return 'true' if linkset processed the collision. 'false' says the linkset didn't have + // anything to add for the collision and it should be passed through normal processing. + // Default processing for a linkset. + public virtual bool HandleCollide(uint collidingWith, BSPhysObject collidee, + OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth) + { + bool ret = false; + + // prims in the same linkset cannot collide with each other + BSPrimLinkable convCollidee = collidee as BSPrimLinkable; + if (convCollidee != null && (LinksetID == convCollidee.Linkset.LinksetID)) + { + // By returning 'true', we tell the caller the collision has been 'handled' so it won't + // do anything about this collision and thus, effectivily, ignoring the collision. + ret = true; + } + else + { + // Not a collision between members of the linkset. Must be a real collision. + // So the linkset root can know if there is a collision anywhere in the linkset. + LinksetRoot.SomeCollisionSimulationStep = m_physicsScene.SimulationStep; + } + + return ret; + } + // I am the root of a linkset and a new child is being added // Called while LinkActivity is locked. protected abstract void AddChildToLinkset(BSPrimLinkable child); @@ -251,6 +278,53 @@ public abstract class BSLinkset public abstract bool RemoveDependencies(BSPrimLinkable child); // ================================================================ + // Some physical setting happen to all members of the linkset + public virtual void SetPhysicalFriction(float friction) + { + ForEachMember((member) => + { + if (member.PhysBody.HasPhysicalBody) + m_physicsScene.PE.SetFriction(member.PhysBody, friction); + return false; // 'false' says to continue looping + } + ); + } + public virtual void SetPhysicalRestitution(float restitution) + { + ForEachMember((member) => + { + if (member.PhysBody.HasPhysicalBody) + m_physicsScene.PE.SetRestitution(member.PhysBody, restitution); + return false; // 'false' says to continue looping + } + ); + } + public virtual void SetPhysicalGravity(OMV.Vector3 gravity) + { + ForEachMember((member) => + { + if (member.PhysBody.HasPhysicalBody) + m_physicsScene.PE.SetGravity(member.PhysBody, gravity); + return false; // 'false' says to continue looping + } + ); + } + public virtual void ComputeLocalInertia() + { + ForEachMember((member) => + { + if (member.PhysBody.HasPhysicalBody) + { + OMV.Vector3 inertia = m_physicsScene.PE.CalculateLocalInertia(member.PhysShape.physShapeInfo, member.Mass); + member.Inertia = inertia * BSParam.VehicleInertiaFactor; + m_physicsScene.PE.SetMassProps(member.PhysBody, member.Mass, member.Inertia); + m_physicsScene.PE.UpdateInertiaTensor(member.PhysBody); + } + return false; // 'false' says to continue looping + } + ); + } + // ================================================================ protected virtual float ComputeLinksetMass() { float mass = LinksetRoot.RawMass; @@ -311,6 +385,5 @@ public abstract class BSLinkset if (m_physicsScene.PhysicsLogging.Enabled) m_physicsScene.DetailLog(msg, args); } - } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index fc4545f..d34b797 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -353,6 +353,16 @@ public abstract class BSPhysObject : PhysicsActor CollidingStep = BSScene.NotASimulationStep; } } + // Complex objects (like linksets) need to know if there is a collision on any part of + // their shape. 'IsColliding' has an existing definition of reporting a collision on + // only this specific prim or component of linksets. + // 'HasSomeCollision' is defined as reporting if there is a collision on any part of + // the complex body that this prim is the root of. + public virtual bool HasSomeCollision + { + get { return IsColliding; } + set { IsColliding = value; } + } public override bool CollidingGround { get { return (CollidingGroundStep == PhysScene.SimulationStep); } set @@ -386,6 +396,7 @@ public abstract class BSPhysObject : PhysicsActor // Return 'true' if a collision was processed and should be sent up. // Return 'false' if this object is not enabled/subscribed/appropriate for or has already seen this collision. // Called at taint time from within the Step() function + public delegate bool CollideCall(uint collidingWith, BSPhysObject collidee, OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth); public virtual bool Collide(uint collidingWith, BSPhysObject collidee, OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth) { diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index d43448e..4771934 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -495,8 +495,8 @@ public class BSPrim : BSPhysObject } } - // Find and return a handle to the current vehicle actor. - // Return 'null' if there is no vehicle actor. + // Find and return a handle to the current vehicle actor. + // Return 'null' if there is no vehicle actor. public BSDynamics GetVehicleActor() { BSDynamics ret = null; @@ -507,6 +507,7 @@ public class BSPrim : BSPhysObject } return ret; } + public override int VehicleType { get { int ret = (int)Vehicle.TYPE_NONE; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs index 1fbcfcc..2f392da 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs @@ -200,20 +200,38 @@ public class BSPrimLinkable : BSPrimDisplaced } // Called after a simulation step to post a collision with this object. + // This returns 'true' if the collision has been queued and the SendCollisions call must + // be made at the end of the simulation step. public override bool Collide(uint collidingWith, BSPhysObject collidee, OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth) { - // prims in the same linkset cannot collide with each other - BSPrimLinkable convCollidee = collidee as BSPrimLinkable; - if (convCollidee != null && (this.Linkset.LinksetID == convCollidee.Linkset.LinksetID)) + bool ret = false; + // Ask the linkset if it wants to handle the collision + if (!Linkset.HandleCollide(collidingWith, collidee, contactPoint, contactNormal, pentrationDepth)) { - return false; + // The linkset didn't handle it so pass the collision through normal processing + ret = base.Collide(collidingWith, collidee, contactPoint, contactNormal, pentrationDepth); } + return ret; + } - // TODO: handle collisions of other objects with with children of linkset. - // This is a problem for LinksetCompound since the children are packed into the root. + // A linkset reports any collision on any part of the linkset. + public long SomeCollisionSimulationStep = 0; + public override bool HasSomeCollision + { + get + { + return (SomeCollisionSimulationStep == PhysScene.SimulationStep) || base.IsColliding; + } + set + { + if (value) + SomeCollisionSimulationStep = PhysScene.SimulationStep; + else + SomeCollisionSimulationStep = 0; - return base.Collide(collidingWith, collidee, contactPoint, contactNormal, pentrationDepth); + base.HasSomeCollision = value; + } } } } -- cgit v1.1 From acb7b4a09ad564d1dfae3ad12adbb593ca3942c9 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 16 Jul 2013 09:59:52 -0700 Subject: BulletSim: only create vehicle prim actor when vehicles are enabled. --- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 43 ++++++++++++++++------ .../Physics/BulletSPlugin/Tests/BasicVehicles.cs | 2 +- 2 files changed, 33 insertions(+), 12 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 4771934..fdb2925 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -96,7 +96,7 @@ public class BSPrim : BSPhysObject _isVolumeDetect = false; // Add a dynamic vehicle to our set of actors that can move this prim. - PhysicalActors.Add(VehicleActorName, new BSDynamics(PhysScene, this, VehicleActorName)); + // PhysicalActors.Add(VehicleActorName, new BSDynamics(PhysScene, this, VehicleActorName)); _mass = CalculateMass(); @@ -497,7 +497,7 @@ public class BSPrim : BSPhysObject // Find and return a handle to the current vehicle actor. // Return 'null' if there is no vehicle actor. - public BSDynamics GetVehicleActor() + public BSDynamics GetVehicleActor(bool createIfNone) { BSDynamics ret = null; BSActor actor; @@ -505,13 +505,21 @@ public class BSPrim : BSPhysObject { ret = actor as BSDynamics; } + else + { + if (createIfNone) + { + ret = new BSDynamics(PhysScene, this, VehicleActorName); + PhysicalActors.Add(ret.ActorName, ret); + } + } return ret; } public override int VehicleType { get { int ret = (int)Vehicle.TYPE_NONE; - BSDynamics vehicleActor = GetVehicleActor(); + BSDynamics vehicleActor = GetVehicleActor(false /* createIfNone */); if (vehicleActor != null) ret = (int)vehicleActor.Type; return ret; @@ -525,11 +533,24 @@ public class BSPrim : BSPhysObject // change all the parameters. Like a plane changing to CAR when on the // ground. In this case, don't want to zero motion. // ZeroMotion(true /* inTaintTime */); - BSDynamics vehicleActor = GetVehicleActor(); - if (vehicleActor != null) + if (type == Vehicle.TYPE_NONE) { - vehicleActor.ProcessTypeChange(type); - ActivateIfPhysical(false); + // Vehicle type is 'none' so get rid of any actor that may have been allocated. + BSDynamics vehicleActor = GetVehicleActor(false /* createIfNone */); + if (vehicleActor != null) + { + PhysicalActors.RemoveAndRelease(vehicleActor.ActorName); + } + } + else + { + // Vehicle type is not 'none' so create an actor and set it running. + BSDynamics vehicleActor = GetVehicleActor(true /* createIfNone */); + if (vehicleActor != null) + { + vehicleActor.ProcessTypeChange(type); + ActivateIfPhysical(false); + } } }); } @@ -538,7 +559,7 @@ public class BSPrim : BSPhysObject { PhysScene.TaintedObject("BSPrim.VehicleFloatParam", delegate() { - BSDynamics vehicleActor = GetVehicleActor(); + BSDynamics vehicleActor = GetVehicleActor(true /* createIfNone */); if (vehicleActor != null) { vehicleActor.ProcessFloatVehicleParam((Vehicle)param, value); @@ -550,7 +571,7 @@ public class BSPrim : BSPhysObject { PhysScene.TaintedObject("BSPrim.VehicleVectorParam", delegate() { - BSDynamics vehicleActor = GetVehicleActor(); + BSDynamics vehicleActor = GetVehicleActor(true /* createIfNone */); if (vehicleActor != null) { vehicleActor.ProcessVectorVehicleParam((Vehicle)param, value); @@ -562,7 +583,7 @@ public class BSPrim : BSPhysObject { PhysScene.TaintedObject("BSPrim.VehicleRotationParam", delegate() { - BSDynamics vehicleActor = GetVehicleActor(); + BSDynamics vehicleActor = GetVehicleActor(true /* createIfNone */); if (vehicleActor != null) { vehicleActor.ProcessRotationVehicleParam((Vehicle)param, rotation); @@ -574,7 +595,7 @@ public class BSPrim : BSPhysObject { PhysScene.TaintedObject("BSPrim.VehicleFlags", delegate() { - BSDynamics vehicleActor = GetVehicleActor(); + BSDynamics vehicleActor = GetVehicleActor(true /* createIfNone */); if (vehicleActor != null) { vehicleActor.ProcessVehicleFlags(param, remove); diff --git a/OpenSim/Region/Physics/BulletSPlugin/Tests/BasicVehicles.cs b/OpenSim/Region/Physics/BulletSPlugin/Tests/BasicVehicles.cs index 48d3742..48e74eb 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/Tests/BasicVehicles.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/Tests/BasicVehicles.cs @@ -116,7 +116,7 @@ public class BasicVehicles : OpenSimTestCase // Instead the appropriate values are set and calls are made just the parts of the // controller we want to exercise. Stepping the physics engine then applies // the actions of that one feature. - BSDynamics vehicleActor = TestVehicle.GetVehicleActor(); + BSDynamics vehicleActor = TestVehicle.GetVehicleActor(true /* createIfNone */); if (vehicleActor != null) { vehicleActor.ProcessFloatVehicleParam(Vehicle.VERTICAL_ATTRACTION_EFFICIENCY, efficiency); -- cgit v1.1 From d0d654e2186c8b81c1150da89a549e4f7162a2b4 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 16 Jul 2013 10:01:03 -0700 Subject: BulletSim: change BSDynamics to expect to be passed a BSPrimLinkable and start changing the logic to handle the base prim as a complex object (ie, a linkset). --- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index 1540df1..82d7c44 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -45,7 +45,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin private static string LogHeader = "[BULLETSIM VEHICLE]"; // the prim this dynamic controller belongs to - private BSPrim ControllingPrim { get; set; } + private BSPrimLinkable ControllingPrim { get; set; } private bool m_haveRegisteredForSceneEvents; @@ -128,9 +128,15 @@ namespace OpenSim.Region.Physics.BulletSPlugin public BSDynamics(BSScene myScene, BSPrim myPrim, string actorName) : base(myScene, myPrim, actorName) { - ControllingPrim = myPrim; Type = Vehicle.TYPE_NONE; m_haveRegisteredForSceneEvents = false; + + ControllingPrim = myPrim as BSPrimLinkable; + if (ControllingPrim == null) + { + // THIS CANNOT HAPPEN!! + } + VDetailLog("{0},Creation", ControllingPrim.LocalID); } // Return 'true' if this vehicle is doing vehicle things @@ -585,6 +591,8 @@ namespace OpenSim.Region.Physics.BulletSPlugin // Friction affects are handled by this vehicle code m_physicsScene.PE.SetFriction(ControllingPrim.PhysBody, BSParam.VehicleFriction); m_physicsScene.PE.SetRestitution(ControllingPrim.PhysBody, BSParam.VehicleRestitution); + // ControllingPrim.Linkset.SetPhysicalFriction(BSParam.VehicleFriction); + // ControllingPrim.Linkset.SetPhysicalRestitution(BSParam.VehicleRestitution); // Moderate angular movement introduced by Bullet. // TODO: possibly set AngularFactor and LinearFactor for the type of vehicle. @@ -595,17 +603,20 @@ namespace OpenSim.Region.Physics.BulletSPlugin // Vehicles report collision events so we know when it's on the ground m_physicsScene.PE.AddToCollisionFlags(ControllingPrim.PhysBody, CollisionFlags.BS_VEHICLE_COLLISIONS); + // ControllingPrim.Linkset.SetPhysicalCollisionFlags(CollisionFlags.BS_VEHICLE_COLLISIONS); Vector3 inertia = m_physicsScene.PE.CalculateLocalInertia(ControllingPrim.PhysShape.physShapeInfo, m_vehicleMass); ControllingPrim.Inertia = inertia * BSParam.VehicleInertiaFactor; m_physicsScene.PE.SetMassProps(ControllingPrim.PhysBody, m_vehicleMass, ControllingPrim.Inertia); m_physicsScene.PE.UpdateInertiaTensor(ControllingPrim.PhysBody); + // ControllingPrim.Linkset.ComputeLocalInertia(BSParam.VehicleInertiaFactor); // Set the gravity for the vehicle depending on the buoyancy // TODO: what should be done if prim and vehicle buoyancy differ? m_VehicleGravity = ControllingPrim.ComputeGravity(m_VehicleBuoyancy); // The actual vehicle gravity is set to zero in Bullet so we can do all the application of same. m_physicsScene.PE.SetGravity(ControllingPrim.PhysBody, Vector3.Zero); + // ControllingPrim.Linkset.SetPhysicalGravity(Vector3.Zero); VDetailLog("{0},BSDynamics.SetPhysicalParameters,mass={1},inert={2},vehGrav={3},aDamp={4},frict={5},rest={6},lFact={7},aFact={8}", ControllingPrim.LocalID, m_vehicleMass, ControllingPrim.Inertia, m_VehicleGravity, @@ -617,6 +628,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin { if (ControllingPrim.PhysBody.HasPhysicalBody) m_physicsScene.PE.RemoveFromCollisionFlags(ControllingPrim.PhysBody, CollisionFlags.BS_VEHICLE_COLLISIONS); + // ControllingPrim.Linkset.RemoveFromPhysicalCollisionFlags(CollisionFlags.BS_VEHICLE_COLLISIONS); } } @@ -629,6 +641,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin // BSActor.Release() public override void Dispose() { + VDetailLog("{0},Dispose", ControllingPrim.LocalID); UnregisterForSceneEvents(); Type = Vehicle.TYPE_NONE; Enabled = false; -- cgit v1.1 From b44f0e1a00eba7f76401692322e48a3b23a81164 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 16 Jul 2013 10:02:14 -0700 Subject: BulletSim: Add logic to linksets to change physical properties for whole linkset. Override physical property setting for BSLinksetCompound as there are not children to the compound spape. --- OpenSim/Region/Physics/BulletSPlugin/BSActors.cs | 6 +--- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 24 +++++++++++++-- .../Physics/BulletSPlugin/BSLinksetCompound.cs | 36 ++++++++++++++++++++++ 3 files changed, 59 insertions(+), 7 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSActors.cs b/OpenSim/Region/Physics/BulletSPlugin/BSActors.cs index fff63e4..e0ccc50 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSActors.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSActors.cs @@ -69,7 +69,7 @@ public class BSActorCollection { lock (m_actors) { - Release(); + ForEachActor(a => a.Dispose()); m_actors.Clear(); } } @@ -98,10 +98,6 @@ public class BSActorCollection { ForEachActor(a => a.SetEnabled(enabl)); } - public void Release() - { - ForEachActor(a => a.Dispose()); - } public void Refresh() { ForEachActor(a => a.Refresh()); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index 78c0af7..960c0b4 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -309,14 +309,14 @@ public abstract class BSLinkset } ); } - public virtual void ComputeLocalInertia() + public virtual void ComputeLocalInertia(OMV.Vector3 inertiaFactor) { ForEachMember((member) => { if (member.PhysBody.HasPhysicalBody) { OMV.Vector3 inertia = m_physicsScene.PE.CalculateLocalInertia(member.PhysShape.physShapeInfo, member.Mass); - member.Inertia = inertia * BSParam.VehicleInertiaFactor; + member.Inertia = inertia * inertiaFactor; m_physicsScene.PE.SetMassProps(member.PhysBody, member.Mass, member.Inertia); m_physicsScene.PE.UpdateInertiaTensor(member.PhysBody); } @@ -324,6 +324,26 @@ public abstract class BSLinkset } ); } + public virtual void SetPhysicalCollisionFlags(CollisionFlags collFlags) + { + ForEachMember((member) => + { + if (member.PhysBody.HasPhysicalBody) + m_physicsScene.PE.SetCollisionFlags(member.PhysBody, collFlags); + return false; // 'false' says to continue looping + } + ); + } + public virtual void RemoveFromPhysicalCollisionFlags(CollisionFlags collFlags) + { + ForEachMember((member) => + { + if (member.PhysBody.HasPhysicalBody) + m_physicsScene.PE.RemoveFromCollisionFlags(member.PhysBody, collFlags); + return false; // 'false' says to continue looping + } + ); + } // ================================================================ protected virtual float ComputeLinksetMass() { diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs index 3668456..33ae5a5 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs @@ -44,6 +44,42 @@ public sealed class BSLinksetCompound : BSLinkset { } + // ================================================================ + // Changing the physical property of the linkset only needs to change the root + public override void SetPhysicalFriction(float friction) + { + if (LinksetRoot.PhysBody.HasPhysicalBody) + m_physicsScene.PE.SetFriction(LinksetRoot.PhysBody, friction); + } + public override void SetPhysicalRestitution(float restitution) + { + if (LinksetRoot.PhysBody.HasPhysicalBody) + m_physicsScene.PE.SetRestitution(LinksetRoot.PhysBody, restitution); + } + public override void SetPhysicalGravity(OMV.Vector3 gravity) + { + if (LinksetRoot.PhysBody.HasPhysicalBody) + m_physicsScene.PE.SetGravity(LinksetRoot.PhysBody, gravity); + } + public override void ComputeLocalInertia(OMV.Vector3 inertiaFactor) + { + OMV.Vector3 inertia = m_physicsScene.PE.CalculateLocalInertia(LinksetRoot.PhysShape.physShapeInfo, LinksetRoot.Mass); + LinksetRoot.Inertia = inertia * inertiaFactor; + m_physicsScene.PE.SetMassProps(LinksetRoot.PhysBody, LinksetRoot.Mass, LinksetRoot.Inertia); + m_physicsScene.PE.UpdateInertiaTensor(LinksetRoot.PhysBody); + } + public override void SetPhysicalCollisionFlags(CollisionFlags collFlags) + { + if (LinksetRoot.PhysBody.HasPhysicalBody) + m_physicsScene.PE.SetCollisionFlags(LinksetRoot.PhysBody, collFlags); + } + public override void RemoveFromPhysicalCollisionFlags(CollisionFlags collFlags) + { + if (LinksetRoot.PhysBody.HasPhysicalBody) + m_physicsScene.PE.RemoveFromCollisionFlags(LinksetRoot.PhysBody, collFlags); + } + // ================================================================ + // When physical properties are changed the linkset needs to recalculate // its internal properties. public override void Refresh(BSPrimLinkable requestor) -- cgit v1.1 From 84d0699761b8da546f9faef084240d7b15f16321 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Mon, 22 Jul 2013 12:07:42 -0700 Subject: Revert "BulletSim: Add logic to linksets to change physical properties for" The changes don't seem to be ready for prime time. This reverts commit b44f0e1a00eba7f76401692322e48a3b23a81164. --- OpenSim/Region/Physics/BulletSPlugin/BSActors.cs | 6 +++- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 24 ++------------- .../Physics/BulletSPlugin/BSLinksetCompound.cs | 36 ---------------------- 3 files changed, 7 insertions(+), 59 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSActors.cs b/OpenSim/Region/Physics/BulletSPlugin/BSActors.cs index e0ccc50..fff63e4 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSActors.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSActors.cs @@ -69,7 +69,7 @@ public class BSActorCollection { lock (m_actors) { - ForEachActor(a => a.Dispose()); + Release(); m_actors.Clear(); } } @@ -98,6 +98,10 @@ public class BSActorCollection { ForEachActor(a => a.SetEnabled(enabl)); } + public void Release() + { + ForEachActor(a => a.Dispose()); + } public void Refresh() { ForEachActor(a => a.Refresh()); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index 960c0b4..78c0af7 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -309,14 +309,14 @@ public abstract class BSLinkset } ); } - public virtual void ComputeLocalInertia(OMV.Vector3 inertiaFactor) + public virtual void ComputeLocalInertia() { ForEachMember((member) => { if (member.PhysBody.HasPhysicalBody) { OMV.Vector3 inertia = m_physicsScene.PE.CalculateLocalInertia(member.PhysShape.physShapeInfo, member.Mass); - member.Inertia = inertia * inertiaFactor; + member.Inertia = inertia * BSParam.VehicleInertiaFactor; m_physicsScene.PE.SetMassProps(member.PhysBody, member.Mass, member.Inertia); m_physicsScene.PE.UpdateInertiaTensor(member.PhysBody); } @@ -324,26 +324,6 @@ public abstract class BSLinkset } ); } - public virtual void SetPhysicalCollisionFlags(CollisionFlags collFlags) - { - ForEachMember((member) => - { - if (member.PhysBody.HasPhysicalBody) - m_physicsScene.PE.SetCollisionFlags(member.PhysBody, collFlags); - return false; // 'false' says to continue looping - } - ); - } - public virtual void RemoveFromPhysicalCollisionFlags(CollisionFlags collFlags) - { - ForEachMember((member) => - { - if (member.PhysBody.HasPhysicalBody) - m_physicsScene.PE.RemoveFromCollisionFlags(member.PhysBody, collFlags); - return false; // 'false' says to continue looping - } - ); - } // ================================================================ protected virtual float ComputeLinksetMass() { diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs index 33ae5a5..3668456 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs @@ -44,42 +44,6 @@ public sealed class BSLinksetCompound : BSLinkset { } - // ================================================================ - // Changing the physical property of the linkset only needs to change the root - public override void SetPhysicalFriction(float friction) - { - if (LinksetRoot.PhysBody.HasPhysicalBody) - m_physicsScene.PE.SetFriction(LinksetRoot.PhysBody, friction); - } - public override void SetPhysicalRestitution(float restitution) - { - if (LinksetRoot.PhysBody.HasPhysicalBody) - m_physicsScene.PE.SetRestitution(LinksetRoot.PhysBody, restitution); - } - public override void SetPhysicalGravity(OMV.Vector3 gravity) - { - if (LinksetRoot.PhysBody.HasPhysicalBody) - m_physicsScene.PE.SetGravity(LinksetRoot.PhysBody, gravity); - } - public override void ComputeLocalInertia(OMV.Vector3 inertiaFactor) - { - OMV.Vector3 inertia = m_physicsScene.PE.CalculateLocalInertia(LinksetRoot.PhysShape.physShapeInfo, LinksetRoot.Mass); - LinksetRoot.Inertia = inertia * inertiaFactor; - m_physicsScene.PE.SetMassProps(LinksetRoot.PhysBody, LinksetRoot.Mass, LinksetRoot.Inertia); - m_physicsScene.PE.UpdateInertiaTensor(LinksetRoot.PhysBody); - } - public override void SetPhysicalCollisionFlags(CollisionFlags collFlags) - { - if (LinksetRoot.PhysBody.HasPhysicalBody) - m_physicsScene.PE.SetCollisionFlags(LinksetRoot.PhysBody, collFlags); - } - public override void RemoveFromPhysicalCollisionFlags(CollisionFlags collFlags) - { - if (LinksetRoot.PhysBody.HasPhysicalBody) - m_physicsScene.PE.RemoveFromCollisionFlags(LinksetRoot.PhysBody, collFlags); - } - // ================================================================ - // When physical properties are changed the linkset needs to recalculate // its internal properties. public override void Refresh(BSPrimLinkable requestor) -- cgit v1.1 From 7b187deb19517aa7c880458894643a5448566a94 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Mon, 22 Jul 2013 12:08:25 -0700 Subject: Revert "BulletSim: change BSDynamics to expect to be passed a BSPrimLinkable" The changes don't seem to be ready for prime time. This reverts commit d0d654e2186c8b81c1150da89a549e4f7162a2b4. --- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 17 ++--------------- 1 file changed, 2 insertions(+), 15 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index 82d7c44..1540df1 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -45,7 +45,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin private static string LogHeader = "[BULLETSIM VEHICLE]"; // the prim this dynamic controller belongs to - private BSPrimLinkable ControllingPrim { get; set; } + private BSPrim ControllingPrim { get; set; } private bool m_haveRegisteredForSceneEvents; @@ -128,15 +128,9 @@ namespace OpenSim.Region.Physics.BulletSPlugin public BSDynamics(BSScene myScene, BSPrim myPrim, string actorName) : base(myScene, myPrim, actorName) { + ControllingPrim = myPrim; Type = Vehicle.TYPE_NONE; m_haveRegisteredForSceneEvents = false; - - ControllingPrim = myPrim as BSPrimLinkable; - if (ControllingPrim == null) - { - // THIS CANNOT HAPPEN!! - } - VDetailLog("{0},Creation", ControllingPrim.LocalID); } // Return 'true' if this vehicle is doing vehicle things @@ -591,8 +585,6 @@ namespace OpenSim.Region.Physics.BulletSPlugin // Friction affects are handled by this vehicle code m_physicsScene.PE.SetFriction(ControllingPrim.PhysBody, BSParam.VehicleFriction); m_physicsScene.PE.SetRestitution(ControllingPrim.PhysBody, BSParam.VehicleRestitution); - // ControllingPrim.Linkset.SetPhysicalFriction(BSParam.VehicleFriction); - // ControllingPrim.Linkset.SetPhysicalRestitution(BSParam.VehicleRestitution); // Moderate angular movement introduced by Bullet. // TODO: possibly set AngularFactor and LinearFactor for the type of vehicle. @@ -603,20 +595,17 @@ namespace OpenSim.Region.Physics.BulletSPlugin // Vehicles report collision events so we know when it's on the ground m_physicsScene.PE.AddToCollisionFlags(ControllingPrim.PhysBody, CollisionFlags.BS_VEHICLE_COLLISIONS); - // ControllingPrim.Linkset.SetPhysicalCollisionFlags(CollisionFlags.BS_VEHICLE_COLLISIONS); Vector3 inertia = m_physicsScene.PE.CalculateLocalInertia(ControllingPrim.PhysShape.physShapeInfo, m_vehicleMass); ControllingPrim.Inertia = inertia * BSParam.VehicleInertiaFactor; m_physicsScene.PE.SetMassProps(ControllingPrim.PhysBody, m_vehicleMass, ControllingPrim.Inertia); m_physicsScene.PE.UpdateInertiaTensor(ControllingPrim.PhysBody); - // ControllingPrim.Linkset.ComputeLocalInertia(BSParam.VehicleInertiaFactor); // Set the gravity for the vehicle depending on the buoyancy // TODO: what should be done if prim and vehicle buoyancy differ? m_VehicleGravity = ControllingPrim.ComputeGravity(m_VehicleBuoyancy); // The actual vehicle gravity is set to zero in Bullet so we can do all the application of same. m_physicsScene.PE.SetGravity(ControllingPrim.PhysBody, Vector3.Zero); - // ControllingPrim.Linkset.SetPhysicalGravity(Vector3.Zero); VDetailLog("{0},BSDynamics.SetPhysicalParameters,mass={1},inert={2},vehGrav={3},aDamp={4},frict={5},rest={6},lFact={7},aFact={8}", ControllingPrim.LocalID, m_vehicleMass, ControllingPrim.Inertia, m_VehicleGravity, @@ -628,7 +617,6 @@ namespace OpenSim.Region.Physics.BulletSPlugin { if (ControllingPrim.PhysBody.HasPhysicalBody) m_physicsScene.PE.RemoveFromCollisionFlags(ControllingPrim.PhysBody, CollisionFlags.BS_VEHICLE_COLLISIONS); - // ControllingPrim.Linkset.RemoveFromPhysicalCollisionFlags(CollisionFlags.BS_VEHICLE_COLLISIONS); } } @@ -641,7 +629,6 @@ namespace OpenSim.Region.Physics.BulletSPlugin // BSActor.Release() public override void Dispose() { - VDetailLog("{0},Dispose", ControllingPrim.LocalID); UnregisterForSceneEvents(); Type = Vehicle.TYPE_NONE; Enabled = false; -- cgit v1.1 From 5f7b2ea81b95a60e882bc65b663a2c9fe134f92a Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Mon, 22 Jul 2013 12:08:49 -0700 Subject: Revert "BulletSim: only create vehicle prim actor when vehicles are enabled." The changes don't seem to be ready for prime time. This reverts commit acb7b4a09ad564d1dfae3ad12adbb593ca3942c9. --- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 43 ++++++---------------- .../Physics/BulletSPlugin/Tests/BasicVehicles.cs | 2 +- 2 files changed, 12 insertions(+), 33 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index fdb2925..4771934 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -96,7 +96,7 @@ public class BSPrim : BSPhysObject _isVolumeDetect = false; // Add a dynamic vehicle to our set of actors that can move this prim. - // PhysicalActors.Add(VehicleActorName, new BSDynamics(PhysScene, this, VehicleActorName)); + PhysicalActors.Add(VehicleActorName, new BSDynamics(PhysScene, this, VehicleActorName)); _mass = CalculateMass(); @@ -497,7 +497,7 @@ public class BSPrim : BSPhysObject // Find and return a handle to the current vehicle actor. // Return 'null' if there is no vehicle actor. - public BSDynamics GetVehicleActor(bool createIfNone) + public BSDynamics GetVehicleActor() { BSDynamics ret = null; BSActor actor; @@ -505,21 +505,13 @@ public class BSPrim : BSPhysObject { ret = actor as BSDynamics; } - else - { - if (createIfNone) - { - ret = new BSDynamics(PhysScene, this, VehicleActorName); - PhysicalActors.Add(ret.ActorName, ret); - } - } return ret; } public override int VehicleType { get { int ret = (int)Vehicle.TYPE_NONE; - BSDynamics vehicleActor = GetVehicleActor(false /* createIfNone */); + BSDynamics vehicleActor = GetVehicleActor(); if (vehicleActor != null) ret = (int)vehicleActor.Type; return ret; @@ -533,24 +525,11 @@ public class BSPrim : BSPhysObject // change all the parameters. Like a plane changing to CAR when on the // ground. In this case, don't want to zero motion. // ZeroMotion(true /* inTaintTime */); - if (type == Vehicle.TYPE_NONE) - { - // Vehicle type is 'none' so get rid of any actor that may have been allocated. - BSDynamics vehicleActor = GetVehicleActor(false /* createIfNone */); - if (vehicleActor != null) - { - PhysicalActors.RemoveAndRelease(vehicleActor.ActorName); - } - } - else + BSDynamics vehicleActor = GetVehicleActor(); + if (vehicleActor != null) { - // Vehicle type is not 'none' so create an actor and set it running. - BSDynamics vehicleActor = GetVehicleActor(true /* createIfNone */); - if (vehicleActor != null) - { - vehicleActor.ProcessTypeChange(type); - ActivateIfPhysical(false); - } + vehicleActor.ProcessTypeChange(type); + ActivateIfPhysical(false); } }); } @@ -559,7 +538,7 @@ public class BSPrim : BSPhysObject { PhysScene.TaintedObject("BSPrim.VehicleFloatParam", delegate() { - BSDynamics vehicleActor = GetVehicleActor(true /* createIfNone */); + BSDynamics vehicleActor = GetVehicleActor(); if (vehicleActor != null) { vehicleActor.ProcessFloatVehicleParam((Vehicle)param, value); @@ -571,7 +550,7 @@ public class BSPrim : BSPhysObject { PhysScene.TaintedObject("BSPrim.VehicleVectorParam", delegate() { - BSDynamics vehicleActor = GetVehicleActor(true /* createIfNone */); + BSDynamics vehicleActor = GetVehicleActor(); if (vehicleActor != null) { vehicleActor.ProcessVectorVehicleParam((Vehicle)param, value); @@ -583,7 +562,7 @@ public class BSPrim : BSPhysObject { PhysScene.TaintedObject("BSPrim.VehicleRotationParam", delegate() { - BSDynamics vehicleActor = GetVehicleActor(true /* createIfNone */); + BSDynamics vehicleActor = GetVehicleActor(); if (vehicleActor != null) { vehicleActor.ProcessRotationVehicleParam((Vehicle)param, rotation); @@ -595,7 +574,7 @@ public class BSPrim : BSPhysObject { PhysScene.TaintedObject("BSPrim.VehicleFlags", delegate() { - BSDynamics vehicleActor = GetVehicleActor(true /* createIfNone */); + BSDynamics vehicleActor = GetVehicleActor(); if (vehicleActor != null) { vehicleActor.ProcessVehicleFlags(param, remove); diff --git a/OpenSim/Region/Physics/BulletSPlugin/Tests/BasicVehicles.cs b/OpenSim/Region/Physics/BulletSPlugin/Tests/BasicVehicles.cs index 48e74eb..48d3742 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/Tests/BasicVehicles.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/Tests/BasicVehicles.cs @@ -116,7 +116,7 @@ public class BasicVehicles : OpenSimTestCase // Instead the appropriate values are set and calls are made just the parts of the // controller we want to exercise. Stepping the physics engine then applies // the actions of that one feature. - BSDynamics vehicleActor = TestVehicle.GetVehicleActor(true /* createIfNone */); + BSDynamics vehicleActor = TestVehicle.GetVehicleActor(); if (vehicleActor != null) { vehicleActor.ProcessFloatVehicleParam(Vehicle.VERTICAL_ATTRACTION_EFFICIENCY, efficiency); -- cgit v1.1 From c45659863d8821a48a32e5b687c7b2a6d90b0300 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Mon, 22 Jul 2013 12:09:17 -0700 Subject: Revert "BulletSim: move collision processing for linksets from BSPrimLinkable" The changes don't seem to be ready for prime time. This reverts commit b4c3a791aa55390bff071b3fe4bbe70c1d252703. --- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 16 ++--- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 75 +--------------------- .../Region/Physics/BulletSPlugin/BSPhysObject.cs | 11 ---- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 5 +- .../Region/Physics/BulletSPlugin/BSPrimLinkable.cs | 32 ++------- 5 files changed, 18 insertions(+), 121 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index 1540df1..4c2c1c1 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -1001,7 +1001,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin else if (newVelocityLengthSq < 0.001f) VehicleVelocity = Vector3.Zero; - VDetailLog("{0}, MoveLinear,done,isColl={1},newVel={2}", ControllingPrim.LocalID, ControllingPrim.HasSomeCollision, VehicleVelocity ); + VDetailLog("{0}, MoveLinear,done,isColl={1},newVel={2}", ControllingPrim.LocalID, ControllingPrim.IsColliding, VehicleVelocity ); } // end MoveLinear() @@ -1062,7 +1062,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin Vector3 linearDeflectionW = linearDeflectionV * VehicleOrientation; // Optionally, if not colliding, don't effect world downward velocity. Let falling things fall. - if (BSParam.VehicleLinearDeflectionNotCollidingNoZ && !m_controllingPrim.HasSomeCollision) + if (BSParam.VehicleLinearDeflectionNotCollidingNoZ && !m_controllingPrim.IsColliding) { linearDeflectionW.Z = 0f; } @@ -1222,7 +1222,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin float targetHeight = Type == Vehicle.TYPE_BOAT ? GetWaterLevel(VehiclePosition) : GetTerrainHeight(VehiclePosition); distanceAboveGround = VehiclePosition.Z - targetHeight; // Not colliding if the vehicle is off the ground - if (!Prim.HasSomeCollision) + if (!Prim.IsColliding) { // downForce = new Vector3(0, 0, -distanceAboveGround / m_bankingTimescale); VehicleVelocity += new Vector3(0, 0, -distanceAboveGround); @@ -1233,12 +1233,12 @@ namespace OpenSim.Region.Physics.BulletSPlugin // be computed with a motor. // TODO: add interaction with banking. VDetailLog("{0}, MoveLinear,limitMotorUp,distAbove={1},colliding={2},ret={3}", - Prim.LocalID, distanceAboveGround, Prim.HasSomeCollision, ret); + Prim.LocalID, distanceAboveGround, Prim.IsColliding, ret); */ // Another approach is to measure if we're going up. If going up and not colliding, // the vehicle is in the air. Fix that by pushing down. - if (!ControllingPrim.HasSomeCollision && VehicleVelocity.Z > 0.1) + if (!ControllingPrim.IsColliding && VehicleVelocity.Z > 0.1) { // Get rid of any of the velocity vector that is pushing us up. float upVelocity = VehicleVelocity.Z; @@ -1260,7 +1260,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin } */ VDetailLog("{0}, MoveLinear,limitMotorUp,collide={1},upVel={2},newVel={3}", - ControllingPrim.LocalID, ControllingPrim.HasSomeCollision, upVelocity, VehicleVelocity); + ControllingPrim.LocalID, ControllingPrim.IsColliding, upVelocity, VehicleVelocity); } } } @@ -1270,14 +1270,14 @@ namespace OpenSim.Region.Physics.BulletSPlugin Vector3 appliedGravity = m_VehicleGravity * m_vehicleMass; // Hack to reduce downward force if the vehicle is probably sitting on the ground - if (ControllingPrim.HasSomeCollision && IsGroundVehicle) + if (ControllingPrim.IsColliding && IsGroundVehicle) appliedGravity *= BSParam.VehicleGroundGravityFudge; VehicleAddForce(appliedGravity); VDetailLog("{0}, MoveLinear,applyGravity,vehGrav={1},collid={2},fudge={3},mass={4},appliedForce={5}", ControllingPrim.LocalID, m_VehicleGravity, - ControllingPrim.HasSomeCollision, BSParam.VehicleGroundGravityFudge, m_vehicleMass, appliedGravity); + ControllingPrim.IsColliding, BSParam.VehicleGroundGravityFudge, m_vehicleMass, appliedGravity); } // ======================================================================= diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index 78c0af7..ad8e10f 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -203,33 +203,6 @@ public abstract class BSLinkset return ret; } - // Called after a simulation step to post a collision with this object. - // Return 'true' if linkset processed the collision. 'false' says the linkset didn't have - // anything to add for the collision and it should be passed through normal processing. - // Default processing for a linkset. - public virtual bool HandleCollide(uint collidingWith, BSPhysObject collidee, - OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth) - { - bool ret = false; - - // prims in the same linkset cannot collide with each other - BSPrimLinkable convCollidee = collidee as BSPrimLinkable; - if (convCollidee != null && (LinksetID == convCollidee.Linkset.LinksetID)) - { - // By returning 'true', we tell the caller the collision has been 'handled' so it won't - // do anything about this collision and thus, effectivily, ignoring the collision. - ret = true; - } - else - { - // Not a collision between members of the linkset. Must be a real collision. - // So the linkset root can know if there is a collision anywhere in the linkset. - LinksetRoot.SomeCollisionSimulationStep = m_physicsScene.SimulationStep; - } - - return ret; - } - // I am the root of a linkset and a new child is being added // Called while LinkActivity is locked. protected abstract void AddChildToLinkset(BSPrimLinkable child); @@ -278,53 +251,6 @@ public abstract class BSLinkset public abstract bool RemoveDependencies(BSPrimLinkable child); // ================================================================ - // Some physical setting happen to all members of the linkset - public virtual void SetPhysicalFriction(float friction) - { - ForEachMember((member) => - { - if (member.PhysBody.HasPhysicalBody) - m_physicsScene.PE.SetFriction(member.PhysBody, friction); - return false; // 'false' says to continue looping - } - ); - } - public virtual void SetPhysicalRestitution(float restitution) - { - ForEachMember((member) => - { - if (member.PhysBody.HasPhysicalBody) - m_physicsScene.PE.SetRestitution(member.PhysBody, restitution); - return false; // 'false' says to continue looping - } - ); - } - public virtual void SetPhysicalGravity(OMV.Vector3 gravity) - { - ForEachMember((member) => - { - if (member.PhysBody.HasPhysicalBody) - m_physicsScene.PE.SetGravity(member.PhysBody, gravity); - return false; // 'false' says to continue looping - } - ); - } - public virtual void ComputeLocalInertia() - { - ForEachMember((member) => - { - if (member.PhysBody.HasPhysicalBody) - { - OMV.Vector3 inertia = m_physicsScene.PE.CalculateLocalInertia(member.PhysShape.physShapeInfo, member.Mass); - member.Inertia = inertia * BSParam.VehicleInertiaFactor; - m_physicsScene.PE.SetMassProps(member.PhysBody, member.Mass, member.Inertia); - m_physicsScene.PE.UpdateInertiaTensor(member.PhysBody); - } - return false; // 'false' says to continue looping - } - ); - } - // ================================================================ protected virtual float ComputeLinksetMass() { float mass = LinksetRoot.RawMass; @@ -385,5 +311,6 @@ public abstract class BSLinkset if (m_physicsScene.PhysicsLogging.Enabled) m_physicsScene.DetailLog(msg, args); } + } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index d34b797..fc4545f 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -353,16 +353,6 @@ public abstract class BSPhysObject : PhysicsActor CollidingStep = BSScene.NotASimulationStep; } } - // Complex objects (like linksets) need to know if there is a collision on any part of - // their shape. 'IsColliding' has an existing definition of reporting a collision on - // only this specific prim or component of linksets. - // 'HasSomeCollision' is defined as reporting if there is a collision on any part of - // the complex body that this prim is the root of. - public virtual bool HasSomeCollision - { - get { return IsColliding; } - set { IsColliding = value; } - } public override bool CollidingGround { get { return (CollidingGroundStep == PhysScene.SimulationStep); } set @@ -396,7 +386,6 @@ public abstract class BSPhysObject : PhysicsActor // Return 'true' if a collision was processed and should be sent up. // Return 'false' if this object is not enabled/subscribed/appropriate for or has already seen this collision. // Called at taint time from within the Step() function - public delegate bool CollideCall(uint collidingWith, BSPhysObject collidee, OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth); public virtual bool Collide(uint collidingWith, BSPhysObject collidee, OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth) { diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 4771934..d43448e 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -495,8 +495,8 @@ public class BSPrim : BSPhysObject } } - // Find and return a handle to the current vehicle actor. - // Return 'null' if there is no vehicle actor. + // Find and return a handle to the current vehicle actor. + // Return 'null' if there is no vehicle actor. public BSDynamics GetVehicleActor() { BSDynamics ret = null; @@ -507,7 +507,6 @@ public class BSPrim : BSPhysObject } return ret; } - public override int VehicleType { get { int ret = (int)Vehicle.TYPE_NONE; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs index 2f392da..1fbcfcc 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs @@ -200,38 +200,20 @@ public class BSPrimLinkable : BSPrimDisplaced } // Called after a simulation step to post a collision with this object. - // This returns 'true' if the collision has been queued and the SendCollisions call must - // be made at the end of the simulation step. public override bool Collide(uint collidingWith, BSPhysObject collidee, OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth) { - bool ret = false; - // Ask the linkset if it wants to handle the collision - if (!Linkset.HandleCollide(collidingWith, collidee, contactPoint, contactNormal, pentrationDepth)) + // prims in the same linkset cannot collide with each other + BSPrimLinkable convCollidee = collidee as BSPrimLinkable; + if (convCollidee != null && (this.Linkset.LinksetID == convCollidee.Linkset.LinksetID)) { - // The linkset didn't handle it so pass the collision through normal processing - ret = base.Collide(collidingWith, collidee, contactPoint, contactNormal, pentrationDepth); + return false; } - return ret; - } - // A linkset reports any collision on any part of the linkset. - public long SomeCollisionSimulationStep = 0; - public override bool HasSomeCollision - { - get - { - return (SomeCollisionSimulationStep == PhysScene.SimulationStep) || base.IsColliding; - } - set - { - if (value) - SomeCollisionSimulationStep = PhysScene.SimulationStep; - else - SomeCollisionSimulationStep = 0; + // TODO: handle collisions of other objects with with children of linkset. + // This is a problem for LinksetCompound since the children are packed into the root. - base.HasSomeCollision = value; - } + return base.Collide(collidingWith, collidee, contactPoint, contactNormal, pentrationDepth); } } } -- cgit v1.1 From 89857378ce79f93a265bc1eb151e17742032abfa Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Mon, 22 Jul 2013 12:09:55 -0700 Subject: Revert "Add experimental stubs for an extension function interface on both" The changes don't seem to be ready for prime time. This reverts commit 13a4a80b3893af13ab748c177b731fed813974ca. --- OpenSim/Region/Physics/Manager/PhysicsActor.cs | 6 ------ OpenSim/Region/Physics/Manager/PhysicsScene.cs | 9 --------- 2 files changed, 15 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/Manager/PhysicsActor.cs b/OpenSim/Region/Physics/Manager/PhysicsActor.cs index 2500f27..bd806eb 100644 --- a/OpenSim/Region/Physics/Manager/PhysicsActor.cs +++ b/OpenSim/Region/Physics/Manager/PhysicsActor.cs @@ -313,12 +313,6 @@ namespace OpenSim.Region.Physics.Manager public abstract void SubscribeEvents(int ms); public abstract void UnSubscribeEvents(); public abstract bool SubscribedEvents(); - - // Extendable interface for new, physics engine specific operations - public virtual object Extension(string pFunct, params object[] pParams) - { - throw new NotImplementedException(); - } } public class NullPhysicsActor : PhysicsActor diff --git a/OpenSim/Region/Physics/Manager/PhysicsScene.cs b/OpenSim/Region/Physics/Manager/PhysicsScene.cs index 07a1d36..290b72e 100644 --- a/OpenSim/Region/Physics/Manager/PhysicsScene.cs +++ b/OpenSim/Region/Physics/Manager/PhysicsScene.cs @@ -25,13 +25,10 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -using System; using System.Collections.Generic; using System.Reflection; - using log4net; using Nini.Config; - using OpenSim.Framework; using OpenMetaverse; @@ -334,11 +331,5 @@ namespace OpenSim.Region.Physics.Manager { return false; } - - // Extendable interface for new, physics engine specific operations - public virtual object Extension(string pFunct, params object[] pParams) - { - throw new NotImplementedException(); - } } } -- cgit v1.1 From 44543ebe638f391fc1c7ff532fe4470006dec55a Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Mon, 22 Jul 2013 12:10:23 -0700 Subject: Revert "BulletSim: freshen up the code for constraint based linksets." The changes don't seem to be ready for prime time. This reverts commit 803632f8f32d91bb4aec678d8b45a8430c2703e1. --- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 4 +- .../Physics/BulletSPlugin/BSLinksetCompound.cs | 1 - .../Physics/BulletSPlugin/BSLinksetConstraints.cs | 82 ++++++---------------- 3 files changed, 23 insertions(+), 64 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index 4c2c1c1..0204967 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -1029,8 +1029,8 @@ namespace OpenSim.Region.Physics.BulletSPlugin // Add this correction to the velocity to make it faster/slower. VehicleVelocity += linearMotorVelocityW; - VDetailLog("{0}, MoveLinear,velocity,origVelW={1},velV={2},tgt={3},correctV={4},correctW={5},newVelW={6},fricFact={7}", - ControllingPrim.LocalID, origVelW, currentVelV, m_linearMotor.TargetValue, linearMotorCorrectionV, + VDetailLog("{0}, MoveLinear,velocity,origVelW={1},velV={2},correctV={3},correctW={4},newVelW={5},fricFact={6}", + ControllingPrim.LocalID, origVelW, currentVelV, linearMotorCorrectionV, linearMotorVelocityW, VehicleVelocity, frictionFactorV); } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs index 3668456..1d94142 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs @@ -59,7 +59,6 @@ public sealed class BSLinksetCompound : BSLinkset { DetailLog("{0},BSLinksetCompound.ScheduleRebuild,,rebuilding={1},hasChildren={2},actuallyScheduling={3}", requestor.LocalID, Rebuilding, HasAnyChildren, (!Rebuilding && HasAnyChildren)); - // When rebuilding, it is possible to set properties that would normally require a rebuild. // If already rebuilding, don't request another rebuild. // If a linkset with just a root prim (simple non-linked prim) don't bother rebuilding. diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs index f17d698..a06a44d 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs @@ -48,22 +48,12 @@ public sealed class BSLinksetConstraints : BSLinkset { base.Refresh(requestor); - } - - private void ScheduleRebuild(BSPrimLinkable requestor) - { - DetailLog("{0},BSLinksetConstraint.ScheduleRebuild,,rebuilding={1},hasChildren={2},actuallyScheduling={3}", - requestor.LocalID, Rebuilding, HasAnyChildren, (!Rebuilding && HasAnyChildren)); - - // When rebuilding, it is possible to set properties that would normally require a rebuild. - // If already rebuilding, don't request another rebuild. - // If a linkset with just a root prim (simple non-linked prim) don't bother rebuilding. - if (!Rebuilding && HasAnyChildren) + if (HasAnyChildren && IsRoot(requestor)) { // Queue to happen after all the other taint processing m_physicsScene.PostTaintObject("BSLinksetContraints.Refresh", requestor.LocalID, delegate() { - if (HasAnyChildren) + if (HasAnyChildren && IsRoot(requestor)) RecomputeLinksetConstraints(); }); } @@ -77,14 +67,8 @@ public sealed class BSLinksetConstraints : BSLinkset // Called at taint-time! public override bool MakeDynamic(BSPrimLinkable child) { - bool ret = false; - DetailLog("{0},BSLinksetConstraints.MakeDynamic,call,IsRoot={1}", child.LocalID, IsRoot(child)); - if (IsRoot(child)) - { - // The root is going dynamic. Rebuild the linkset so parts and mass get computed properly. - ScheduleRebuild(LinksetRoot); - } - return ret; + // What is done for each object in BSPrim is what we want. + return false; } // The object is going static (non-physical). Do any setup necessary for a static linkset. @@ -94,16 +78,8 @@ public sealed class BSLinksetConstraints : BSLinkset // Called at taint-time! public override bool MakeStatic(BSPrimLinkable child) { - bool ret = false; - - DetailLog("{0},BSLinksetConstraint.MakeStatic,call,IsRoot={1}", child.LocalID, IsRoot(child)); - child.ClearDisplacement(); - if (IsRoot(child)) - { - // Schedule a rebuild to verify that the root shape is set to the real shape. - ScheduleRebuild(LinksetRoot); - } - return ret; + // What is done for each object in BSPrim is what we want. + return false; } // Called at taint-time!! @@ -129,7 +105,7 @@ public sealed class BSLinksetConstraints : BSLinkset // Just undo all the constraints for this linkset. Rebuild at the end of the step. ret = PhysicallyUnlinkAllChildrenFromRoot(LinksetRoot); // Cause the constraints, et al to be rebuilt before the next simulation step. - ScheduleRebuild(LinksetRoot); + Refresh(LinksetRoot); } return ret; } @@ -147,7 +123,7 @@ public sealed class BSLinksetConstraints : BSLinkset DetailLog("{0},BSLinksetConstraints.AddChildToLinkset,call,child={1}", LinksetRoot.LocalID, child.LocalID); // Cause constraints and assorted properties to be recomputed before the next simulation step. - ScheduleRebuild(LinksetRoot); + Refresh(LinksetRoot); } return; } @@ -171,7 +147,7 @@ public sealed class BSLinksetConstraints : BSLinkset PhysicallyUnlinkAChildFromRoot(rootx, childx); }); // See that the linkset parameters are recomputed at the end of the taint time. - ScheduleRebuild(LinksetRoot); + Refresh(LinksetRoot); } else { @@ -189,7 +165,6 @@ public sealed class BSLinksetConstraints : BSLinkset Refresh(rootPrim); } - // Create a static constraint between the two passed objects private BSConstraint BuildConstraint(BSPrimLinkable rootPrim, BSPrimLinkable childPrim) { // Zero motion for children so they don't interpolate @@ -306,39 +281,24 @@ public sealed class BSLinksetConstraints : BSLinkset DetailLog("{0},BSLinksetConstraint.RecomputeLinksetConstraints,set,rBody={1},linksetMass={2}", LinksetRoot.LocalID, LinksetRoot.PhysBody.AddrString, linksetMass); - try + foreach (BSPrimLinkable child in m_children) { - Rebuilding = true; + // A child in the linkset physically shows the mass of the whole linkset. + // This allows Bullet to apply enough force on the child to move the whole linkset. + // (Also do the mass stuff before recomputing the constraint so mass is not zero.) + child.UpdatePhysicalMassProperties(linksetMass, true); - // There is no reason to build all this physical stuff for a non-physical linkset. - if (!LinksetRoot.IsPhysicallyActive) + BSConstraint constrain; + if (!m_physicsScene.Constraints.TryGetConstraint(LinksetRoot.PhysBody, child.PhysBody, out constrain)) { - DetailLog("{0},BSLinksetConstraint.RecomputeLinksetCompound,notPhysical", LinksetRoot.LocalID); - return; // Note the 'finally' clause at the botton which will get executed. + // If constraint doesn't exist yet, create it. + constrain = BuildConstraint(LinksetRoot, child); } + constrain.RecomputeConstraintVariables(linksetMass); - foreach (BSPrimLinkable child in m_children) - { - // A child in the linkset physically shows the mass of the whole linkset. - // This allows Bullet to apply enough force on the child to move the whole linkset. - // (Also do the mass stuff before recomputing the constraint so mass is not zero.) - child.UpdatePhysicalMassProperties(linksetMass, true); - - BSConstraint constrain; - if (!m_physicsScene.Constraints.TryGetConstraint(LinksetRoot.PhysBody, child.PhysBody, out constrain)) - { - // If constraint doesn't exist yet, create it. - constrain = BuildConstraint(LinksetRoot, child); - } - constrain.RecomputeConstraintVariables(linksetMass); - - // PhysicsScene.PE.DumpConstraint(PhysicsScene.World, constrain.Constraint); // DEBUG DEBUG - } - } - finally - { - Rebuilding = false; + // PhysicsScene.PE.DumpConstraint(PhysicsScene.World, constrain.Constraint); // DEBUG DEBUG } + } } } -- cgit v1.1 From af9deed13593a85aef64205f9ca616a06711963c Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 23 Jul 2013 08:11:21 -0700 Subject: Revert "Revert "BulletSim: freshen up the code for constraint based linksets."" Found that the vehicle movement problem was not caused by these physics changes. This reverts commit 44543ebe638f391fc1c7ff532fe4470006dec55a. --- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 4 +- .../Physics/BulletSPlugin/BSLinksetCompound.cs | 1 + .../Physics/BulletSPlugin/BSLinksetConstraints.cs | 82 ++++++++++++++++------ 3 files changed, 64 insertions(+), 23 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index 0204967..4c2c1c1 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -1029,8 +1029,8 @@ namespace OpenSim.Region.Physics.BulletSPlugin // Add this correction to the velocity to make it faster/slower. VehicleVelocity += linearMotorVelocityW; - VDetailLog("{0}, MoveLinear,velocity,origVelW={1},velV={2},correctV={3},correctW={4},newVelW={5},fricFact={6}", - ControllingPrim.LocalID, origVelW, currentVelV, linearMotorCorrectionV, + VDetailLog("{0}, MoveLinear,velocity,origVelW={1},velV={2},tgt={3},correctV={4},correctW={5},newVelW={6},fricFact={7}", + ControllingPrim.LocalID, origVelW, currentVelV, m_linearMotor.TargetValue, linearMotorCorrectionV, linearMotorVelocityW, VehicleVelocity, frictionFactorV); } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs index 1d94142..3668456 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs @@ -59,6 +59,7 @@ public sealed class BSLinksetCompound : BSLinkset { DetailLog("{0},BSLinksetCompound.ScheduleRebuild,,rebuilding={1},hasChildren={2},actuallyScheduling={3}", requestor.LocalID, Rebuilding, HasAnyChildren, (!Rebuilding && HasAnyChildren)); + // When rebuilding, it is possible to set properties that would normally require a rebuild. // If already rebuilding, don't request another rebuild. // If a linkset with just a root prim (simple non-linked prim) don't bother rebuilding. diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs index a06a44d..f17d698 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs @@ -48,12 +48,22 @@ public sealed class BSLinksetConstraints : BSLinkset { base.Refresh(requestor); - if (HasAnyChildren && IsRoot(requestor)) + } + + private void ScheduleRebuild(BSPrimLinkable requestor) + { + DetailLog("{0},BSLinksetConstraint.ScheduleRebuild,,rebuilding={1},hasChildren={2},actuallyScheduling={3}", + requestor.LocalID, Rebuilding, HasAnyChildren, (!Rebuilding && HasAnyChildren)); + + // When rebuilding, it is possible to set properties that would normally require a rebuild. + // If already rebuilding, don't request another rebuild. + // If a linkset with just a root prim (simple non-linked prim) don't bother rebuilding. + if (!Rebuilding && HasAnyChildren) { // Queue to happen after all the other taint processing m_physicsScene.PostTaintObject("BSLinksetContraints.Refresh", requestor.LocalID, delegate() { - if (HasAnyChildren && IsRoot(requestor)) + if (HasAnyChildren) RecomputeLinksetConstraints(); }); } @@ -67,8 +77,14 @@ public sealed class BSLinksetConstraints : BSLinkset // Called at taint-time! public override bool MakeDynamic(BSPrimLinkable child) { - // What is done for each object in BSPrim is what we want. - return false; + bool ret = false; + DetailLog("{0},BSLinksetConstraints.MakeDynamic,call,IsRoot={1}", child.LocalID, IsRoot(child)); + if (IsRoot(child)) + { + // The root is going dynamic. Rebuild the linkset so parts and mass get computed properly. + ScheduleRebuild(LinksetRoot); + } + return ret; } // The object is going static (non-physical). Do any setup necessary for a static linkset. @@ -78,8 +94,16 @@ public sealed class BSLinksetConstraints : BSLinkset // Called at taint-time! public override bool MakeStatic(BSPrimLinkable child) { - // What is done for each object in BSPrim is what we want. - return false; + bool ret = false; + + DetailLog("{0},BSLinksetConstraint.MakeStatic,call,IsRoot={1}", child.LocalID, IsRoot(child)); + child.ClearDisplacement(); + if (IsRoot(child)) + { + // Schedule a rebuild to verify that the root shape is set to the real shape. + ScheduleRebuild(LinksetRoot); + } + return ret; } // Called at taint-time!! @@ -105,7 +129,7 @@ public sealed class BSLinksetConstraints : BSLinkset // Just undo all the constraints for this linkset. Rebuild at the end of the step. ret = PhysicallyUnlinkAllChildrenFromRoot(LinksetRoot); // Cause the constraints, et al to be rebuilt before the next simulation step. - Refresh(LinksetRoot); + ScheduleRebuild(LinksetRoot); } return ret; } @@ -123,7 +147,7 @@ public sealed class BSLinksetConstraints : BSLinkset DetailLog("{0},BSLinksetConstraints.AddChildToLinkset,call,child={1}", LinksetRoot.LocalID, child.LocalID); // Cause constraints and assorted properties to be recomputed before the next simulation step. - Refresh(LinksetRoot); + ScheduleRebuild(LinksetRoot); } return; } @@ -147,7 +171,7 @@ public sealed class BSLinksetConstraints : BSLinkset PhysicallyUnlinkAChildFromRoot(rootx, childx); }); // See that the linkset parameters are recomputed at the end of the taint time. - Refresh(LinksetRoot); + ScheduleRebuild(LinksetRoot); } else { @@ -165,6 +189,7 @@ public sealed class BSLinksetConstraints : BSLinkset Refresh(rootPrim); } + // Create a static constraint between the two passed objects private BSConstraint BuildConstraint(BSPrimLinkable rootPrim, BSPrimLinkable childPrim) { // Zero motion for children so they don't interpolate @@ -281,24 +306,39 @@ public sealed class BSLinksetConstraints : BSLinkset DetailLog("{0},BSLinksetConstraint.RecomputeLinksetConstraints,set,rBody={1},linksetMass={2}", LinksetRoot.LocalID, LinksetRoot.PhysBody.AddrString, linksetMass); - foreach (BSPrimLinkable child in m_children) + try { - // A child in the linkset physically shows the mass of the whole linkset. - // This allows Bullet to apply enough force on the child to move the whole linkset. - // (Also do the mass stuff before recomputing the constraint so mass is not zero.) - child.UpdatePhysicalMassProperties(linksetMass, true); + Rebuilding = true; - BSConstraint constrain; - if (!m_physicsScene.Constraints.TryGetConstraint(LinksetRoot.PhysBody, child.PhysBody, out constrain)) + // There is no reason to build all this physical stuff for a non-physical linkset. + if (!LinksetRoot.IsPhysicallyActive) { - // If constraint doesn't exist yet, create it. - constrain = BuildConstraint(LinksetRoot, child); + DetailLog("{0},BSLinksetConstraint.RecomputeLinksetCompound,notPhysical", LinksetRoot.LocalID); + return; // Note the 'finally' clause at the botton which will get executed. } - constrain.RecomputeConstraintVariables(linksetMass); - // PhysicsScene.PE.DumpConstraint(PhysicsScene.World, constrain.Constraint); // DEBUG DEBUG - } + foreach (BSPrimLinkable child in m_children) + { + // A child in the linkset physically shows the mass of the whole linkset. + // This allows Bullet to apply enough force on the child to move the whole linkset. + // (Also do the mass stuff before recomputing the constraint so mass is not zero.) + child.UpdatePhysicalMassProperties(linksetMass, true); + + BSConstraint constrain; + if (!m_physicsScene.Constraints.TryGetConstraint(LinksetRoot.PhysBody, child.PhysBody, out constrain)) + { + // If constraint doesn't exist yet, create it. + constrain = BuildConstraint(LinksetRoot, child); + } + constrain.RecomputeConstraintVariables(linksetMass); + // PhysicsScene.PE.DumpConstraint(PhysicsScene.World, constrain.Constraint); // DEBUG DEBUG + } + } + finally + { + Rebuilding = false; + } } } } -- cgit v1.1 From 401c2e2f2ec7c6001387df505665b19477afd4cf Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 23 Jul 2013 08:12:34 -0700 Subject: Revert "Revert "Add experimental stubs for an extension function interface on both"" Found that the vehicle movement problem was not caused by these physics changes. This reverts commit 89857378ce79f93a265bc1eb151e17742032abfa. --- OpenSim/Region/Physics/Manager/PhysicsActor.cs | 6 ++++++ OpenSim/Region/Physics/Manager/PhysicsScene.cs | 9 +++++++++ 2 files changed, 15 insertions(+) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/Manager/PhysicsActor.cs b/OpenSim/Region/Physics/Manager/PhysicsActor.cs index bd806eb..2500f27 100644 --- a/OpenSim/Region/Physics/Manager/PhysicsActor.cs +++ b/OpenSim/Region/Physics/Manager/PhysicsActor.cs @@ -313,6 +313,12 @@ namespace OpenSim.Region.Physics.Manager public abstract void SubscribeEvents(int ms); public abstract void UnSubscribeEvents(); public abstract bool SubscribedEvents(); + + // Extendable interface for new, physics engine specific operations + public virtual object Extension(string pFunct, params object[] pParams) + { + throw new NotImplementedException(); + } } public class NullPhysicsActor : PhysicsActor diff --git a/OpenSim/Region/Physics/Manager/PhysicsScene.cs b/OpenSim/Region/Physics/Manager/PhysicsScene.cs index 290b72e..07a1d36 100644 --- a/OpenSim/Region/Physics/Manager/PhysicsScene.cs +++ b/OpenSim/Region/Physics/Manager/PhysicsScene.cs @@ -25,10 +25,13 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +using System; using System.Collections.Generic; using System.Reflection; + using log4net; using Nini.Config; + using OpenSim.Framework; using OpenMetaverse; @@ -331,5 +334,11 @@ namespace OpenSim.Region.Physics.Manager { return false; } + + // Extendable interface for new, physics engine specific operations + public virtual object Extension(string pFunct, params object[] pParams) + { + throw new NotImplementedException(); + } } } -- cgit v1.1 From aec8852af793699a4c1093a38b992daf2dbd97f3 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 23 Jul 2013 08:13:01 -0700 Subject: Revert "Revert "BulletSim: move collision processing for linksets from BSPrimLinkable"" Found that the vehicle movement problem was not caused by these physics changes. This reverts commit c45659863d8821a48a32e5b687c7b2a6d90b0300. --- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 16 ++--- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 75 +++++++++++++++++++++- .../Region/Physics/BulletSPlugin/BSPhysObject.cs | 11 ++++ OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 5 +- .../Region/Physics/BulletSPlugin/BSPrimLinkable.cs | 32 +++++++-- 5 files changed, 121 insertions(+), 18 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index 4c2c1c1..1540df1 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -1001,7 +1001,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin else if (newVelocityLengthSq < 0.001f) VehicleVelocity = Vector3.Zero; - VDetailLog("{0}, MoveLinear,done,isColl={1},newVel={2}", ControllingPrim.LocalID, ControllingPrim.IsColliding, VehicleVelocity ); + VDetailLog("{0}, MoveLinear,done,isColl={1},newVel={2}", ControllingPrim.LocalID, ControllingPrim.HasSomeCollision, VehicleVelocity ); } // end MoveLinear() @@ -1062,7 +1062,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin Vector3 linearDeflectionW = linearDeflectionV * VehicleOrientation; // Optionally, if not colliding, don't effect world downward velocity. Let falling things fall. - if (BSParam.VehicleLinearDeflectionNotCollidingNoZ && !m_controllingPrim.IsColliding) + if (BSParam.VehicleLinearDeflectionNotCollidingNoZ && !m_controllingPrim.HasSomeCollision) { linearDeflectionW.Z = 0f; } @@ -1222,7 +1222,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin float targetHeight = Type == Vehicle.TYPE_BOAT ? GetWaterLevel(VehiclePosition) : GetTerrainHeight(VehiclePosition); distanceAboveGround = VehiclePosition.Z - targetHeight; // Not colliding if the vehicle is off the ground - if (!Prim.IsColliding) + if (!Prim.HasSomeCollision) { // downForce = new Vector3(0, 0, -distanceAboveGround / m_bankingTimescale); VehicleVelocity += new Vector3(0, 0, -distanceAboveGround); @@ -1233,12 +1233,12 @@ namespace OpenSim.Region.Physics.BulletSPlugin // be computed with a motor. // TODO: add interaction with banking. VDetailLog("{0}, MoveLinear,limitMotorUp,distAbove={1},colliding={2},ret={3}", - Prim.LocalID, distanceAboveGround, Prim.IsColliding, ret); + Prim.LocalID, distanceAboveGround, Prim.HasSomeCollision, ret); */ // Another approach is to measure if we're going up. If going up and not colliding, // the vehicle is in the air. Fix that by pushing down. - if (!ControllingPrim.IsColliding && VehicleVelocity.Z > 0.1) + if (!ControllingPrim.HasSomeCollision && VehicleVelocity.Z > 0.1) { // Get rid of any of the velocity vector that is pushing us up. float upVelocity = VehicleVelocity.Z; @@ -1260,7 +1260,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin } */ VDetailLog("{0}, MoveLinear,limitMotorUp,collide={1},upVel={2},newVel={3}", - ControllingPrim.LocalID, ControllingPrim.IsColliding, upVelocity, VehicleVelocity); + ControllingPrim.LocalID, ControllingPrim.HasSomeCollision, upVelocity, VehicleVelocity); } } } @@ -1270,14 +1270,14 @@ namespace OpenSim.Region.Physics.BulletSPlugin Vector3 appliedGravity = m_VehicleGravity * m_vehicleMass; // Hack to reduce downward force if the vehicle is probably sitting on the ground - if (ControllingPrim.IsColliding && IsGroundVehicle) + if (ControllingPrim.HasSomeCollision && IsGroundVehicle) appliedGravity *= BSParam.VehicleGroundGravityFudge; VehicleAddForce(appliedGravity); VDetailLog("{0}, MoveLinear,applyGravity,vehGrav={1},collid={2},fudge={3},mass={4},appliedForce={5}", ControllingPrim.LocalID, m_VehicleGravity, - ControllingPrim.IsColliding, BSParam.VehicleGroundGravityFudge, m_vehicleMass, appliedGravity); + ControllingPrim.HasSomeCollision, BSParam.VehicleGroundGravityFudge, m_vehicleMass, appliedGravity); } // ======================================================================= diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index ad8e10f..78c0af7 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -203,6 +203,33 @@ public abstract class BSLinkset return ret; } + // Called after a simulation step to post a collision with this object. + // Return 'true' if linkset processed the collision. 'false' says the linkset didn't have + // anything to add for the collision and it should be passed through normal processing. + // Default processing for a linkset. + public virtual bool HandleCollide(uint collidingWith, BSPhysObject collidee, + OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth) + { + bool ret = false; + + // prims in the same linkset cannot collide with each other + BSPrimLinkable convCollidee = collidee as BSPrimLinkable; + if (convCollidee != null && (LinksetID == convCollidee.Linkset.LinksetID)) + { + // By returning 'true', we tell the caller the collision has been 'handled' so it won't + // do anything about this collision and thus, effectivily, ignoring the collision. + ret = true; + } + else + { + // Not a collision between members of the linkset. Must be a real collision. + // So the linkset root can know if there is a collision anywhere in the linkset. + LinksetRoot.SomeCollisionSimulationStep = m_physicsScene.SimulationStep; + } + + return ret; + } + // I am the root of a linkset and a new child is being added // Called while LinkActivity is locked. protected abstract void AddChildToLinkset(BSPrimLinkable child); @@ -251,6 +278,53 @@ public abstract class BSLinkset public abstract bool RemoveDependencies(BSPrimLinkable child); // ================================================================ + // Some physical setting happen to all members of the linkset + public virtual void SetPhysicalFriction(float friction) + { + ForEachMember((member) => + { + if (member.PhysBody.HasPhysicalBody) + m_physicsScene.PE.SetFriction(member.PhysBody, friction); + return false; // 'false' says to continue looping + } + ); + } + public virtual void SetPhysicalRestitution(float restitution) + { + ForEachMember((member) => + { + if (member.PhysBody.HasPhysicalBody) + m_physicsScene.PE.SetRestitution(member.PhysBody, restitution); + return false; // 'false' says to continue looping + } + ); + } + public virtual void SetPhysicalGravity(OMV.Vector3 gravity) + { + ForEachMember((member) => + { + if (member.PhysBody.HasPhysicalBody) + m_physicsScene.PE.SetGravity(member.PhysBody, gravity); + return false; // 'false' says to continue looping + } + ); + } + public virtual void ComputeLocalInertia() + { + ForEachMember((member) => + { + if (member.PhysBody.HasPhysicalBody) + { + OMV.Vector3 inertia = m_physicsScene.PE.CalculateLocalInertia(member.PhysShape.physShapeInfo, member.Mass); + member.Inertia = inertia * BSParam.VehicleInertiaFactor; + m_physicsScene.PE.SetMassProps(member.PhysBody, member.Mass, member.Inertia); + m_physicsScene.PE.UpdateInertiaTensor(member.PhysBody); + } + return false; // 'false' says to continue looping + } + ); + } + // ================================================================ protected virtual float ComputeLinksetMass() { float mass = LinksetRoot.RawMass; @@ -311,6 +385,5 @@ public abstract class BSLinkset if (m_physicsScene.PhysicsLogging.Enabled) m_physicsScene.DetailLog(msg, args); } - } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index fc4545f..d34b797 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -353,6 +353,16 @@ public abstract class BSPhysObject : PhysicsActor CollidingStep = BSScene.NotASimulationStep; } } + // Complex objects (like linksets) need to know if there is a collision on any part of + // their shape. 'IsColliding' has an existing definition of reporting a collision on + // only this specific prim or component of linksets. + // 'HasSomeCollision' is defined as reporting if there is a collision on any part of + // the complex body that this prim is the root of. + public virtual bool HasSomeCollision + { + get { return IsColliding; } + set { IsColliding = value; } + } public override bool CollidingGround { get { return (CollidingGroundStep == PhysScene.SimulationStep); } set @@ -386,6 +396,7 @@ public abstract class BSPhysObject : PhysicsActor // Return 'true' if a collision was processed and should be sent up. // Return 'false' if this object is not enabled/subscribed/appropriate for or has already seen this collision. // Called at taint time from within the Step() function + public delegate bool CollideCall(uint collidingWith, BSPhysObject collidee, OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth); public virtual bool Collide(uint collidingWith, BSPhysObject collidee, OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth) { diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index d43448e..4771934 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -495,8 +495,8 @@ public class BSPrim : BSPhysObject } } - // Find and return a handle to the current vehicle actor. - // Return 'null' if there is no vehicle actor. + // Find and return a handle to the current vehicle actor. + // Return 'null' if there is no vehicle actor. public BSDynamics GetVehicleActor() { BSDynamics ret = null; @@ -507,6 +507,7 @@ public class BSPrim : BSPhysObject } return ret; } + public override int VehicleType { get { int ret = (int)Vehicle.TYPE_NONE; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs index 1fbcfcc..2f392da 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs @@ -200,20 +200,38 @@ public class BSPrimLinkable : BSPrimDisplaced } // Called after a simulation step to post a collision with this object. + // This returns 'true' if the collision has been queued and the SendCollisions call must + // be made at the end of the simulation step. public override bool Collide(uint collidingWith, BSPhysObject collidee, OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth) { - // prims in the same linkset cannot collide with each other - BSPrimLinkable convCollidee = collidee as BSPrimLinkable; - if (convCollidee != null && (this.Linkset.LinksetID == convCollidee.Linkset.LinksetID)) + bool ret = false; + // Ask the linkset if it wants to handle the collision + if (!Linkset.HandleCollide(collidingWith, collidee, contactPoint, contactNormal, pentrationDepth)) { - return false; + // The linkset didn't handle it so pass the collision through normal processing + ret = base.Collide(collidingWith, collidee, contactPoint, contactNormal, pentrationDepth); } + return ret; + } - // TODO: handle collisions of other objects with with children of linkset. - // This is a problem for LinksetCompound since the children are packed into the root. + // A linkset reports any collision on any part of the linkset. + public long SomeCollisionSimulationStep = 0; + public override bool HasSomeCollision + { + get + { + return (SomeCollisionSimulationStep == PhysScene.SimulationStep) || base.IsColliding; + } + set + { + if (value) + SomeCollisionSimulationStep = PhysScene.SimulationStep; + else + SomeCollisionSimulationStep = 0; - return base.Collide(collidingWith, collidee, contactPoint, contactNormal, pentrationDepth); + base.HasSomeCollision = value; + } } } } -- cgit v1.1 From b14156aa6317b2c0ca6801730beb7c51eed97244 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 23 Jul 2013 08:13:29 -0700 Subject: Revert "Revert "BulletSim: only create vehicle prim actor when vehicles are enabled."" Found that the vehicle movement problem was not caused by these physics changes. This reverts commit 5f7b2ea81b95a60e882bc65b663a2c9fe134f92a. --- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 43 ++++++++++++++++------ .../Physics/BulletSPlugin/Tests/BasicVehicles.cs | 2 +- 2 files changed, 33 insertions(+), 12 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 4771934..fdb2925 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -96,7 +96,7 @@ public class BSPrim : BSPhysObject _isVolumeDetect = false; // Add a dynamic vehicle to our set of actors that can move this prim. - PhysicalActors.Add(VehicleActorName, new BSDynamics(PhysScene, this, VehicleActorName)); + // PhysicalActors.Add(VehicleActorName, new BSDynamics(PhysScene, this, VehicleActorName)); _mass = CalculateMass(); @@ -497,7 +497,7 @@ public class BSPrim : BSPhysObject // Find and return a handle to the current vehicle actor. // Return 'null' if there is no vehicle actor. - public BSDynamics GetVehicleActor() + public BSDynamics GetVehicleActor(bool createIfNone) { BSDynamics ret = null; BSActor actor; @@ -505,13 +505,21 @@ public class BSPrim : BSPhysObject { ret = actor as BSDynamics; } + else + { + if (createIfNone) + { + ret = new BSDynamics(PhysScene, this, VehicleActorName); + PhysicalActors.Add(ret.ActorName, ret); + } + } return ret; } public override int VehicleType { get { int ret = (int)Vehicle.TYPE_NONE; - BSDynamics vehicleActor = GetVehicleActor(); + BSDynamics vehicleActor = GetVehicleActor(false /* createIfNone */); if (vehicleActor != null) ret = (int)vehicleActor.Type; return ret; @@ -525,11 +533,24 @@ public class BSPrim : BSPhysObject // change all the parameters. Like a plane changing to CAR when on the // ground. In this case, don't want to zero motion. // ZeroMotion(true /* inTaintTime */); - BSDynamics vehicleActor = GetVehicleActor(); - if (vehicleActor != null) + if (type == Vehicle.TYPE_NONE) { - vehicleActor.ProcessTypeChange(type); - ActivateIfPhysical(false); + // Vehicle type is 'none' so get rid of any actor that may have been allocated. + BSDynamics vehicleActor = GetVehicleActor(false /* createIfNone */); + if (vehicleActor != null) + { + PhysicalActors.RemoveAndRelease(vehicleActor.ActorName); + } + } + else + { + // Vehicle type is not 'none' so create an actor and set it running. + BSDynamics vehicleActor = GetVehicleActor(true /* createIfNone */); + if (vehicleActor != null) + { + vehicleActor.ProcessTypeChange(type); + ActivateIfPhysical(false); + } } }); } @@ -538,7 +559,7 @@ public class BSPrim : BSPhysObject { PhysScene.TaintedObject("BSPrim.VehicleFloatParam", delegate() { - BSDynamics vehicleActor = GetVehicleActor(); + BSDynamics vehicleActor = GetVehicleActor(true /* createIfNone */); if (vehicleActor != null) { vehicleActor.ProcessFloatVehicleParam((Vehicle)param, value); @@ -550,7 +571,7 @@ public class BSPrim : BSPhysObject { PhysScene.TaintedObject("BSPrim.VehicleVectorParam", delegate() { - BSDynamics vehicleActor = GetVehicleActor(); + BSDynamics vehicleActor = GetVehicleActor(true /* createIfNone */); if (vehicleActor != null) { vehicleActor.ProcessVectorVehicleParam((Vehicle)param, value); @@ -562,7 +583,7 @@ public class BSPrim : BSPhysObject { PhysScene.TaintedObject("BSPrim.VehicleRotationParam", delegate() { - BSDynamics vehicleActor = GetVehicleActor(); + BSDynamics vehicleActor = GetVehicleActor(true /* createIfNone */); if (vehicleActor != null) { vehicleActor.ProcessRotationVehicleParam((Vehicle)param, rotation); @@ -574,7 +595,7 @@ public class BSPrim : BSPhysObject { PhysScene.TaintedObject("BSPrim.VehicleFlags", delegate() { - BSDynamics vehicleActor = GetVehicleActor(); + BSDynamics vehicleActor = GetVehicleActor(true /* createIfNone */); if (vehicleActor != null) { vehicleActor.ProcessVehicleFlags(param, remove); diff --git a/OpenSim/Region/Physics/BulletSPlugin/Tests/BasicVehicles.cs b/OpenSim/Region/Physics/BulletSPlugin/Tests/BasicVehicles.cs index 48d3742..48e74eb 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/Tests/BasicVehicles.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/Tests/BasicVehicles.cs @@ -116,7 +116,7 @@ public class BasicVehicles : OpenSimTestCase // Instead the appropriate values are set and calls are made just the parts of the // controller we want to exercise. Stepping the physics engine then applies // the actions of that one feature. - BSDynamics vehicleActor = TestVehicle.GetVehicleActor(); + BSDynamics vehicleActor = TestVehicle.GetVehicleActor(true /* createIfNone */); if (vehicleActor != null) { vehicleActor.ProcessFloatVehicleParam(Vehicle.VERTICAL_ATTRACTION_EFFICIENCY, efficiency); -- cgit v1.1 From 75686e0e49308a21ca013d246544f88cd8e90cbd Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 23 Jul 2013 08:13:56 -0700 Subject: Revert "Revert "BulletSim: change BSDynamics to expect to be passed a BSPrimLinkable"" Found that the vehicle movement problem was not caused by these physics changes. This reverts commit 7b187deb19517aa7c880458894643a5448566a94. --- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index 1540df1..82d7c44 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -45,7 +45,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin private static string LogHeader = "[BULLETSIM VEHICLE]"; // the prim this dynamic controller belongs to - private BSPrim ControllingPrim { get; set; } + private BSPrimLinkable ControllingPrim { get; set; } private bool m_haveRegisteredForSceneEvents; @@ -128,9 +128,15 @@ namespace OpenSim.Region.Physics.BulletSPlugin public BSDynamics(BSScene myScene, BSPrim myPrim, string actorName) : base(myScene, myPrim, actorName) { - ControllingPrim = myPrim; Type = Vehicle.TYPE_NONE; m_haveRegisteredForSceneEvents = false; + + ControllingPrim = myPrim as BSPrimLinkable; + if (ControllingPrim == null) + { + // THIS CANNOT HAPPEN!! + } + VDetailLog("{0},Creation", ControllingPrim.LocalID); } // Return 'true' if this vehicle is doing vehicle things @@ -585,6 +591,8 @@ namespace OpenSim.Region.Physics.BulletSPlugin // Friction affects are handled by this vehicle code m_physicsScene.PE.SetFriction(ControllingPrim.PhysBody, BSParam.VehicleFriction); m_physicsScene.PE.SetRestitution(ControllingPrim.PhysBody, BSParam.VehicleRestitution); + // ControllingPrim.Linkset.SetPhysicalFriction(BSParam.VehicleFriction); + // ControllingPrim.Linkset.SetPhysicalRestitution(BSParam.VehicleRestitution); // Moderate angular movement introduced by Bullet. // TODO: possibly set AngularFactor and LinearFactor for the type of vehicle. @@ -595,17 +603,20 @@ namespace OpenSim.Region.Physics.BulletSPlugin // Vehicles report collision events so we know when it's on the ground m_physicsScene.PE.AddToCollisionFlags(ControllingPrim.PhysBody, CollisionFlags.BS_VEHICLE_COLLISIONS); + // ControllingPrim.Linkset.SetPhysicalCollisionFlags(CollisionFlags.BS_VEHICLE_COLLISIONS); Vector3 inertia = m_physicsScene.PE.CalculateLocalInertia(ControllingPrim.PhysShape.physShapeInfo, m_vehicleMass); ControllingPrim.Inertia = inertia * BSParam.VehicleInertiaFactor; m_physicsScene.PE.SetMassProps(ControllingPrim.PhysBody, m_vehicleMass, ControllingPrim.Inertia); m_physicsScene.PE.UpdateInertiaTensor(ControllingPrim.PhysBody); + // ControllingPrim.Linkset.ComputeLocalInertia(BSParam.VehicleInertiaFactor); // Set the gravity for the vehicle depending on the buoyancy // TODO: what should be done if prim and vehicle buoyancy differ? m_VehicleGravity = ControllingPrim.ComputeGravity(m_VehicleBuoyancy); // The actual vehicle gravity is set to zero in Bullet so we can do all the application of same. m_physicsScene.PE.SetGravity(ControllingPrim.PhysBody, Vector3.Zero); + // ControllingPrim.Linkset.SetPhysicalGravity(Vector3.Zero); VDetailLog("{0},BSDynamics.SetPhysicalParameters,mass={1},inert={2},vehGrav={3},aDamp={4},frict={5},rest={6},lFact={7},aFact={8}", ControllingPrim.LocalID, m_vehicleMass, ControllingPrim.Inertia, m_VehicleGravity, @@ -617,6 +628,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin { if (ControllingPrim.PhysBody.HasPhysicalBody) m_physicsScene.PE.RemoveFromCollisionFlags(ControllingPrim.PhysBody, CollisionFlags.BS_VEHICLE_COLLISIONS); + // ControllingPrim.Linkset.RemoveFromPhysicalCollisionFlags(CollisionFlags.BS_VEHICLE_COLLISIONS); } } @@ -629,6 +641,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin // BSActor.Release() public override void Dispose() { + VDetailLog("{0},Dispose", ControllingPrim.LocalID); UnregisterForSceneEvents(); Type = Vehicle.TYPE_NONE; Enabled = false; -- cgit v1.1 From f499b328c44ef29d92aa2ef8102aad6ff5cbe336 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 23 Jul 2013 08:14:20 -0700 Subject: Revert "Revert "BulletSim: Add logic to linksets to change physical properties for"" Found that the vehicle movement problem was not caused by these physics changes. This reverts commit 84d0699761b8da546f9faef084240d7b15f16321. --- OpenSim/Region/Physics/BulletSPlugin/BSActors.cs | 6 +--- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 24 +++++++++++++-- .../Physics/BulletSPlugin/BSLinksetCompound.cs | 36 ++++++++++++++++++++++ 3 files changed, 59 insertions(+), 7 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSActors.cs b/OpenSim/Region/Physics/BulletSPlugin/BSActors.cs index fff63e4..e0ccc50 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSActors.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSActors.cs @@ -69,7 +69,7 @@ public class BSActorCollection { lock (m_actors) { - Release(); + ForEachActor(a => a.Dispose()); m_actors.Clear(); } } @@ -98,10 +98,6 @@ public class BSActorCollection { ForEachActor(a => a.SetEnabled(enabl)); } - public void Release() - { - ForEachActor(a => a.Dispose()); - } public void Refresh() { ForEachActor(a => a.Refresh()); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index 78c0af7..960c0b4 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -309,14 +309,14 @@ public abstract class BSLinkset } ); } - public virtual void ComputeLocalInertia() + public virtual void ComputeLocalInertia(OMV.Vector3 inertiaFactor) { ForEachMember((member) => { if (member.PhysBody.HasPhysicalBody) { OMV.Vector3 inertia = m_physicsScene.PE.CalculateLocalInertia(member.PhysShape.physShapeInfo, member.Mass); - member.Inertia = inertia * BSParam.VehicleInertiaFactor; + member.Inertia = inertia * inertiaFactor; m_physicsScene.PE.SetMassProps(member.PhysBody, member.Mass, member.Inertia); m_physicsScene.PE.UpdateInertiaTensor(member.PhysBody); } @@ -324,6 +324,26 @@ public abstract class BSLinkset } ); } + public virtual void SetPhysicalCollisionFlags(CollisionFlags collFlags) + { + ForEachMember((member) => + { + if (member.PhysBody.HasPhysicalBody) + m_physicsScene.PE.SetCollisionFlags(member.PhysBody, collFlags); + return false; // 'false' says to continue looping + } + ); + } + public virtual void RemoveFromPhysicalCollisionFlags(CollisionFlags collFlags) + { + ForEachMember((member) => + { + if (member.PhysBody.HasPhysicalBody) + m_physicsScene.PE.RemoveFromCollisionFlags(member.PhysBody, collFlags); + return false; // 'false' says to continue looping + } + ); + } // ================================================================ protected virtual float ComputeLinksetMass() { diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs index 3668456..33ae5a5 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs @@ -44,6 +44,42 @@ public sealed class BSLinksetCompound : BSLinkset { } + // ================================================================ + // Changing the physical property of the linkset only needs to change the root + public override void SetPhysicalFriction(float friction) + { + if (LinksetRoot.PhysBody.HasPhysicalBody) + m_physicsScene.PE.SetFriction(LinksetRoot.PhysBody, friction); + } + public override void SetPhysicalRestitution(float restitution) + { + if (LinksetRoot.PhysBody.HasPhysicalBody) + m_physicsScene.PE.SetRestitution(LinksetRoot.PhysBody, restitution); + } + public override void SetPhysicalGravity(OMV.Vector3 gravity) + { + if (LinksetRoot.PhysBody.HasPhysicalBody) + m_physicsScene.PE.SetGravity(LinksetRoot.PhysBody, gravity); + } + public override void ComputeLocalInertia(OMV.Vector3 inertiaFactor) + { + OMV.Vector3 inertia = m_physicsScene.PE.CalculateLocalInertia(LinksetRoot.PhysShape.physShapeInfo, LinksetRoot.Mass); + LinksetRoot.Inertia = inertia * inertiaFactor; + m_physicsScene.PE.SetMassProps(LinksetRoot.PhysBody, LinksetRoot.Mass, LinksetRoot.Inertia); + m_physicsScene.PE.UpdateInertiaTensor(LinksetRoot.PhysBody); + } + public override void SetPhysicalCollisionFlags(CollisionFlags collFlags) + { + if (LinksetRoot.PhysBody.HasPhysicalBody) + m_physicsScene.PE.SetCollisionFlags(LinksetRoot.PhysBody, collFlags); + } + public override void RemoveFromPhysicalCollisionFlags(CollisionFlags collFlags) + { + if (LinksetRoot.PhysBody.HasPhysicalBody) + m_physicsScene.PE.RemoveFromCollisionFlags(LinksetRoot.PhysBody, collFlags); + } + // ================================================================ + // When physical properties are changed the linkset needs to recalculate // its internal properties. public override void Refresh(BSPrimLinkable requestor) -- cgit v1.1 From aec8d1e6be43422b0f93de47d6e46cc3e17399cc Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 23 Jul 2013 09:09:25 -0700 Subject: BulletSim: Turn on center-of-mass calculation by default. Reduce object density by factor of 100 to bring physical mass computations into a range better suited for Bullet. --- OpenSim/Region/Physics/BulletSPlugin/BSParam.cs | 8 +++++--- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 4 ++-- 2 files changed, 7 insertions(+), 5 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs index dcf1e83..0bdb5f1 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs @@ -461,8 +461,9 @@ public static class BSParam (s) => { return MaxAddForceMagnitude; }, (s,v) => { MaxAddForceMagnitude = v; MaxAddForceMagnitudeSquared = v * v; } ), // Density is passed around as 100kg/m3. This scales that to 1kg/m3. + // Reduce by power of 100 because Bullet doesn't seem to handle objects with large mass very well new ParameterDefn("DensityScaleFactor", "Conversion for simulator/viewer density (100kg/m3) to physical density (1kg/m3)", - 0.01f ), + 0.0001f ), new ParameterDefn("PID_D", "Derivitive factor for motion smoothing", 2200f ), @@ -607,8 +608,9 @@ public static class BSParam 0.0f ), new ParameterDefn("VehicleRestitution", "Bouncyness factor for vehicles (0.0 - 1.0)", 0.0f ), + // Turn off fudge with DensityScaleFactor = 0.0001. Value used to be 0.2f; new ParameterDefn("VehicleGroundGravityFudge", "Factor to multiply gravity if a ground vehicle is probably on the ground (0.0 - 1.0)", - 0.2f ), + 1.0f ), new ParameterDefn("VehicleAngularBankingTimescaleFudge", "Factor to multiple angular banking timescale. Tune to increase realism.", 60.0f ), new ParameterDefn("VehicleEnableLinearDeflection", "Turn on/off vehicle linear deflection effect", @@ -701,7 +703,7 @@ public static class BSParam new ParameterDefn("LinksetImplementation", "Type of linkset implementation (0=Constraint, 1=Compound, 2=Manual)", (float)BSLinkset.LinksetImplementation.Compound ), new ParameterDefn("LinksetOffsetCenterOfMass", "If 'true', compute linkset center-of-mass and offset linkset position to account for same", - false ), + true ), new ParameterDefn("LinkConstraintUseFrameOffset", "For linksets built with constraints, enable frame offsetFor linksets built with constraints, enable frame offset.", false ), new ParameterDefn("LinkConstraintEnableTransMotor", "Whether to enable translational motor on linkset constraints", diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index fdb2925..e92a1d2 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -440,8 +440,8 @@ public class BSPrim : BSPhysObject Gravity = ComputeGravity(Buoyancy); PhysScene.PE.SetGravity(PhysBody, Gravity); - OMV.Vector3 currentScale = PhysScene.PE.GetLocalScaling(PhysShape.physShapeInfo); // DEBUG DEBUG - DetailLog("{0},BSPrim.UpdateMassProperties,currentScale{1},shape={2}", LocalID, currentScale, PhysShape.physShapeInfo); // DEBUG DEBUG + // OMV.Vector3 currentScale = PhysScene.PE.GetLocalScaling(PhysShape.physShapeInfo); // DEBUG DEBUG + // DetailLog("{0},BSPrim.UpdateMassProperties,currentScale{1},shape={2}", LocalID, currentScale, PhysShape.physShapeInfo); // DEBUG DEBUG Inertia = PhysScene.PE.CalculateLocalInertia(PhysShape.physShapeInfo, physMass); PhysScene.PE.SetMassProps(PhysBody, physMass, Inertia); -- cgit v1.1 From 5a7784a0e6c3f549d0e7b59380ad05729cb93a4f Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Wed, 24 Jul 2013 10:52:54 -0700 Subject: BulletSim: make density display and return value consistant with how the simulator expects it (scaled to 100kg/m^3). --- OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs | 2 +- OpenSim/Region/Physics/BulletSPlugin/BSParam.cs | 13 +++++++------ OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs | 15 ++++++++++++++- 3 files changed, 22 insertions(+), 8 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index 59e7f5f..58a417e 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -75,7 +75,7 @@ public sealed class BSCharacter : BSPhysObject RawVelocity = OMV.Vector3.Zero; _buoyancy = ComputeBuoyancyFromFlying(isFlying); Friction = BSParam.AvatarStandingFriction; - Density = BSParam.AvatarDensity / BSParam.DensityScaleFactor; + Density = BSParam.AvatarDensity; // Old versions of ScenePresence passed only the height. If width and/or depth are zero, // replace with the default values. diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs index 0bdb5f1..4520171 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs @@ -463,7 +463,7 @@ public static class BSParam // Density is passed around as 100kg/m3. This scales that to 1kg/m3. // Reduce by power of 100 because Bullet doesn't seem to handle objects with large mass very well new ParameterDefn("DensityScaleFactor", "Conversion for simulator/viewer density (100kg/m3) to physical density (1kg/m3)", - 0.0001f ), + 0.01f ), new ParameterDefn("PID_D", "Derivitive factor for motion smoothing", 2200f ), @@ -474,8 +474,9 @@ public static class BSParam 0.2f, (s) => { return DefaultFriction; }, (s,v) => { DefaultFriction = v; s.UnmanagedParams[0].defaultFriction = v; } ), + // For historical reasons, the viewer and simulator multiply the density by 100 new ParameterDefn("DefaultDensity", "Density for new objects" , - 10.000006836f, // Aluminum g/cm3 + 1000.0006836f, // Aluminum g/cm3 * 100 (s) => { return DefaultDensity; }, (s,v) => { DefaultDensity = v; s.UnmanagedParams[0].defaultDensity = v; } ), new ParameterDefn("DefaultRestitution", "Bouncyness of an object" , @@ -555,8 +556,9 @@ public static class BSParam 0.95f ), new ParameterDefn("AvatarAlwaysRunFactor", "Speed multiplier if avatar is set to always run", 1.3f ), - new ParameterDefn("AvatarDensity", "Density of an avatar. Changed on avatar recreation.", - 3.5f) , + // For historical reasons, density is reported * 100 + new ParameterDefn("AvatarDensity", "Density of an avatar. Changed on avatar recreation. Scaled times 100.", + 3500f) , // 3.5 * 100 new ParameterDefn("AvatarRestitution", "Bouncyness. Changed on avatar recreation.", 0f ), new ParameterDefn("AvatarCapsuleWidth", "The distance between the sides of the avatar capsule", @@ -608,9 +610,8 @@ public static class BSParam 0.0f ), new ParameterDefn("VehicleRestitution", "Bouncyness factor for vehicles (0.0 - 1.0)", 0.0f ), - // Turn off fudge with DensityScaleFactor = 0.0001. Value used to be 0.2f; new ParameterDefn("VehicleGroundGravityFudge", "Factor to multiply gravity if a ground vehicle is probably on the ground (0.0 - 1.0)", - 1.0f ), + 0.2f ), new ParameterDefn("VehicleAngularBankingTimescaleFudge", "Factor to multiple angular banking timescale. Tune to increase realism.", 60.0f ), new ParameterDefn("VehicleEnableLinearDeflection", "Turn on/off vehicle linear deflection effect", diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index d34b797..0704591 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -187,10 +187,23 @@ public abstract class BSPhysObject : PhysicsActor MaterialAttributes matAttrib = BSMaterials.GetAttributes(Material, false); Friction = matAttrib.friction; Restitution = matAttrib.restitution; - Density = matAttrib.density / BSParam.DensityScaleFactor; + Density = matAttrib.density; // DetailLog("{0},{1}.SetMaterial,Mat={2},frict={3},rest={4},den={5}", LocalID, TypeName, Material, Friction, Restitution, Density); } + public override float Density + { + get + { + return base.Density; + } + set + { + DetailLog("{0},BSPhysObject.Density,set,den={1}", LocalID, value); + base.Density = value; + } + } + // Stop all physical motion. public abstract void ZeroMotion(bool inTaintTime); public abstract void ZeroAngularMotion(bool inTaintTime); -- cgit v1.1 From 0d189165a83bb97f243a1f29cfa6896936ca6db0 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 30 Jul 2013 15:23:33 -0700 Subject: BulletSim: distribute vehicle physical settings to all members of a linkset. Enables constraint based linksets. Rename some internal variables to clarify whether values world or vehicle relative. --- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 75 +++++++++++----------- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 18 +++++- .../Physics/BulletSPlugin/BSLinksetCompound.cs | 11 +++- 3 files changed, 61 insertions(+), 43 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index 82d7c44..f0d17d3 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -589,10 +589,10 @@ namespace OpenSim.Region.Physics.BulletSPlugin m_vehicleMass = ControllingPrim.TotalMass; // Friction affects are handled by this vehicle code - m_physicsScene.PE.SetFriction(ControllingPrim.PhysBody, BSParam.VehicleFriction); - m_physicsScene.PE.SetRestitution(ControllingPrim.PhysBody, BSParam.VehicleRestitution); - // ControllingPrim.Linkset.SetPhysicalFriction(BSParam.VehicleFriction); - // ControllingPrim.Linkset.SetPhysicalRestitution(BSParam.VehicleRestitution); + // m_physicsScene.PE.SetFriction(ControllingPrim.PhysBody, BSParam.VehicleFriction); + // m_physicsScene.PE.SetRestitution(ControllingPrim.PhysBody, BSParam.VehicleRestitution); + ControllingPrim.Linkset.SetPhysicalFriction(BSParam.VehicleFriction); + ControllingPrim.Linkset.SetPhysicalRestitution(BSParam.VehicleRestitution); // Moderate angular movement introduced by Bullet. // TODO: possibly set AngularFactor and LinearFactor for the type of vehicle. @@ -602,21 +602,21 @@ namespace OpenSim.Region.Physics.BulletSPlugin m_physicsScene.PE.SetAngularFactorV(ControllingPrim.PhysBody, BSParam.VehicleAngularFactor); // Vehicles report collision events so we know when it's on the ground - m_physicsScene.PE.AddToCollisionFlags(ControllingPrim.PhysBody, CollisionFlags.BS_VEHICLE_COLLISIONS); - // ControllingPrim.Linkset.SetPhysicalCollisionFlags(CollisionFlags.BS_VEHICLE_COLLISIONS); + // m_physicsScene.PE.AddToCollisionFlags(ControllingPrim.PhysBody, CollisionFlags.BS_VEHICLE_COLLISIONS); + ControllingPrim.Linkset.AddToPhysicalCollisionFlags(CollisionFlags.BS_VEHICLE_COLLISIONS); - Vector3 inertia = m_physicsScene.PE.CalculateLocalInertia(ControllingPrim.PhysShape.physShapeInfo, m_vehicleMass); - ControllingPrim.Inertia = inertia * BSParam.VehicleInertiaFactor; - m_physicsScene.PE.SetMassProps(ControllingPrim.PhysBody, m_vehicleMass, ControllingPrim.Inertia); - m_physicsScene.PE.UpdateInertiaTensor(ControllingPrim.PhysBody); - // ControllingPrim.Linkset.ComputeLocalInertia(BSParam.VehicleInertiaFactor); + // Vector3 inertia = m_physicsScene.PE.CalculateLocalInertia(ControllingPrim.PhysShape.physShapeInfo, m_vehicleMass); + // ControllingPrim.Inertia = inertia * BSParam.VehicleInertiaFactor; + // m_physicsScene.PE.SetMassProps(ControllingPrim.PhysBody, m_vehicleMass, ControllingPrim.Inertia); + // m_physicsScene.PE.UpdateInertiaTensor(ControllingPrim.PhysBody); + ControllingPrim.Linkset.ComputeAndSetLocalInertia(BSParam.VehicleInertiaFactor, m_vehicleMass); // Set the gravity for the vehicle depending on the buoyancy // TODO: what should be done if prim and vehicle buoyancy differ? m_VehicleGravity = ControllingPrim.ComputeGravity(m_VehicleBuoyancy); // The actual vehicle gravity is set to zero in Bullet so we can do all the application of same. - m_physicsScene.PE.SetGravity(ControllingPrim.PhysBody, Vector3.Zero); - // ControllingPrim.Linkset.SetPhysicalGravity(Vector3.Zero); + // m_physicsScene.PE.SetGravity(ControllingPrim.PhysBody, Vector3.Zero); + ControllingPrim.Linkset.SetPhysicalGravity(Vector3.Zero); VDetailLog("{0},BSDynamics.SetPhysicalParameters,mass={1},inert={2},vehGrav={3},aDamp={4},frict={5},rest={6},lFact={7},aFact={8}", ControllingPrim.LocalID, m_vehicleMass, ControllingPrim.Inertia, m_VehicleGravity, @@ -1121,7 +1121,6 @@ namespace OpenSim.Region.Physics.BulletSPlugin { m_VhoverTargetHeight = m_VhoverHeight; } - if ((m_flags & VehicleFlag.HOVER_UP_ONLY) != 0) { // If body is already heigher, use its height as target height @@ -1170,7 +1169,6 @@ namespace OpenSim.Region.Physics.BulletSPlugin m_VhoverTimescale, m_VhoverHeight, m_VhoverTargetHeight, verticalError, verticalCorrection); } - } } @@ -1357,6 +1355,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin private void ComputeAngularTurning(float pTimestep) { // The user wants this many radians per second angular change? + Vector3 origVehicleRotationalVelocity = VehicleRotationalVelocity; // DEBUG DEBUG Vector3 currentAngularV = VehicleRotationalVelocity * Quaternion.Inverse(VehicleOrientation); Vector3 angularMotorContributionV = m_angularMotor.Step(pTimestep, currentAngularV); @@ -1369,20 +1368,20 @@ namespace OpenSim.Region.Physics.BulletSPlugin // TODO: This is here because this is where ODE put it but documentation says it // is a linear effect. Where should this check go? //if ((m_flags & (VehicleFlag.NO_DEFLECTION_UP)) != 0) - // { + // { // angularMotorContributionV.X = 0f; // angularMotorContributionV.Y = 0f; - // } + // } // Reduce any velocity by friction. Vector3 frictionFactorW = ComputeFrictionFactor(m_angularFrictionTimescale, pTimestep); angularMotorContributionV -= (currentAngularV * frictionFactorW); - VehicleRotationalVelocity += angularMotorContributionV * VehicleOrientation; - - + Vector3 angularMotorContributionW = angularMotorContributionV * VehicleOrientation; + VehicleRotationalVelocity += angularMotorContributionW; - VDetailLog("{0}, MoveAngular,angularTurning,angContribV={1}", ControllingPrim.LocalID, angularMotorContributionV); + VDetailLog("{0}, MoveAngular,angularTurning,curAngVelV={1},origVehRotVel={2},vehRotVel={3},frictFact={4}, angContribV={5},angContribW={6}", + ControllingPrim.LocalID, currentAngularV, origVehicleRotationalVelocity, VehicleRotationalVelocity, frictionFactorW, angularMotorContributionV, angularMotorContributionW); } // From http://wiki.secondlife.com/wiki/Linden_Vehicle_Tutorial: @@ -1409,7 +1408,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin // Flipping what was originally a timescale into a speed variable and then multiplying it by 2 // since only computing half the distance between the angles. - float VerticalAttractionSpeed = (1 / m_verticalAttractionTimescale) * 2.0f; + float verticalAttractionSpeed = (1 / m_verticalAttractionTimescale) * 2.0f; // Make a prediction of where the up axis will be when this is applied rather then where it is now as // this makes for a smoother adjustment and less fighting between the various forces. @@ -1419,12 +1418,13 @@ namespace OpenSim.Region.Physics.BulletSPlugin Vector3 torqueVector = Vector3.Cross(predictedUp, Vector3.UnitZ); // Scale vector by our timescale since it is an acceleration it is r/s^2 or radians a timescale squared - Vector3 vertContributionV = torqueVector * VerticalAttractionSpeed * VerticalAttractionSpeed; + Vector3 vertContributionV = torqueVector * verticalAttractionSpeed * verticalAttractionSpeed; VehicleRotationalVelocity += vertContributionV; - VDetailLog("{0}, MoveAngular,verticalAttraction,upAxis={1},PredictedUp={2},torqueVector={3},contrib={4}", + VDetailLog("{0}, MoveAngular,verticalAttraction,vertAttrSpeed={1},upAxis={2},PredictedUp={3},torqueVector={4},contrib={5}", ControllingPrim.LocalID, + verticalAttractionSpeed, vehicleUpAxis, predictedUp, torqueVector, @@ -1437,37 +1437,38 @@ namespace OpenSim.Region.Physics.BulletSPlugin // http://stackoverflow.com/questions/14939657/computing-vector-from-quaternion-works-computing-quaternion-from-vector-does-no // Create a rotation that is only the vehicle's rotation around Z - Vector3 currentEuler = Vector3.Zero; - VehicleOrientation.GetEulerAngles(out currentEuler.X, out currentEuler.Y, out currentEuler.Z); - Quaternion justZOrientation = Quaternion.CreateFromAxisAngle(Vector3.UnitZ, currentEuler.Z); + Vector3 currentEulerW = Vector3.Zero; + VehicleOrientation.GetEulerAngles(out currentEulerW.X, out currentEulerW.Y, out currentEulerW.Z); + Quaternion justZOrientation = Quaternion.CreateFromAxisAngle(Vector3.UnitZ, currentEulerW.Z); // Create the axis that is perpendicular to the up vector and the rotated up vector. - Vector3 differenceAxis = Vector3.Cross(Vector3.UnitZ * justZOrientation, Vector3.UnitZ * VehicleOrientation); + Vector3 differenceAxisW = Vector3.Cross(Vector3.UnitZ * justZOrientation, Vector3.UnitZ * VehicleOrientation); // Compute the angle between those to vectors. double differenceAngle = Math.Acos((double)Vector3.Dot(Vector3.UnitZ, Vector3.Normalize(Vector3.UnitZ * VehicleOrientation))); // 'differenceAngle' is the angle to rotate and 'differenceAxis' is the plane to rotate in to get the vehicle vertical // Reduce the change by the time period it is to change in. Timestep is handled when velocity is applied. // TODO: add 'efficiency'. - differenceAngle /= m_verticalAttractionTimescale; + // differenceAngle /= m_verticalAttractionTimescale; // Create the quaterian representing the correction angle - Quaternion correctionRotation = Quaternion.CreateFromAxisAngle(differenceAxis, (float)differenceAngle); + Quaternion correctionRotationW = Quaternion.CreateFromAxisAngle(differenceAxisW, (float)differenceAngle); // Turn that quaternion into Euler values to make it into velocities to apply. - Vector3 vertContributionV = Vector3.Zero; - correctionRotation.GetEulerAngles(out vertContributionV.X, out vertContributionV.Y, out vertContributionV.Z); - vertContributionV *= -1f; + Vector3 vertContributionW = Vector3.Zero; + correctionRotationW.GetEulerAngles(out vertContributionW.X, out vertContributionW.Y, out vertContributionW.Z); + vertContributionW *= -1f; + vertContributionW /= m_verticalAttractionTimescale; - VehicleRotationalVelocity += vertContributionV; + VehicleRotationalVelocity += vertContributionW; VDetailLog("{0}, MoveAngular,verticalAttraction,upAxis={1},diffAxis={2},diffAng={3},corrRot={4},contrib={5}", ControllingPrim.LocalID, vehicleUpAxis, - differenceAxis, + differenceAxisW, differenceAngle, - correctionRotation, - vertContributionV); + correctionRotationW, + vertContributionW); break; } case 2: diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index 960c0b4..7f94666 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -309,16 +309,18 @@ public abstract class BSLinkset } ); } - public virtual void ComputeLocalInertia(OMV.Vector3 inertiaFactor) + public virtual void ComputeAndSetLocalInertia(OMV.Vector3 inertiaFactor, float linksetMass) { ForEachMember((member) => { if (member.PhysBody.HasPhysicalBody) { - OMV.Vector3 inertia = m_physicsScene.PE.CalculateLocalInertia(member.PhysShape.physShapeInfo, member.Mass); + OMV.Vector3 inertia = m_physicsScene.PE.CalculateLocalInertia(member.PhysShape.physShapeInfo, linksetMass); member.Inertia = inertia * inertiaFactor; - m_physicsScene.PE.SetMassProps(member.PhysBody, member.Mass, member.Inertia); + m_physicsScene.PE.SetMassProps(member.PhysBody, linksetMass, member.Inertia); m_physicsScene.PE.UpdateInertiaTensor(member.PhysBody); + DetailLog("{0},BSLinkset.ComputeAndSetLocalInertia,m.mass={1}, inertia={2}", member.LocalID, linksetMass, member.Inertia); + } return false; // 'false' says to continue looping } @@ -334,6 +336,16 @@ public abstract class BSLinkset } ); } + public virtual void AddToPhysicalCollisionFlags(CollisionFlags collFlags) + { + ForEachMember((member) => + { + if (member.PhysBody.HasPhysicalBody) + m_physicsScene.PE.AddToCollisionFlags(member.PhysBody, collFlags); + return false; // 'false' says to continue looping + } + ); + } public virtual void RemoveFromPhysicalCollisionFlags(CollisionFlags collFlags) { ForEachMember((member) => diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs index 33ae5a5..6359046 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs @@ -61,11 +61,11 @@ public sealed class BSLinksetCompound : BSLinkset if (LinksetRoot.PhysBody.HasPhysicalBody) m_physicsScene.PE.SetGravity(LinksetRoot.PhysBody, gravity); } - public override void ComputeLocalInertia(OMV.Vector3 inertiaFactor) + public override void ComputeAndSetLocalInertia(OMV.Vector3 inertiaFactor, float linksetMass) { - OMV.Vector3 inertia = m_physicsScene.PE.CalculateLocalInertia(LinksetRoot.PhysShape.physShapeInfo, LinksetRoot.Mass); + OMV.Vector3 inertia = m_physicsScene.PE.CalculateLocalInertia(LinksetRoot.PhysShape.physShapeInfo, linksetMass); LinksetRoot.Inertia = inertia * inertiaFactor; - m_physicsScene.PE.SetMassProps(LinksetRoot.PhysBody, LinksetRoot.Mass, LinksetRoot.Inertia); + m_physicsScene.PE.SetMassProps(LinksetRoot.PhysBody, linksetMass, LinksetRoot.Inertia); m_physicsScene.PE.UpdateInertiaTensor(LinksetRoot.PhysBody); } public override void SetPhysicalCollisionFlags(CollisionFlags collFlags) @@ -73,6 +73,11 @@ public sealed class BSLinksetCompound : BSLinkset if (LinksetRoot.PhysBody.HasPhysicalBody) m_physicsScene.PE.SetCollisionFlags(LinksetRoot.PhysBody, collFlags); } + public override void AddToPhysicalCollisionFlags(CollisionFlags collFlags) + { + if (LinksetRoot.PhysBody.HasPhysicalBody) + m_physicsScene.PE.AddToCollisionFlags(LinksetRoot.PhysBody, collFlags); + } public override void RemoveFromPhysicalCollisionFlags(CollisionFlags collFlags) { if (LinksetRoot.PhysBody.HasPhysicalBody) -- cgit v1.1 From 5bcccfc305ae4f5a74b9b816781a2a643daa23b3 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Thu, 1 Aug 2013 12:35:22 -0700 Subject: BulletSim: add BSLinkInfo structure to remember link specific information for each link in a linkset. Extend BSLinksetConstraint to create and use BSLinkInfo with the default static constraint. --- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 51 +++-- .../Physics/BulletSPlugin/BSLinksetCompound.cs | 4 +- .../Physics/BulletSPlugin/BSLinksetConstraints.cs | 205 ++++++++++++++------- 3 files changed, 174 insertions(+), 86 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index 7f94666..9613fe0 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -70,6 +70,15 @@ public abstract class BSLinkset return ret; } + public class BSLinkInfo + { + public BSPrimLinkable member; + public BSLinkInfo(BSPrimLinkable pMember) + { + member = pMember; + } + } + public BSPrimLinkable LinksetRoot { get; protected set; } protected BSScene m_physicsScene { get; private set; } @@ -78,7 +87,8 @@ public abstract class BSLinkset public int LinksetID { get; private set; } // The children under the root in this linkset. - protected HashSet m_children; + // protected HashSet m_children; + protected Dictionary m_children; // We lock the diddling of linkset classes to prevent any badness. // This locks the modification of the instances of this class. Changes @@ -109,7 +119,7 @@ public abstract class BSLinkset m_nextLinksetID = 1; m_physicsScene = scene; LinksetRoot = parent; - m_children = new HashSet(); + m_children = new Dictionary(); LinksetMass = parent.RawMass; Rebuilding = false; @@ -170,17 +180,7 @@ public abstract class BSLinkset bool ret = false; lock (m_linksetActivityLock) { - ret = m_children.Contains(child); - /* Safer version but the above should work - foreach (BSPrimLinkable bp in m_children) - { - if (child.LocalID == bp.LocalID) - { - ret = true; - break; - } - } - */ + ret = m_children.ContainsKey(child); } return ret; } @@ -194,7 +194,24 @@ public abstract class BSLinkset lock (m_linksetActivityLock) { action(LinksetRoot); - foreach (BSPrimLinkable po in m_children) + foreach (BSPrimLinkable po in m_children.Keys) + { + if (action(po)) + break; + } + } + return ret; + } + + // Perform an action on each member of the linkset including root prim. + // Depends on the action on whether this should be done at taint time. + public delegate bool ForEachLinkInfoAction(BSLinkInfo obj); + public virtual bool ForEachLinkInfo(ForEachLinkInfoAction action) + { + bool ret = false; + lock (m_linksetActivityLock) + { + foreach (BSLinkInfo po in m_children.Values) { if (action(po)) break; @@ -364,7 +381,7 @@ public abstract class BSLinkset { lock (m_linksetActivityLock) { - foreach (BSPrimLinkable bp in m_children) + foreach (BSPrimLinkable bp in m_children.Keys) { mass += bp.RawMass; } @@ -382,7 +399,7 @@ public abstract class BSLinkset com = LinksetRoot.Position * LinksetRoot.RawMass; float totalMass = LinksetRoot.RawMass; - foreach (BSPrimLinkable bp in m_children) + foreach (BSPrimLinkable bp in m_children.Keys) { com += bp.Position * bp.RawMass; totalMass += bp.RawMass; @@ -401,7 +418,7 @@ public abstract class BSLinkset { com = LinksetRoot.Position; - foreach (BSPrimLinkable bp in m_children) + foreach (BSPrimLinkable bp in m_children.Keys) { com += bp.Position; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs index 6359046..53c3584 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs @@ -257,7 +257,7 @@ public sealed class BSLinksetCompound : BSLinkset { if (!HasChild(child)) { - m_children.Add(child); + m_children.Add(child, new BSLinkInfo(child)); DetailLog("{0},BSLinksetCompound.AddChildToLinkset,call,child={1}", LinksetRoot.LocalID, child.LocalID); @@ -353,7 +353,7 @@ public sealed class BSLinksetCompound : BSLinkset // Add the shapes of all the components of the linkset int memberIndex = 1; - ForEachMember(delegate(BSPrimLinkable cPrim) + ForEachMember((cPrim) => { if (IsRoot(cPrim)) { diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs index f17d698..d98bf77 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs @@ -36,6 +36,75 @@ public sealed class BSLinksetConstraints : BSLinkset { // private static string LogHeader = "[BULLETSIM LINKSET CONSTRAINTS]"; + public class BSLinkInfoConstraint : BSLinkInfo + { + public ConstraintType constraintType; + public BSConstraint constraint; + public OMV.Vector3 linearLimitLow; + public OMV.Vector3 linearLimitHigh; + public OMV.Vector3 angularLimitLow; + public OMV.Vector3 angularLimitHigh; + public bool useFrameOffset; + public bool enableTransMotor; + public float transMotorMaxVel; + public float transMotorMaxForce; + public float cfm; + public float erp; + public float solverIterations; + + public BSLinkInfoConstraint(BSPrimLinkable pMember) + : base(pMember) + { + constraint = null; + ResetToFixedConstraint(); + } + + // Set all the parameters for this constraint to a fixed, non-movable constraint. + public void ResetToFixedConstraint() + { + constraintType = ConstraintType.D6_CONSTRAINT_TYPE; + linearLimitLow = OMV.Vector3.Zero; + linearLimitHigh = OMV.Vector3.Zero; + angularLimitLow = OMV.Vector3.Zero; + angularLimitHigh = OMV.Vector3.Zero; + useFrameOffset = BSParam.LinkConstraintUseFrameOffset; + enableTransMotor = BSParam.LinkConstraintEnableTransMotor; + transMotorMaxVel = BSParam.LinkConstraintTransMotorMaxVel; + transMotorMaxForce = BSParam.LinkConstraintTransMotorMaxForce; + cfm = BSParam.LinkConstraintCFM; + erp = BSParam.LinkConstraintERP; + solverIterations = BSParam.LinkConstraintSolverIterations; + } + + // Given a constraint, apply the current constraint parameters to same. + public void SetConstraintParameters(BSConstraint constrain) + { + switch (constraintType) + { + case ConstraintType.D6_CONSTRAINT_TYPE: + BSConstraint6Dof constrain6dof = constrain as BSConstraint6Dof; + if (constrain6dof != null) + { + // zero linear and angular limits makes the objects unable to move in relation to each other + constrain6dof.SetLinearLimits(linearLimitLow, linearLimitHigh); + constrain6dof.SetAngularLimits(angularLimitLow, angularLimitHigh); + + // tweek the constraint to increase stability + constrain6dof.UseFrameOffset(useFrameOffset); + constrain6dof.TranslationalLimitMotor(enableTransMotor, transMotorMaxVel, transMotorMaxForce); + constrain6dof.SetCFMAndERP(cfm, erp); + if (solverIterations != 0f) + { + constrain6dof.SetSolverIterations(solverIterations); + } + } + break; + default: + break; + } + } + } + public BSLinksetConstraints(BSScene scene, BSPrimLinkable parent) : base(scene, parent) { } @@ -142,7 +211,7 @@ public sealed class BSLinksetConstraints : BSLinkset { if (!HasChild(child)) { - m_children.Add(child); + m_children.Add(child, new BSLinkInfoConstraint(child)); DetailLog("{0},BSLinksetConstraints.AddChildToLinkset,call,child={1}", LinksetRoot.LocalID, child.LocalID); @@ -190,73 +259,74 @@ public sealed class BSLinksetConstraints : BSLinkset } // Create a static constraint between the two passed objects - private BSConstraint BuildConstraint(BSPrimLinkable rootPrim, BSPrimLinkable childPrim) + private BSConstraint BuildConstraint(BSPrimLinkable rootPrim, BSLinkInfo li) { + BSLinkInfoConstraint liConstraint = li as BSLinkInfoConstraint; + if (liConstraint == null) + return null; + // Zero motion for children so they don't interpolate - childPrim.ZeroMotion(true); - - // Relative position normalized to the root prim - // Essentually a vector pointing from center of rootPrim to center of childPrim - OMV.Vector3 childRelativePosition = childPrim.Position - rootPrim.Position; - - // real world coordinate of midpoint between the two objects - OMV.Vector3 midPoint = rootPrim.Position + (childRelativePosition / 2); - - DetailLog("{0},BSLinksetConstraint.BuildConstraint,taint,root={1},rBody={2},child={3},cBody={4},rLoc={5},cLoc={6},midLoc={7}", - rootPrim.LocalID, - rootPrim.LocalID, rootPrim.PhysBody.AddrString, - childPrim.LocalID, childPrim.PhysBody.AddrString, - rootPrim.Position, childPrim.Position, midPoint); - - // create a constraint that allows no freedom of movement between the two objects - // http://bulletphysics.org/Bullet/phpBB3/viewtopic.php?t=4818 - - BSConstraint6Dof constrain = new BSConstraint6Dof( - m_physicsScene.World, rootPrim.PhysBody, childPrim.PhysBody, midPoint, true, true ); - // PhysicsScene.World, childPrim.BSBody, rootPrim.BSBody, midPoint, true, true ); - - /* NOTE: below is an attempt to build constraint with full frame computation, etc. - * Using the midpoint is easier since it lets the Bullet code manipulate the transforms - * of the objects. - * Code left for future programmers. - // ================================================================================== - // relative position normalized to the root prim - OMV.Quaternion invThisOrientation = OMV.Quaternion.Inverse(rootPrim.Orientation); - OMV.Vector3 childRelativePosition = (childPrim.Position - rootPrim.Position) * invThisOrientation; - - // relative rotation of the child to the parent - OMV.Quaternion childRelativeRotation = invThisOrientation * childPrim.Orientation; - OMV.Quaternion inverseChildRelativeRotation = OMV.Quaternion.Inverse(childRelativeRotation); - - DetailLog("{0},BSLinksetConstraint.PhysicallyLinkAChildToRoot,taint,root={1},child={2}", rootPrim.LocalID, rootPrim.LocalID, childPrim.LocalID); - BS6DofConstraint constrain = new BS6DofConstraint( - PhysicsScene.World, rootPrim.Body, childPrim.Body, - OMV.Vector3.Zero, - OMV.Quaternion.Inverse(rootPrim.Orientation), - OMV.Vector3.Zero, - OMV.Quaternion.Inverse(childPrim.Orientation), - true, - true - ); - // ================================================================================== - */ + li.member.ZeroMotion(true); - m_physicsScene.Constraints.AddConstraint(constrain); + BSConstraint constrain = null; - // zero linear and angular limits makes the objects unable to move in relation to each other - constrain.SetLinearLimits(OMV.Vector3.Zero, OMV.Vector3.Zero); - constrain.SetAngularLimits(OMV.Vector3.Zero, OMV.Vector3.Zero); - - // tweek the constraint to increase stability - constrain.UseFrameOffset(BSParam.LinkConstraintUseFrameOffset); - constrain.TranslationalLimitMotor(BSParam.LinkConstraintEnableTransMotor, - BSParam.LinkConstraintTransMotorMaxVel, - BSParam.LinkConstraintTransMotorMaxForce); - constrain.SetCFMAndERP(BSParam.LinkConstraintCFM, BSParam.LinkConstraintERP); - if (BSParam.LinkConstraintSolverIterations != 0f) + switch (liConstraint.constraintType) { - constrain.SetSolverIterations(BSParam.LinkConstraintSolverIterations); + case ConstraintType.D6_CONSTRAINT_TYPE: + // Relative position normalized to the root prim + // Essentually a vector pointing from center of rootPrim to center of li.member + OMV.Vector3 childRelativePosition = liConstraint.member.Position - rootPrim.Position; + + // real world coordinate of midpoint between the two objects + OMV.Vector3 midPoint = rootPrim.Position + (childRelativePosition / 2); + + DetailLog("{0},BSLinksetConstraint.BuildConstraint,taint,root={1},rBody={2},child={3},cBody={4},rLoc={5},cLoc={6},midLoc={7}", + rootPrim.LocalID, + rootPrim.LocalID, rootPrim.PhysBody.AddrString, + liConstraint.member.LocalID, liConstraint.member.PhysBody.AddrString, + rootPrim.Position, liConstraint.member.Position, midPoint); + + // create a constraint that allows no freedom of movement between the two objects + // http://bulletphysics.org/Bullet/phpBB3/viewtopic.php?t=4818 + + constrain = new BSConstraint6Dof( + m_physicsScene.World, rootPrim.PhysBody, liConstraint.member.PhysBody, midPoint, true, true ); + + /* NOTE: below is an attempt to build constraint with full frame computation, etc. + * Using the midpoint is easier since it lets the Bullet code manipulate the transforms + * of the objects. + * Code left for future programmers. + // ================================================================================== + // relative position normalized to the root prim + OMV.Quaternion invThisOrientation = OMV.Quaternion.Inverse(rootPrim.Orientation); + OMV.Vector3 childRelativePosition = (liConstraint.member.Position - rootPrim.Position) * invThisOrientation; + + // relative rotation of the child to the parent + OMV.Quaternion childRelativeRotation = invThisOrientation * liConstraint.member.Orientation; + OMV.Quaternion inverseChildRelativeRotation = OMV.Quaternion.Inverse(childRelativeRotation); + + DetailLog("{0},BSLinksetConstraint.PhysicallyLinkAChildToRoot,taint,root={1},child={2}", rootPrim.LocalID, rootPrim.LocalID, liConstraint.member.LocalID); + constrain = new BS6DofConstraint( + PhysicsScene.World, rootPrim.Body, liConstraint.member.Body, + OMV.Vector3.Zero, + OMV.Quaternion.Inverse(rootPrim.Orientation), + OMV.Vector3.Zero, + OMV.Quaternion.Inverse(liConstraint.member.Orientation), + true, + true + ); + // ================================================================================== + */ + + break; + default: + break; } + + liConstraint.SetConstraintParameters(constrain); + + m_physicsScene.Constraints.AddConstraint(constrain); + return constrain; } @@ -317,23 +387,24 @@ public sealed class BSLinksetConstraints : BSLinkset return; // Note the 'finally' clause at the botton which will get executed. } - foreach (BSPrimLinkable child in m_children) + ForEachLinkInfo((li) => { // A child in the linkset physically shows the mass of the whole linkset. // This allows Bullet to apply enough force on the child to move the whole linkset. // (Also do the mass stuff before recomputing the constraint so mass is not zero.) - child.UpdatePhysicalMassProperties(linksetMass, true); + li.member.UpdatePhysicalMassProperties(linksetMass, true); BSConstraint constrain; - if (!m_physicsScene.Constraints.TryGetConstraint(LinksetRoot.PhysBody, child.PhysBody, out constrain)) + if (!m_physicsScene.Constraints.TryGetConstraint(LinksetRoot.PhysBody, li.member.PhysBody, out constrain)) { // If constraint doesn't exist yet, create it. - constrain = BuildConstraint(LinksetRoot, child); + constrain = BuildConstraint(LinksetRoot, li); } constrain.RecomputeConstraintVariables(linksetMass); // PhysicsScene.PE.DumpConstraint(PhysicsScene.World, constrain.Constraint); // DEBUG DEBUG - } + return false; // 'false' says to keep processing other members + }); } finally { -- cgit v1.1 From 24df15dab7befd50f7a45eb54f001e6e481f0ec4 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Thu, 1 Aug 2013 17:43:06 -0700 Subject: BulletSim: add implementation of 'physSetLinksetType' and 'physGetLinksetType' and processing routines in BulletSim. Add linkset rebuild/conversion routine in BSLinkset. --- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 2 + .../Physics/BulletSPlugin/BSLinksetCompound.cs | 1 + .../Physics/BulletSPlugin/BSLinksetConstraints.cs | 1 + OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 44 ++++++++++++++++++++++ .../Region/Physics/BulletSPlugin/BSPrimLinkable.cs | 30 +++++++++++++++ OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 17 +++++++++ OpenSim/Region/Physics/Manager/PhysicsActor.cs | 3 +- OpenSim/Region/Physics/Manager/PhysicsScene.cs | 3 +- 8 files changed, 99 insertions(+), 2 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index 9613fe0..3afd52e 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -79,6 +79,8 @@ public abstract class BSLinkset } } + public LinksetImplementation LinksetImpl { get; protected set; } + public BSPrimLinkable LinksetRoot { get; protected set; } protected BSScene m_physicsScene { get; private set; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs index 53c3584..085d195 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs @@ -42,6 +42,7 @@ public sealed class BSLinksetCompound : BSLinkset public BSLinksetCompound(BSScene scene, BSPrimLinkable parent) : base(scene, parent) { + LinksetImpl = LinksetImplementation.Compound; } // ================================================================ diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs index d98bf77..4bac222 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs @@ -107,6 +107,7 @@ public sealed class BSLinksetConstraints : BSLinkset public BSLinksetConstraints(BSScene scene, BSPrimLinkable parent) : base(scene, parent) { + LinksetImpl = LinksetImplementation.Constraint; } // When physical properties are changed the linkset needs to recalculate diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index e92a1d2..a0b6abc 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -1541,6 +1541,50 @@ public class BSPrim : BSPhysObject PhysicalActors.RemoveDependencies(); } + #region Extension + public override object Extension(string pFunct, params object[] pParams) + { + object ret = null; + switch (pFunct) + { + case BSScene.PhysFunctGetLinksetType: + { + BSPrimLinkable myHandle = this as BSPrimLinkable; + if (myHandle != null) + { + ret = (object)myHandle.LinksetType; + } + m_log.DebugFormat("{0} Extension.physGetLinksetType, type={1}", LogHeader, ret); + break; + } + case BSScene.PhysFunctSetLinksetType: + { + if (pParams.Length > 0) + { + BSLinkset.LinksetImplementation linksetType = (BSLinkset.LinksetImplementation)pParams[0]; + BSPrimLinkable myHandle = this as BSPrimLinkable; + if (myHandle != null && myHandle.Linkset.IsRoot(myHandle)) + { + PhysScene.TaintedObject("BSPrim.PhysFunctSetLinksetType", delegate() + { + // Cause the linkset type to change + m_log.DebugFormat("{0} Extension.physSetLinksetType, oldType={1}, newType={2}", + LogHeader, myHandle.Linkset.LinksetImpl, linksetType); + myHandle.ConvertLinkset(linksetType); + }); + } + ret = (object)(int)linksetType; + } + break; + } + default: + ret = base.Extension(pFunct, pParams); + break; + } + return ret; + } + #endregion // Extension + // The physics engine says that properties have updated. Update same and inform // the world that things have changed. // NOTE: BSPrim.UpdateProperties is overloaded by BSPrimLinkable which modifies updates from root and children prims. diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs index 2f392da..c565998 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs @@ -233,5 +233,35 @@ public class BSPrimLinkable : BSPrimDisplaced base.HasSomeCollision = value; } } + + // Convert the existing linkset of this prim into a new type. + public bool ConvertLinkset(BSLinkset.LinksetImplementation newType) + { + bool ret = false; + if (LinksetType != newType) + { + BSLinkset oldLinkset = Linkset; + BSLinkset newLinkset = BSLinkset.Factory(PhysScene, this); + + // Pick up any physical dependencies this linkset might have in the physics engine. + oldLinkset.RemoveDependencies(this); + + // Copy the linkset children from the old linkset to the new (will be a new instance from the factory) + oldLinkset.ForEachLinkInfo((li) => + { + oldLinkset.RemoveMeFromLinkset(li.member); + newLinkset.AddMeToLinkset(li.member); + li.member.Linkset = newLinkset; + return false; + }); + + this.Linkset = newLinkset; + + // Force the shape and linkset to get reconstructed + newLinkset.Refresh(this); + this.ForceBodyShapeRebuild(true); + } + return ret; + } } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index 41aca3b..79ac5a5 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -862,6 +862,23 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters public override bool IsThreaded { get { return false; } } + #region Extensions + // ============================================================= + // Per scene functions. See below. + + // Per avatar functions. See BSCharacter. + + // Per prim functions. See BSPrim. + public const string PhysFunctGetLinksetType = "BulletSim.GetLinksetType"; + public const string PhysFunctSetLinksetType = "BulletSim.SetLinksetType"; + // ============================================================= + + public override object Extension(string pFunct, params object[] pParams) + { + return base.Extension(pFunct, pParams); + } + #endregion // Extensions + #region Taints // The simulation execution order is: // Simulate() diff --git a/OpenSim/Region/Physics/Manager/PhysicsActor.cs b/OpenSim/Region/Physics/Manager/PhysicsActor.cs index 2500f27..1750853 100644 --- a/OpenSim/Region/Physics/Manager/PhysicsActor.cs +++ b/OpenSim/Region/Physics/Manager/PhysicsActor.cs @@ -317,7 +317,8 @@ namespace OpenSim.Region.Physics.Manager // Extendable interface for new, physics engine specific operations public virtual object Extension(string pFunct, params object[] pParams) { - throw new NotImplementedException(); + // A NOP of the physics engine does not implement this feature + return null; } } diff --git a/OpenSim/Region/Physics/Manager/PhysicsScene.cs b/OpenSim/Region/Physics/Manager/PhysicsScene.cs index 07a1d36..c93206d 100644 --- a/OpenSim/Region/Physics/Manager/PhysicsScene.cs +++ b/OpenSim/Region/Physics/Manager/PhysicsScene.cs @@ -338,7 +338,8 @@ namespace OpenSim.Region.Physics.Manager // Extendable interface for new, physics engine specific operations public virtual object Extension(string pFunct, params object[] pParams) { - throw new NotImplementedException(); + // A NOP if the extension thing is not implemented by the physics engine + return null; } } } -- cgit v1.1 From 5bdfd55ace4b673d8aaa3f25fd4bb675b1b28263 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Fri, 2 Aug 2013 10:32:43 -0700 Subject: BulletSim: When converting linkset types, don't try to change the list of linkset children while iterating through the list. --- .../Region/Physics/BulletSPlugin/BSPrimLinkable.cs | 29 +++++++++++++++------- 1 file changed, 20 insertions(+), 9 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs index c565998..7179a6d 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs @@ -240,26 +240,37 @@ public class BSPrimLinkable : BSPrimDisplaced bool ret = false; if (LinksetType != newType) { - BSLinkset oldLinkset = Linkset; + // Set the implementation type first so the call to BSLinkset.Factory gets the new type. + this.LinksetType = newType; + + BSLinkset oldLinkset = this.Linkset; BSLinkset newLinkset = BSLinkset.Factory(PhysScene, this); + this.Linkset = newLinkset; + // Pick up any physical dependencies this linkset might have in the physics engine. oldLinkset.RemoveDependencies(this); - // Copy the linkset children from the old linkset to the new (will be a new instance from the factory) - oldLinkset.ForEachLinkInfo((li) => + // Create a list of the children (mainly because can't interate through a list that's changing) + List children = new List(); + oldLinkset.ForEachMember((child) => { - oldLinkset.RemoveMeFromLinkset(li.member); - newLinkset.AddMeToLinkset(li.member); - li.member.Linkset = newLinkset; - return false; + if (!oldLinkset.IsRoot(child)) + children.Add(child); + return false; // 'false' says to continue to next member }); - this.Linkset = newLinkset; + // Remove the children from the old linkset and add to the new (will be a new instance from the factory) + foreach (BSPrimLinkable child in children) + { + oldLinkset.RemoveMeFromLinkset(child); + newLinkset.AddMeToLinkset(child); + child.Linkset = newLinkset; + } // Force the shape and linkset to get reconstructed newLinkset.Refresh(this); - this.ForceBodyShapeRebuild(true); + this.ForceBodyShapeRebuild(true /* inTaintTime */); } return ret; } -- cgit v1.1 From 6410a25cefcb1e7f87b76f273f8c6569fbe17670 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Thu, 8 Aug 2013 13:53:12 -0700 Subject: BulletSim: adjust avatar position when the avatar's size is changed. This fixes the problem of avatars bouncing when logged in. Added a little height to the avatar height fudges to eliminate a problem of feet being in the ground a bit. --- OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs | 12 ++++++++++-- OpenSim/Region/Physics/BulletSPlugin/BSParam.cs | 4 ++-- 2 files changed, 12 insertions(+), 4 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index 58a417e..9af3dce 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -96,8 +96,8 @@ public sealed class BSCharacter : BSPhysObject m_moveActor = new BSActorAvatarMove(PhysScene, this, AvatarMoveActorName); PhysicalActors.Add(AvatarMoveActorName, m_moveActor); - DetailLog("{0},BSCharacter.create,call,size={1},scale={2},density={3},volume={4},mass={5}", - LocalID, _size, Scale, Density, _avatarVolume, RawMass); + DetailLog("{0},BSCharacter.create,call,size={1},scale={2},density={3},volume={4},mass={5},pos={6}", + LocalID, _size, Scale, Density, _avatarVolume, RawMass, pos); // do actual creation in taint time PhysScene.TaintedObject("BSCharacter.create", delegate() @@ -190,6 +190,10 @@ public sealed class BSCharacter : BSPhysObject } set { + // This is how much the avatar size is changing. Positive means getting bigger. + // The avatar altitude must be adjusted for this change. + float heightChange = value.Z - _size.Z; + _size = value; // Old versions of ScenePresence passed only the height. If width and/or depth are zero, // replace with the default values. @@ -207,6 +211,10 @@ public sealed class BSCharacter : BSPhysObject { PhysScene.PE.SetLocalScaling(PhysShape.physShapeInfo, Scale); UpdatePhysicalMassProperties(RawMass, true); + + // Adjust the avatar's position to account for the increase/decrease in size + ForcePosition = new OMV.Vector3(RawPosition.X, RawPosition.Y, RawPosition.Z + heightChange / 2f); + // Make sure this change appears as a property update event PhysScene.PE.PushUpdate(PhysBody); } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs index 4520171..fcb892a 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs @@ -570,9 +570,9 @@ public static class BSParam new ParameterDefn("AvatarHeightLowFudge", "A fudge factor to make small avatars stand on the ground", -0.2f ), new ParameterDefn("AvatarHeightMidFudge", "A fudge distance to adjust average sized avatars to be standing on ground", - 0.1f ), + 0.2f ), new ParameterDefn("AvatarHeightHighFudge", "A fudge factor to make tall avatars stand on the ground", - 0.1f ), + 0.2f ), new ParameterDefn("AvatarContactProcessingThreshold", "Distance from capsule to check for collisions", 0.1f ), new ParameterDefn("AvatarBelowGroundUpCorrectionMeters", "Meters to move avatar up if it seems to be below ground", -- cgit v1.1 From 2c31fe4614fc193f2600b36eac892ceee86f61e0 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Mon, 12 Aug 2013 13:44:53 -0700 Subject: BulletSim: add check in avatar stair step code to verify the collision is not with a volume detect object. This fixes a problem of avatars trying to step over a volume detect object that they collide with. This appeared as the avatar popping up as it started to step up but then continuing on since the object wasn't physically interacting. --- .../Physics/BulletSPlugin/BSActorAvatarMove.cs | 33 +++++++++++++--------- .../Region/Physics/BulletSPlugin/BSCharacter.cs | 1 + .../Region/Physics/BulletSPlugin/BSPhysObject.cs | 1 + OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 4 +++ 4 files changed, 26 insertions(+), 13 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs b/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs index 0f11c4a..5f232a4 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs @@ -311,21 +311,28 @@ public class BSActorAvatarMove : BSActor // Don't care about collisions with the terrain if (kvp.Key > m_physicsScene.TerrainManager.HighestTerrainID) { - OMV.Vector3 touchPosition = kvp.Value.Position; - m_physicsScene.DetailLog("{0},BSCharacter.WalkUpStairs,min={1},max={2},touch={3}", - m_controllingPrim.LocalID, nearFeetHeightMin, nearFeetHeightMax, touchPosition); - if (touchPosition.Z >= nearFeetHeightMin && touchPosition.Z <= nearFeetHeightMax) + BSPhysObject collisionObject; + if (m_physicsScene.PhysObjects.TryGetValue(kvp.Key, out collisionObject)) { - // This contact is within the 'near the feet' range. - // The normal should be our contact point to the object so it is pointing away - // thus the difference between our facing orientation and the normal should be small. - OMV.Vector3 directionFacing = OMV.Vector3.UnitX * m_controllingPrim.RawOrientation; - OMV.Vector3 touchNormal = OMV.Vector3.Normalize(kvp.Value.SurfaceNormal); - float diff = Math.Abs(OMV.Vector3.Distance(directionFacing, touchNormal)); - if (diff < BSParam.AvatarStepApproachFactor) + if (!collisionObject.IsVolumeDetect) { - if (highestTouchPosition.Z < touchPosition.Z) - highestTouchPosition = touchPosition; + OMV.Vector3 touchPosition = kvp.Value.Position; + m_physicsScene.DetailLog("{0},BSCharacter.WalkUpStairs,min={1},max={2},touch={3}", + m_controllingPrim.LocalID, nearFeetHeightMin, nearFeetHeightMax, touchPosition); + if (touchPosition.Z >= nearFeetHeightMin && touchPosition.Z <= nearFeetHeightMax) + { + // This contact is within the 'near the feet' range. + // The normal should be our contact point to the object so it is pointing away + // thus the difference between our facing orientation and the normal should be small. + OMV.Vector3 directionFacing = OMV.Vector3.UnitX * m_controllingPrim.RawOrientation; + OMV.Vector3 touchNormal = OMV.Vector3.Normalize(kvp.Value.SurfaceNormal); + float diff = Math.Abs(OMV.Vector3.Distance(directionFacing, touchNormal)); + if (diff < BSParam.AvatarStepApproachFactor) + { + if (highestTouchPosition.Z < touchPosition.Z) + highestTouchPosition = touchPosition; + } + } } } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index 9af3dce..d584782 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -404,6 +404,7 @@ public sealed class BSCharacter : BSPhysObject // Allows the detection of collisions with inherently non-physical prims. see llVolumeDetect for more public override void SetVolumeDetect(int param) { return; } + public override bool IsVolumeDetect { get { return false; } } public override OMV.Vector3 GeometricCenter { get { return OMV.Vector3.Zero; } } public override OMV.Vector3 CenterOfMass { get { return OMV.Vector3.Zero; } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index 0704591..27caf62 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -175,6 +175,7 @@ public abstract class BSPhysObject : PhysicsActor public abstract bool IsSolid { get; } public abstract bool IsStatic { get; } public abstract bool IsSelected { get; } + public abstract bool IsVolumeDetect { get; } // Materialness public MaterialAttributes.Material Material { get; private set; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index a0b6abc..6b5dea3 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -617,6 +617,10 @@ public class BSPrim : BSPhysObject } return; } + public override bool IsVolumeDetect + { + get { return _isVolumeDetect; } + } public override void SetMaterial(int material) { base.SetMaterial(material); -- cgit v1.1 From 0feb5da31e0986d46ea06ffb9804cf30f700e119 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 13 Aug 2013 21:06:24 -0700 Subject: BulletSim: move the creation of the avatar movement actor creating to taint time. Attempt to fix a problem of teleporting within the same region where the remove and addition of the physical avatar occasionally ends up with a non-moving avatar. --- OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index d584782..502f85f 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -89,13 +89,6 @@ public sealed class BSCharacter : BSPhysObject // set _avatarVolume and _mass based on capsule size, _density and Scale ComputeAvatarVolumeAndMass(); - // The avatar's movement is controlled by this motor that speeds up and slows down - // the avatar seeking to reach the motor's target speed. - // This motor runs as a prestep action for the avatar so it will keep the avatar - // standing as well as moving. Destruction of the avatar will destroy the pre-step action. - m_moveActor = new BSActorAvatarMove(PhysScene, this, AvatarMoveActorName); - PhysicalActors.Add(AvatarMoveActorName, m_moveActor); - DetailLog("{0},BSCharacter.create,call,size={1},scale={2},density={3},volume={4},mass={5},pos={6}", LocalID, _size, Scale, Density, _avatarVolume, RawMass, pos); @@ -106,6 +99,13 @@ public sealed class BSCharacter : BSPhysObject // New body and shape into PhysBody and PhysShape PhysScene.Shapes.GetBodyAndShape(true, PhysScene.World, this); + // The avatar's movement is controlled by this motor that speeds up and slows down + // the avatar seeking to reach the motor's target speed. + // This motor runs as a prestep action for the avatar so it will keep the avatar + // standing as well as moving. Destruction of the avatar will destroy the pre-step action. + m_moveActor = new BSActorAvatarMove(PhysScene, this, AvatarMoveActorName); + PhysicalActors.Add(AvatarMoveActorName, m_moveActor); + SetPhysicalProperties(); }); return; -- cgit v1.1 From 7c3b71d294987943058c8b3bcb18a424ca70dea5 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Wed, 14 Aug 2013 14:13:08 -0700 Subject: BulletSim: add physical object initialized flag so updates and collisions don't happen until the object is completely initialized. This fixes the problem of doing a teleport while the simulator is running. The destruction of the physical object while the engine is running means that the physics parameter update would overwrite the new position of the newly created avatar. --- OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs | 4 +++- OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs | 4 ++++ OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs | 4 ++++ OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 4 ++++ OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 12 ++++++++---- 5 files changed, 23 insertions(+), 5 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs b/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs index 5f232a4..c0589cd 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs @@ -69,7 +69,9 @@ public class BSActorAvatarMove : BSActor // BSActor.Dispose() public override void Dispose() { - Enabled = false; + base.SetEnabled(false); + // Now that turned off, remove any state we have in the scene. + Refresh(); } // Called when physical parameters (properties set in Bullet) need to be re-applied. diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index 502f85f..291dfcd 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -107,6 +107,8 @@ public sealed class BSCharacter : BSPhysObject PhysicalActors.Add(AvatarMoveActorName, m_moveActor); SetPhysicalProperties(); + + IsInitialized = true; }); return; } @@ -114,6 +116,8 @@ public sealed class BSCharacter : BSPhysObject // called when this character is being destroyed and the resources should be released public override void Destroy() { + IsInitialized = false; + base.Destroy(); DetailLog("{0},BSCharacter.Destroy", LocalID); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index 27caf62..b26fef0 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -72,6 +72,8 @@ public abstract class BSPhysObject : PhysicsActor } protected BSPhysObject(BSScene parentScene, uint localID, string name, string typeName) { + IsInitialized = false; + PhysScene = parentScene; LocalID = localID; PhysObjectName = name; @@ -130,6 +132,8 @@ public abstract class BSPhysObject : PhysicsActor public string PhysObjectName { get; protected set; } public string TypeName { get; protected set; } + // Set to 'true' when the object is completely initialized + public bool IsInitialized { get; protected set; } // Return the object mass without calculating it or having side effects public abstract float RawMass { get; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 6b5dea3..d5b999d 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -110,6 +110,8 @@ public class BSPrim : BSPhysObject CreateGeomAndObject(true); CurrentCollisionFlags = PhysScene.PE.GetCollisionFlags(PhysBody); + + IsInitialized = true; }); } @@ -117,6 +119,8 @@ public class BSPrim : BSPhysObject public override void Destroy() { // m_log.DebugFormat("{0}: Destroy, id={1}", LogHeader, LocalID); + IsInitialized = false; + base.Destroy(); // Undo any vehicle properties diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index 79ac5a5..88d50b4 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -639,7 +639,8 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters BSPhysObject pobj; if (PhysObjects.TryGetValue(entprop.ID, out pobj)) { - pobj.UpdateProperties(entprop); + if (pobj.IsInitialized) + pobj.UpdateProperties(entprop); } } } @@ -766,10 +767,13 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters // DetailLog("{0},BSScene.SendCollision,collide,id={1},with={2}", DetailLogZero, localID, collidingWith); - if (collider.Collide(collidingWith, collidee, collidePoint, collideNormal, penetration)) + if (collider.IsInitialized) { - // If a collision was 'good', remember to send it to the simulator - ObjectsWithCollisions.Add(collider); + if (collider.Collide(collidingWith, collidee, collidePoint, collideNormal, penetration)) + { + // If a collision was 'good', remember to send it to the simulator + ObjectsWithCollisions.Add(collider); + } } return; -- cgit v1.1 From e8b1e91a1d4bb3ca65886c367c654a82033f4e03 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Wed, 14 Aug 2013 14:36:13 -0700 Subject: BulletSim: include check for volume detect in check for zeroing avatar motion. Normally, avatar motion is zeroed if colliding with a stationary object so they don't slide down hills and such. Without volume detect check this also allowed avatars to stand on volume detect objects and to have some jiggling when they were in the volume detect object. This commit fixes both. --- OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs | 2 +- OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs | 6 +++++- 2 files changed, 6 insertions(+), 2 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs b/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs index c0589cd..68bc1b9 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs @@ -183,7 +183,7 @@ public class BSActorAvatarMove : BSActor if (m_controllingPrim.IsColliding) { // If we are colliding with a stationary object, presume we're standing and don't move around - if (!m_controllingPrim.ColliderIsMoving) + if (!m_controllingPrim.ColliderIsMoving && !m_controllingPrim.ColliderIsVolumeDetect) { m_physicsScene.DetailLog("{0},BSCharacter.MoveMotor,collidingWithStationary,zeroingMotion", m_controllingPrim.LocalID); m_controllingPrim.IsStationary = true; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index b26fef0..9dc52d5 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -132,7 +132,8 @@ public abstract class BSPhysObject : PhysicsActor public string PhysObjectName { get; protected set; } public string TypeName { get; protected set; } - // Set to 'true' when the object is completely initialized + // Set to 'true' when the object is completely initialized. + // This mostly prevents property updates and collisions until the object is completely here. public bool IsInitialized { get; protected set; } // Return the object mass without calculating it or having side effects @@ -356,6 +357,8 @@ public abstract class BSPhysObject : PhysicsActor // On a collision, check the collider and remember if the last collider was moving // Used to modify the standing of avatars (avatars on stationary things stand still) public bool ColliderIsMoving; + // 'true' if the last collider was a volume detect object + public bool ColliderIsVolumeDetect; // Used by BSCharacter to manage standing (and not slipping) public bool IsStationary; @@ -435,6 +438,7 @@ public abstract class BSPhysObject : PhysicsActor // For movement tests, remember if we are colliding with an object that is moving. ColliderIsMoving = collidee != null ? (collidee.RawVelocity != OMV.Vector3.Zero) : false; + ColliderIsVolumeDetect = collidee != null ? (collidee.IsVolumeDetect) : false; // Make a collection of the collisions that happened the last simulation tick. // This is different than the collection created for sending up to the simulator as it is cleared every tick. -- cgit v1.1 From a6af561660759ef7625d88213b7d43b76e687280 Mon Sep 17 00:00:00 2001 From: teravus Date: Tue, 20 Aug 2013 21:09:17 -0500 Subject: * Fix some threading issues in BulletXNA (the managed bullet library), this should better allow you to run it in multiple region scenarios (but why would you really want to do that?) Source in OpenSimLibs. * Fixed a null ref during shutdown. --- OpenSim/Region/Physics/BulletSPlugin/BSAPIXNA.cs | 46 +++++++++++++++++++++++- 1 file changed, 45 insertions(+), 1 deletion(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSAPIXNA.cs b/OpenSim/Region/Physics/BulletSPlugin/BSAPIXNA.cs index 6db5f5e..2a820be 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSAPIXNA.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSAPIXNA.cs @@ -1221,6 +1221,50 @@ private sealed class BulletConstraintXNA : BulletConstraint //BSParam.TerrainImplementation = 0; world.SetGravity(new IndexedVector3(0,0,p.gravity)); + // Turn off Pooling since globals and pooling are bad for threading. + BulletGlobals.VoronoiSimplexSolverPool.SetPoolingEnabled(false); + BulletGlobals.SubSimplexConvexCastPool.SetPoolingEnabled(false); + BulletGlobals.ManifoldPointPool.SetPoolingEnabled(false); + BulletGlobals.CastResultPool.SetPoolingEnabled(false); + BulletGlobals.SphereShapePool.SetPoolingEnabled(false); + BulletGlobals.DbvtNodePool.SetPoolingEnabled(false); + BulletGlobals.SingleRayCallbackPool.SetPoolingEnabled(false); + BulletGlobals.SubSimplexClosestResultPool.SetPoolingEnabled(false); + BulletGlobals.GjkPairDetectorPool.SetPoolingEnabled(false); + BulletGlobals.DbvtTreeColliderPool.SetPoolingEnabled(false); + BulletGlobals.SingleSweepCallbackPool.SetPoolingEnabled(false); + BulletGlobals.BroadphaseRayTesterPool.SetPoolingEnabled(false); + BulletGlobals.ClosestNotMeConvexResultCallbackPool.SetPoolingEnabled(false); + BulletGlobals.GjkEpaPenetrationDepthSolverPool.SetPoolingEnabled(false); + BulletGlobals.ContinuousConvexCollisionPool.SetPoolingEnabled(false); + BulletGlobals.DbvtStackDataBlockPool.SetPoolingEnabled(false); + + BulletGlobals.BoxBoxCollisionAlgorithmPool.SetPoolingEnabled(false); + BulletGlobals.CompoundCollisionAlgorithmPool.SetPoolingEnabled(false); + BulletGlobals.ConvexConcaveCollisionAlgorithmPool.SetPoolingEnabled(false); + BulletGlobals.ConvexConvexAlgorithmPool.SetPoolingEnabled(false); + BulletGlobals.ConvexPlaneAlgorithmPool.SetPoolingEnabled(false); + BulletGlobals.SphereBoxCollisionAlgorithmPool.SetPoolingEnabled(false); + BulletGlobals.SphereSphereCollisionAlgorithmPool.SetPoolingEnabled(false); + BulletGlobals.SphereTriangleCollisionAlgorithmPool.SetPoolingEnabled(false); + BulletGlobals.GImpactCollisionAlgorithmPool.SetPoolingEnabled(false); + BulletGlobals.GjkEpaSolver2MinkowskiDiffPool.SetPoolingEnabled(false); + BulletGlobals.PersistentManifoldPool.SetPoolingEnabled(false); + BulletGlobals.ManifoldResultPool.SetPoolingEnabled(false); + BulletGlobals.GJKPool.SetPoolingEnabled(false); + BulletGlobals.GIM_ShapeRetrieverPool.SetPoolingEnabled(false); + BulletGlobals.TriangleShapePool.SetPoolingEnabled(false); + BulletGlobals.SphereTriangleDetectorPool.SetPoolingEnabled(false); + BulletGlobals.CompoundLeafCallbackPool.SetPoolingEnabled(false); + BulletGlobals.GjkConvexCastPool.SetPoolingEnabled(false); + BulletGlobals.LocalTriangleSphereCastCallbackPool.SetPoolingEnabled(false); + BulletGlobals.BridgeTriangleRaycastCallbackPool.SetPoolingEnabled(false); + BulletGlobals.BridgeTriangleConcaveRaycastCallbackPool.SetPoolingEnabled(false); + BulletGlobals.BridgeTriangleConvexcastCallbackPool.SetPoolingEnabled(false); + BulletGlobals.MyNodeOverlapCallbackPool.SetPoolingEnabled(false); + BulletGlobals.ClosestRayResultCallbackPool.SetPoolingEnabled(false); + BulletGlobals.DebugDrawcallbackPool.SetPoolingEnabled(false); + return world; } //m_constraint.ptr, ConstraintParams.BT_CONSTRAINT_STOP_CFM, cfm, ConstraintParamAxis.AXIS_ALL @@ -1914,7 +1958,7 @@ private sealed class BulletConstraintXNA : BulletConstraint heightMap, scaleFactor, minHeight, maxHeight, upAxis, false); - terrainShape.SetMargin(collisionMargin + 0.5f); + terrainShape.SetMargin(collisionMargin); terrainShape.SetUseDiamondSubdivision(true); terrainShape.SetUserPointer(id); return new BulletShapeXNA(terrainShape, BSPhysicsShapeType.SHAPE_TERRAIN); -- cgit v1.1 From 0882cf0fc32dac05d0e762abf68d6956305543bc Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 27 Aug 2013 09:55:50 -0700 Subject: BulletSim: add some protections for processing when shutting down. Attempt to fix Mantis 6740 (http://opensimulator.org/mantis/view.php?id=6740). --- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index 88d50b4..c92c9b9 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -946,7 +946,7 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters private void ProcessRegularTaints() { - if (_taintOperations.Count > 0) // save allocating new list if there is nothing to process + if (m_initialized && _taintOperations.Count > 0) // save allocating new list if there is nothing to process { // swizzle a new list into the list location so we can process what's there List oldList; @@ -989,7 +989,7 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters // Taints that happen after the normal taint processing but before the simulation step. private void ProcessPostTaintTaints() { - if (_postTaintOperations.Count > 0) + if (m_initialized && _postTaintOperations.Count > 0) { Dictionary oldList; lock (_taintLock) -- cgit v1.1 From 725751fd6c0101b8610e84716d28b6af91e20b61 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 6 Aug 2013 10:32:56 -0700 Subject: BulletSim: fixes for change linkset implementation of physical linksets. --- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 6 +++--- OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs | 14 +++++++------- .../Region/Physics/BulletSPlugin/BSLinksetConstraints.cs | 8 ++++---- OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs | 11 ++++++++--- 4 files changed, 22 insertions(+), 17 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index 3afd52e..a051002 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -148,7 +148,7 @@ public abstract class BSLinkset // Returns a new linkset for the child which is a linkset of one (just the // orphened child). // Called at runtime. - public BSLinkset RemoveMeFromLinkset(BSPrimLinkable child) + public BSLinkset RemoveMeFromLinkset(BSPrimLinkable child, bool inTaintTime) { lock (m_linksetActivityLock) { @@ -157,7 +157,7 @@ public abstract class BSLinkset // Cannot remove the root from a linkset. return this; } - RemoveChildFromLinkset(child); + RemoveChildFromLinkset(child, inTaintTime); LinksetMass = ComputeLinksetMass(); } @@ -255,7 +255,7 @@ public abstract class BSLinkset // I am the root of a linkset and one of my children is being removed. // Safe to call even if the child is not really in my linkset. - protected abstract void RemoveChildFromLinkset(BSPrimLinkable child); + protected abstract void RemoveChildFromLinkset(BSPrimLinkable child, bool inTaintTime); // When physical properties are changed the linkset needs to recalculate // its internal properties. diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs index 085d195..47ab842 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs @@ -242,7 +242,7 @@ public sealed class BSLinksetCompound : BSLinkset { bool ret = false; - DetailLog("{0},BSLinksetCompound.RemoveBodyDependencies,refreshIfChild,rID={1},rBody={2},isRoot={3}", + DetailLog("{0},BSLinksetCompound.RemoveDependencies,refreshIfChild,rID={1},rBody={2},isRoot={3}", child.LocalID, LinksetRoot.LocalID, LinksetRoot.PhysBody, IsRoot(child)); ScheduleRebuild(child); @@ -270,7 +270,7 @@ public sealed class BSLinksetCompound : BSLinkset // Remove the specified child from the linkset. // Safe to call even if the child is not really in the linkset. - protected override void RemoveChildFromLinkset(BSPrimLinkable child) + protected override void RemoveChildFromLinkset(BSPrimLinkable child, bool inTaintTime) { child.ClearDisplacement(); @@ -282,12 +282,12 @@ public sealed class BSLinksetCompound : BSLinkset child.LocalID, child.PhysBody.AddrString); // Cause the child's body to be rebuilt and thus restored to normal operation - child.ForceBodyShapeRebuild(false); + child.ForceBodyShapeRebuild(inTaintTime); if (!HasAnyChildren) { // The linkset is now empty. The root needs rebuilding. - LinksetRoot.ForceBodyShapeRebuild(false); + LinksetRoot.ForceBodyShapeRebuild(inTaintTime); } else { @@ -318,10 +318,10 @@ public sealed class BSLinksetCompound : BSLinkset // being destructed and going non-physical. LinksetRoot.ForceBodyShapeRebuild(true); - // There is no reason to build all this physical stuff for a non-physical linkset. - if (!LinksetRoot.IsPhysicallyActive) + // There is no reason to build all this physical stuff for a non-physical or empty linkset. + if (!LinksetRoot.IsPhysicallyActive || !HasAnyChildren) { - DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,notPhysical", LinksetRoot.LocalID); + DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,notPhysicalOrNoChildren", LinksetRoot.LocalID); return; // Note the 'finally' clause at the botton which will get executed. } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs index 4bac222..d4ee27d 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs @@ -224,7 +224,7 @@ public sealed class BSLinksetConstraints : BSLinkset // Remove the specified child from the linkset. // Safe to call even if the child is not really in my linkset. - protected override void RemoveChildFromLinkset(BSPrimLinkable child) + protected override void RemoveChildFromLinkset(BSPrimLinkable child, bool inTaintTime) { if (m_children.Remove(child)) { @@ -236,7 +236,7 @@ public sealed class BSLinksetConstraints : BSLinkset rootx.LocalID, rootx.PhysBody.AddrString, childx.LocalID, childx.PhysBody.AddrString); - m_physicsScene.TaintedObject("BSLinksetConstraints.RemoveChildFromLinkset", delegate() + m_physicsScene.TaintedObject(inTaintTime, "BSLinksetConstraints.RemoveChildFromLinkset", delegate() { PhysicallyUnlinkAChildFromRoot(rootx, childx); }); @@ -382,9 +382,9 @@ public sealed class BSLinksetConstraints : BSLinkset Rebuilding = true; // There is no reason to build all this physical stuff for a non-physical linkset. - if (!LinksetRoot.IsPhysicallyActive) + if (!LinksetRoot.IsPhysicallyActive || !HasAnyChildren) { - DetailLog("{0},BSLinksetConstraint.RecomputeLinksetCompound,notPhysical", LinksetRoot.LocalID); + DetailLog("{0},BSLinksetConstraint.RecomputeLinksetCompound,notPhysicalOrNoChildren", LinksetRoot.LocalID); return; // Note the 'finally' clause at the botton which will get executed. } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs index 7179a6d..38d1f88 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs @@ -66,7 +66,7 @@ public class BSPrimLinkable : BSPrimDisplaced public override void Destroy() { - Linkset = Linkset.RemoveMeFromLinkset(this); + Linkset = Linkset.RemoveMeFromLinkset(this, false /* inTaintTime */); base.Destroy(); } @@ -94,7 +94,7 @@ public class BSPrimLinkable : BSPrimDisplaced BSPhysObject parentBefore = Linkset.LinksetRoot; // DEBUG int childrenBefore = Linkset.NumberOfChildren; // DEBUG - Linkset = Linkset.RemoveMeFromLinkset(this); + Linkset = Linkset.RemoveMeFromLinkset(this, false /* inTaintTime*/); DetailLog("{0},BSPrimLinkset.delink,parentBefore={1},childrenBefore={2},parentAfter={3},childrenAfter={4}, ", LocalID, parentBefore.LocalID, childrenBefore, Linkset.LinksetRoot.LocalID, Linkset.NumberOfChildren); @@ -240,6 +240,8 @@ public class BSPrimLinkable : BSPrimDisplaced bool ret = false; if (LinksetType != newType) { + DetailLog("{0},BSPrimLinkset.ConvertLinkset,oldT={1},newT={2}", LocalID, LinksetType, newType); + // Set the implementation type first so the call to BSLinkset.Factory gets the new type. this.LinksetType = newType; @@ -263,7 +265,10 @@ public class BSPrimLinkable : BSPrimDisplaced // Remove the children from the old linkset and add to the new (will be a new instance from the factory) foreach (BSPrimLinkable child in children) { - oldLinkset.RemoveMeFromLinkset(child); + oldLinkset.RemoveMeFromLinkset(child, true /*inTaintTime*/); + } + foreach (BSPrimLinkable child in children) + { newLinkset.AddMeToLinkset(child); child.Linkset = newLinkset; } -- cgit v1.1 From 48ee73bfa771de64685a694417b34188f0a3350e Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Wed, 7 Aug 2013 07:54:47 -0700 Subject: BulletSim: add API and calls for spring constraint parameters. --- OpenSim/Region/Physics/BulletSPlugin/BSAPIUnman.cs | 36 ++++++++++++++++++++ OpenSim/Region/Physics/BulletSPlugin/BSAPIXNA.cs | 38 ++++++++++++++++++++++ .../Region/Physics/BulletSPlugin/BSApiTemplate.cs | 8 +++++ 3 files changed, 82 insertions(+) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSAPIUnman.cs b/OpenSim/Region/Physics/BulletSPlugin/BSAPIUnman.cs index 12a0c17..6c36485 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSAPIUnman.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSAPIUnman.cs @@ -596,6 +596,30 @@ public override bool SetBreakingImpulseThreshold(BulletConstraint constrain, flo return BSAPICPP.SetBreakingImpulseThreshold2(constrainu.ptr, threshold); } +public override bool SpringEnable(BulletConstraint constrain, int index, float numericTrueFalse) +{ + BulletConstraintUnman constrainu = constrain as BulletConstraintUnman; + return BSAPICPP.ConstraintSpringEnable2(constrainu.ptr, index, numericTrueFalse); +} + +public override bool SpringSetEquilibriumPoint(BulletConstraint constrain, int index, float equilibriumPoint) +{ + BulletConstraintUnman constrainu = constrain as BulletConstraintUnman; + return BSAPICPP.ConstraintSpringSetEquilibriumPoint2(constrainu.ptr, index, equilibriumPoint); +} + +public override bool SpringSetStiffness(BulletConstraint constrain, int index, float stiffnesss) +{ + BulletConstraintUnman constrainu = constrain as BulletConstraintUnman; + return BSAPICPP.ConstraintSpringSetStiffness2(constrainu.ptr, index, stiffnesss); +} + +public override bool SpringSetDamping(BulletConstraint constrain, int index, float damping) +{ + BulletConstraintUnman constrainu = constrain as BulletConstraintUnman; + return BSAPICPP.ConstraintSpringSetDamping2(constrainu.ptr, index, damping); +} + public override bool CalculateTransforms(BulletConstraint constrain) { BulletConstraintUnman constrainu = constrain as BulletConstraintUnman; @@ -1601,6 +1625,18 @@ public static extern bool TranslationalLimitMotor2(IntPtr constrain, float enabl public static extern bool SetBreakingImpulseThreshold2(IntPtr constrain, float threshold); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern bool ConstraintSpringEnable2(IntPtr constrain, int index, float numericTrueFalse); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern bool ConstraintSpringSetEquilibriumPoint2(IntPtr constrain, int index, float equilibriumPoint); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern bool ConstraintSpringSetStiffness2(IntPtr constrain, int index, float stiffness); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern bool ConstraintSpringSetDamping2(IntPtr constrain, int index, float damping); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern bool CalculateTransforms2(IntPtr constrain); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSAPIXNA.cs b/OpenSim/Region/Physics/BulletSPlugin/BSAPIXNA.cs index 2a820be..9ad12a9 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSAPIXNA.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSAPIXNA.cs @@ -752,6 +752,44 @@ private sealed class BulletConstraintXNA : BulletConstraint constraint.SetBreakingImpulseThreshold(threshold); return true; } + public override bool SpringEnable(BulletConstraint pConstraint, int index, float numericTrueFalse) + { + Generic6DofSpringConstraint constraint = (pConstraint as BulletConstraintXNA).constrain as Generic6DofSpringConstraint; + constraint.EnableSpring(index, (numericTrueFalse == 0f ? false : true)); + return true; + } + + public override bool SpringSetEquilibriumPoint(BulletConstraint pConstraint, int index, float equilibriumPoint) + { + Generic6DofSpringConstraint constraint = (pConstraint as BulletConstraintXNA).constrain as Generic6DofSpringConstraint; + if (index == -1) + { + constraint.SetEquilibriumPoint(); + } + else + { + if (equilibriumPoint == -1) + constraint.SetEquilibriumPoint(index); + else + constraint.SetEquilibriumPoint(index, equilibriumPoint); + } + return true; + } + + public override bool SpringSetStiffness(BulletConstraint pConstraint, int index, float stiffness) + { + Generic6DofSpringConstraint constraint = (pConstraint as BulletConstraintXNA).constrain as Generic6DofSpringConstraint; + constraint.SetStiffness(index, stiffness); + return true; + } + + public override bool SpringSetDamping(BulletConstraint pConstraint, int index, float damping) + { + Generic6DofSpringConstraint constraint = (pConstraint as BulletConstraintXNA).constrain as Generic6DofSpringConstraint; + constraint.SetDamping(index, damping); + return true; + } + //BulletSimAPI.SetAngularDamping(Prim.PhysBody.ptr, angularDamping); public override void SetAngularDamping(BulletBody pBody, float angularDamping) { diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSApiTemplate.cs b/OpenSim/Region/Physics/BulletSPlugin/BSApiTemplate.cs index 6cdc112..8cca29f 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSApiTemplate.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSApiTemplate.cs @@ -441,6 +441,14 @@ public abstract bool TranslationalLimitMotor(BulletConstraint constrain, float e public abstract bool SetBreakingImpulseThreshold(BulletConstraint constrain, float threshold); +public abstract bool SpringEnable(BulletConstraint constrain, int index, float numericTrueFalse); + +public abstract bool SpringSetEquilibriumPoint(BulletConstraint constrain, int index, float equilibriumPoint); + +public abstract bool SpringSetStiffness(BulletConstraint constrain, int index, float stiffnesss); + +public abstract bool SpringSetDamping(BulletConstraint constrain, int index, float damping); + public abstract bool CalculateTransforms(BulletConstraint constrain); public abstract bool SetConstraintParam(BulletConstraint constrain, ConstraintParams paramIndex, float value, ConstraintParamAxis axis); -- cgit v1.1 From 9a7d0e489cf726f00379917cd507839d5fe56725 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Wed, 7 Aug 2013 07:55:46 -0700 Subject: BulletSim: add spring constraint to linkset constraint types. --- .../Physics/BulletSPlugin/BSConstraintSpring.cs | 85 ++++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100755 OpenSim/Region/Physics/BulletSPlugin/BSConstraintSpring.cs (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSConstraintSpring.cs b/OpenSim/Region/Physics/BulletSPlugin/BSConstraintSpring.cs new file mode 100755 index 0000000..01d67d4 --- /dev/null +++ b/OpenSim/Region/Physics/BulletSPlugin/BSConstraintSpring.cs @@ -0,0 +1,85 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyrightD + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +using System; +using System.Collections.Generic; +using System.Text; +using OpenMetaverse; + +namespace OpenSim.Region.Physics.BulletSPlugin +{ + +public sealed class BSConstraintSpring : BSConstraint6Dof +{ + public override ConstraintType Type { get { return ConstraintType.D6_SPRING_CONSTRAINT_TYPE; } } + + public BSConstraintSpring(BulletWorld world, BulletBody obj1, BulletBody obj2, + Vector3 frame1Loc, Quaternion frame1Rot, + Vector3 frame2Loc, Quaternion frame2Rot, + bool useLinearReferenceFrameA, bool disableCollisionsBetweenLinkedBodies) + :base(world, obj1, obj2) + { + m_constraint = PhysicsScene.PE.Create6DofSpringConstraint(world, obj1, obj2, + frame1Loc, frame1Rot, frame2Loc, frame2Rot, + useLinearReferenceFrameA, disableCollisionsBetweenLinkedBodies); + m_enabled = true; + + world.physicsScene.DetailLog("{0},BSConstraintSpring,createFrame,wID={1}, rID={2}, rBody={3}, cID={4}, cBody={5}", + BSScene.DetailLogZero, world.worldID, + obj1.ID, obj1.AddrString, obj2.ID, obj2.AddrString); + } + + public bool SetEnable(int index, bool axisEnable) + { + bool ret = false; + + return ret; + } + + public bool SetStiffness(int index, float stiffness) + { + bool ret = false; + + return ret; + } + + public bool SetDamping(int index, float damping) + { + bool ret = false; + + return ret; + } + + public bool SetEquilibriumPoint(int index, float eqPoint) + { + bool ret = false; + + return ret; + } + +} + +} \ No newline at end of file -- cgit v1.1 From 0971c7ae77cae3d238be31f46994b4692af949e3 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Wed, 7 Aug 2013 07:56:37 -0700 Subject: BulletSim: complete linkage of spring constraint into linkset constraint. --- .../Physics/BulletSPlugin/BSConstraint6Dof.cs | 9 ++- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 2 + .../Physics/BulletSPlugin/BSLinksetConstraints.cs | 81 ++++++++++++++++++---- 3 files changed, 77 insertions(+), 15 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSConstraint6Dof.cs b/OpenSim/Region/Physics/BulletSPlugin/BSConstraint6Dof.cs index d0949f5..5008ff7 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSConstraint6Dof.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSConstraint6Dof.cs @@ -32,12 +32,19 @@ using OpenMetaverse; namespace OpenSim.Region.Physics.BulletSPlugin { -public sealed class BSConstraint6Dof : BSConstraint +public class BSConstraint6Dof : BSConstraint { private static string LogHeader = "[BULLETSIM 6DOF CONSTRAINT]"; public override ConstraintType Type { get { return ConstraintType.D6_CONSTRAINT_TYPE; } } + public BSConstraint6Dof(BulletWorld world, BulletBody obj1, BulletBody obj2) :base(world) + { + m_body1 = obj1; + m_body2 = obj2; + m_enabled = false; + } + // Create a btGeneric6DofConstraint public BSConstraint6Dof(BulletWorld world, BulletBody obj1, BulletBody obj2, Vector3 frame1, Quaternion frame1rot, diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index a051002..d4b1c1e 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -77,6 +77,8 @@ public abstract class BSLinkset { member = pMember; } + public virtual void ResetLink() { } + public virtual void SetLinkParameters(BSConstraint constrain) { } } public LinksetImplementation LinksetImpl { get; protected set; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs index d4ee27d..f3b70c3 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs @@ -51,16 +51,26 @@ public sealed class BSLinksetConstraints : BSLinkset public float cfm; public float erp; public float solverIterations; + // + public OMV.Vector3 frameInAloc; + public OMV.Quaternion frameInArot; + public OMV.Vector3 frameInBloc; + public OMV.Quaternion frameInBrot; + // Spring + public float springDamping; + public float springStiffness; + + public BSLinkInfoConstraint(BSPrimLinkable pMember) : base(pMember) { constraint = null; - ResetToFixedConstraint(); + ResetLink(); } // Set all the parameters for this constraint to a fixed, non-movable constraint. - public void ResetToFixedConstraint() + public override void ResetLink() { constraintType = ConstraintType.D6_CONSTRAINT_TYPE; linearLimitLow = OMV.Vector3.Zero; @@ -74,10 +84,16 @@ public sealed class BSLinksetConstraints : BSLinkset cfm = BSParam.LinkConstraintCFM; erp = BSParam.LinkConstraintERP; solverIterations = BSParam.LinkConstraintSolverIterations; + frameInAloc = OMV.Vector3.Zero; + frameInArot = OMV.Quaternion.Identity; + frameInBloc = OMV.Vector3.Zero; + frameInBrot = OMV.Quaternion.Identity; + springDamping = -1f; + springStiffness = -1f; } // Given a constraint, apply the current constraint parameters to same. - public void SetConstraintParameters(BSConstraint constrain) + public override void SetLinkParameters(BSConstraint constrain) { switch (constraintType) { @@ -85,6 +101,7 @@ public sealed class BSLinksetConstraints : BSLinkset BSConstraint6Dof constrain6dof = constrain as BSConstraint6Dof; if (constrain6dof != null) { + // NOTE: D6_SPRING_CONSTRAINT_TYPE should be updated if you change any of this code. // zero linear and angular limits makes the objects unable to move in relation to each other constrain6dof.SetLinearLimits(linearLimitLow, linearLimitHigh); constrain6dof.SetAngularLimits(angularLimitLow, angularLimitHigh); @@ -99,6 +116,31 @@ public sealed class BSLinksetConstraints : BSLinkset } } break; + case ConstraintType.D6_SPRING_CONSTRAINT_TYPE: + BSConstraintSpring constrainSpring = constrain as BSConstraintSpring; + if (constrainSpring != null) + { + // zero linear and angular limits makes the objects unable to move in relation to each other + constrainSpring.SetLinearLimits(linearLimitLow, linearLimitHigh); + constrainSpring.SetAngularLimits(angularLimitLow, angularLimitHigh); + + // tweek the constraint to increase stability + constrainSpring.UseFrameOffset(useFrameOffset); + constrainSpring.TranslationalLimitMotor(enableTransMotor, transMotorMaxVel, transMotorMaxForce); + constrainSpring.SetCFMAndERP(cfm, erp); + if (solverIterations != 0f) + { + constrainSpring.SetSolverIterations(solverIterations); + } + for (int ii = 0; ii < 6; ii++) + { + if (springDamping != -1) + constrainSpring.SetDamping(ii, springDamping); + if (springStiffness != -1) + constrainSpring.SetStiffness(ii, springStiffness); + } + } + break; default: break; } @@ -262,8 +304,8 @@ public sealed class BSLinksetConstraints : BSLinkset // Create a static constraint between the two passed objects private BSConstraint BuildConstraint(BSPrimLinkable rootPrim, BSLinkInfo li) { - BSLinkInfoConstraint liConstraint = li as BSLinkInfoConstraint; - if (liConstraint == null) + BSLinkInfoConstraint linkInfo = li as BSLinkInfoConstraint; + if (linkInfo == null) return null; // Zero motion for children so they don't interpolate @@ -271,27 +313,25 @@ public sealed class BSLinksetConstraints : BSLinkset BSConstraint constrain = null; - switch (liConstraint.constraintType) + switch (linkInfo.constraintType) { case ConstraintType.D6_CONSTRAINT_TYPE: // Relative position normalized to the root prim // Essentually a vector pointing from center of rootPrim to center of li.member - OMV.Vector3 childRelativePosition = liConstraint.member.Position - rootPrim.Position; + OMV.Vector3 childRelativePosition = linkInfo.member.Position - rootPrim.Position; // real world coordinate of midpoint between the two objects OMV.Vector3 midPoint = rootPrim.Position + (childRelativePosition / 2); - DetailLog("{0},BSLinksetConstraint.BuildConstraint,taint,root={1},rBody={2},child={3},cBody={4},rLoc={5},cLoc={6},midLoc={7}", - rootPrim.LocalID, - rootPrim.LocalID, rootPrim.PhysBody.AddrString, - liConstraint.member.LocalID, liConstraint.member.PhysBody.AddrString, - rootPrim.Position, liConstraint.member.Position, midPoint); + DetailLog("{0},BSLinksetConstraint.BuildConstraint,6Dof,rBody={1},cBody={2},rLoc={3},cLoc={4},midLoc={7}", + rootPrim.LocalID, rootPrim.PhysBody, linkInfo.member.PhysBody, + rootPrim.Position, linkInfo.member.Position, midPoint); // create a constraint that allows no freedom of movement between the two objects // http://bulletphysics.org/Bullet/phpBB3/viewtopic.php?t=4818 constrain = new BSConstraint6Dof( - m_physicsScene.World, rootPrim.PhysBody, liConstraint.member.PhysBody, midPoint, true, true ); + m_physicsScene.World, rootPrim.PhysBody, linkInfo.member.PhysBody, midPoint, true, true ); /* NOTE: below is an attempt to build constraint with full frame computation, etc. * Using the midpoint is easier since it lets the Bullet code manipulate the transforms @@ -320,11 +360,23 @@ public sealed class BSLinksetConstraints : BSLinkset */ break; + case ConstraintType.D6_SPRING_CONSTRAINT_TYPE: + constrain = new BSConstraintSpring(m_physicsScene.World, rootPrim.PhysBody, linkInfo.member.PhysBody, + linkInfo.frameInAloc, linkInfo.frameInArot, linkInfo.frameInBloc, linkInfo.frameInBrot, + true /*useLinearReferenceFrameA*/, + true /*disableCollisionsBetweenLinkedBodies*/); + DetailLog("{0},BSLinksetConstraint.BuildConstraint,spring,root={1},rBody={2},child={3},cBody={4},rLoc={5},cLoc={6},midLoc={7}", + rootPrim.LocalID, + rootPrim.LocalID, rootPrim.PhysBody.AddrString, + linkInfo.member.LocalID, linkInfo.member.PhysBody.AddrString, + rootPrim.Position, linkInfo.member.Position); + + break; default: break; } - liConstraint.SetConstraintParameters(constrain); + linkInfo.SetLinkParameters(constrain); m_physicsScene.Constraints.AddConstraint(constrain); @@ -401,6 +453,7 @@ public sealed class BSLinksetConstraints : BSLinkset // If constraint doesn't exist yet, create it. constrain = BuildConstraint(LinksetRoot, li); } + li.SetLinkParameters(constrain); constrain.RecomputeConstraintVariables(linksetMass); // PhysicsScene.PE.DumpConstraint(PhysicsScene.World, constrain.Constraint); // DEBUG DEBUG -- cgit v1.1 From 993bcec088ce5c3ec2f76f61842f19cbdcc89384 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Wed, 7 Aug 2013 10:15:28 -0700 Subject: BulletSim: add unmanaged and XNA functions for hinge, slider and spring constraints. --- OpenSim/Region/Physics/BulletSPlugin/BSAPIUnman.cs | 45 ++++++ OpenSim/Region/Physics/BulletSPlugin/BSAPIXNA.cs | 174 ++++++++++++++++++++- .../Region/Physics/BulletSPlugin/BSApiTemplate.cs | 24 +++ 3 files changed, 241 insertions(+), 2 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSAPIUnman.cs b/OpenSim/Region/Physics/BulletSPlugin/BSAPIUnman.cs index 6c36485..8dfb01c 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSAPIUnman.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSAPIUnman.cs @@ -596,6 +596,12 @@ public override bool SetBreakingImpulseThreshold(BulletConstraint constrain, flo return BSAPICPP.SetBreakingImpulseThreshold2(constrainu.ptr, threshold); } +public override bool HingeSetLimits(BulletConstraint constrain, float low, float high, float softness, float bias, float relaxation) +{ + BulletConstraintUnman constrainu = constrain as BulletConstraintUnman; + return BSAPICPP.HingeSetLimits2(constrainu.ptr, low, high, softness, bias, relaxation); +} + public override bool SpringEnable(BulletConstraint constrain, int index, float numericTrueFalse) { BulletConstraintUnman constrainu = constrain as BulletConstraintUnman; @@ -620,6 +626,30 @@ public override bool SpringSetDamping(BulletConstraint constrain, int index, flo return BSAPICPP.ConstraintSpringSetDamping2(constrainu.ptr, index, damping); } +public override bool SliderSetLimits(BulletConstraint constrain, int lowerUpper, int linAng, float val) +{ + BulletConstraintUnman constrainu = constrain as BulletConstraintUnman; + return BSAPICPP.SliderSetLimits2(constrainu.ptr, lowerUpper, linAng, val); +} + +public override bool SliderSet(BulletConstraint constrain, int softRestDamp, int dirLimOrtho, int linAng, float val) +{ + BulletConstraintUnman constrainu = constrain as BulletConstraintUnman; + return BSAPICPP.SliderSet2(constrainu.ptr, softRestDamp, dirLimOrtho, linAng, val); +} + +public override bool SliderMotorEnable(BulletConstraint constrain, int linAng, float numericTrueFalse) +{ + BulletConstraintUnman constrainu = constrain as BulletConstraintUnman; + return BSAPICPP.SliderMotorEnable2(constrainu.ptr, linAng, numericTrueFalse); +} + +public override bool SliderMotor(BulletConstraint constrain, int forceVel, int linAng, float val) +{ + BulletConstraintUnman constrainu = constrain as BulletConstraintUnman; + return BSAPICPP.SliderMotor2(constrainu.ptr, forceVel, linAng, val); +} + public override bool CalculateTransforms(BulletConstraint constrain) { BulletConstraintUnman constrainu = constrain as BulletConstraintUnman; @@ -1625,6 +1655,9 @@ public static extern bool TranslationalLimitMotor2(IntPtr constrain, float enabl public static extern bool SetBreakingImpulseThreshold2(IntPtr constrain, float threshold); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern bool HingeSetLimits2(IntPtr constrain, float low, float high, float softness, float bias, float relaxation); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern bool ConstraintSpringEnable2(IntPtr constrain, int index, float numericTrueFalse); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] @@ -1637,6 +1670,18 @@ public static extern bool ConstraintSpringSetStiffness2(IntPtr constrain, int in public static extern bool ConstraintSpringSetDamping2(IntPtr constrain, int index, float damping); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern bool SliderSetLimits2(IntPtr constrain, int lowerUpper, int linAng, float val); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern bool SliderSet2(IntPtr constrain, int softRestDamp, int dirLimOrtho, int linAng, float val); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern bool SliderMotorEnable2(IntPtr constrain, int linAng, float numericTrueFalse); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern bool SliderMotor2(IntPtr constrain, int forceVel, int linAng, float val); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern bool CalculateTransforms2(IntPtr constrain); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSAPIXNA.cs b/OpenSim/Region/Physics/BulletSPlugin/BSAPIXNA.cs index 9ad12a9..ff2b497 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSAPIXNA.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSAPIXNA.cs @@ -752,6 +752,15 @@ private sealed class BulletConstraintXNA : BulletConstraint constraint.SetBreakingImpulseThreshold(threshold); return true; } + public override bool HingeSetLimits(BulletConstraint pConstraint, float low, float high, float softness, float bias, float relaxation) + { + HingeConstraint constraint = (pConstraint as BulletConstraintXNA).constrain as HingeConstraint; + if (softness == HINGE_NOT_SPECIFIED) + constraint.SetLimit(low, high); + else + constraint.SetLimit(low, high, softness, bias, relaxation); + return true; + } public override bool SpringEnable(BulletConstraint pConstraint, int index, float numericTrueFalse) { Generic6DofSpringConstraint constraint = (pConstraint as BulletConstraintXNA).constrain as Generic6DofSpringConstraint; @@ -762,13 +771,13 @@ private sealed class BulletConstraintXNA : BulletConstraint public override bool SpringSetEquilibriumPoint(BulletConstraint pConstraint, int index, float equilibriumPoint) { Generic6DofSpringConstraint constraint = (pConstraint as BulletConstraintXNA).constrain as Generic6DofSpringConstraint; - if (index == -1) + if (index == SPRING_NOT_SPECIFIED) { constraint.SetEquilibriumPoint(); } else { - if (equilibriumPoint == -1) + if (equilibriumPoint == SPRING_NOT_SPECIFIED) constraint.SetEquilibriumPoint(index); else constraint.SetEquilibriumPoint(index, equilibriumPoint); @@ -790,6 +799,167 @@ private sealed class BulletConstraintXNA : BulletConstraint return true; } + public override bool SliderSetLimits(BulletConstraint pConstraint, int lowerUpper, int linAng, float val) + { + SliderConstraint constraint = (pConstraint as BulletConstraintXNA).constrain as SliderConstraint; + switch (lowerUpper) + { + case SLIDER_LOWER_LIMIT: + switch (linAng) + { + case SLIDER_LINEAR: + constraint.SetLowerLinLimit(val); + break; + case SLIDER_ANGULAR: + constraint.SetLowerAngLimit(val); + break; + } + break; + case SLIDER_UPPER_LIMIT: + switch (linAng) + { + case SLIDER_LINEAR: + constraint.SetUpperLinLimit(val); + break; + case SLIDER_ANGULAR: + constraint.SetUpperAngLimit(val); + break; + } + break; + } + return true; + } + public override bool SliderSet(BulletConstraint pConstraint, int softRestDamp, int dirLimOrtho, int linAng, float val) + { + SliderConstraint constraint = (pConstraint as BulletConstraintXNA).constrain as SliderConstraint; + switch (softRestDamp) + { + case SLIDER_SET_SOFTNESS: + switch (dirLimOrtho) + { + case SLIDER_SET_DIRECTION: + switch (linAng) + { + case SLIDER_LINEAR: constraint.SetSoftnessDirLin(val); break; + case SLIDER_ANGULAR: constraint.SetSoftnessDirAng(val); break; + } + break; + case SLIDER_SET_LIMIT: + switch (linAng) + { + case SLIDER_LINEAR: constraint.SetSoftnessLimLin(val); break; + case SLIDER_ANGULAR: constraint.SetSoftnessLimAng(val); break; + } + break; + case SLIDER_SET_ORTHO: + switch (linAng) + { + case SLIDER_LINEAR: constraint.SetSoftnessOrthoLin(val); break; + case SLIDER_ANGULAR: constraint.SetSoftnessOrthoAng(val); break; + } + break; + } + break; + case SLIDER_SET_RESTITUTION: + switch (dirLimOrtho) + { + case SLIDER_SET_DIRECTION: + switch (linAng) + { + case SLIDER_LINEAR: constraint.SetRestitutionDirLin(val); break; + case SLIDER_ANGULAR: constraint.SetRestitutionDirAng(val); break; + } + break; + case SLIDER_SET_LIMIT: + switch (linAng) + { + case SLIDER_LINEAR: constraint.SetRestitutionLimLin(val); break; + case SLIDER_ANGULAR: constraint.SetRestitutionLimAng(val); break; + } + break; + case SLIDER_SET_ORTHO: + switch (linAng) + { + case SLIDER_LINEAR: constraint.SetRestitutionOrthoLin(val); break; + case SLIDER_ANGULAR: constraint.SetRestitutionOrthoAng(val); break; + } + break; + } + break; + case SLIDER_SET_DAMPING: + switch (dirLimOrtho) + { + case SLIDER_SET_DIRECTION: + switch (linAng) + { + case SLIDER_LINEAR: constraint.SetDampingDirLin(val); break; + case SLIDER_ANGULAR: constraint.SetDampingDirAng(val); break; + } + break; + case SLIDER_SET_LIMIT: + switch (linAng) + { + case SLIDER_LINEAR: constraint.SetDampingLimLin(val); break; + case SLIDER_ANGULAR: constraint.SetDampingLimAng(val); break; + } + break; + case SLIDER_SET_ORTHO: + switch (linAng) + { + case SLIDER_LINEAR: constraint.SetDampingOrthoLin(val); break; + case SLIDER_ANGULAR: constraint.SetDampingOrthoAng(val); break; + } + break; + } + break; + } + return true; + } + public override bool SliderMotorEnable(BulletConstraint pConstraint, int linAng, float numericTrueFalse) + { + SliderConstraint constraint = (pConstraint as BulletConstraintXNA).constrain as SliderConstraint; + switch (linAng) + { + case SLIDER_LINEAR: + constraint.SetPoweredLinMotor(numericTrueFalse == 0.0 ? false : true); + break; + case SLIDER_ANGULAR: + constraint.SetPoweredAngMotor(numericTrueFalse == 0.0 ? false : true); + break; + } + return true; + } + public override bool SliderMotor(BulletConstraint pConstraint, int forceVel, int linAng, float val) + { + SliderConstraint constraint = (pConstraint as BulletConstraintXNA).constrain as SliderConstraint; + switch (forceVel) + { + case SLIDER_MOTOR_VELOCITY: + switch (linAng) + { + case SLIDER_LINEAR: + constraint.SetTargetLinMotorVelocity(val); + break; + case SLIDER_ANGULAR: + constraint.SetTargetAngMotorVelocity(val); + break; + } + break; + case SLIDER_MAX_MOTOR_FORCE: + switch (linAng) + { + case SLIDER_LINEAR: + constraint.SetMaxLinMotorForce(val); + break; + case SLIDER_ANGULAR: + constraint.SetMaxAngMotorForce(val); + break; + } + break; + } + return true; + } + //BulletSimAPI.SetAngularDamping(Prim.PhysBody.ptr, angularDamping); public override void SetAngularDamping(BulletBody pBody, float angularDamping) { diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSApiTemplate.cs b/OpenSim/Region/Physics/BulletSPlugin/BSApiTemplate.cs index 8cca29f..b241059 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSApiTemplate.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSApiTemplate.cs @@ -441,14 +441,38 @@ public abstract bool TranslationalLimitMotor(BulletConstraint constrain, float e public abstract bool SetBreakingImpulseThreshold(BulletConstraint constrain, float threshold); +public const int HINGE_NOT_SPECIFIED = -1; +public abstract bool HingeSetLimits(BulletConstraint constrain, float low, float high, float softness, float bias, float relaxation); + public abstract bool SpringEnable(BulletConstraint constrain, int index, float numericTrueFalse); +public const int SPRING_NOT_SPECIFIED = -1; public abstract bool SpringSetEquilibriumPoint(BulletConstraint constrain, int index, float equilibriumPoint); public abstract bool SpringSetStiffness(BulletConstraint constrain, int index, float stiffnesss); public abstract bool SpringSetDamping(BulletConstraint constrain, int index, float damping); +public const int SLIDER_LOWER_LIMIT = 0; +public const int SLIDER_UPPER_LIMIT = 1; +public const int SLIDER_LINEAR = 2; +public const int SLIDER_ANGULAR = 3; +public abstract bool SliderSetLimits(BulletConstraint constrain, int lowerUpper, int linAng, float val); + +public const int SLIDER_SET_SOFTNESS = 4; +public const int SLIDER_SET_RESTITUTION = 5; +public const int SLIDER_SET_DAMPING = 6; +public const int SLIDER_SET_DIRECTION = 7; +public const int SLIDER_SET_LIMIT = 8; +public const int SLIDER_SET_ORTHO = 9; +public abstract bool SliderSet(BulletConstraint constrain, int softRestDamp, int dirLimOrtho, int linAng, float val); + +public abstract bool SliderMotorEnable(BulletConstraint constrain, int linAng, float numericTrueFalse); + +public const int SLIDER_MOTOR_VELOCITY = 10; +public const int SLIDER_MAX_MOTOR_FORCE = 11; +public abstract bool SliderMotor(BulletConstraint constrain, int forceVel, int linAng, float val); + public abstract bool CalculateTransforms(BulletConstraint constrain); public abstract bool SetConstraintParam(BulletConstraint constrain, ConstraintParams paramIndex, float value, ConstraintParamAxis axis); -- cgit v1.1 From c6a6631efc74ac8c139e0ae8cad683496fdd0050 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Wed, 7 Aug 2013 10:24:37 -0700 Subject: BulletSim: move linkset extension operations into BSPrimLinkable where they should be. --- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 32 +---------------- .../Region/Physics/BulletSPlugin/BSPrimLinkable.cs | 41 ++++++++++++++++++++++ 2 files changed, 42 insertions(+), 31 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index d5b999d..4685b48 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -41,7 +41,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin [Serializable] public class BSPrim : BSPhysObject { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + protected static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static readonly string LogHeader = "[BULLETS PRIM]"; // _size is what the user passed. Scale is what we pass to the physics engine with the mesh. @@ -1555,36 +1555,6 @@ public class BSPrim : BSPhysObject object ret = null; switch (pFunct) { - case BSScene.PhysFunctGetLinksetType: - { - BSPrimLinkable myHandle = this as BSPrimLinkable; - if (myHandle != null) - { - ret = (object)myHandle.LinksetType; - } - m_log.DebugFormat("{0} Extension.physGetLinksetType, type={1}", LogHeader, ret); - break; - } - case BSScene.PhysFunctSetLinksetType: - { - if (pParams.Length > 0) - { - BSLinkset.LinksetImplementation linksetType = (BSLinkset.LinksetImplementation)pParams[0]; - BSPrimLinkable myHandle = this as BSPrimLinkable; - if (myHandle != null && myHandle.Linkset.IsRoot(myHandle)) - { - PhysScene.TaintedObject("BSPrim.PhysFunctSetLinksetType", delegate() - { - // Cause the linkset type to change - m_log.DebugFormat("{0} Extension.physSetLinksetType, oldType={1}, newType={2}", - LogHeader, myHandle.Linkset.LinksetImpl, linksetType); - myHandle.ConvertLinkset(linksetType); - }); - } - ret = (object)(int)linksetType; - } - break; - } default: ret = base.Extension(pFunct, pParams); break; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs index 38d1f88..fc639ad 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs @@ -41,6 +41,8 @@ public class BSPrimLinkable : BSPrimDisplaced // operations necessary for keeping the linkset created and, additionally, this // calls the linkset implementation for its creation and management. + private static readonly string LogHeader = "[BULLETS PRIMLINKABLE]"; + // This adds the overrides for link() and delink() so the prim is linkable. public BSLinkset Linkset { get; set; } @@ -279,5 +281,44 @@ public class BSPrimLinkable : BSPrimDisplaced } return ret; } + + #region Extension + public override object Extension(string pFunct, params object[] pParams) + { + object ret = null; + switch (pFunct) + { + case BSScene.PhysFunctGetLinksetType: + { + ret = (object)LinksetType; + m_log.DebugFormat("{0} Extension.physGetLinksetType, type={1}", LogHeader, ret); + break; + } + case BSScene.PhysFunctSetLinksetType: + { + if (pParams.Length > 0) + { + BSLinkset.LinksetImplementation linksetType = (BSLinkset.LinksetImplementation)pParams[0]; + if (Linkset.IsRoot(this)) + { + PhysScene.TaintedObject("BSPrim.PhysFunctSetLinksetType", delegate() + { + // Cause the linkset type to change + m_log.DebugFormat("{0} Extension.physSetLinksetType, oldType={1}, newType={2}", + LogHeader, Linkset.LinksetImpl, linksetType); + ConvertLinkset(linksetType); + }); + } + ret = (object)(int)linksetType; + } + break; + } + default: + ret = base.Extension(pFunct, pParams); + break; + } + return ret; + } + #endregion // Extension } } -- cgit v1.1 From f3cc20050e8e4ce047509589f828ccafbc59e3a9 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Wed, 7 Aug 2013 11:13:53 -0700 Subject: BulletSim: initial implementation of physChangeLinkFixed that resets a linkset's link back to a fixed, non-moving connection. --- .../Region/Physics/BulletSPlugin/BSPrimLinkable.cs | 29 +++++++++++++++------- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 4 +++ 2 files changed, 24 insertions(+), 9 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs index fc639ad..77d8246 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs @@ -60,10 +60,7 @@ public class BSPrimLinkable : BSPrimDisplaced Linkset = BSLinkset.Factory(PhysScene, this); - PhysScene.TaintedObject("BSPrimLinksetCompound.Refresh", delegate() - { - Linkset.Refresh(this); - }); + Linkset.Refresh(this); } public override void Destroy() @@ -82,7 +79,7 @@ public class BSPrimLinkable : BSPrimDisplaced Linkset = parent.Linkset.AddMeToLinkset(this); - DetailLog("{0},BSPrimLinkset.link,call,parentBefore={1}, childrenBefore=={2}, parentAfter={3}, childrenAfter={4}", + DetailLog("{0},BSPrimLinkable.link,call,parentBefore={1}, childrenBefore=={2}, parentAfter={3}, childrenAfter={4}", LocalID, parentBefore.LocalID, childrenBefore, Linkset.LinksetRoot.LocalID, Linkset.NumberOfChildren); } return; @@ -98,7 +95,7 @@ public class BSPrimLinkable : BSPrimDisplaced Linkset = Linkset.RemoveMeFromLinkset(this, false /* inTaintTime*/); - DetailLog("{0},BSPrimLinkset.delink,parentBefore={1},childrenBefore={2},parentAfter={3},childrenAfter={4}, ", + DetailLog("{0},BSPrimLinkable.delink,parentBefore={1},childrenBefore={2},parentAfter={3},childrenAfter={4}, ", LocalID, parentBefore.LocalID, childrenBefore, Linkset.LinksetRoot.LocalID, Linkset.NumberOfChildren); return; } @@ -110,7 +107,7 @@ public class BSPrimLinkable : BSPrimDisplaced set { base.Position = value; - PhysScene.TaintedObject("BSPrimLinkset.setPosition", delegate() + PhysScene.TaintedObject("BSPrimLinkable.setPosition", delegate() { Linkset.UpdateProperties(UpdatedProperties.Position, this); }); @@ -124,7 +121,7 @@ public class BSPrimLinkable : BSPrimDisplaced set { base.Orientation = value; - PhysScene.TaintedObject("BSPrimLinkset.setOrientation", delegate() + PhysScene.TaintedObject("BSPrimLinkable.setOrientation", delegate() { Linkset.UpdateProperties(UpdatedProperties.Orientation, this); }); @@ -242,7 +239,7 @@ public class BSPrimLinkable : BSPrimDisplaced bool ret = false; if (LinksetType != newType) { - DetailLog("{0},BSPrimLinkset.ConvertLinkset,oldT={1},newT={2}", LocalID, LinksetType, newType); + DetailLog("{0},BSPrimLinkable.ConvertLinkset,oldT={1},newT={2}", LocalID, LinksetType, newType); // Set the implementation type first so the call to BSLinkset.Factory gets the new type. this.LinksetType = newType; @@ -288,12 +285,14 @@ public class BSPrimLinkable : BSPrimDisplaced object ret = null; switch (pFunct) { + // physGetLinksetType(); case BSScene.PhysFunctGetLinksetType: { ret = (object)LinksetType; m_log.DebugFormat("{0} Extension.physGetLinksetType, type={1}", LogHeader, ret); break; } + // physSetLinksetType(type); case BSScene.PhysFunctSetLinksetType: { if (pParams.Length > 0) @@ -313,6 +312,18 @@ public class BSPrimLinkable : BSPrimDisplaced } break; } + // physChangeLinkFixed(linknum); + // Params: int linkNum, PhysActor linkedPrim + case BSScene.PhysFunctChangeLinkFixed: + { + if (pParams.Length > 1) + { + int linkNum = (int)pParams[0]; + Manager.PhysicsActor linkActor = (Manager.PhysicsActor)pParams[1]; + Linkset.Refresh(this); + } + break; + } default: ret = base.Extension(pFunct, pParams); break; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index c92c9b9..571db86 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -875,6 +875,10 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters // Per prim functions. See BSPrim. public const string PhysFunctGetLinksetType = "BulletSim.GetLinksetType"; public const string PhysFunctSetLinksetType = "BulletSim.SetLinksetType"; + public const string PhysFunctChangeLinkFixed = "BulletSim.ChangeLinkFixed"; + public const string PhysFunctChangeLinkHinge = "BulletSim.ChangeLinkHinge"; + public const string PhysFunctChangeLinkSpring = "BulletSim.ChangeLinkSpring"; + public const string PhysFunctChangeLinkSlider = "BulletSim.ChangeLinkSlider"; // ============================================================= public override object Extension(string pFunct, params object[] pParams) -- cgit v1.1 From dff0fb56902f62b070ec6fd05769babfad32ed2e Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Wed, 7 Aug 2013 11:18:23 -0700 Subject: BulletSim: Linkset.Refresh() calls internal ScheduleRebuild() to recreate the linkset physics at next PostTaint time. Replace the existing calls to ScheduleRebuild to be calls to Refresh(). This allows external routines to make changes to parameters and then cause the linkset to rebuild. --- .../Region/Physics/BulletSPlugin/BSLinksetCompound.cs | 17 ++++++++--------- .../Physics/BulletSPlugin/BSLinksetConstraints.cs | 11 ++++++----- 2 files changed, 14 insertions(+), 14 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs index 47ab842..8f12189 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs @@ -90,10 +90,9 @@ public sealed class BSLinksetCompound : BSLinkset // its internal properties. public override void Refresh(BSPrimLinkable requestor) { - base.Refresh(requestor); - // Something changed so do the rebuilding thing - // ScheduleRebuild(); + ScheduleRebuild(requestor); + base.Refresh(requestor); } // Schedule a refresh to happen after all the other taint processing. @@ -127,7 +126,7 @@ public sealed class BSLinksetCompound : BSLinkset if (IsRoot(child)) { // The root is going dynamic. Rebuild the linkset so parts and mass get computed properly. - ScheduleRebuild(LinksetRoot); + Refresh(LinksetRoot); } return ret; } @@ -144,7 +143,7 @@ public sealed class BSLinksetCompound : BSLinkset if (IsRoot(child)) { // Schedule a rebuild to verify that the root shape is set to the real shape. - ScheduleRebuild(LinksetRoot); + Refresh(LinksetRoot); } return ret; } @@ -227,7 +226,7 @@ public sealed class BSLinksetCompound : BSLinkset // there will already be a rebuild scheduled. DetailLog("{0},BSLinksetCompound.UpdateProperties,couldNotUpdateChild.schedulingRebuild,whichUpdated={1}", updated.LocalID, whichUpdated); - ScheduleRebuild(updated); + Refresh(updated); } } } @@ -245,7 +244,7 @@ public sealed class BSLinksetCompound : BSLinkset DetailLog("{0},BSLinksetCompound.RemoveDependencies,refreshIfChild,rID={1},rBody={2},isRoot={3}", child.LocalID, LinksetRoot.LocalID, LinksetRoot.PhysBody, IsRoot(child)); - ScheduleRebuild(child); + Refresh(child); return ret; } @@ -263,7 +262,7 @@ public sealed class BSLinksetCompound : BSLinkset DetailLog("{0},BSLinksetCompound.AddChildToLinkset,call,child={1}", LinksetRoot.LocalID, child.LocalID); // Rebuild the compound shape with the new child shape included - ScheduleRebuild(child); + Refresh(child); } return; } @@ -292,7 +291,7 @@ public sealed class BSLinksetCompound : BSLinkset else { // Rebuild the compound shape with the child removed - ScheduleRebuild(LinksetRoot); + Refresh(LinksetRoot); } } return; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs index f3b70c3..db323c2 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs @@ -158,6 +158,7 @@ public sealed class BSLinksetConstraints : BSLinkset // refresh will happen once after all the other taints are applied. public override void Refresh(BSPrimLinkable requestor) { + ScheduleRebuild(requestor); base.Refresh(requestor); } @@ -194,7 +195,7 @@ public sealed class BSLinksetConstraints : BSLinkset if (IsRoot(child)) { // The root is going dynamic. Rebuild the linkset so parts and mass get computed properly. - ScheduleRebuild(LinksetRoot); + Refresh(LinksetRoot); } return ret; } @@ -213,7 +214,7 @@ public sealed class BSLinksetConstraints : BSLinkset if (IsRoot(child)) { // Schedule a rebuild to verify that the root shape is set to the real shape. - ScheduleRebuild(LinksetRoot); + Refresh(LinksetRoot); } return ret; } @@ -241,7 +242,7 @@ public sealed class BSLinksetConstraints : BSLinkset // Just undo all the constraints for this linkset. Rebuild at the end of the step. ret = PhysicallyUnlinkAllChildrenFromRoot(LinksetRoot); // Cause the constraints, et al to be rebuilt before the next simulation step. - ScheduleRebuild(LinksetRoot); + Refresh(LinksetRoot); } return ret; } @@ -259,7 +260,7 @@ public sealed class BSLinksetConstraints : BSLinkset DetailLog("{0},BSLinksetConstraints.AddChildToLinkset,call,child={1}", LinksetRoot.LocalID, child.LocalID); // Cause constraints and assorted properties to be recomputed before the next simulation step. - ScheduleRebuild(LinksetRoot); + Refresh(LinksetRoot); } return; } @@ -283,7 +284,7 @@ public sealed class BSLinksetConstraints : BSLinkset PhysicallyUnlinkAChildFromRoot(rootx, childx); }); // See that the linkset parameters are recomputed at the end of the taint time. - ScheduleRebuild(LinksetRoot); + Refresh(LinksetRoot); } else { -- cgit v1.1 From 6aee08ac3c48b55ebd8e945c8b11f17dc1ab3151 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Thu, 8 Aug 2013 08:36:36 -0700 Subject: BulletSim: add physChangeLinkSpring to change linkset link to be a spring constraint. Add implementation to create spring constraint. Send up property updates for linkset children at the end of flexible linkset links. The simulator probably doesn't do the right thing yet. --- .../Region/Physics/BulletSPlugin/BSApiTemplate.cs | 4 +- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 24 +++++ .../Physics/BulletSPlugin/BSLinksetConstraints.cs | 102 ++++++++++++++++++++- .../Region/Physics/BulletSPlugin/BSPrimLinkable.cs | 9 +- 4 files changed, 128 insertions(+), 11 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSApiTemplate.cs b/OpenSim/Region/Physics/BulletSPlugin/BSApiTemplate.cs index b241059..9d8838b 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSApiTemplate.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSApiTemplate.cs @@ -43,7 +43,9 @@ public enum ConstraintType : int SLIDER_CONSTRAINT_TYPE, CONTACT_CONSTRAINT_TYPE, D6_SPRING_CONSTRAINT_TYPE, - MAX_CONSTRAINT_TYPE + MAX_CONSTRAINT_TYPE, // last type defined by Bullet + // + FIXED_CONSTRAINT_TYPE = 1234 // BulletSim constraint that is fixed and unmoving } // =============================================================================== diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index d4b1c1e..2058e3a 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -79,6 +79,8 @@ public abstract class BSLinkset } public virtual void ResetLink() { } public virtual void SetLinkParameters(BSConstraint constrain) { } + // Returns 'true' if physical property updates from the child should be reported to the simulator + public virtual bool ShouldUpdateChildProperties() { return false; } } public LinksetImplementation LinksetImpl { get; protected set; } @@ -224,6 +226,21 @@ public abstract class BSLinkset return ret; } + // Check the type of the link and return 'true' if the link is flexible and the + // updates from the child should be sent to the simulator so things change. + public virtual bool ShouldReportPropertyUpdates(BSPrimLinkable child) + { + bool ret = false; + + BSLinkInfo linkInfo; + if (m_children.TryGetValue(child, out linkInfo)) + { + ret = linkInfo.ShouldUpdateChildProperties(); + } + + return ret; + } + // Called after a simulation step to post a collision with this object. // Return 'true' if linkset processed the collision. 'false' says the linkset didn't have // anything to add for the collision and it should be passed through normal processing. @@ -432,6 +449,13 @@ public abstract class BSLinkset return com; } + #region Extension + public virtual object Extension(string pFunct, params object[] pParams) + { + return null; + } + #endregion // Extension + // Invoke the detailed logger and output something if it's enabled. protected void DetailLog(string msg, params Object[] args) { diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs index db323c2..17fec9d 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs @@ -60,8 +60,6 @@ public sealed class BSLinksetConstraints : BSLinkset public float springDamping; public float springStiffness; - - public BSLinkInfoConstraint(BSPrimLinkable pMember) : base(pMember) { @@ -72,7 +70,8 @@ public sealed class BSLinksetConstraints : BSLinkset // Set all the parameters for this constraint to a fixed, non-movable constraint. public override void ResetLink() { - constraintType = ConstraintType.D6_CONSTRAINT_TYPE; + // constraintType = ConstraintType.D6_CONSTRAINT_TYPE; + constraintType = ConstraintType.FIXED_CONSTRAINT_TYPE; linearLimitLow = OMV.Vector3.Zero; linearLimitHigh = OMV.Vector3.Zero; angularLimitLow = OMV.Vector3.Zero; @@ -97,6 +96,7 @@ public sealed class BSLinksetConstraints : BSLinkset { switch (constraintType) { + case ConstraintType.FIXED_CONSTRAINT_TYPE: case ConstraintType.D6_CONSTRAINT_TYPE: BSConstraint6Dof constrain6dof = constrain as BSConstraint6Dof; if (constrain6dof != null) @@ -145,6 +145,20 @@ public sealed class BSLinksetConstraints : BSLinkset break; } } + + // Return 'true' if the property updates from the physics engine should be reported + // to the simulator. + // If the constraint is fixed, we don't need to report as the simulator and viewer will + // report the right things. + public override bool ShouldUpdateChildProperties() + { + bool ret = true; + + if (constraintType == ConstraintType.FIXED_CONSTRAINT_TYPE) + ret = false; + + return ret; + } } public BSLinksetConstraints(BSScene scene, BSPrimLinkable parent) : base(scene, parent) @@ -316,6 +330,7 @@ public sealed class BSLinksetConstraints : BSLinkset switch (linkInfo.constraintType) { + case ConstraintType.FIXED_CONSTRAINT_TYPE: case ConstraintType.D6_CONSTRAINT_TYPE: // Relative position normalized to the root prim // Essentually a vector pointing from center of rootPrim to center of li.member @@ -466,5 +481,86 @@ public sealed class BSLinksetConstraints : BSLinkset Rebuilding = false; } } + + #region Extension + public override object Extension(string pFunct, params object[] pParams) + { + object ret = null; + switch (pFunct) + { + // pParams = (int linkNUm, PhysActor linkChild) + case BSScene.PhysFunctChangeLinkFixed: + if (pParams.Length > 1) + { + BSPrimLinkable child = pParams[1] as BSPrimLinkable; + if (child != null) + { + m_physicsScene.TaintedObject("BSLinksetConstraint.PhysFunctChangeLinkFixed", delegate() + { + // Pick up all the constraints currently created. + RemoveDependencies(child); + + BSLinkInfo linkInfo = null; + if (m_children.TryGetValue(child, out linkInfo)) + { + BSLinkInfoConstraint linkInfoC = linkInfo as BSLinkInfoConstraint; + if (linkInfoC != null) + { + // Setting to fixed is easy. The reset state is the fixed link configuration. + linkInfoC.ResetLink(); + ret = (object)true; + } + } + // Cause the whole linkset to be rebuilt in post-taint time. + Refresh(child); + }); + } + } + break; + case BSScene.PhysFunctChangeLinkSpring: + if (pParams.Length > 11) + { + BSPrimLinkable child = pParams[1] as BSPrimLinkable; + if (child != null) + { + m_physicsScene.TaintedObject("BSLinksetConstraint.PhysFunctChangeLinkFixed", delegate() + { + // Pick up all the constraints currently created. + RemoveDependencies(child); + + BSLinkInfo linkInfo = null; + if (m_children.TryGetValue(child, out linkInfo)) + { + BSLinkInfoConstraint linkInfoC = linkInfo as BSLinkInfoConstraint; + if (linkInfoC != null) + { + // Start with a reset link definition + linkInfoC.ResetLink(); + linkInfoC.constraintType = ConstraintType.D6_SPRING_CONSTRAINT_TYPE; + linkInfoC.frameInAloc = (OMV.Vector3)pParams[2]; + linkInfoC.frameInArot = (OMV.Quaternion)pParams[3]; + linkInfoC.frameInBloc = (OMV.Vector3)pParams[4]; + linkInfoC.frameInBrot = (OMV.Quaternion)pParams[5]; + linkInfoC.linearLimitLow = (OMV.Vector3)pParams[6]; + linkInfoC.linearLimitHigh = (OMV.Vector3)pParams[7]; + linkInfoC.angularLimitLow = (OMV.Vector3)pParams[8]; + linkInfoC.angularLimitHigh = (OMV.Vector3)pParams[9]; + ret = (object)true; + } + } + // Cause the whole linkset to be rebuilt in post-taint time. + Refresh(child); + }); + } + } + break; + default: + ret = base.Extension(pFunct, pParams); + break; + } + return ret; + } + #endregion // Extension + } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs index 77d8246..4c384a6 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs @@ -179,7 +179,7 @@ public class BSPrimLinkable : BSPrimDisplaced // Do any filtering/modification needed for linksets. public override void UpdateProperties(EntityProperties entprop) { - if (Linkset.IsRoot(this)) + if (Linkset.IsRoot(this) || Linkset.ShouldReportPropertyUpdates(this)) { // Properties are only updated for the roots of a linkset. // TODO: this will have to change when linksets are articulated. @@ -316,12 +316,7 @@ public class BSPrimLinkable : BSPrimDisplaced // Params: int linkNum, PhysActor linkedPrim case BSScene.PhysFunctChangeLinkFixed: { - if (pParams.Length > 1) - { - int linkNum = (int)pParams[0]; - Manager.PhysicsActor linkActor = (Manager.PhysicsActor)pParams[1]; - Linkset.Refresh(this); - } + Linkset.Extension(pFunct, pParams); break; } default: -- cgit v1.1 From b2a1348adc2bd27d3266a7d7c7594a2aa8272100 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Thu, 8 Aug 2013 16:37:37 -0700 Subject: BulletSim: update C++ HACD parameters to values that handle enclosed hollow spaces better. This shouldn't affect many since this HACD routine is off by default. --- OpenSim/Region/Physics/BulletSPlugin/BSParam.cs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs index fcb892a..737dda1 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs @@ -683,21 +683,21 @@ public static class BSParam 0f ), new ParameterDefn("BHullMaxVerticesPerHull", "Bullet impl: max number of vertices per created hull", - 100f ), + 200f ), new ParameterDefn("BHullMinClusters", "Bullet impl: minimum number of hulls to create per mesh", - 2f ), + 10f ), new ParameterDefn("BHullCompacityWeight", "Bullet impl: weight factor for how compact to make hulls", - 0.1f ), + 20f ), new ParameterDefn("BHullVolumeWeight", "Bullet impl: weight factor for volume in created hull", - 0f ), + 0.1f ), new ParameterDefn("BHullConcavity", "Bullet impl: weight factor for how convex a created hull can be", - 100f ), + 10f ), new ParameterDefn("BHullAddExtraDistPoints", "Bullet impl: whether to add extra vertices for long distance vectors", - false ), + true ), new ParameterDefn("BHullAddNeighboursDistPoints", "Bullet impl: whether to add extra vertices between neighbor hulls", - false ), + true ), new ParameterDefn("BHullAddFacesPoints", "Bullet impl: whether to add extra vertices to break up hull faces", - false ), + true ), new ParameterDefn("BHullShouldAdjustCollisionMargin", "Bullet impl: whether to shrink resulting hulls to account for collision margin", false ), -- cgit v1.1 From 455d36c4c70a55c5d48dc1410b8729929fafedf6 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Fri, 9 Aug 2013 10:59:10 -0700 Subject: BulletSim: add physChangeLinkParams to set individual parameters on link constraints. Not fully functional. Remove double definition of ExtendedPhysics parameters by having BulletSim reference the optional module (addition to prebuild.xml and usings). --- .../Physics/BulletSPlugin/BSConstraintConeTwist.cs | 54 ++++++++++++++ .../Physics/BulletSPlugin/BSConstraintSlider.cs | 55 ++++++++++++++ .../Physics/BulletSPlugin/BSLinksetConstraints.cs | 85 ++++++++-------------- .../Region/Physics/BulletSPlugin/BSPrimLinkable.cs | 18 +++-- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 14 ---- 5 files changed, 153 insertions(+), 73 deletions(-) create mode 100755 OpenSim/Region/Physics/BulletSPlugin/BSConstraintConeTwist.cs create mode 100755 OpenSim/Region/Physics/BulletSPlugin/BSConstraintSlider.cs (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSConstraintConeTwist.cs b/OpenSim/Region/Physics/BulletSPlugin/BSConstraintConeTwist.cs new file mode 100755 index 0000000..7a76a9a --- /dev/null +++ b/OpenSim/Region/Physics/BulletSPlugin/BSConstraintConeTwist.cs @@ -0,0 +1,54 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyrightD + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +using System; +using System.Collections.Generic; +using System.Text; +using OpenMetaverse; + +namespace OpenSim.Region.Physics.BulletSPlugin +{ + +public sealed class BSConstraintConeTwist : BSConstraint +{ + public override ConstraintType Type { get { return ConstraintType.CONETWIST_CONSTRAINT_TYPE; } } + + public BSConstraintConeTwist(BulletWorld world, BulletBody obj1, BulletBody obj2, + Vector3 frameInAloc, Quaternion frameInArot, + Vector3 frameInBloc, Quaternion frameInBrot, + bool disableCollisionsBetweenLinkedBodies) + : base(world) + { + m_body1 = obj1; + m_body2 = obj2; + m_constraint = PhysicsScene.PE.CreateConeTwistConstraint(world, obj1, obj2, + frameInAloc, frameInArot, frameInBloc, frameInBrot, + disableCollisionsBetweenLinkedBodies); + m_enabled = true; + } +} + +} diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSConstraintSlider.cs b/OpenSim/Region/Physics/BulletSPlugin/BSConstraintSlider.cs new file mode 100755 index 0000000..37cfa07 --- /dev/null +++ b/OpenSim/Region/Physics/BulletSPlugin/BSConstraintSlider.cs @@ -0,0 +1,55 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyrightD + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +using System; +using System.Collections.Generic; +using System.Text; +using OpenMetaverse; + +namespace OpenSim.Region.Physics.BulletSPlugin +{ + +public sealed class BSConstraintSlider : BSConstraint +{ + public override ConstraintType Type { get { return ConstraintType.SLIDER_CONSTRAINT_TYPE; } } + + public BSConstraintSlider(BulletWorld world, BulletBody obj1, BulletBody obj2, + Vector3 frameInAloc, Quaternion frameInArot, + Vector3 frameInBloc, Quaternion frameInBrot, + bool useLinearReferenceFrameA, bool disableCollisionsBetweenLinkedBodies) + : base(world) + { + m_body1 = obj1; + m_body2 = obj2; + m_constraint = PhysicsScene.PE.CreateSliderConstraint(world, obj1, obj2, + frameInAloc, frameInArot, frameInBloc, frameInBrot, + useLinearReferenceFrameA, disableCollisionsBetweenLinkedBodies); + m_enabled = true; + } + +} + +} diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs index 17fec9d..c09dd42 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs @@ -28,6 +28,8 @@ using System; using System.Collections.Generic; using System.Text; +using OpenSim.Region.OptionalModules.Scripting; + using OMV = OpenMetaverse; namespace OpenSim.Region.Physics.BulletSPlugin @@ -489,71 +491,46 @@ public sealed class BSLinksetConstraints : BSLinkset switch (pFunct) { // pParams = (int linkNUm, PhysActor linkChild) - case BSScene.PhysFunctChangeLinkFixed: + case ExtendedPhysics.PhysFunctChangeLinkType: if (pParams.Length > 1) { - BSPrimLinkable child = pParams[1] as BSPrimLinkable; - if (child != null) + int requestedType = (int)pParams[1]; + if (requestedType == (int)ConstraintType.FIXED_CONSTRAINT_TYPE + || requestedType == (int)ConstraintType.D6_CONSTRAINT_TYPE + || requestedType == (int)ConstraintType.D6_SPRING_CONSTRAINT_TYPE + || requestedType == (int)ConstraintType.HINGE_CONSTRAINT_TYPE + || requestedType == (int)ConstraintType.CONETWIST_CONSTRAINT_TYPE + || requestedType == (int)ConstraintType.SLIDER_CONSTRAINT_TYPE) { - m_physicsScene.TaintedObject("BSLinksetConstraint.PhysFunctChangeLinkFixed", delegate() + BSPrimLinkable child = pParams[0] as BSPrimLinkable; + if (child != null) { - // Pick up all the constraints currently created. - RemoveDependencies(child); - - BSLinkInfo linkInfo = null; - if (m_children.TryGetValue(child, out linkInfo)) + m_physicsScene.TaintedObject("BSLinksetConstraint.PhysFunctChangeLinkFixed", delegate() { - BSLinkInfoConstraint linkInfoC = linkInfo as BSLinkInfoConstraint; - if (linkInfoC != null) - { - // Setting to fixed is easy. The reset state is the fixed link configuration. - linkInfoC.ResetLink(); - ret = (object)true; - } - } - // Cause the whole linkset to be rebuilt in post-taint time. - Refresh(child); - }); - } - } - break; - case BSScene.PhysFunctChangeLinkSpring: - if (pParams.Length > 11) - { - BSPrimLinkable child = pParams[1] as BSPrimLinkable; - if (child != null) - { - m_physicsScene.TaintedObject("BSLinksetConstraint.PhysFunctChangeLinkFixed", delegate() - { - // Pick up all the constraints currently created. - RemoveDependencies(child); + // Pick up all the constraints currently created. + RemoveDependencies(child); - BSLinkInfo linkInfo = null; - if (m_children.TryGetValue(child, out linkInfo)) - { - BSLinkInfoConstraint linkInfoC = linkInfo as BSLinkInfoConstraint; - if (linkInfoC != null) + BSLinkInfo linkInfo = null; + if (m_children.TryGetValue(child, out linkInfo)) { - // Start with a reset link definition - linkInfoC.ResetLink(); - linkInfoC.constraintType = ConstraintType.D6_SPRING_CONSTRAINT_TYPE; - linkInfoC.frameInAloc = (OMV.Vector3)pParams[2]; - linkInfoC.frameInArot = (OMV.Quaternion)pParams[3]; - linkInfoC.frameInBloc = (OMV.Vector3)pParams[4]; - linkInfoC.frameInBrot = (OMV.Quaternion)pParams[5]; - linkInfoC.linearLimitLow = (OMV.Vector3)pParams[6]; - linkInfoC.linearLimitHigh = (OMV.Vector3)pParams[7]; - linkInfoC.angularLimitLow = (OMV.Vector3)pParams[8]; - linkInfoC.angularLimitHigh = (OMV.Vector3)pParams[9]; - ret = (object)true; + BSLinkInfoConstraint linkInfoC = linkInfo as BSLinkInfoConstraint; + if (linkInfoC != null) + { + // Setting to fixed is easy. The reset state is the fixed link configuration. + linkInfoC.ResetLink(); + linkInfoC.constraintType = (ConstraintType)requestedType; + ret = (object)true; + } } - } - // Cause the whole linkset to be rebuilt in post-taint time. - Refresh(child); - }); + // Cause the whole linkset to be rebuilt in post-taint time. + Refresh(child); + }); + } } } break; + case ExtendedPhysics.PhysFunctChangeLinkParams: + break; default: ret = base.Extension(pFunct, pParams); break; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs index 4c384a6..6136257 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs @@ -30,6 +30,7 @@ using System.Linq; using System.Text; using OpenSim.Framework; +using OpenSim.Region.OptionalModules.Scripting; using OMV = OpenMetaverse; @@ -286,14 +287,14 @@ public class BSPrimLinkable : BSPrimDisplaced switch (pFunct) { // physGetLinksetType(); - case BSScene.PhysFunctGetLinksetType: + case ExtendedPhysics.PhysFunctGetLinksetType: { ret = (object)LinksetType; m_log.DebugFormat("{0} Extension.physGetLinksetType, type={1}", LogHeader, ret); break; } // physSetLinksetType(type); - case BSScene.PhysFunctSetLinksetType: + case ExtendedPhysics.PhysFunctSetLinksetType: { if (pParams.Length > 0) { @@ -312,9 +313,16 @@ public class BSPrimLinkable : BSPrimDisplaced } break; } - // physChangeLinkFixed(linknum); - // Params: int linkNum, PhysActor linkedPrim - case BSScene.PhysFunctChangeLinkFixed: + // physChangeLinkType(linknum, typeCode); + // Params: PhysActor linkedPrim, int typeCode + case ExtendedPhysics.PhysFunctChangeLinkType: + { + Linkset.Extension(pFunct, pParams); + break; + } + // physChangeLinkParams(linknum, [code, value, code, value, ...]); + // Params: PhysActor linkedPrim, object[] params + case ExtendedPhysics.PhysFunctChangeLinkParams: { Linkset.Extension(pFunct, pParams); break; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index 571db86..7440468 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -867,20 +867,6 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters public override bool IsThreaded { get { return false; } } #region Extensions - // ============================================================= - // Per scene functions. See below. - - // Per avatar functions. See BSCharacter. - - // Per prim functions. See BSPrim. - public const string PhysFunctGetLinksetType = "BulletSim.GetLinksetType"; - public const string PhysFunctSetLinksetType = "BulletSim.SetLinksetType"; - public const string PhysFunctChangeLinkFixed = "BulletSim.ChangeLinkFixed"; - public const string PhysFunctChangeLinkHinge = "BulletSim.ChangeLinkHinge"; - public const string PhysFunctChangeLinkSpring = "BulletSim.ChangeLinkSpring"; - public const string PhysFunctChangeLinkSlider = "BulletSim.ChangeLinkSlider"; - // ============================================================= - public override object Extension(string pFunct, params object[] pParams) { return base.Extension(pFunct, pParams); -- cgit v1.1 From f6fdfd16f55c3e1bd55775f1f21e0ac9e44ff2ee Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Fri, 9 Aug 2013 17:01:35 -0700 Subject: BulletSim: change ExtendedPhysics constants to 'const' so they can be used as case variables in switch statements. --- .../Physics/BulletSPlugin/BSLinksetConstraints.cs | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs index c09dd42..b72afc0 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs @@ -530,6 +530,28 @@ public sealed class BSLinksetConstraints : BSLinkset } break; case ExtendedPhysics.PhysFunctChangeLinkParams: + int setParam = 2; + switch (setParam) + { + case ExtendedPhysics.PHYS_PARAM_FRAMEINA_LOC: + case ExtendedPhysics.PHYS_PARAM_FRAMEINA_ROT: + case ExtendedPhysics.PHYS_PARAM_FRAMEINB_LOC: + case ExtendedPhysics.PHYS_PARAM_FRAMEINB_ROT: + case ExtendedPhysics.PHYS_PARAM_LINEAR_LIMIT_LOW: + case ExtendedPhysics.PHYS_PARAM_LINEAR_LIMIT_HIGH: + case ExtendedPhysics.PHYS_PARAM_ANGULAR_LIMIT_LOW: + case ExtendedPhysics.PHYS_PARAM_ANGULAR_LIMIT_HIGH: + case ExtendedPhysics.PHYS_PARAM_USE_FRAME_OFFSET: + case ExtendedPhysics.PHYS_PARAM_ENABLE_TRANSMOTOR: + case ExtendedPhysics.PHYS_PARAM_TRANSMOTOR_MAXVEL: + case ExtendedPhysics.PHYS_PARAM_TRANSMOTOR_MAXFORCE: + case ExtendedPhysics.PHYS_PARAM_CFM: + case ExtendedPhysics.PHYS_PARAM_ERP: + case ExtendedPhysics.PHYS_PARAM_SOLVER_ITERATIONS: + case ExtendedPhysics.PHYS_PARAM_SPRING_DAMPING: + case ExtendedPhysics.PHYS_PARAM_SPRING_STIFFNESS: + break; + } break; default: ret = base.Extension(pFunct, pParams); -- cgit v1.1 From e1120cb74db9092cc0f9a7fc245d2f2ed6160b7a Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Fri, 16 Aug 2013 13:44:31 -0700 Subject: BulletSim: add extended physics function physGetLinkType(linkNum). Add implementation of physChangeLinkParams() in BSLinksetConstraint. --- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 11 ++ .../Physics/BulletSPlugin/BSLinksetConstraints.cs | 145 ++++++++++++++++++--- .../Region/Physics/BulletSPlugin/BSPrimLinkable.cs | 11 +- 3 files changed, 144 insertions(+), 23 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index 2058e3a..77f69a5 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -209,6 +209,17 @@ public abstract class BSLinkset return ret; } + public bool TryGetLinkInfo(BSPrimLinkable child, out BSLinkInfo foundInfo) + { + bool ret = false; + BSLinkInfo found = null; + lock (m_linksetActivityLock) + { + ret = m_children.TryGetValue(child, out found); + } + foundInfo = found; + return ret; + } // Perform an action on each member of the linkset including root prim. // Depends on the action on whether this should be done at taint time. public delegate bool ForEachLinkInfoAction(BSLinkInfo obj); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs index b72afc0..92df84e 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs @@ -168,6 +168,8 @@ public sealed class BSLinksetConstraints : BSLinkset LinksetImpl = LinksetImplementation.Constraint; } + private static string LogHeader = "[BULLETSIM LINKSET CONSTRAINT]"; + // When physical properties are changed the linkset needs to recalculate // its internal properties. // This is queued in the 'post taint' queue so the @@ -511,7 +513,7 @@ public sealed class BSLinksetConstraints : BSLinkset RemoveDependencies(child); BSLinkInfo linkInfo = null; - if (m_children.TryGetValue(child, out linkInfo)) + if (TryGetLinkInfo(child, out linkInfo)) { BSLinkInfoConstraint linkInfoC = linkInfo as BSLinkInfoConstraint; if (linkInfoC != null) @@ -529,28 +531,129 @@ public sealed class BSLinksetConstraints : BSLinkset } } break; + case ExtendedPhysics.PhysFunctGetLinkType: + if (pParams.Length > 0) + { + BSPrimLinkable child = pParams[0] as BSPrimLinkable; + if (child != null) + { + BSLinkInfo linkInfo = null; + if (TryGetLinkInfo(child, out linkInfo)) + { + BSLinkInfoConstraint linkInfoC = linkInfo as BSLinkInfoConstraint; + if (linkInfoC != null) + { + ret = (object)(int)linkInfoC.constraintType; + } + } + } + } + break; case ExtendedPhysics.PhysFunctChangeLinkParams: - int setParam = 2; - switch (setParam) + // There should be two parameters: the childActor and a list of parameters to set + try + { + if (pParams.Length > 1) + { + BSPrimLinkable child = pParams[0] as BSPrimLinkable; + object[] setOps = (object[])pParams[1]; + BSLinkInfo baseLinkInfo = null; + if (TryGetLinkInfo(child, out baseLinkInfo)) + { + BSLinkInfoConstraint linkInfo = baseLinkInfo as BSLinkInfoConstraint; + if (linkInfo != null) + { + float valueFloat; + bool valueBool; + OMV.Vector3 valueVector; + OMV.Quaternion valueQuaternion; + + int opIndex = 0; + while (opIndex < setOps.Length) + { + int thisOp = (int)setOps[opIndex]; + switch (thisOp) + { + case ExtendedPhysics.PHYS_PARAM_FRAMEINA_LOC: + valueVector = (OMV.Vector3)setOps[opIndex + 1]; + linkInfo.frameInAloc = valueVector; + break; + case ExtendedPhysics.PHYS_PARAM_FRAMEINA_ROT: + valueQuaternion = (OMV.Quaternion)setOps[opIndex + 1]; + linkInfo.frameInArot = valueQuaternion; + break; + case ExtendedPhysics.PHYS_PARAM_FRAMEINB_LOC: + valueVector = (OMV.Vector3)setOps[opIndex + 1]; + linkInfo.frameInBloc = valueVector; + break; + case ExtendedPhysics.PHYS_PARAM_FRAMEINB_ROT: + valueQuaternion = (OMV.Quaternion)setOps[opIndex + 1]; + linkInfo.frameInBrot = valueQuaternion; + break; + case ExtendedPhysics.PHYS_PARAM_LINEAR_LIMIT_LOW: + valueVector = (OMV.Vector3)setOps[opIndex + 1]; + linkInfo.linearLimitLow = valueVector; + break; + case ExtendedPhysics.PHYS_PARAM_LINEAR_LIMIT_HIGH: + valueVector = (OMV.Vector3)setOps[opIndex + 1]; + linkInfo.linearLimitHigh = valueVector; + break; + case ExtendedPhysics.PHYS_PARAM_ANGULAR_LIMIT_LOW: + valueVector = (OMV.Vector3)setOps[opIndex + 1]; + linkInfo.angularLimitLow = valueVector; + break; + case ExtendedPhysics.PHYS_PARAM_ANGULAR_LIMIT_HIGH: + valueVector = (OMV.Vector3)setOps[opIndex + 1]; + linkInfo.angularLimitHigh = valueVector; + break; + case ExtendedPhysics.PHYS_PARAM_USE_FRAME_OFFSET: + valueBool = (bool)setOps[opIndex + 1]; + linkInfo.useFrameOffset = valueBool; + break; + case ExtendedPhysics.PHYS_PARAM_ENABLE_TRANSMOTOR: + valueBool = (bool)setOps[opIndex + 1]; + linkInfo.enableTransMotor = valueBool; + break; + case ExtendedPhysics.PHYS_PARAM_TRANSMOTOR_MAXVEL: + valueFloat = (float)setOps[opIndex + 1]; + linkInfo.transMotorMaxVel = valueFloat; + break; + case ExtendedPhysics.PHYS_PARAM_TRANSMOTOR_MAXFORCE: + valueFloat = (float)setOps[opIndex + 1]; + linkInfo.transMotorMaxForce = valueFloat; + break; + case ExtendedPhysics.PHYS_PARAM_CFM: + valueFloat = (float)setOps[opIndex + 1]; + linkInfo.cfm = valueFloat; + break; + case ExtendedPhysics.PHYS_PARAM_ERP: + valueFloat = (float)setOps[opIndex + 1]; + linkInfo.erp = valueFloat; + break; + case ExtendedPhysics.PHYS_PARAM_SOLVER_ITERATIONS: + valueFloat = (float)setOps[opIndex + 1]; + linkInfo.solverIterations = valueFloat; + break; + case ExtendedPhysics.PHYS_PARAM_SPRING_DAMPING: + valueFloat = (float)setOps[opIndex + 1]; + linkInfo.springDamping = valueFloat; + break; + case ExtendedPhysics.PHYS_PARAM_SPRING_STIFFNESS: + valueFloat = (float)setOps[opIndex + 1]; + linkInfo.springStiffness = valueFloat; + break; + default: + break; + } + } + } + } + } + } + catch (Exception e) { - case ExtendedPhysics.PHYS_PARAM_FRAMEINA_LOC: - case ExtendedPhysics.PHYS_PARAM_FRAMEINA_ROT: - case ExtendedPhysics.PHYS_PARAM_FRAMEINB_LOC: - case ExtendedPhysics.PHYS_PARAM_FRAMEINB_ROT: - case ExtendedPhysics.PHYS_PARAM_LINEAR_LIMIT_LOW: - case ExtendedPhysics.PHYS_PARAM_LINEAR_LIMIT_HIGH: - case ExtendedPhysics.PHYS_PARAM_ANGULAR_LIMIT_LOW: - case ExtendedPhysics.PHYS_PARAM_ANGULAR_LIMIT_HIGH: - case ExtendedPhysics.PHYS_PARAM_USE_FRAME_OFFSET: - case ExtendedPhysics.PHYS_PARAM_ENABLE_TRANSMOTOR: - case ExtendedPhysics.PHYS_PARAM_TRANSMOTOR_MAXVEL: - case ExtendedPhysics.PHYS_PARAM_TRANSMOTOR_MAXFORCE: - case ExtendedPhysics.PHYS_PARAM_CFM: - case ExtendedPhysics.PHYS_PARAM_ERP: - case ExtendedPhysics.PHYS_PARAM_SOLVER_ITERATIONS: - case ExtendedPhysics.PHYS_PARAM_SPRING_DAMPING: - case ExtendedPhysics.PHYS_PARAM_SPRING_STIFFNESS: - break; + // There are many ways to mess up the parameters. If not just right don't fail without some error. + m_physicsScene.Logger.WarnFormat("{0} bad parameters in physSetLinksetParams: {1}", LogHeader, e); } break; default: diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs index 6136257..28ea8c0 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs @@ -317,14 +317,21 @@ public class BSPrimLinkable : BSPrimDisplaced // Params: PhysActor linkedPrim, int typeCode case ExtendedPhysics.PhysFunctChangeLinkType: { - Linkset.Extension(pFunct, pParams); + ret = Linkset.Extension(pFunct, pParams); + break; + } + // physGetLinkType(linknum); + // Params: PhysActor linkedPrim + case ExtendedPhysics.PhysFunctGetLinkType: + { + ret = Linkset.Extension(pFunct, pParams); break; } // physChangeLinkParams(linknum, [code, value, code, value, ...]); // Params: PhysActor linkedPrim, object[] params case ExtendedPhysics.PhysFunctChangeLinkParams: { - Linkset.Extension(pFunct, pParams); + ret = Linkset.Extension(pFunct, pParams); break; } default: -- cgit v1.1 From 6d83f3f02190509119f65da92def19d08ef825f9 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Mon, 19 Aug 2013 11:08:22 -0700 Subject: BulletSim: adjust avatar capsule height calculation to be closer to defined SL heights. Correct BSParam avatar height defaults to be what's in OpenSimDefaults.ini. --- OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs | 15 ++++++++++----- OpenSim/Region/Physics/BulletSPlugin/BSParam.cs | 4 ++-- 2 files changed, 12 insertions(+), 7 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index 291dfcd..28b2a7e 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -676,18 +676,20 @@ public sealed class BSCharacter : BSPhysObject float heightAdjust = BSParam.AvatarHeightMidFudge; if (BSParam.AvatarHeightLowFudge != 0f || BSParam.AvatarHeightHighFudge != 0f) { - // An avatar is between 1.61 and 2.12 meters. Midpoint is 1.87m. - // The "times 4" relies on the fact that the difference from the midpoint to the extremes is exactly 0.25 - float midHeightOffset = size.Z - 1.87f; + const float AVATAR_LOW = 1.1f; + const float AVATAR_MID = 1.775f; // 1.87f + const float AVATAR_HI = 2.45f; + // An avatar is between 1.1 and 2.45 meters. Midpoint is 1.775m. + float midHeightOffset = size.Z - AVATAR_MID; if (midHeightOffset < 0f) { // Small avatar. Add the adjustment based on the distance from midheight - heightAdjust += -1f * midHeightOffset * 4f * BSParam.AvatarHeightLowFudge; + heightAdjust += ((-1f * midHeightOffset) / (AVATAR_MID - AVATAR_LOW)) * BSParam.AvatarHeightLowFudge; } else { // Large avatar. Add the adjustment based on the distance from midheight - heightAdjust += midHeightOffset * 4f * BSParam.AvatarHeightHighFudge; + heightAdjust += ((midHeightOffset) / (AVATAR_HI - AVATAR_MID)) * BSParam.AvatarHeightHighFudge; } } // The total scale height is the central cylindar plus the caps on the two ends. @@ -698,6 +700,9 @@ public sealed class BSCharacter : BSPhysObject if (newScale.Z < 0) newScale.Z = 0.1f; + DetailLog("{0},BSCharacter.ComputerAvatarScale,size={1},lowF={2},midF={3},hiF={4},adj={5},newScale={6}", + LocalID, size, BSParam.AvatarHeightLowFudge, BSParam.AvatarHeightMidFudge, BSParam.AvatarHeightHighFudge, heightAdjust, newScale); + return newScale; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs index 737dda1..4e92e6d 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs @@ -570,9 +570,9 @@ public static class BSParam new ParameterDefn("AvatarHeightLowFudge", "A fudge factor to make small avatars stand on the ground", -0.2f ), new ParameterDefn("AvatarHeightMidFudge", "A fudge distance to adjust average sized avatars to be standing on ground", - 0.2f ), + 0.1f ), new ParameterDefn("AvatarHeightHighFudge", "A fudge factor to make tall avatars stand on the ground", - 0.2f ), + 0.1f ), new ParameterDefn("AvatarContactProcessingThreshold", "Distance from capsule to check for collisions", 0.1f ), new ParameterDefn("AvatarBelowGroundUpCorrectionMeters", "Meters to move avatar up if it seems to be below ground", -- cgit v1.1 From 4781297b4ee5908b76039ce3b38291eb2e89e157 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 20 Aug 2013 08:14:08 -0700 Subject: BulletSim: Extension parameters passed through the classes made to pass just and array of objects rather than a mixture of parameters and array. Makes understanding and parsing what is being passed much easier. --- .../Physics/BulletSPlugin/BSLinksetConstraints.cs | 93 ++++++++++++++++------ OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 1 + .../Region/Physics/BulletSPlugin/BSPrimLinkable.cs | 15 ++-- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 1 + 4 files changed, 80 insertions(+), 30 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs index 92df84e..87716b4 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs @@ -343,7 +343,7 @@ public sealed class BSLinksetConstraints : BSLinkset // real world coordinate of midpoint between the two objects OMV.Vector3 midPoint = rootPrim.Position + (childRelativePosition / 2); - DetailLog("{0},BSLinksetConstraint.BuildConstraint,6Dof,rBody={1},cBody={2},rLoc={3},cLoc={4},midLoc={7}", + DetailLog("{0},BSLinksetConstraint.BuildConstraint,6Dof,rBody={1},cBody={2},rLoc={3},cLoc={4},midLoc={5}", rootPrim.LocalID, rootPrim.PhysBody, linkInfo.member.PhysBody, rootPrim.Position, linkInfo.member.Position, midPoint); @@ -492,11 +492,12 @@ public sealed class BSLinksetConstraints : BSLinkset object ret = null; switch (pFunct) { - // pParams = (int linkNUm, PhysActor linkChild) + // pParams = [ BSPhysObject child, integer linkType ] case ExtendedPhysics.PhysFunctChangeLinkType: if (pParams.Length > 1) { int requestedType = (int)pParams[1]; + DetailLog("{0},BSLinksetConstraint.SetLinkType,requestedType={1}", LinksetRoot.LocalID, requestedType); if (requestedType == (int)ConstraintType.FIXED_CONSTRAINT_TYPE || requestedType == (int)ConstraintType.D6_CONSTRAINT_TYPE || requestedType == (int)ConstraintType.D6_SPRING_CONSTRAINT_TYPE @@ -507,7 +508,7 @@ public sealed class BSLinksetConstraints : BSLinkset BSPrimLinkable child = pParams[0] as BSPrimLinkable; if (child != null) { - m_physicsScene.TaintedObject("BSLinksetConstraint.PhysFunctChangeLinkFixed", delegate() + m_physicsScene.TaintedObject("BSLinksetConstraint.PhysFunctChangeLinkType", delegate() { // Pick up all the constraints currently created. RemoveDependencies(child); @@ -522,15 +523,35 @@ public sealed class BSLinksetConstraints : BSLinkset linkInfoC.ResetLink(); linkInfoC.constraintType = (ConstraintType)requestedType; ret = (object)true; + DetailLog("{0},BSLinksetConstraint.SetLinkType,link={1},type={2}", + linkInfo.member.LocalID, linkInfo.member.LocalID, linkInfoC.constraintType); + } + else + { + DetailLog("{0},BSLinksetConstraint.SetLinkType,linkInfoNotConstraint,childID={1}", LinksetRoot.LocalID, child.LocalID); } } + else + { + DetailLog("{0},BSLinksetConstraint.SetLinkType,noLinkInfoForChild,childID={1}", LinksetRoot.LocalID, child.LocalID); + } // Cause the whole linkset to be rebuilt in post-taint time. Refresh(child); }); } + else + { + DetailLog("{0},BSLinksetConstraint.SetLinkType,childNotBSPrimLinkable", LinksetRoot.LocalID); + } + } + else + { + DetailLog("{0},BSLinksetConstraint.SetLinkType,illegalRequestedType,reqested={1},spring={2}", + LinksetRoot.LocalID, requestedType, ((int)ConstraintType.D6_SPRING_CONSTRAINT_TYPE)); } } break; + // pParams = [] case ExtendedPhysics.PhysFunctGetLinkType: if (pParams.Length > 0) { @@ -544,11 +565,15 @@ public sealed class BSLinksetConstraints : BSLinkset if (linkInfoC != null) { ret = (object)(int)linkInfoC.constraintType; + DetailLog("{0},BSLinksetConstraint.GetLinkType,link={1},type={2}", + linkInfo.member.LocalID, linkInfo.member.LocalID, linkInfoC.constraintType); + } } } } break; + // pParams = [ BSPhysObject child, int op, object opParams, int op, object opParams, ... ] case ExtendedPhysics.PhysFunctChangeLinkParams: // There should be two parameters: the childActor and a list of parameters to set try @@ -556,7 +581,6 @@ public sealed class BSLinksetConstraints : BSLinkset if (pParams.Length > 1) { BSPrimLinkable child = pParams[0] as BSPrimLinkable; - object[] setOps = (object[])pParams[1]; BSLinkInfo baseLinkInfo = null; if (TryGetLinkInfo(child, out baseLinkInfo)) { @@ -568,85 +592,106 @@ public sealed class BSLinksetConstraints : BSLinkset OMV.Vector3 valueVector; OMV.Quaternion valueQuaternion; - int opIndex = 0; - while (opIndex < setOps.Length) + int opIndex = 1; + while (opIndex < pParams.Length) { - int thisOp = (int)setOps[opIndex]; + int thisOp = (int)pParams[opIndex]; + DetailLog("{0},BSLinksetConstraint.ChangeLinkParams2,op={1},val={2}", + linkInfo.member.LocalID, thisOp, pParams[opIndex+1]); switch (thisOp) { case ExtendedPhysics.PHYS_PARAM_FRAMEINA_LOC: - valueVector = (OMV.Vector3)setOps[opIndex + 1]; + valueVector = (OMV.Vector3)pParams[opIndex + 1]; linkInfo.frameInAloc = valueVector; + opIndex += 2; break; case ExtendedPhysics.PHYS_PARAM_FRAMEINA_ROT: - valueQuaternion = (OMV.Quaternion)setOps[opIndex + 1]; + valueQuaternion = (OMV.Quaternion)pParams[opIndex + 1]; linkInfo.frameInArot = valueQuaternion; + opIndex += 2; break; case ExtendedPhysics.PHYS_PARAM_FRAMEINB_LOC: - valueVector = (OMV.Vector3)setOps[opIndex + 1]; + valueVector = (OMV.Vector3)pParams[opIndex + 1]; linkInfo.frameInBloc = valueVector; + opIndex += 2; break; case ExtendedPhysics.PHYS_PARAM_FRAMEINB_ROT: - valueQuaternion = (OMV.Quaternion)setOps[opIndex + 1]; + valueQuaternion = (OMV.Quaternion)pParams[opIndex + 1]; linkInfo.frameInBrot = valueQuaternion; + opIndex += 2; break; case ExtendedPhysics.PHYS_PARAM_LINEAR_LIMIT_LOW: - valueVector = (OMV.Vector3)setOps[opIndex + 1]; + valueVector = (OMV.Vector3)pParams[opIndex + 1]; linkInfo.linearLimitLow = valueVector; + opIndex += 2; break; case ExtendedPhysics.PHYS_PARAM_LINEAR_LIMIT_HIGH: - valueVector = (OMV.Vector3)setOps[opIndex + 1]; + valueVector = (OMV.Vector3)pParams[opIndex + 1]; linkInfo.linearLimitHigh = valueVector; + opIndex += 2; break; case ExtendedPhysics.PHYS_PARAM_ANGULAR_LIMIT_LOW: - valueVector = (OMV.Vector3)setOps[opIndex + 1]; + valueVector = (OMV.Vector3)pParams[opIndex + 1]; linkInfo.angularLimitLow = valueVector; + opIndex += 2; break; case ExtendedPhysics.PHYS_PARAM_ANGULAR_LIMIT_HIGH: - valueVector = (OMV.Vector3)setOps[opIndex + 1]; + valueVector = (OMV.Vector3)pParams[opIndex + 1]; linkInfo.angularLimitHigh = valueVector; + opIndex += 2; break; case ExtendedPhysics.PHYS_PARAM_USE_FRAME_OFFSET: - valueBool = (bool)setOps[opIndex + 1]; + valueBool = (bool)pParams[opIndex + 1]; linkInfo.useFrameOffset = valueBool; + opIndex += 2; break; case ExtendedPhysics.PHYS_PARAM_ENABLE_TRANSMOTOR: - valueBool = (bool)setOps[opIndex + 1]; + valueBool = (bool)pParams[opIndex + 1]; linkInfo.enableTransMotor = valueBool; + opIndex += 2; break; case ExtendedPhysics.PHYS_PARAM_TRANSMOTOR_MAXVEL: - valueFloat = (float)setOps[opIndex + 1]; + valueFloat = (float)pParams[opIndex + 1]; linkInfo.transMotorMaxVel = valueFloat; + opIndex += 2; break; case ExtendedPhysics.PHYS_PARAM_TRANSMOTOR_MAXFORCE: - valueFloat = (float)setOps[opIndex + 1]; + valueFloat = (float)pParams[opIndex + 1]; linkInfo.transMotorMaxForce = valueFloat; + opIndex += 2; break; case ExtendedPhysics.PHYS_PARAM_CFM: - valueFloat = (float)setOps[opIndex + 1]; + valueFloat = (float)pParams[opIndex + 1]; linkInfo.cfm = valueFloat; + opIndex += 2; break; case ExtendedPhysics.PHYS_PARAM_ERP: - valueFloat = (float)setOps[opIndex + 1]; + valueFloat = (float)pParams[opIndex + 1]; linkInfo.erp = valueFloat; + opIndex += 2; break; case ExtendedPhysics.PHYS_PARAM_SOLVER_ITERATIONS: - valueFloat = (float)setOps[opIndex + 1]; + valueFloat = (float)pParams[opIndex + 1]; linkInfo.solverIterations = valueFloat; + opIndex += 2; break; case ExtendedPhysics.PHYS_PARAM_SPRING_DAMPING: - valueFloat = (float)setOps[opIndex + 1]; + valueFloat = (float)pParams[opIndex + 1]; linkInfo.springDamping = valueFloat; + opIndex += 2; break; case ExtendedPhysics.PHYS_PARAM_SPRING_STIFFNESS: - valueFloat = (float)setOps[opIndex + 1]; + valueFloat = (float)pParams[opIndex + 1]; linkInfo.springStiffness = valueFloat; + opIndex += 2; break; default: break; } } } + // Something changed so a rebuild is in order + Refresh(child); } } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 4685b48..45056bc 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -1552,6 +1552,7 @@ public class BSPrim : BSPhysObject #region Extension public override object Extension(string pFunct, params object[] pParams) { + DetailLog("{0} BSPrim.Extension,op={1}", LocalID, pFunct); object ret = null; switch (pFunct) { diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs index 28ea8c0..531f8fb 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs @@ -283,17 +283,20 @@ public class BSPrimLinkable : BSPrimDisplaced #region Extension public override object Extension(string pFunct, params object[] pParams) { + DetailLog("{0} BSPrimLinkable.Extension,op={1},nParam={2}", LocalID, pFunct, pParams.Length); object ret = null; switch (pFunct) { // physGetLinksetType(); + // pParams = [] case ExtendedPhysics.PhysFunctGetLinksetType: { ret = (object)LinksetType; - m_log.DebugFormat("{0} Extension.physGetLinksetType, type={1}", LogHeader, ret); + DetailLog("{0},BSPrimLinkable.Extension.physGetLinksetType,type={1}", LocalID, ret); break; } // physSetLinksetType(type); + // pParams = [ BSPhysObject child, integer type ] case ExtendedPhysics.PhysFunctSetLinksetType: { if (pParams.Length > 0) @@ -304,8 +307,8 @@ public class BSPrimLinkable : BSPrimDisplaced PhysScene.TaintedObject("BSPrim.PhysFunctSetLinksetType", delegate() { // Cause the linkset type to change - m_log.DebugFormat("{0} Extension.physSetLinksetType, oldType={1}, newType={2}", - LogHeader, Linkset.LinksetImpl, linksetType); + DetailLog("{0},BSPrimLinkable.Extension.physSetLinksetType, oldType={1},newType={2}", + LocalID, Linkset.LinksetImpl, linksetType); ConvertLinkset(linksetType); }); } @@ -314,21 +317,21 @@ public class BSPrimLinkable : BSPrimDisplaced break; } // physChangeLinkType(linknum, typeCode); - // Params: PhysActor linkedPrim, int typeCode + // pParams = [ BSPhysObject child, integer linkType ] case ExtendedPhysics.PhysFunctChangeLinkType: { ret = Linkset.Extension(pFunct, pParams); break; } // physGetLinkType(linknum); - // Params: PhysActor linkedPrim + // pParams = [ BSPhysObject child ] case ExtendedPhysics.PhysFunctGetLinkType: { ret = Linkset.Extension(pFunct, pParams); break; } // physChangeLinkParams(linknum, [code, value, code, value, ...]); - // Params: PhysActor linkedPrim, object[] params + // pParams = [ BSPhysObject child, object[] [ string op, object opParam, string op, object opParam, ... ] ] case ExtendedPhysics.PhysFunctChangeLinkParams: { ret = Linkset.Extension(pFunct, pParams); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index 7440468..b2ec0e5 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -869,6 +869,7 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters #region Extensions public override object Extension(string pFunct, params object[] pParams) { + DetailLog("{0} BSScene.Extension,op={1}", DetailLogZero, pFunct); return base.Extension(pFunct, pParams); } #endregion // Extensions -- cgit v1.1 From 995314f91f72eef0048a58f30e8dd8051f6bf14e Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 20 Aug 2013 09:20:48 -0700 Subject: BulletSim: add ID parameter to TaintedObject calls so logging will include LocalID of object which created the taint. --- .../Physics/BulletSPlugin/BSActorAvatarMove.cs | 2 +- .../Region/Physics/BulletSPlugin/BSCharacter.cs | 26 +++++----- .../Physics/BulletSPlugin/BSLinksetConstraints.cs | 4 +- OpenSim/Region/Physics/BulletSPlugin/BSParam.cs | 2 +- .../Region/Physics/BulletSPlugin/BSPhysObject.cs | 6 +-- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 58 +++++++++++----------- .../Region/Physics/BulletSPlugin/BSPrimLinkable.cs | 6 +-- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 55 +++++++++++++------- 8 files changed, 89 insertions(+), 70 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs b/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs index 68bc1b9..04a4a32 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs @@ -105,7 +105,7 @@ public class BSActorAvatarMove : BSActor // into the movement motor. public void SetVelocityAndTarget(OMV.Vector3 vel, OMV.Vector3 targ, bool inTaintTime) { - m_physicsScene.TaintedObject(inTaintTime, "BSActorAvatarMove.setVelocityAndTarget", delegate() + m_physicsScene.TaintedObject(inTaintTime, m_controllingPrim.LocalID, "BSActorAvatarMove.setVelocityAndTarget", delegate() { if (m_velocityMotor != null) { diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index 28b2a7e..fc18960 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -93,7 +93,7 @@ public sealed class BSCharacter : BSPhysObject LocalID, _size, Scale, Density, _avatarVolume, RawMass, pos); // do actual creation in taint time - PhysScene.TaintedObject("BSCharacter.create", delegate() + PhysScene.TaintedObject(LocalID, "BSCharacter.create", delegate() { DetailLog("{0},BSCharacter.create,taint", LocalID); // New body and shape into PhysBody and PhysShape @@ -121,7 +121,7 @@ public sealed class BSCharacter : BSPhysObject base.Destroy(); DetailLog("{0},BSCharacter.Destroy", LocalID); - PhysScene.TaintedObject("BSCharacter.destroy", delegate() + PhysScene.TaintedObject(LocalID, "BSCharacter.destroy", delegate() { PhysScene.Shapes.DereferenceBody(PhysBody, null /* bodyCallback */); PhysBody.Clear(); @@ -209,7 +209,7 @@ public sealed class BSCharacter : BSPhysObject DetailLog("{0},BSCharacter.setSize,call,size={1},scale={2},density={3},volume={4},mass={5}", LocalID, _size, Scale, Density, _avatarVolume, RawMass); - PhysScene.TaintedObject("BSCharacter.setSize", delegate() + PhysScene.TaintedObject(LocalID, "BSCharacter.setSize", delegate() { if (PhysBody.HasPhysicalBody && PhysShape.physShapeInfo.HasPhysicalShape) { @@ -257,7 +257,7 @@ public sealed class BSCharacter : BSPhysObject _rotationalVelocity = OMV.Vector3.Zero; // Zero some other properties directly into the physics engine - PhysScene.TaintedObject(inTaintTime, "BSCharacter.ZeroMotion", delegate() + PhysScene.TaintedObject(inTaintTime, LocalID, "BSCharacter.ZeroMotion", delegate() { if (PhysBody.HasPhysicalBody) PhysScene.PE.ClearAllForces(PhysBody); @@ -267,7 +267,7 @@ public sealed class BSCharacter : BSPhysObject { _rotationalVelocity = OMV.Vector3.Zero; - PhysScene.TaintedObject(inTaintTime, "BSCharacter.ZeroMotion", delegate() + PhysScene.TaintedObject(inTaintTime, LocalID, "BSCharacter.ZeroMotion", delegate() { if (PhysBody.HasPhysicalBody) { @@ -291,7 +291,7 @@ public sealed class BSCharacter : BSPhysObject set { RawPosition = value; - PhysScene.TaintedObject("BSCharacter.setPosition", delegate() + PhysScene.TaintedObject(LocalID, "BSCharacter.setPosition", delegate() { DetailLog("{0},BSCharacter.SetPosition,taint,pos={1},orient={2}", LocalID, RawPosition, RawOrientation); PositionSanityCheck(); @@ -363,7 +363,7 @@ public sealed class BSCharacter : BSPhysObject { // The new position value must be pushed into the physics engine but we can't // just assign to "Position" because of potential call loops. - PhysScene.TaintedObject(inTaintTime, "BSCharacter.PositionSanityCheck", delegate() + PhysScene.TaintedObject(inTaintTime, LocalID, "BSCharacter.PositionSanityCheck", delegate() { DetailLog("{0},BSCharacter.PositionSanityCheck,taint,pos={1},orient={2}", LocalID, RawPosition, RawOrientation); ForcePosition = RawPosition; @@ -390,7 +390,7 @@ public sealed class BSCharacter : BSPhysObject set { RawForce = value; // m_log.DebugFormat("{0}: Force = {1}", LogHeader, _force); - PhysScene.TaintedObject("BSCharacter.SetForce", delegate() + PhysScene.TaintedObject(LocalID, "BSCharacter.SetForce", delegate() { DetailLog("{0},BSCharacter.setForce,taint,force={1}", LocalID, RawForce); if (PhysBody.HasPhysicalBody) @@ -438,7 +438,7 @@ public sealed class BSCharacter : BSPhysObject set { RawVelocity = value; // m_log.DebugFormat("{0}: set velocity = {1}", LogHeader, RawVelocity); - PhysScene.TaintedObject("BSCharacter.setVelocity", delegate() + PhysScene.TaintedObject(LocalID, "BSCharacter.setVelocity", delegate() { if (m_moveActor != null) m_moveActor.SetVelocityAndTarget(RawVelocity, RawVelocity, true /* inTaintTime */); @@ -480,7 +480,7 @@ public sealed class BSCharacter : BSPhysObject if (RawOrientation != value) { RawOrientation = value; - PhysScene.TaintedObject("BSCharacter.setOrientation", delegate() + PhysScene.TaintedObject(LocalID, "BSCharacter.setOrientation", delegate() { // Bullet assumes we know what we are doing when forcing orientation // so it lets us go against all the rules and just compensates for them later. @@ -560,7 +560,7 @@ public sealed class BSCharacter : BSPhysObject public override bool FloatOnWater { set { _floatOnWater = value; - PhysScene.TaintedObject("BSCharacter.setFloatOnWater", delegate() + PhysScene.TaintedObject(LocalID, "BSCharacter.setFloatOnWater", delegate() { if (PhysBody.HasPhysicalBody) { @@ -588,7 +588,7 @@ public sealed class BSCharacter : BSPhysObject public override float Buoyancy { get { return _buoyancy; } set { _buoyancy = value; - PhysScene.TaintedObject("BSCharacter.setBuoyancy", delegate() + PhysScene.TaintedObject(LocalID, "BSCharacter.setBuoyancy", delegate() { DetailLog("{0},BSCharacter.setBuoyancy,taint,buoy={1}", LocalID, _buoyancy); ForceBuoyancy = _buoyancy; @@ -633,7 +633,7 @@ public sealed class BSCharacter : BSPhysObject OMV.Vector3 addForce = Util.ClampV(force, BSParam.MaxAddForceMagnitude); // DetailLog("{0},BSCharacter.addForce,call,force={1}", LocalID, addForce); - PhysScene.TaintedObject(inTaintTime, "BSCharacter.AddForce", delegate() + PhysScene.TaintedObject(inTaintTime, LocalID, "BSCharacter.AddForce", delegate() { // Bullet adds this central force to the total force for this tick // DetailLog("{0},BSCharacter.addForce,taint,force={1}", LocalID, addForce); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs index 87716b4..b2a9501 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs @@ -297,7 +297,7 @@ public sealed class BSLinksetConstraints : BSLinkset rootx.LocalID, rootx.PhysBody.AddrString, childx.LocalID, childx.PhysBody.AddrString); - m_physicsScene.TaintedObject(inTaintTime, "BSLinksetConstraints.RemoveChildFromLinkset", delegate() + m_physicsScene.TaintedObject(inTaintTime, childx.LocalID, "BSLinksetConstraints.RemoveChildFromLinkset", delegate() { PhysicallyUnlinkAChildFromRoot(rootx, childx); }); @@ -508,7 +508,7 @@ public sealed class BSLinksetConstraints : BSLinkset BSPrimLinkable child = pParams[0] as BSPrimLinkable; if (child != null) { - m_physicsScene.TaintedObject("BSLinksetConstraint.PhysFunctChangeLinkType", delegate() + m_physicsScene.TaintedObject(child.LocalID, "BSLinksetConstraint.PhysFunctChangeLinkType", delegate() { // Pick up all the constraints currently created. RemoveDependencies(child); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs index 4e92e6d..2f1799b 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs @@ -826,7 +826,7 @@ public static class BSParam private static void ResetConstraintSolverTainted(BSScene pPhysScene, float v) { BSScene physScene = pPhysScene; - physScene.TaintedObject("BSParam.ResetConstraintSolver", delegate() + physScene.TaintedObject(BSScene.DetailLogZero, "BSParam.ResetConstraintSolver", delegate() { physScene.PE.ResetConstraintSolver(physScene.World); }); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index 9dc52d5..2efb1a5 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -121,7 +121,7 @@ public abstract class BSPhysObject : PhysicsActor public virtual void Destroy() { PhysicalActors.Enable(false); - PhysScene.TaintedObject("BSPhysObject.Destroy", delegate() + PhysScene.TaintedObject(LocalID, "BSPhysObject.Destroy", delegate() { PhysicalActors.Dispose(); }); @@ -509,7 +509,7 @@ public abstract class BSPhysObject : PhysicsActor // make sure first collision happens NextCollisionOkTime = Util.EnvironmentTickCountSubtract(SubscribedEventsMs); - PhysScene.TaintedObject(TypeName+".SubscribeEvents", delegate() + PhysScene.TaintedObject(LocalID, TypeName+".SubscribeEvents", delegate() { if (PhysBody.HasPhysicalBody) CurrentCollisionFlags = PhysScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); @@ -524,7 +524,7 @@ public abstract class BSPhysObject : PhysicsActor public override void UnSubscribeEvents() { // DetailLog("{0},{1}.UnSubscribeEvents,unsubscribing", LocalID, TypeName); SubscribedEventsMs = 0; - PhysScene.TaintedObject(TypeName+".UnSubscribeEvents", delegate() + PhysScene.TaintedObject(LocalID, TypeName+".UnSubscribeEvents", delegate() { // Make sure there is a body there because sometimes destruction happens in an un-ideal order. if (PhysBody.HasPhysicalBody) diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 45056bc..15b7090 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -102,7 +102,7 @@ public class BSPrim : BSPhysObject // DetailLog("{0},BSPrim.constructor,call", LocalID); // do the actual object creation at taint time - PhysScene.TaintedObject("BSPrim.create", delegate() + PhysScene.TaintedObject(LocalID, "BSPrim.create", delegate() { // Make sure the object is being created with some sanity. ExtremeSanityCheck(true /* inTaintTime */); @@ -126,7 +126,7 @@ public class BSPrim : BSPhysObject // Undo any vehicle properties this.VehicleType = (int)Vehicle.TYPE_NONE; - PhysScene.TaintedObject("BSPrim.Destroy", delegate() + PhysScene.TaintedObject(LocalID, "BSPrim.Destroy", delegate() { DetailLog("{0},BSPrim.Destroy,taint,", LocalID); // If there are physical body and shape, release my use of same. @@ -161,7 +161,7 @@ public class BSPrim : BSPhysObject } public override bool ForceBodyShapeRebuild(bool inTaintTime) { - PhysScene.TaintedObject(inTaintTime, "BSPrim.ForceBodyShapeRebuild", delegate() + PhysScene.TaintedObject(inTaintTime, LocalID, "BSPrim.ForceBodyShapeRebuild", delegate() { _mass = CalculateMass(); // changing the shape changes the mass CreateGeomAndObject(true); @@ -178,7 +178,7 @@ public class BSPrim : BSPhysObject if (value != _isSelected) { _isSelected = value; - PhysScene.TaintedObject("BSPrim.setSelected", delegate() + PhysScene.TaintedObject(LocalID, "BSPrim.setSelected", delegate() { DetailLog("{0},BSPrim.selected,taint,selected={1}", LocalID, _isSelected); SetObjectDynamic(false); @@ -224,7 +224,7 @@ public class BSPrim : BSPhysObject _rotationalVelocity = OMV.Vector3.Zero; // Zero some other properties in the physics engine - PhysScene.TaintedObject(inTaintTime, "BSPrim.ZeroMotion", delegate() + PhysScene.TaintedObject(inTaintTime, LocalID, "BSPrim.ZeroMotion", delegate() { if (PhysBody.HasPhysicalBody) PhysScene.PE.ClearAllForces(PhysBody); @@ -234,7 +234,7 @@ public class BSPrim : BSPhysObject { _rotationalVelocity = OMV.Vector3.Zero; // Zero some other properties in the physics engine - PhysScene.TaintedObject(inTaintTime, "BSPrim.ZeroMotion", delegate() + PhysScene.TaintedObject(inTaintTime, LocalID, "BSPrim.ZeroMotion", delegate() { // DetailLog("{0},BSPrim.ZeroAngularMotion,call,rotVel={1}", LocalID, _rotationalVelocity); if (PhysBody.HasPhysicalBody) @@ -262,7 +262,7 @@ public class BSPrim : BSPhysObject }); // Update parameters so the new actor's Refresh() action is called at the right time. - PhysScene.TaintedObject("BSPrim.LockAngularMotion", delegate() + PhysScene.TaintedObject(LocalID, "BSPrim.LockAngularMotion", delegate() { UpdatePhysicalParameters(); }); @@ -287,7 +287,7 @@ public class BSPrim : BSPhysObject RawPosition = value; PositionSanityCheck(false); - PhysScene.TaintedObject("BSPrim.setPosition", delegate() + PhysScene.TaintedObject(LocalID, "BSPrim.setPosition", delegate() { DetailLog("{0},BSPrim.SetPosition,taint,pos={1},orient={2}", LocalID, RawPosition, RawOrientation); ForcePosition = RawPosition; @@ -531,7 +531,7 @@ public class BSPrim : BSPhysObject set { Vehicle type = (Vehicle)value; - PhysScene.TaintedObject("setVehicleType", delegate() + PhysScene.TaintedObject(LocalID, "setVehicleType", delegate() { // Some vehicle scripts change vehicle type on the fly as an easy way to // change all the parameters. Like a plane changing to CAR when on the @@ -561,7 +561,7 @@ public class BSPrim : BSPhysObject } public override void VehicleFloatParam(int param, float value) { - PhysScene.TaintedObject("BSPrim.VehicleFloatParam", delegate() + PhysScene.TaintedObject(LocalID, "BSPrim.VehicleFloatParam", delegate() { BSDynamics vehicleActor = GetVehicleActor(true /* createIfNone */); if (vehicleActor != null) @@ -573,7 +573,7 @@ public class BSPrim : BSPhysObject } public override void VehicleVectorParam(int param, OMV.Vector3 value) { - PhysScene.TaintedObject("BSPrim.VehicleVectorParam", delegate() + PhysScene.TaintedObject(LocalID, "BSPrim.VehicleVectorParam", delegate() { BSDynamics vehicleActor = GetVehicleActor(true /* createIfNone */); if (vehicleActor != null) @@ -585,7 +585,7 @@ public class BSPrim : BSPhysObject } public override void VehicleRotationParam(int param, OMV.Quaternion rotation) { - PhysScene.TaintedObject("BSPrim.VehicleRotationParam", delegate() + PhysScene.TaintedObject(LocalID, "BSPrim.VehicleRotationParam", delegate() { BSDynamics vehicleActor = GetVehicleActor(true /* createIfNone */); if (vehicleActor != null) @@ -597,7 +597,7 @@ public class BSPrim : BSPhysObject } public override void VehicleFlags(int param, bool remove) { - PhysScene.TaintedObject("BSPrim.VehicleFlags", delegate() + PhysScene.TaintedObject(LocalID, "BSPrim.VehicleFlags", delegate() { BSDynamics vehicleActor = GetVehicleActor(true /* createIfNone */); if (vehicleActor != null) @@ -613,7 +613,7 @@ public class BSPrim : BSPhysObject if (_isVolumeDetect != newValue) { _isVolumeDetect = newValue; - PhysScene.TaintedObject("BSPrim.SetVolumeDetect", delegate() + PhysScene.TaintedObject(LocalID, "BSPrim.SetVolumeDetect", delegate() { // DetailLog("{0},setVolumeDetect,taint,volDetect={1}", LocalID, _isVolumeDetect); SetObjectDynamic(true); @@ -628,7 +628,7 @@ public class BSPrim : BSPhysObject public override void SetMaterial(int material) { base.SetMaterial(material); - PhysScene.TaintedObject("BSPrim.SetMaterial", delegate() + PhysScene.TaintedObject(LocalID, "BSPrim.SetMaterial", delegate() { UpdatePhysicalParameters(); }); @@ -641,7 +641,7 @@ public class BSPrim : BSPhysObject if (base.Friction != value) { base.Friction = value; - PhysScene.TaintedObject("BSPrim.setFriction", delegate() + PhysScene.TaintedObject(LocalID, "BSPrim.setFriction", delegate() { UpdatePhysicalParameters(); }); @@ -656,7 +656,7 @@ public class BSPrim : BSPhysObject if (base.Restitution != value) { base.Restitution = value; - PhysScene.TaintedObject("BSPrim.setRestitution", delegate() + PhysScene.TaintedObject(LocalID, "BSPrim.setRestitution", delegate() { UpdatePhysicalParameters(); }); @@ -673,7 +673,7 @@ public class BSPrim : BSPhysObject if (base.Density != value) { base.Density = value; - PhysScene.TaintedObject("BSPrim.setDensity", delegate() + PhysScene.TaintedObject(LocalID, "BSPrim.setDensity", delegate() { UpdatePhysicalParameters(); }); @@ -688,7 +688,7 @@ public class BSPrim : BSPhysObject if (base.GravModifier != value) { base.GravModifier = value; - PhysScene.TaintedObject("BSPrim.setGravityModifier", delegate() + PhysScene.TaintedObject(LocalID, "BSPrim.setGravityModifier", delegate() { UpdatePhysicalParameters(); }); @@ -699,7 +699,7 @@ public class BSPrim : BSPhysObject get { return RawVelocity; } set { RawVelocity = value; - PhysScene.TaintedObject("BSPrim.setVelocity", delegate() + PhysScene.TaintedObject(LocalID, "BSPrim.setVelocity", delegate() { // DetailLog("{0},BSPrim.SetVelocity,taint,vel={1}", LocalID, RawVelocity); ForceVelocity = RawVelocity; @@ -745,7 +745,7 @@ public class BSPrim : BSPhysObject return; RawOrientation = value; - PhysScene.TaintedObject("BSPrim.setOrientation", delegate() + PhysScene.TaintedObject(LocalID, "BSPrim.setOrientation", delegate() { ForceOrientation = RawOrientation; }); @@ -776,7 +776,7 @@ public class BSPrim : BSPhysObject if (_isPhysical != value) { _isPhysical = value; - PhysScene.TaintedObject("BSPrim.setIsPhysical", delegate() + PhysScene.TaintedObject(LocalID, "BSPrim.setIsPhysical", delegate() { DetailLog("{0},setIsPhysical,taint,isPhys={1}", LocalID, _isPhysical); SetObjectDynamic(true); @@ -1020,7 +1020,7 @@ public class BSPrim : BSPhysObject public override bool FloatOnWater { set { _floatOnWater = value; - PhysScene.TaintedObject("BSPrim.setFloatOnWater", delegate() + PhysScene.TaintedObject(LocalID, "BSPrim.setFloatOnWater", delegate() { if (_floatOnWater) CurrentCollisionFlags = PhysScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.BS_FLOATS_ON_WATER); @@ -1037,7 +1037,7 @@ public class BSPrim : BSPhysObject _rotationalVelocity = value; Util.ClampV(_rotationalVelocity, BSParam.MaxAngularVelocity); // m_log.DebugFormat("{0}: RotationalVelocity={1}", LogHeader, _rotationalVelocity); - PhysScene.TaintedObject("BSPrim.setRotationalVelocity", delegate() + PhysScene.TaintedObject(LocalID, "BSPrim.setRotationalVelocity", delegate() { ForceRotationalVelocity = _rotationalVelocity; }); @@ -1068,7 +1068,7 @@ public class BSPrim : BSPhysObject get { return _buoyancy; } set { _buoyancy = value; - PhysScene.TaintedObject("BSPrim.setBuoyancy", delegate() + PhysScene.TaintedObject(LocalID, "BSPrim.setBuoyancy", delegate() { ForceBuoyancy = _buoyancy; }); @@ -1142,7 +1142,7 @@ public class BSPrim : BSPhysObject // DetailLog("{0},BSPrim.addForce,call,force={1}", LocalID, addForce); OMV.Vector3 addForce = force; - PhysScene.TaintedObject(inTaintTime, "BSPrim.AddForce", delegate() + PhysScene.TaintedObject(inTaintTime, LocalID, "BSPrim.AddForce", delegate() { // Bullet adds this central force to the total force for this tick. // Deep down in Bullet: @@ -1172,7 +1172,7 @@ public class BSPrim : BSPhysObject OMV.Vector3 addImpulse = Util.ClampV(impulse, BSParam.MaxAddForceMagnitude); // DetailLog("{0},BSPrim.addForceImpulse,call,impulse={1}", LocalID, impulse); - PhysScene.TaintedObject(inTaintTime, "BSPrim.AddImpulse", delegate() + PhysScene.TaintedObject(inTaintTime, LocalID, "BSPrim.AddImpulse", delegate() { // Bullet adds this impulse immediately to the velocity DetailLog("{0},BSPrim.addForceImpulse,taint,impulseforce={1}", LocalID, addImpulse); @@ -1197,7 +1197,7 @@ public class BSPrim : BSPhysObject if (force.IsFinite()) { OMV.Vector3 angForce = force; - PhysScene.TaintedObject(inTaintTime, "BSPrim.AddAngularForce", delegate() + PhysScene.TaintedObject(inTaintTime, LocalID, "BSPrim.AddAngularForce", delegate() { if (PhysBody.HasPhysicalBody) { @@ -1221,7 +1221,7 @@ public class BSPrim : BSPhysObject public void ApplyTorqueImpulse(OMV.Vector3 impulse, bool inTaintTime) { OMV.Vector3 applyImpulse = impulse; - PhysScene.TaintedObject(inTaintTime, "BSPrim.ApplyTorqueImpulse", delegate() + PhysScene.TaintedObject(inTaintTime, LocalID, "BSPrim.ApplyTorqueImpulse", delegate() { if (PhysBody.HasPhysicalBody) { diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs index 531f8fb..840265b 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs @@ -108,7 +108,7 @@ public class BSPrimLinkable : BSPrimDisplaced set { base.Position = value; - PhysScene.TaintedObject("BSPrimLinkable.setPosition", delegate() + PhysScene.TaintedObject(LocalID, "BSPrimLinkable.setPosition", delegate() { Linkset.UpdateProperties(UpdatedProperties.Position, this); }); @@ -122,7 +122,7 @@ public class BSPrimLinkable : BSPrimDisplaced set { base.Orientation = value; - PhysScene.TaintedObject("BSPrimLinkable.setOrientation", delegate() + PhysScene.TaintedObject(LocalID, "BSPrimLinkable.setOrientation", delegate() { Linkset.UpdateProperties(UpdatedProperties.Orientation, this); }); @@ -304,7 +304,7 @@ public class BSPrimLinkable : BSPrimDisplaced BSLinkset.LinksetImplementation linksetType = (BSLinkset.LinksetImplementation)pParams[0]; if (Linkset.IsRoot(this)) { - PhysScene.TaintedObject("BSPrim.PhysFunctSetLinksetType", delegate() + PhysScene.TaintedObject(LocalID, "BSPrim.PhysFunctSetLinksetType", delegate() { // Cause the linkset type to change DetailLog("{0},BSPrimLinkable.Extension.physSetLinksetType, oldType={1},newType={2}", diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index b2ec0e5..24233cc 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -157,12 +157,20 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters public delegate void TaintCallback(); private struct TaintCallbackEntry { + public String originator; public String ident; public TaintCallback callback; - public TaintCallbackEntry(string i, TaintCallback c) + public TaintCallbackEntry(string pIdent, TaintCallback pCallBack) { - ident = i; - callback = c; + originator = BSScene.DetailLogZero; + ident = pIdent; + callback = pCallBack; + } + public TaintCallbackEntry(string pOrigin, string pIdent, TaintCallback pCallBack) + { + originator = pOrigin; + ident = pIdent; + callback = pCallBack; } } private Object _taintLock = new Object(); // lock for using the next object @@ -888,26 +896,37 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters // Calls to the PhysicsActors can't directly call into the physics engine // because it might be busy. We delay changes to a known time. // We rely on C#'s closure to save and restore the context for the delegate. - public void TaintedObject(String ident, TaintCallback callback) + public void TaintedObject(string pOriginator, string pIdent, TaintCallback pCallback) { - if (!m_initialized) return; - - lock (_taintLock) - { - _taintOperations.Add(new TaintCallbackEntry(ident, callback)); - } - - return; + TaintedObject(false /*inTaintTime*/, pOriginator, pIdent, pCallback); + } + public void TaintedObject(uint pOriginator, String pIdent, TaintCallback pCallback) + { + TaintedObject(false /*inTaintTime*/, m_physicsLoggingEnabled ? pOriginator.ToString() : BSScene.DetailLogZero, pIdent, pCallback); + } + public void TaintedObject(bool inTaintTime, String pIdent, TaintCallback pCallback) + { + TaintedObject(inTaintTime, BSScene.DetailLogZero, pIdent, pCallback); + } + public void TaintedObject(bool inTaintTime, uint pOriginator, String pIdent, TaintCallback pCallback) + { + TaintedObject(inTaintTime, m_physicsLoggingEnabled ? pOriginator.ToString() : BSScene.DetailLogZero, pIdent, pCallback); } - // Sometimes a potentially tainted operation can be used in and out of taint time. // This routine executes the command immediately if in taint-time otherwise it is queued. - public void TaintedObject(bool inTaintTime, string ident, TaintCallback callback) + public void TaintedObject(bool inTaintTime, string pOriginator, string pIdent, TaintCallback pCallback) { + if (!m_initialized) return; + if (inTaintTime) - callback(); + pCallback(); else - TaintedObject(ident, callback); + { + lock (_taintLock) + { + _taintOperations.Add(new TaintCallbackEntry(pOriginator, pIdent, pCallback)); + } + } } private void TriggerPreStepEvent(float timeStep) @@ -951,7 +970,7 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters { try { - DetailLog("{0},BSScene.ProcessTaints,doTaint,id={1}", DetailLogZero, tcbe.ident); // DEBUG DEBUG DEBUG + DetailLog("{0},BSScene.ProcessTaints,doTaint,id={1}", tcbe.originator, tcbe.ident); // DEBUG DEBUG DEBUG tcbe.callback(); } catch (Exception e) @@ -1081,7 +1100,7 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters string xval = val; List xlIDs = lIDs; string xparm = parm; - TaintedObject("BSScene.UpdateParameterSet", delegate() { + TaintedObject(DetailLogZero, "BSScene.UpdateParameterSet", delegate() { BSParam.ParameterDefnBase thisParam; if (BSParam.TryGetParameter(xparm, out thisParam)) { -- cgit v1.1 From d09c35f5063114880aecb94a938bfc49f5af5f7d Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 20 Aug 2013 13:09:40 -0700 Subject: BulletSim: pass both root and child BSPhysObjects to Extension function. Update routines to use the new parameters list from above change. --- .../Physics/BulletSPlugin/BSLinksetConstraints.cs | 32 ++++++++++++---------- .../Region/Physics/BulletSPlugin/BSPrimLinkable.cs | 14 +++++----- 2 files changed, 24 insertions(+), 22 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs index b2a9501..a9ae89d 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs @@ -385,7 +385,7 @@ public sealed class BSLinksetConstraints : BSLinkset linkInfo.frameInAloc, linkInfo.frameInArot, linkInfo.frameInBloc, linkInfo.frameInBrot, true /*useLinearReferenceFrameA*/, true /*disableCollisionsBetweenLinkedBodies*/); - DetailLog("{0},BSLinksetConstraint.BuildConstraint,spring,root={1},rBody={2},child={3},cBody={4},rLoc={5},cLoc={6},midLoc={7}", + DetailLog("{0},BSLinksetConstraint.BuildConstraint,spring,root={1},rBody={2},child={3},cBody={4},rLoc={5},cLoc={6}", rootPrim.LocalID, rootPrim.LocalID, rootPrim.PhysBody.AddrString, linkInfo.member.LocalID, linkInfo.member.PhysBody.AddrString, @@ -492,12 +492,12 @@ public sealed class BSLinksetConstraints : BSLinkset object ret = null; switch (pFunct) { - // pParams = [ BSPhysObject child, integer linkType ] + // pParams = [ BSPhysObject root, BSPhysObject child, integer linkType ] case ExtendedPhysics.PhysFunctChangeLinkType: - if (pParams.Length > 1) + if (pParams.Length > 2) { - int requestedType = (int)pParams[1]; - DetailLog("{0},BSLinksetConstraint.SetLinkType,requestedType={1}", LinksetRoot.LocalID, requestedType); + int requestedType = (int)pParams[2]; + DetailLog("{0},BSLinksetConstraint.ChangeLinkType,requestedType={1}", LinksetRoot.LocalID, requestedType); if (requestedType == (int)ConstraintType.FIXED_CONSTRAINT_TYPE || requestedType == (int)ConstraintType.D6_CONSTRAINT_TYPE || requestedType == (int)ConstraintType.D6_SPRING_CONSTRAINT_TYPE @@ -505,9 +505,11 @@ public sealed class BSLinksetConstraints : BSLinkset || requestedType == (int)ConstraintType.CONETWIST_CONSTRAINT_TYPE || requestedType == (int)ConstraintType.SLIDER_CONSTRAINT_TYPE) { - BSPrimLinkable child = pParams[0] as BSPrimLinkable; + BSPrimLinkable child = pParams[1] as BSPrimLinkable; if (child != null) { + DetailLog("{0},BSLinksetConstraint.ChangeLinkType,rootID={1},childID={2},type={3}", + LinksetRoot.LocalID, LinksetRoot.LocalID, child.LocalID, requestedType); m_physicsScene.TaintedObject(child.LocalID, "BSLinksetConstraint.PhysFunctChangeLinkType", delegate() { // Pick up all the constraints currently created. @@ -523,17 +525,17 @@ public sealed class BSLinksetConstraints : BSLinkset linkInfoC.ResetLink(); linkInfoC.constraintType = (ConstraintType)requestedType; ret = (object)true; - DetailLog("{0},BSLinksetConstraint.SetLinkType,link={1},type={2}", + DetailLog("{0},BSLinksetConstraint.ChangeLinkType,link={1},type={2}", linkInfo.member.LocalID, linkInfo.member.LocalID, linkInfoC.constraintType); } else { - DetailLog("{0},BSLinksetConstraint.SetLinkType,linkInfoNotConstraint,childID={1}", LinksetRoot.LocalID, child.LocalID); + DetailLog("{0},BSLinksetConstraint.ChangeLinkType,linkInfoNotConstraint,childID={1}", LinksetRoot.LocalID, child.LocalID); } } else { - DetailLog("{0},BSLinksetConstraint.SetLinkType,noLinkInfoForChild,childID={1}", LinksetRoot.LocalID, child.LocalID); + DetailLog("{0},BSLinksetConstraint.ChangeLinkType,noLinkInfoForChild,childID={1}", LinksetRoot.LocalID, child.LocalID); } // Cause the whole linkset to be rebuilt in post-taint time. Refresh(child); @@ -551,11 +553,11 @@ public sealed class BSLinksetConstraints : BSLinkset } } break; - // pParams = [] + // pParams = [ BSPhysObject root, BSPhysObject child ] case ExtendedPhysics.PhysFunctGetLinkType: if (pParams.Length > 0) { - BSPrimLinkable child = pParams[0] as BSPrimLinkable; + BSPrimLinkable child = pParams[1] as BSPrimLinkable; if (child != null) { BSLinkInfo linkInfo = null; @@ -573,14 +575,14 @@ public sealed class BSLinksetConstraints : BSLinkset } } break; - // pParams = [ BSPhysObject child, int op, object opParams, int op, object opParams, ... ] + // pParams = [ BSPhysObject root, BSPhysObject child, int op, object opParams, int op, object opParams, ... ] case ExtendedPhysics.PhysFunctChangeLinkParams: // There should be two parameters: the childActor and a list of parameters to set try { - if (pParams.Length > 1) + if (pParams.Length > 2) { - BSPrimLinkable child = pParams[0] as BSPrimLinkable; + BSPrimLinkable child = pParams[1] as BSPrimLinkable; BSLinkInfo baseLinkInfo = null; if (TryGetLinkInfo(child, out baseLinkInfo)) { @@ -592,7 +594,7 @@ public sealed class BSLinksetConstraints : BSLinkset OMV.Vector3 valueVector; OMV.Quaternion valueQuaternion; - int opIndex = 1; + int opIndex = 2; while (opIndex < pParams.Length) { int thisOp = (int)pParams[opIndex]; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs index 840265b..126b146 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrimLinkable.cs @@ -288,7 +288,7 @@ public class BSPrimLinkable : BSPrimDisplaced switch (pFunct) { // physGetLinksetType(); - // pParams = [] + // pParams = [ BSPhysObject root, null ] case ExtendedPhysics.PhysFunctGetLinksetType: { ret = (object)LinksetType; @@ -296,12 +296,12 @@ public class BSPrimLinkable : BSPrimDisplaced break; } // physSetLinksetType(type); - // pParams = [ BSPhysObject child, integer type ] + // pParams = [ BSPhysObject root, null, integer type ] case ExtendedPhysics.PhysFunctSetLinksetType: { - if (pParams.Length > 0) + if (pParams.Length > 2) { - BSLinkset.LinksetImplementation linksetType = (BSLinkset.LinksetImplementation)pParams[0]; + BSLinkset.LinksetImplementation linksetType = (BSLinkset.LinksetImplementation)pParams[2]; if (Linkset.IsRoot(this)) { PhysScene.TaintedObject(LocalID, "BSPrim.PhysFunctSetLinksetType", delegate() @@ -317,21 +317,21 @@ public class BSPrimLinkable : BSPrimDisplaced break; } // physChangeLinkType(linknum, typeCode); - // pParams = [ BSPhysObject child, integer linkType ] + // pParams = [ BSPhysObject root, BSPhysObject child, integer linkType ] case ExtendedPhysics.PhysFunctChangeLinkType: { ret = Linkset.Extension(pFunct, pParams); break; } // physGetLinkType(linknum); - // pParams = [ BSPhysObject child ] + // pParams = [ BSPhysObject root, BSPhysObject child ] case ExtendedPhysics.PhysFunctGetLinkType: { ret = Linkset.Extension(pFunct, pParams); break; } // physChangeLinkParams(linknum, [code, value, code, value, ...]); - // pParams = [ BSPhysObject child, object[] [ string op, object opParam, string op, object opParam, ... ] ] + // pParams = [ BSPhysObject root, BSPhysObject child, object[] [ string op, object opParam, string op, object opParam, ... ] ] case ExtendedPhysics.PhysFunctChangeLinkParams: { ret = Linkset.Extension(pFunct, pParams); -- cgit v1.1 From 67195618d580eb6cd848cf1e6462572ad2b2b118 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Thu, 22 Aug 2013 09:07:58 -0700 Subject: BulletSim: add requestor's ID to post taint detail log message. --- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index 24233cc..b3dfa41 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -987,10 +987,11 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters // will replace any previous operation by the same object. public void PostTaintObject(String ident, uint ID, TaintCallback callback) { - string uniqueIdent = ident + "-" + ID.ToString(); + string IDAsString = ID.ToString(); + string uniqueIdent = ident + "-" + IDAsString; lock (_taintLock) { - _postTaintOperations[uniqueIdent] = new TaintCallbackEntry(uniqueIdent, callback); + _postTaintOperations[uniqueIdent] = new TaintCallbackEntry(IDAsString, uniqueIdent, callback); } return; -- cgit v1.1 From 30b3657a66e5a4012b96baae2c0424ec13409f83 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Thu, 22 Aug 2013 09:08:58 -0700 Subject: BulletSim: implementation of setting spring specific physical parameters. Add setting of linkset type to physChangeLinkParams. Lots of detail logging for setting of linkset constraint parameters. --- .../Physics/BulletSPlugin/BSConstraint6Dof.cs | 16 ++++--- .../Physics/BulletSPlugin/BSConstraintSpring.cs | 43 ++++++++++-------- .../Physics/BulletSPlugin/BSLinksetConstraints.cs | 52 +++++++++++++++++----- 3 files changed, 76 insertions(+), 35 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSConstraint6Dof.cs b/OpenSim/Region/Physics/BulletSPlugin/BSConstraint6Dof.cs index 5008ff7..7fcb75c 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSConstraint6Dof.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSConstraint6Dof.cs @@ -59,9 +59,11 @@ public class BSConstraint6Dof : BSConstraint frame2, frame2rot, useLinearReferenceFrameA, disableCollisionsBetweenLinkedBodies); m_enabled = true; - world.physicsScene.DetailLog("{0},BS6DofConstraint,createFrame,wID={1}, rID={2}, rBody={3}, cID={4}, cBody={5}", - BSScene.DetailLogZero, world.worldID, + PhysicsScene.DetailLog("{0},BS6DofConstraint,create,wID={1}, rID={2}, rBody={3}, cID={4}, cBody={5}", + m_body1.ID, world.worldID, obj1.ID, obj1.AddrString, obj2.ID, obj2.AddrString); + PhysicsScene.DetailLog("{0},BS6DofConstraint,create, f1Loc={1},f1Rot={2},f2Loc={3},f2Rot={4},usefA={5},disCol={6}", + m_body1.ID, frame1, frame1rot, frame2, frame2rot, useLinearReferenceFrameA, disableCollisionsBetweenLinkedBodies); } // 6 Dof constraint based on a midpoint between the two constrained bodies @@ -86,9 +88,11 @@ public class BSConstraint6Dof : BSConstraint m_constraint = PhysicsScene.PE.Create6DofConstraintToPoint(m_world, m_body1, m_body2, joinPoint, useLinearReferenceFrameA, disableCollisionsBetweenLinkedBodies); + PhysicsScene.DetailLog("{0},BS6DofConstraint,createMidPoint,wID={1}, csrt={2}, rID={3}, rBody={4}, cID={5}, cBody={6}", - BSScene.DetailLogZero, world.worldID, m_constraint.AddrString, + m_body1.ID, world.worldID, m_constraint.AddrString, obj1.ID, obj1.AddrString, obj2.ID, obj2.AddrString); + if (!m_constraint.HasPhysicalConstraint) { world.physicsScene.Logger.ErrorFormat("{0} Failed creation of 6Dof constraint. rootID={1}, childID={2}", @@ -113,8 +117,10 @@ public class BSConstraint6Dof : BSConstraint frameInBloc, frameInBrot, useLinearReferenceFrameB, disableCollisionsBetweenLinkedBodies); m_enabled = true; - world.physicsScene.DetailLog("{0},BS6DofConstraint,createFixed,wID={1},rID={2},rBody={3}", - BSScene.DetailLogZero, world.worldID, obj1.ID, obj1.AddrString); + PhysicsScene.DetailLog("{0},BS6DofConstraint,createFixed,wID={1},rID={2},rBody={3}", + m_body1.ID, world.worldID, obj1.ID, obj1.AddrString); + PhysicsScene.DetailLog("{0},BS6DofConstraint,createFixed, fBLoc={1},fBRot={2},usefA={3},disCol={4}", + m_body1.ID, frameInBloc, frameInBrot, useLinearReferenceFrameB, disableCollisionsBetweenLinkedBodies); } public bool SetFrames(Vector3 frameA, Quaternion frameArot, Vector3 frameB, Quaternion frameBrot) diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSConstraintSpring.cs b/OpenSim/Region/Physics/BulletSPlugin/BSConstraintSpring.cs index 01d67d4..410584d 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSConstraintSpring.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSConstraintSpring.cs @@ -47,37 +47,42 @@ public sealed class BSConstraintSpring : BSConstraint6Dof useLinearReferenceFrameA, disableCollisionsBetweenLinkedBodies); m_enabled = true; - world.physicsScene.DetailLog("{0},BSConstraintSpring,createFrame,wID={1}, rID={2}, rBody={3}, cID={4}, cBody={5}", - BSScene.DetailLogZero, world.worldID, - obj1.ID, obj1.AddrString, obj2.ID, obj2.AddrString); + PhysicsScene.DetailLog("{0},BSConstraintSpring,create,wID={1}, rID={2}, rBody={3}, cID={4}, cBody={5}", + obj1.ID, world.worldID, obj1.ID, obj1.AddrString, obj2.ID, obj2.AddrString); + PhysicsScene.DetailLog("{0},BSConstraintSpring,create, f1Loc={1},f1Rot={2},f2Loc={3},f2Rot={4},usefA={5},disCol={6}", + m_body1.ID, frame1Loc, frame1Rot, frame2Loc, frame2Rot, useLinearReferenceFrameA, disableCollisionsBetweenLinkedBodies); } - public bool SetEnable(int index, bool axisEnable) + public bool SetEnable(int pIndex, bool pAxisEnable) { - bool ret = false; - - return ret; + PhysicsScene.DetailLog("{0},BSConstraintSpring.SetEnable,obj1ID={1},obj2ID={2},indx={3},enable={4}", + m_body1.ID, m_body1.ID, m_body2.ID, pIndex, pAxisEnable); + PhysicsScene.PE.SpringEnable(m_constraint, pIndex, BSParam.NumericBool(pAxisEnable)); + return true; } - public bool SetStiffness(int index, float stiffness) + public bool SetStiffness(int pIndex, float pStiffness) { - bool ret = false; - - return ret; + PhysicsScene.DetailLog("{0},BSConstraintSpring.SetStiffness,obj1ID={1},obj2ID={2},indx={3},enable={4}", + m_body1.ID, m_body1.ID, m_body2.ID, pIndex, pStiffness); + PhysicsScene.PE.SpringSetStiffness(m_constraint, pIndex, pStiffness); + return true; } - public bool SetDamping(int index, float damping) + public bool SetDamping(int pIndex, float pDamping) { - bool ret = false; - - return ret; + PhysicsScene.DetailLog("{0},BSConstraintSpring.SetDamping,obj1ID={1},obj2ID={2},indx={3},enable={4}", + m_body1.ID, m_body1.ID, m_body2.ID, pIndex, pDamping); + PhysicsScene.PE.SpringSetDamping(m_constraint, pIndex, pDamping); + return true; } - public bool SetEquilibriumPoint(int index, float eqPoint) + public bool SetEquilibriumPoint(int pIndex, float pEqPoint) { - bool ret = false; - - return ret; + PhysicsScene.DetailLog("{0},BSConstraintSpring.SetEquilibriumPoint,obj1ID={1},obj2ID={2},indx={3},enable={4}", + m_body1.ID, m_body1.ID, m_body2.ID, pIndex, pEqPoint); + PhysicsScene.PE.SpringSetEquilibriumPoint(m_constraint, pIndex, pEqPoint); + return true; } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs index a9ae89d..be97c29 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs @@ -67,6 +67,7 @@ public sealed class BSLinksetConstraints : BSLinkset { constraint = null; ResetLink(); + member.PhysScene.DetailLog("{0},BSLinkInfoConstraint.creation", member.LocalID); } // Set all the parameters for this constraint to a fixed, non-movable constraint. @@ -91,11 +92,13 @@ public sealed class BSLinksetConstraints : BSLinkset frameInBrot = OMV.Quaternion.Identity; springDamping = -1f; springStiffness = -1f; + member.PhysScene.DetailLog("{0},BSLinkInfoConstraint.ResetLink", member.LocalID); } // Given a constraint, apply the current constraint parameters to same. public override void SetLinkParameters(BSConstraint constrain) { + member.PhysScene.DetailLog("{0},BSLinkInfoConstraint.SetLinkParameters,type={1}", member.LocalID, constraintType); switch (constraintType) { case ConstraintType.FIXED_CONSTRAINT_TYPE: @@ -139,7 +142,7 @@ public sealed class BSLinksetConstraints : BSLinkset if (springDamping != -1) constrainSpring.SetDamping(ii, springDamping); if (springStiffness != -1) - constrainSpring.SetStiffness(ii, springStiffness); + constrainSpring.SetStiffness(ii, springStiffness); } } break; @@ -155,7 +158,6 @@ public sealed class BSLinksetConstraints : BSLinkset public override bool ShouldUpdateChildProperties() { bool ret = true; - if (constraintType == ConstraintType.FIXED_CONSTRAINT_TYPE) ret = false; @@ -193,10 +195,16 @@ public sealed class BSLinksetConstraints : BSLinkset { // Queue to happen after all the other taint processing m_physicsScene.PostTaintObject("BSLinksetContraints.Refresh", requestor.LocalID, delegate() + { + if (HasAnyChildren) { - if (HasAnyChildren) - RecomputeLinksetConstraints(); - }); + // Constraints that have not been changed are not rebuild but make sure + // the constraint of the requestor is rebuilt. + PhysicallyUnlinkAChildFromRoot(LinksetRoot, requestor); + // Rebuild the linkset and all its constraints. + RecomputeLinksetConstraints(); + } + }); } } @@ -415,13 +423,22 @@ public sealed class BSLinksetConstraints : BSLinkset rootPrim.LocalID, rootPrim.PhysBody.AddrString, childPrim.LocalID, childPrim.PhysBody.AddrString); - // Find the constraint for this link and get rid of it from the overall collection and from my list - if (m_physicsScene.Constraints.RemoveAndDestroyConstraint(rootPrim.PhysBody, childPrim.PhysBody)) + // If asked to unlink root from root, just remove all the constraints + if (rootPrim == childPrim || childPrim == LinksetRoot) { - // Make the child refresh its location - m_physicsScene.PE.PushUpdate(childPrim.PhysBody); + PhysicallyUnlinkAllChildrenFromRoot(LinksetRoot); ret = true; } + else + { + // Find the constraint for this link and get rid of it from the overall collection and from my list + if (m_physicsScene.Constraints.RemoveAndDestroyConstraint(rootPrim.PhysBody, childPrim.PhysBody)) + { + // Make the child refresh its location + m_physicsScene.PE.PushUpdate(childPrim.PhysBody); + ret = true; + } + } return ret; } @@ -521,8 +538,6 @@ public sealed class BSLinksetConstraints : BSLinkset BSLinkInfoConstraint linkInfoC = linkInfo as BSLinkInfoConstraint; if (linkInfoC != null) { - // Setting to fixed is easy. The reset state is the fixed link configuration. - linkInfoC.ResetLink(); linkInfoC.constraintType = (ConstraintType)requestedType; ret = (object)true; DetailLog("{0},BSLinksetConstraint.ChangeLinkType,link={1},type={2}", @@ -589,6 +604,7 @@ public sealed class BSLinksetConstraints : BSLinkset BSLinkInfoConstraint linkInfo = baseLinkInfo as BSLinkInfoConstraint; if (linkInfo != null) { + int valueInt; float valueFloat; bool valueBool; OMV.Vector3 valueVector; @@ -602,6 +618,20 @@ public sealed class BSLinksetConstraints : BSLinkset linkInfo.member.LocalID, thisOp, pParams[opIndex+1]); switch (thisOp) { + case ExtendedPhysics.PHYS_PARAM_LINK_TYPE: + valueInt = (int)pParams[opIndex + 1]; + ConstraintType valueType = (ConstraintType)valueInt; + if (valueType == ConstraintType.FIXED_CONSTRAINT_TYPE + || valueType == ConstraintType.D6_CONSTRAINT_TYPE + || valueType == ConstraintType.D6_SPRING_CONSTRAINT_TYPE + || valueType == ConstraintType.HINGE_CONSTRAINT_TYPE + || valueType == ConstraintType.CONETWIST_CONSTRAINT_TYPE + || valueType == ConstraintType.SLIDER_CONSTRAINT_TYPE) + { + linkInfo.constraintType = valueType; + } + opIndex += 2; + break; case ExtendedPhysics.PHYS_PARAM_FRAMEINA_LOC: valueVector = (OMV.Vector3)pParams[opIndex + 1]; linkInfo.frameInAloc = valueVector; -- cgit v1.1 From 7c54630a2dde768e92b3034d76314cb1e061c348 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Thu, 22 Aug 2013 16:31:17 -0700 Subject: BulletSim: add axis parameter for specifying enable, damping, and stiffness for spring constraints. Renumber parameter ops since I can as no one is using them yet. --- .../Region/Physics/BulletSPlugin/BSApiTemplate.cs | 2 +- .../Physics/BulletSPlugin/BSConstraintSpring.cs | 2 +- .../Physics/BulletSPlugin/BSLinksetConstraints.cs | 51 +++++++++++++++------- 3 files changed, 38 insertions(+), 17 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSApiTemplate.cs b/OpenSim/Region/Physics/BulletSPlugin/BSApiTemplate.cs index 9d8838b..0b3f467 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSApiTemplate.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSApiTemplate.cs @@ -292,7 +292,7 @@ public enum ConstraintParamAxis : int AXIS_ANGULAR_X, AXIS_ANGULAR_Y, AXIS_ANGULAR_Z, - AXIS_LINEAR_ALL = 20, // these last three added by BulletSim so we don't have to do zillions of calls + AXIS_LINEAR_ALL = 20, // added by BulletSim so we don't have to do zillions of calls AXIS_ANGULAR_ALL, AXIS_ALL }; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSConstraintSpring.cs b/OpenSim/Region/Physics/BulletSPlugin/BSConstraintSpring.cs index 410584d..432e5b2 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSConstraintSpring.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSConstraintSpring.cs @@ -53,7 +53,7 @@ public sealed class BSConstraintSpring : BSConstraint6Dof m_body1.ID, frame1Loc, frame1Rot, frame2Loc, frame2Rot, useLinearReferenceFrameA, disableCollisionsBetweenLinkedBodies); } - public bool SetEnable(int pIndex, bool pAxisEnable) + public bool SetAxisEnable(int pIndex, bool pAxisEnable) { PhysicsScene.DetailLog("{0},BSConstraintSpring.SetEnable,obj1ID={1},obj2ID={2},indx={3},enable={4}", m_body1.ID, m_body1.ID, m_body2.ID, pIndex, pAxisEnable); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs index be97c29..f623231 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs @@ -1,4 +1,4 @@ -/* +/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * @@ -59,8 +59,9 @@ public sealed class BSLinksetConstraints : BSLinkset public OMV.Vector3 frameInBloc; public OMV.Quaternion frameInBrot; // Spring - public float springDamping; - public float springStiffness; + public bool[] springAxisEnable; + public float[] springDamping; + public float[] springStiffness; public BSLinkInfoConstraint(BSPrimLinkable pMember) : base(pMember) @@ -90,8 +91,15 @@ public sealed class BSLinksetConstraints : BSLinkset frameInArot = OMV.Quaternion.Identity; frameInBloc = OMV.Vector3.Zero; frameInBrot = OMV.Quaternion.Identity; - springDamping = -1f; - springStiffness = -1f; + springAxisEnable = new bool[6]; + springDamping = new float[6]; + springStiffness = new float[6]; + for (int ii = 0; ii < springAxisEnable.Length; ii++) + { + springAxisEnable[ii] = false; + springDamping[ii] = BSAPITemplate.SPRING_NOT_SPECIFIED; + springStiffness[ii] = BSAPITemplate.SPRING_NOT_SPECIFIED; + } member.PhysScene.DetailLog("{0},BSLinkInfoConstraint.ResetLink", member.LocalID); } @@ -139,11 +147,13 @@ public sealed class BSLinksetConstraints : BSLinkset } for (int ii = 0; ii < 6; ii++) { - if (springDamping != -1) - constrainSpring.SetDamping(ii, springDamping); - if (springStiffness != -1) - constrainSpring.SetStiffness(ii, springStiffness); + constrainSpring.SetAxisEnable(ii, springAxisEnable[ii]); + if (springDamping[ii] != BSAPITemplate.SPRING_NOT_SPECIFIED) + constrainSpring.SetDamping(ii, springDamping[ii]); + if (springStiffness[ii] != BSAPITemplate.SPRING_NOT_SPECIFIED) + constrainSpring.SetStiffness(ii, springStiffness[ii]); } + constrainSpring.SetEquilibriumPoint(BSAPITemplate.SPRING_NOT_SPECIFIED, BSAPITemplate.SPRING_NOT_SPECIFIED); } break; default: @@ -707,15 +717,26 @@ public sealed class BSLinksetConstraints : BSLinkset linkInfo.solverIterations = valueFloat; opIndex += 2; break; + case ExtendedPhysics.PHYS_PARAM_SPRING_AXIS_ENABLE: + valueInt = (int)pParams[opIndex + 1]; + valueBool = ((int)pParams[opIndex + 2] != 0); + if (valueInt >=0 && valueInt < linkInfo.springAxisEnable.Length) + linkInfo.springAxisEnable[valueInt] = valueBool; + opIndex += 3; + break; case ExtendedPhysics.PHYS_PARAM_SPRING_DAMPING: - valueFloat = (float)pParams[opIndex + 1]; - linkInfo.springDamping = valueFloat; - opIndex += 2; + valueInt = (int)pParams[opIndex + 1]; + valueFloat = (float)pParams[opIndex + 2]; + if (valueInt >=0 && valueInt < linkInfo.springDamping.Length) + linkInfo.springDamping[valueInt] = valueFloat; + opIndex += 3; break; case ExtendedPhysics.PHYS_PARAM_SPRING_STIFFNESS: - valueFloat = (float)pParams[opIndex + 1]; - linkInfo.springStiffness = valueFloat; - opIndex += 2; + valueInt = (int)pParams[opIndex + 1]; + valueFloat = (float)pParams[opIndex + 2]; + if (valueInt >=0 && valueInt < linkInfo.springStiffness.Length) + linkInfo.springStiffness[valueInt] = valueFloat; + opIndex += 3; break; default: break; -- cgit v1.1 From cf2cdc191d0a93860da1ff4c42d34138e8f369fb Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Sat, 24 Aug 2013 08:33:28 -0700 Subject: BulletSim: ability to specify groups of axis to modify in constraint parameters that control multiple axis. Add useLinearReferenceFrameA constraint parameter. --- .../Physics/BulletSPlugin/BSLinksetConstraints.cs | 53 ++++++++++++++++++---- 1 file changed, 45 insertions(+), 8 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs index f623231..ff5ac0e 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs @@ -58,6 +58,7 @@ public sealed class BSLinksetConstraints : BSLinkset public OMV.Quaternion frameInArot; public OMV.Vector3 frameInBloc; public OMV.Quaternion frameInBrot; + public bool useLinearReferenceFrameA; // Spring public bool[] springAxisEnable; public float[] springDamping; @@ -91,6 +92,7 @@ public sealed class BSLinksetConstraints : BSLinkset frameInArot = OMV.Quaternion.Identity; frameInBloc = OMV.Vector3.Zero; frameInBrot = OMV.Quaternion.Identity; + useLinearReferenceFrameA = true; springAxisEnable = new bool[6]; springDamping = new float[6]; springStiffness = new float[6]; @@ -145,7 +147,7 @@ public sealed class BSLinksetConstraints : BSLinkset { constrainSpring.SetSolverIterations(solverIterations); } - for (int ii = 0; ii < 6; ii++) + for (int ii = 0; ii < springAxisEnable.Length; ii++) { constrainSpring.SetAxisEnable(ii, springAxisEnable[ii]); if (springDamping[ii] != BSAPITemplate.SPRING_NOT_SPECIFIED) @@ -401,7 +403,7 @@ public sealed class BSLinksetConstraints : BSLinkset case ConstraintType.D6_SPRING_CONSTRAINT_TYPE: constrain = new BSConstraintSpring(m_physicsScene.World, rootPrim.PhysBody, linkInfo.member.PhysBody, linkInfo.frameInAloc, linkInfo.frameInArot, linkInfo.frameInBloc, linkInfo.frameInBrot, - true /*useLinearReferenceFrameA*/, + linkInfo.useLinearReferenceFrameA, true /*disableCollisionsBetweenLinkedBodies*/); DetailLog("{0},BSLinksetConstraint.BuildConstraint,spring,root={1},rBody={2},child={3},cBody={4},rLoc={5},cLoc={6}", rootPrim.LocalID, @@ -619,6 +621,7 @@ public sealed class BSLinksetConstraints : BSLinkset bool valueBool; OMV.Vector3 valueVector; OMV.Quaternion valueQuaternion; + int axisLow, axisHigh; int opIndex = 2; while (opIndex < pParams.Length) @@ -720,24 +723,32 @@ public sealed class BSLinksetConstraints : BSLinkset case ExtendedPhysics.PHYS_PARAM_SPRING_AXIS_ENABLE: valueInt = (int)pParams[opIndex + 1]; valueBool = ((int)pParams[opIndex + 2] != 0); - if (valueInt >=0 && valueInt < linkInfo.springAxisEnable.Length) - linkInfo.springAxisEnable[valueInt] = valueBool; + GetAxisRange(valueInt, out axisLow, out axisHigh); + for (int ii = axisLow; ii <= axisHigh; ii++) + linkInfo.springAxisEnable[ii] = valueBool; opIndex += 3; break; case ExtendedPhysics.PHYS_PARAM_SPRING_DAMPING: valueInt = (int)pParams[opIndex + 1]; valueFloat = (float)pParams[opIndex + 2]; - if (valueInt >=0 && valueInt < linkInfo.springDamping.Length) - linkInfo.springDamping[valueInt] = valueFloat; + GetAxisRange(valueInt, out axisLow, out axisHigh); + for (int ii = axisLow; ii <= axisHigh; ii++) + linkInfo.springDamping[ii] = valueFloat; opIndex += 3; break; case ExtendedPhysics.PHYS_PARAM_SPRING_STIFFNESS: valueInt = (int)pParams[opIndex + 1]; valueFloat = (float)pParams[opIndex + 2]; - if (valueInt >=0 && valueInt < linkInfo.springStiffness.Length) - linkInfo.springStiffness[valueInt] = valueFloat; + GetAxisRange(valueInt, out axisLow, out axisHigh); + for (int ii = axisLow; ii <= axisHigh; ii++) + linkInfo.springStiffness[ii] = valueFloat; opIndex += 3; break; + case ExtendedPhysics.PHYS_PARAM_USE_LINEAR_FRAMEA: + valueBool = (bool)pParams[opIndex + 1]; + linkInfo.useLinearReferenceFrameA = valueBool; + opIndex += 2; + break; default: break; } @@ -760,6 +771,32 @@ public sealed class BSLinksetConstraints : BSLinkset } return ret; } + + // Bullet constraints keep some limit parameters for each linear and angular axis. + // Setting same is easier if there is an easy way to see all or types. + // This routine returns the array limits for the set of axis. + private void GetAxisRange(int rangeSpec, out int low, out int high) + { + switch (rangeSpec) + { + case ExtendedPhysics.PHYS_AXIS_ALL_LINEAR: + low = 0; + high = 2; + break; + case ExtendedPhysics.PHYS_AXIS_ALL_ANGULAR: + low = 3; + high = 5; + break; + case ExtendedPhysics.PHYS_AXIS_ALL: + low = 0; + high = 5; + break; + default: + low = high = rangeSpec; + break; + } + return; + } #endregion // Extension } -- cgit v1.1 From 5827b6e1aabf2e19624faf0141b9611917fb84c5 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Wed, 4 Sep 2013 07:56:59 -0700 Subject: BulletSim: add extended physics LSL constants for axis specification. Add specific error warnings for mis-matched parameter types in extended physics functions. --- .../Physics/BulletSPlugin/BSConstraintSpring.cs | 6 +- .../Physics/BulletSPlugin/BSLinksetConstraints.cs | 89 ++++++++++++++-------- 2 files changed, 60 insertions(+), 35 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSConstraintSpring.cs b/OpenSim/Region/Physics/BulletSPlugin/BSConstraintSpring.cs index 432e5b2..652c94a 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSConstraintSpring.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSConstraintSpring.cs @@ -63,7 +63,7 @@ public sealed class BSConstraintSpring : BSConstraint6Dof public bool SetStiffness(int pIndex, float pStiffness) { - PhysicsScene.DetailLog("{0},BSConstraintSpring.SetStiffness,obj1ID={1},obj2ID={2},indx={3},enable={4}", + PhysicsScene.DetailLog("{0},BSConstraintSpring.SetStiffness,obj1ID={1},obj2ID={2},indx={3},stiff={4}", m_body1.ID, m_body1.ID, m_body2.ID, pIndex, pStiffness); PhysicsScene.PE.SpringSetStiffness(m_constraint, pIndex, pStiffness); return true; @@ -71,7 +71,7 @@ public sealed class BSConstraintSpring : BSConstraint6Dof public bool SetDamping(int pIndex, float pDamping) { - PhysicsScene.DetailLog("{0},BSConstraintSpring.SetDamping,obj1ID={1},obj2ID={2},indx={3},enable={4}", + PhysicsScene.DetailLog("{0},BSConstraintSpring.SetDamping,obj1ID={1},obj2ID={2},indx={3},damp={4}", m_body1.ID, m_body1.ID, m_body2.ID, pIndex, pDamping); PhysicsScene.PE.SpringSetDamping(m_constraint, pIndex, pDamping); return true; @@ -79,7 +79,7 @@ public sealed class BSConstraintSpring : BSConstraint6Dof public bool SetEquilibriumPoint(int pIndex, float pEqPoint) { - PhysicsScene.DetailLog("{0},BSConstraintSpring.SetEquilibriumPoint,obj1ID={1},obj2ID={2},indx={3},enable={4}", + PhysicsScene.DetailLog("{0},BSConstraintSpring.SetEquilibriumPoint,obj1ID={1},obj2ID={2},indx={3},eqPoint={4}", m_body1.ID, m_body1.ID, m_body2.ID, pIndex, pEqPoint); PhysicsScene.PE.SpringSetEquilibriumPoint(m_constraint, pIndex, pEqPoint); return true; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs index ff5ac0e..b3347bf 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs @@ -605,30 +605,32 @@ public sealed class BSLinksetConstraints : BSLinkset // pParams = [ BSPhysObject root, BSPhysObject child, int op, object opParams, int op, object opParams, ... ] case ExtendedPhysics.PhysFunctChangeLinkParams: // There should be two parameters: the childActor and a list of parameters to set - try + if (pParams.Length > 2) { - if (pParams.Length > 2) + BSPrimLinkable child = pParams[1] as BSPrimLinkable; + BSLinkInfo baseLinkInfo = null; + if (TryGetLinkInfo(child, out baseLinkInfo)) { - BSPrimLinkable child = pParams[1] as BSPrimLinkable; - BSLinkInfo baseLinkInfo = null; - if (TryGetLinkInfo(child, out baseLinkInfo)) + BSLinkInfoConstraint linkInfo = baseLinkInfo as BSLinkInfoConstraint; + if (linkInfo != null) { - BSLinkInfoConstraint linkInfo = baseLinkInfo as BSLinkInfoConstraint; - if (linkInfo != null) + int valueInt; + float valueFloat; + bool valueBool; + OMV.Vector3 valueVector; + OMV.Quaternion valueQuaternion; + int axisLow, axisHigh; + + int opIndex = 2; + while (opIndex < pParams.Length) { - int valueInt; - float valueFloat; - bool valueBool; - OMV.Vector3 valueVector; - OMV.Quaternion valueQuaternion; - int axisLow, axisHigh; - - int opIndex = 2; - while (opIndex < pParams.Length) + int thisOp = 0; + string errMsg = ""; + try { - int thisOp = (int)pParams[opIndex]; + thisOp = (int)pParams[opIndex]; DetailLog("{0},BSLinksetConstraint.ChangeLinkParams2,op={1},val={2}", - linkInfo.member.LocalID, thisOp, pParams[opIndex+1]); + linkInfo.member.LocalID, thisOp, pParams[opIndex + 1]); switch (thisOp) { case ExtendedPhysics.PHYS_PARAM_LINK_TYPE: @@ -646,89 +648,106 @@ public sealed class BSLinksetConstraints : BSLinkset opIndex += 2; break; case ExtendedPhysics.PHYS_PARAM_FRAMEINA_LOC: + errMsg = "PHYS_PARAM_FRAMEINA_LOC takes one parameter of type vector"; valueVector = (OMV.Vector3)pParams[opIndex + 1]; linkInfo.frameInAloc = valueVector; opIndex += 2; break; case ExtendedPhysics.PHYS_PARAM_FRAMEINA_ROT: + errMsg = "PHYS_PARAM_FRAMEINA_ROT takes one parameter of type rotation"; valueQuaternion = (OMV.Quaternion)pParams[opIndex + 1]; linkInfo.frameInArot = valueQuaternion; opIndex += 2; break; case ExtendedPhysics.PHYS_PARAM_FRAMEINB_LOC: + errMsg = "PHYS_PARAM_FRAMEINB_LOC takes one parameter of type vector"; valueVector = (OMV.Vector3)pParams[opIndex + 1]; linkInfo.frameInBloc = valueVector; opIndex += 2; break; case ExtendedPhysics.PHYS_PARAM_FRAMEINB_ROT: + errMsg = "PHYS_PARAM_FRAMEINB_ROT takes one parameter of type rotation"; valueQuaternion = (OMV.Quaternion)pParams[opIndex + 1]; linkInfo.frameInBrot = valueQuaternion; opIndex += 2; break; case ExtendedPhysics.PHYS_PARAM_LINEAR_LIMIT_LOW: + errMsg = "PHYS_PARAM_LINEAR_LIMIT_LOW takes one parameter of type vector"; valueVector = (OMV.Vector3)pParams[opIndex + 1]; linkInfo.linearLimitLow = valueVector; opIndex += 2; break; case ExtendedPhysics.PHYS_PARAM_LINEAR_LIMIT_HIGH: + errMsg = "PHYS_PARAM_LINEAR_LIMIT_HIGH takes one parameter of type vector"; valueVector = (OMV.Vector3)pParams[opIndex + 1]; linkInfo.linearLimitHigh = valueVector; opIndex += 2; break; case ExtendedPhysics.PHYS_PARAM_ANGULAR_LIMIT_LOW: + errMsg = "PHYS_PARAM_ANGULAR_LIMIT_LOW takes one parameter of type vector"; valueVector = (OMV.Vector3)pParams[opIndex + 1]; linkInfo.angularLimitLow = valueVector; opIndex += 2; break; case ExtendedPhysics.PHYS_PARAM_ANGULAR_LIMIT_HIGH: + errMsg = "PHYS_PARAM_ANGULAR_LIMIT_HIGH takes one parameter of type vector"; valueVector = (OMV.Vector3)pParams[opIndex + 1]; linkInfo.angularLimitHigh = valueVector; opIndex += 2; break; case ExtendedPhysics.PHYS_PARAM_USE_FRAME_OFFSET: - valueBool = (bool)pParams[opIndex + 1]; + errMsg = "PHYS_PARAM_USE_FRAME_OFFSET takes one parameter of type integer (bool)"; + valueBool = ((int)pParams[opIndex + 1]) != 0; linkInfo.useFrameOffset = valueBool; opIndex += 2; break; case ExtendedPhysics.PHYS_PARAM_ENABLE_TRANSMOTOR: - valueBool = (bool)pParams[opIndex + 1]; + errMsg = "PHYS_PARAM_ENABLE_TRANSMOTOR takes one parameter of type integer (bool)"; + valueBool = ((int)pParams[opIndex + 1]) != 0; linkInfo.enableTransMotor = valueBool; opIndex += 2; break; case ExtendedPhysics.PHYS_PARAM_TRANSMOTOR_MAXVEL: + errMsg = "PHYS_PARAM_TRANSMOTOR_MAXVEL takes one parameter of type float"; valueFloat = (float)pParams[opIndex + 1]; linkInfo.transMotorMaxVel = valueFloat; opIndex += 2; break; case ExtendedPhysics.PHYS_PARAM_TRANSMOTOR_MAXFORCE: + errMsg = "PHYS_PARAM_TRANSMOTOR_MAXFORCE takes one parameter of type float"; valueFloat = (float)pParams[opIndex + 1]; linkInfo.transMotorMaxForce = valueFloat; opIndex += 2; break; case ExtendedPhysics.PHYS_PARAM_CFM: + errMsg = "PHYS_PARAM_CFM takes one parameter of type float"; valueFloat = (float)pParams[opIndex + 1]; linkInfo.cfm = valueFloat; opIndex += 2; break; case ExtendedPhysics.PHYS_PARAM_ERP: + errMsg = "PHYS_PARAM_ERP takes one parameter of type float"; valueFloat = (float)pParams[opIndex + 1]; linkInfo.erp = valueFloat; opIndex += 2; break; case ExtendedPhysics.PHYS_PARAM_SOLVER_ITERATIONS: + errMsg = "PHYS_PARAM_SOLVER_ITERATIONS takes one parameter of type float"; valueFloat = (float)pParams[opIndex + 1]; linkInfo.solverIterations = valueFloat; opIndex += 2; break; case ExtendedPhysics.PHYS_PARAM_SPRING_AXIS_ENABLE: + errMsg = "PHYS_PARAM_SPRING_AXIS_ENABLE takes two parameters of types integer and integer (bool)"; valueInt = (int)pParams[opIndex + 1]; - valueBool = ((int)pParams[opIndex + 2] != 0); + valueBool = ((int)pParams[opIndex + 2]) != 0; GetAxisRange(valueInt, out axisLow, out axisHigh); for (int ii = axisLow; ii <= axisHigh; ii++) linkInfo.springAxisEnable[ii] = valueBool; opIndex += 3; break; case ExtendedPhysics.PHYS_PARAM_SPRING_DAMPING: + errMsg = "PHYS_PARAM_SPRING_DAMPING takes two parameters of types integer and float"; valueInt = (int)pParams[opIndex + 1]; valueFloat = (float)pParams[opIndex + 2]; GetAxisRange(valueInt, out axisLow, out axisHigh); @@ -737,6 +756,7 @@ public sealed class BSLinksetConstraints : BSLinkset opIndex += 3; break; case ExtendedPhysics.PHYS_PARAM_SPRING_STIFFNESS: + errMsg = "PHYS_PARAM_SPRING_STIFFNESS takes two parameters of types integer and float"; valueInt = (int)pParams[opIndex + 1]; valueFloat = (float)pParams[opIndex + 2]; GetAxisRange(valueInt, out axisLow, out axisHigh); @@ -745,7 +765,8 @@ public sealed class BSLinksetConstraints : BSLinkset opIndex += 3; break; case ExtendedPhysics.PHYS_PARAM_USE_LINEAR_FRAMEA: - valueBool = (bool)pParams[opIndex + 1]; + errMsg = "PHYS_PARAM_USE_LINEAR_FRAMEA takes one parameter of type integer (bool)"; + valueBool = ((int)pParams[opIndex + 1]) != 0; linkInfo.useLinearReferenceFrameA = valueBool; opIndex += 2; break; @@ -753,18 +774,22 @@ public sealed class BSLinksetConstraints : BSLinkset break; } } + catch (InvalidCastException e) + { + m_physicsScene.Logger.WarnFormat("{0} value of wrong type in physSetLinksetParams: {1}, err={2}", + LogHeader, errMsg, e); + } + catch (Exception e) + { + m_physicsScene.Logger.WarnFormat("{0} bad parameters in physSetLinksetParams: {1}", LogHeader, e); + } } - // Something changed so a rebuild is in order - Refresh(child); } + // Something changed so a rebuild is in order + Refresh(child); } } - catch (Exception e) - { - // There are many ways to mess up the parameters. If not just right don't fail without some error. - m_physicsScene.Logger.WarnFormat("{0} bad parameters in physSetLinksetParams: {1}", LogHeader, e); - } - break; + break; default: ret = base.Extension(pFunct, pParams); break; @@ -779,11 +804,11 @@ public sealed class BSLinksetConstraints : BSLinkset { switch (rangeSpec) { - case ExtendedPhysics.PHYS_AXIS_ALL_LINEAR: + case ExtendedPhysics.PHYS_AXIS_LINEAR_ALL: low = 0; high = 2; break; - case ExtendedPhysics.PHYS_AXIS_ALL_ANGULAR: + case ExtendedPhysics.PHYS_AXIS_ANGULAR_ALL: low = 3; high = 5; break; -- cgit v1.1 From c5eabb28b4c933cfacefa85381e290372fbc094e Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Mon, 9 Sep 2013 14:53:16 -0700 Subject: BulletSim: add LSL function and plumbing for setting a spring equilibrium point in the physics engine constraint. --- OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs | 6 +++++- .../Physics/BulletSPlugin/BSConstraintSpring.cs | 13 +++++++++++++ .../Physics/BulletSPlugin/BSLinksetConstraints.cs | 20 +++++++++++++++++++- 3 files changed, 37 insertions(+), 2 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs b/OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs index 42b5c49..b47e9a8 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs @@ -64,7 +64,7 @@ public abstract class BSConstraint : IDisposable { bool success = PhysicsScene.PE.DestroyConstraint(m_world, m_constraint); m_world.physicsScene.DetailLog("{0},BSConstraint.Dispose,taint,id1={1},body1={2},id2={3},body2={4},success={5}", - BSScene.DetailLogZero, + m_body1.ID, m_body1.ID, m_body1.AddrString, m_body2.ID, m_body2.AddrString, success); @@ -77,7 +77,10 @@ public abstract class BSConstraint : IDisposable { bool ret = false; if (m_enabled) + { + m_world.physicsScene.DetailLog("{0},BSConstraint.SetLinearLimits,taint,low={1},high={2}", m_body1.ID, low, high); ret = PhysicsScene.PE.SetLinearLimits(m_constraint, low, high); + } return ret; } @@ -86,6 +89,7 @@ public abstract class BSConstraint : IDisposable bool ret = false; if (m_enabled) { + m_world.physicsScene.DetailLog("{0},BSConstraint.SetAngularLimits,taint,low={1},high={2}", m_body1.ID, low, high); ret = PhysicsScene.PE.SetAngularLimits(m_constraint, low, high); } return ret; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSConstraintSpring.cs b/OpenSim/Region/Physics/BulletSPlugin/BSConstraintSpring.cs index 652c94a..8e7ddff 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSConstraintSpring.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSConstraintSpring.cs @@ -85,6 +85,19 @@ public sealed class BSConstraintSpring : BSConstraint6Dof return true; } + public bool SetEquilibriumPoint(Vector3 linearEq, Vector3 angularEq) + { + PhysicsScene.DetailLog("{0},BSConstraintSpring.SetEquilibriumPoint,obj1ID={1},obj2ID={2},linearEq={3},angularEq={4}", + m_body1.ID, m_body1.ID, m_body2.ID, linearEq, angularEq); + PhysicsScene.PE.SpringSetEquilibriumPoint(m_constraint, 0, linearEq.X); + PhysicsScene.PE.SpringSetEquilibriumPoint(m_constraint, 1, linearEq.Y); + PhysicsScene.PE.SpringSetEquilibriumPoint(m_constraint, 2, linearEq.Z); + PhysicsScene.PE.SpringSetEquilibriumPoint(m_constraint, 3, angularEq.X); + PhysicsScene.PE.SpringSetEquilibriumPoint(m_constraint, 4, angularEq.Y); + PhysicsScene.PE.SpringSetEquilibriumPoint(m_constraint, 5, angularEq.Z); + return true; + } + } } \ No newline at end of file diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs index b3347bf..aaf92c8 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs @@ -63,6 +63,8 @@ public sealed class BSLinksetConstraints : BSLinkset public bool[] springAxisEnable; public float[] springDamping; public float[] springStiffness; + public OMV.Vector3 springLinearEquilibriumPoint; + public OMV.Vector3 springAngularEquilibriumPoint; public BSLinkInfoConstraint(BSPrimLinkable pMember) : base(pMember) @@ -102,6 +104,8 @@ public sealed class BSLinksetConstraints : BSLinkset springDamping[ii] = BSAPITemplate.SPRING_NOT_SPECIFIED; springStiffness[ii] = BSAPITemplate.SPRING_NOT_SPECIFIED; } + springLinearEquilibriumPoint = OMV.Vector3.Zero; + springAngularEquilibriumPoint = OMV.Vector3.Zero; member.PhysScene.DetailLog("{0},BSLinkInfoConstraint.ResetLink", member.LocalID); } @@ -155,7 +159,12 @@ public sealed class BSLinksetConstraints : BSLinkset if (springStiffness[ii] != BSAPITemplate.SPRING_NOT_SPECIFIED) constrainSpring.SetStiffness(ii, springStiffness[ii]); } - constrainSpring.SetEquilibriumPoint(BSAPITemplate.SPRING_NOT_SPECIFIED, BSAPITemplate.SPRING_NOT_SPECIFIED); + constrainSpring.CalculateTransforms(); + + if (springLinearEquilibriumPoint != OMV.Vector3.Zero) + constrainSpring.SetEquilibriumPoint(springLinearEquilibriumPoint, springAngularEquilibriumPoint); + else + constrainSpring.SetEquilibriumPoint(BSAPITemplate.SPRING_NOT_SPECIFIED, BSAPITemplate.SPRING_NOT_SPECIFIED); } break; default: @@ -618,6 +627,7 @@ public sealed class BSLinksetConstraints : BSLinkset float valueFloat; bool valueBool; OMV.Vector3 valueVector; + OMV.Vector3 valueVector2; OMV.Quaternion valueQuaternion; int axisLow, axisHigh; @@ -764,6 +774,14 @@ public sealed class BSLinksetConstraints : BSLinkset linkInfo.springStiffness[ii] = valueFloat; opIndex += 3; break; + case ExtendedPhysics.PHYS_PARAM_SPRING_EQUILIBRIUM_POINT: + errMsg = "PHYS_PARAM_SPRING_EQUILIBRIUM_POINT takes two parameters of type vector"; + valueVector = (OMV.Vector3)pParams[opIndex + 1]; + valueVector2 = (OMV.Vector3)pParams[opIndex + 2]; + linkInfo.springLinearEquilibriumPoint = valueVector; + linkInfo.springAngularEquilibriumPoint = valueVector2; + opIndex += 3; + break; case ExtendedPhysics.PHYS_PARAM_USE_LINEAR_FRAMEA: errMsg = "PHYS_PARAM_USE_LINEAR_FRAMEA takes one parameter of type integer (bool)"; valueBool = ((int)pParams[opIndex + 1]) != 0; -- cgit v1.1 From 6e39cc316f502855a89c51775e7394b73135ab86 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 10 Sep 2013 17:32:01 -0700 Subject: BulletSim: add ClearCollisionProxyCache function to API. Add proxy cache clearing when some properties are changed. This fixes a problem where objects would stop colliding of they were moved with setPosition mulitple times. --- OpenSim/Region/Physics/BulletSPlugin/BSAPIUnman.cs | 10 ++++++++++ OpenSim/Region/Physics/BulletSPlugin/BSAPIXNA.cs | 13 +++++++++++++ OpenSim/Region/Physics/BulletSPlugin/BSApiTemplate.cs | 2 ++ OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs | 12 ++++++++++-- 4 files changed, 35 insertions(+), 2 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSAPIUnman.cs b/OpenSim/Region/Physics/BulletSPlugin/BSAPIUnman.cs index 8dfb01c..3bd81d4 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSAPIUnman.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSAPIUnman.cs @@ -725,6 +725,13 @@ public override bool RemoveObjectFromWorld(BulletWorld world, BulletBody obj) return BSAPICPP.RemoveObjectFromWorld2(worldu.ptr, bodyu.ptr); } +public override bool ClearCollisionProxyCache(BulletWorld world, BulletBody obj) +{ + BulletWorldUnman worldu = world as BulletWorldUnman; + BulletBodyUnman bodyu = obj as BulletBodyUnman; + return BSAPICPP.ClearCollisionProxyCache2(worldu.ptr, bodyu.ptr); +} + public override bool AddConstraintToWorld(BulletWorld world, BulletConstraint constrain, bool disableCollisionsBetweenLinkedObjects) { BulletWorldUnman worldu = world as BulletWorldUnman; @@ -1713,6 +1720,9 @@ public static extern bool AddObjectToWorld2(IntPtr world, IntPtr obj); public static extern bool RemoveObjectFromWorld2(IntPtr world, IntPtr obj); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern bool ClearCollisionProxyCache2(IntPtr world, IntPtr obj); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern bool AddConstraintToWorld2(IntPtr world, IntPtr constrain, bool disableCollisionsBetweenLinkedObjects); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSAPIXNA.cs b/OpenSim/Region/Physics/BulletSPlugin/BSAPIXNA.cs index ff2b497..17ebed2 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSAPIXNA.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSAPIXNA.cs @@ -169,6 +169,19 @@ private sealed class BulletConstraintXNA : BulletConstraint return true; } + public override bool ClearCollisionProxyCache(BulletWorld pWorld, BulletBody pBody) + { + DiscreteDynamicsWorld world = (pWorld as BulletWorldXNA).world; + RigidBody body = ((BulletBodyXNA)pBody).rigidBody; + CollisionObject collisionObject = ((BulletBodyXNA)pBody).body; + if (body != null && collisionObject != null && collisionObject.GetBroadphaseHandle() != null) + { + world.RemoveCollisionObject(collisionObject); + world.AddCollisionObject(collisionObject); + } + return true; + } + public override bool AddConstraintToWorld(BulletWorld pWorld, BulletConstraint pConstraint, bool pDisableCollisionsBetweenLinkedObjects) { DiscreteDynamicsWorld world = (pWorld as BulletWorldXNA).world; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSApiTemplate.cs b/OpenSim/Region/Physics/BulletSPlugin/BSApiTemplate.cs index 0b3f467..f7dd158 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSApiTemplate.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSApiTemplate.cs @@ -498,6 +498,8 @@ public abstract bool AddObjectToWorld(BulletWorld world, BulletBody obj); public abstract bool RemoveObjectFromWorld(BulletWorld world, BulletBody obj); +public abstract bool ClearCollisionProxyCache(BulletWorld world, BulletBody obj); + public abstract bool AddConstraintToWorld(BulletWorld world, BulletConstraint constrain, bool disableCollisionsBetweenLinkedObjects); public abstract bool RemoveConstraintFromWorld(BulletWorld world, BulletConstraint constrain); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index 2efb1a5..47df611 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -300,8 +300,16 @@ public abstract class BSPhysObject : PhysicsActor // Called in taint-time!! public void ActivateIfPhysical(bool forceIt) { - if (IsPhysical && PhysBody.HasPhysicalBody) - PhysScene.PE.Activate(PhysBody, forceIt); + if (PhysBody.HasPhysicalBody) + { + // Clear the collision cache since we've changed some properties. + PhysScene.PE.ClearCollisionProxyCache(PhysScene.World, PhysBody); + if (IsPhysical) + { + // Physical objects might need activating + PhysScene.PE.Activate(PhysBody, forceIt); + } + } } // 'actors' act on the physical object to change or constrain its motion. These can range from -- cgit v1.1 From dacc20ee48883efe3702c284edff5ee3fa0e96b0 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Wed, 11 Sep 2013 16:48:15 -0700 Subject: BulletSim: remove collision cache clearing logic for physical objects. This fixes constraints from getting messed up when properties change. --- OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index 47df611..f89b376 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -302,13 +302,16 @@ public abstract class BSPhysObject : PhysicsActor { if (PhysBody.HasPhysicalBody) { - // Clear the collision cache since we've changed some properties. - PhysScene.PE.ClearCollisionProxyCache(PhysScene.World, PhysBody); if (IsPhysical) { // Physical objects might need activating PhysScene.PE.Activate(PhysBody, forceIt); } + else + { + // Clear the collision cache since we've changed some properties. + PhysScene.PE.ClearCollisionProxyCache(PhysScene.World, PhysBody); + } } } -- cgit v1.1 From 07d7a5fd76460a16b97d285a1b2c4a101e5543b6 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Fri, 20 Sep 2013 09:36:19 -0700 Subject: BulletSim: zero velocity when avatar not moving. This fixes a movement jitter that happens when an avatar is standing on a tilted surface. --- OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs | 1 + 1 file changed, 1 insertion(+) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs b/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs index 04a4a32..8ca55e5 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs @@ -278,6 +278,7 @@ public class BSActorAvatarMove : BSActor if (m_controllingPrim.IsStationary) { entprop.Position = m_controllingPrim.RawPosition; + entprop.Velocity = OMV.Vector3.Zero; m_physicsScene.PE.SetTranslation(m_controllingPrim.PhysBody, entprop.Position, entprop.Rotation); } -- cgit v1.1 From 35a6361b2431abf9d49b4413c5b9eaac51934134 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Fri, 20 Sep 2013 09:23:12 -0700 Subject: BulletSim: reduce avatar walking stopped threshold. Add parameter for setting the walking stopped threshold. This fixes the slight jump when an avatar stops walking. --- OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs | 1 + OpenSim/Region/Physics/BulletSPlugin/BSParam.cs | 3 +++ 2 files changed, 4 insertions(+) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs b/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs index 8ca55e5..1bcf879 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSActorAvatarMove.cs @@ -128,6 +128,7 @@ public class BSActorAvatarMove : BSActor BSMotor.Infinite, // decay time scale 1f // efficiency ); + m_velocityMotor.ErrorZeroThreshold = BSParam.AvatarStopZeroThreshold; // _velocityMotor.PhysicsScene = PhysicsScene; // DEBUG DEBUG so motor will output detail log messages. SetVelocityAndTarget(m_controllingPrim.RawVelocity, m_controllingPrim.TargetVelocity, true /* inTaintTime */); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs index 2f1799b..43aa63e 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs @@ -134,6 +134,7 @@ public static class BSParam public static float AvatarHeightMidFudge { get; private set; } public static float AvatarHeightHighFudge { get; private set; } public static float AvatarContactProcessingThreshold { get; private set; } + public static float AvatarStopZeroThreshold { get; private set; } public static int AvatarJumpFrames { get; private set; } public static float AvatarBelowGroundUpCorrectionMeters { get; private set; } public static float AvatarStepHeight { get; private set; } @@ -575,6 +576,8 @@ public static class BSParam 0.1f ), new ParameterDefn("AvatarContactProcessingThreshold", "Distance from capsule to check for collisions", 0.1f ), + new ParameterDefn("AvatarStopZeroThreshold", "Movement velocity below which avatar is assumed to be stopped", + 0.1f ), new ParameterDefn("AvatarBelowGroundUpCorrectionMeters", "Meters to move avatar up if it seems to be below ground", 1.0f ), new ParameterDefn("AvatarJumpFrames", "Number of frames to allow jump forces. Changes jump height.", -- cgit v1.1 From 42bdf446585007029faf4cd21abd289487f0f797 Mon Sep 17 00:00:00 2001 From: Justin Clark-Casey (justincc) Date: Fri, 4 Oct 2013 23:33:47 +0100 Subject: Bump OPenSimulator version and assembly versions up to 0.8.0 Dev --- OpenSim/Region/Physics/BasicPhysicsPlugin/AssemblyInfo.cs | 2 +- OpenSim/Region/Physics/BulletSPlugin/Properties/AssemblyInfo.cs | 2 +- .../Region/Physics/ConvexDecompositionDotNet/Properties/AssemblyInfo.cs | 2 +- OpenSim/Region/Physics/Manager/AssemblyInfo.cs | 2 +- OpenSim/Region/Physics/Meshing/Properties/AssemblyInfo.cs | 2 +- OpenSim/Region/Physics/OdePlugin/AssemblyInfo.cs | 2 +- OpenSim/Region/Physics/POSPlugin/AssemblyInfo.cs | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BasicPhysicsPlugin/AssemblyInfo.cs b/OpenSim/Region/Physics/BasicPhysicsPlugin/AssemblyInfo.cs index 6fd6f7e..ffcb01e 100644 --- a/OpenSim/Region/Physics/BasicPhysicsPlugin/AssemblyInfo.cs +++ b/OpenSim/Region/Physics/BasicPhysicsPlugin/AssemblyInfo.cs @@ -55,4 +55,4 @@ using System.Runtime.InteropServices; // You can specify all values by your own or you can build default build and revision // numbers with the '*' character (the default): -[assembly : AssemblyVersion("0.7.6.*")] +[assembly : AssemblyVersion("0.8.0.*")] diff --git a/OpenSim/Region/Physics/BulletSPlugin/Properties/AssemblyInfo.cs b/OpenSim/Region/Physics/BulletSPlugin/Properties/AssemblyInfo.cs index 02b03a8..d069178 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/Properties/AssemblyInfo.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/Properties/AssemblyInfo.cs @@ -29,5 +29,5 @@ using System.Runtime.InteropServices; // Build Number // Revision // -[assembly: AssemblyVersion("0.7.6.*")] +[assembly: AssemblyVersion("0.8.0.*")] diff --git a/OpenSim/Region/Physics/ConvexDecompositionDotNet/Properties/AssemblyInfo.cs b/OpenSim/Region/Physics/ConvexDecompositionDotNet/Properties/AssemblyInfo.cs index f611b9a..b8cf624 100644 --- a/OpenSim/Region/Physics/ConvexDecompositionDotNet/Properties/AssemblyInfo.cs +++ b/OpenSim/Region/Physics/ConvexDecompositionDotNet/Properties/AssemblyInfo.cs @@ -32,5 +32,5 @@ using System.Runtime.InteropServices; // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("0.7.6.*")] +[assembly: AssemblyVersion("0.8.0.*")] diff --git a/OpenSim/Region/Physics/Manager/AssemblyInfo.cs b/OpenSim/Region/Physics/Manager/AssemblyInfo.cs index 5da3956..10e850e 100644 --- a/OpenSim/Region/Physics/Manager/AssemblyInfo.cs +++ b/OpenSim/Region/Physics/Manager/AssemblyInfo.cs @@ -55,4 +55,4 @@ using System.Runtime.InteropServices; // You can specify all values by your own or you can build default build and revision // numbers with the '*' character (the default): -[assembly : AssemblyVersion("0.7.6.*")] +[assembly : AssemblyVersion("0.8.0.*")] diff --git a/OpenSim/Region/Physics/Meshing/Properties/AssemblyInfo.cs b/OpenSim/Region/Physics/Meshing/Properties/AssemblyInfo.cs index 3de061a..8542753 100644 --- a/OpenSim/Region/Physics/Meshing/Properties/AssemblyInfo.cs +++ b/OpenSim/Region/Physics/Meshing/Properties/AssemblyInfo.cs @@ -29,5 +29,5 @@ using System.Runtime.InteropServices; // Build Number // Revision // -[assembly: AssemblyVersion("0.7.6.*")] +[assembly: AssemblyVersion("0.8.0.*")] diff --git a/OpenSim/Region/Physics/OdePlugin/AssemblyInfo.cs b/OpenSim/Region/Physics/OdePlugin/AssemblyInfo.cs index f477ed1..288cab5 100644 --- a/OpenSim/Region/Physics/OdePlugin/AssemblyInfo.cs +++ b/OpenSim/Region/Physics/OdePlugin/AssemblyInfo.cs @@ -55,4 +55,4 @@ using System.Runtime.InteropServices; // You can specify all values by your own or you can build default build and revision // numbers with the '*' character (the default): -[assembly : AssemblyVersion("0.7.6.*")] +[assembly : AssemblyVersion("0.8.0.*")] diff --git a/OpenSim/Region/Physics/POSPlugin/AssemblyInfo.cs b/OpenSim/Region/Physics/POSPlugin/AssemblyInfo.cs index 4289863..83be103 100644 --- a/OpenSim/Region/Physics/POSPlugin/AssemblyInfo.cs +++ b/OpenSim/Region/Physics/POSPlugin/AssemblyInfo.cs @@ -55,4 +55,4 @@ using System.Runtime.InteropServices; // You can specify all values by your own or you can build default build and revision // numbers with the '*' character (the default): -[assembly : AssemblyVersion("0.7.6.*")] +[assembly : AssemblyVersion("0.8.0.*")] -- cgit v1.1 From 8b5e2f2cd28510fc249bade0ca0d71e02b6b5f34 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Fri, 11 Oct 2013 13:29:43 -0700 Subject: BulletSim: Fix snap back from edge of region problem. Mantis 6794. --- OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs index c4807c4..c016eed 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs @@ -354,6 +354,8 @@ public sealed class BSTerrainManager : IDisposable // Return a new position that is over known terrain if the position is outside our terrain. public Vector3 ClampPositionIntoKnownTerrain(Vector3 pPos) { + float edgeEpsilon = 0.1f; + Vector3 ret = pPos; // First, base addresses are never negative so correct for that possible problem. @@ -378,10 +380,19 @@ public sealed class BSTerrainManager : IDisposable // NOTE that GetTerrainPhysicalAtXYZ will set 'terrainBaseXYZ' to the base of the unfound region. // Must be off the top of a region. Find an adjacent region to move into. + // The returned terrain is always 'lower'. That is, closer to <0,0>. Vector3 adjacentTerrainBase = FindAdjacentTerrainBase(terrainBaseXYZ); - ret.X = Math.Min(ret.X, adjacentTerrainBase.X + (ret.X % DefaultRegionSize.X)); - ret.Y = Math.Min(ret.Y, adjacentTerrainBase.Y + (ret.X % DefaultRegionSize.Y)); + if (adjacentTerrainBase.X < terrainBaseXYZ.X) + { + // moving down into a new region in the X dimension. New position will be the max in the new base. + ret.X = adjacentTerrainBase.X + DefaultRegionSize.X - edgeEpsilon; + } + if (adjacentTerrainBase.Y < terrainBaseXYZ.Y) + { + // moving down into a new region in the X dimension. New position will be the max in the new base. + ret.Y = adjacentTerrainBase.Y + DefaultRegionSize.Y - edgeEpsilon; + } DetailLog("{0},BSTerrainManager.ClampPositionToKnownTerrain,findingAdjacentRegion,adjacentRegBase={1},oldPos={2},newPos={3}", BSScene.DetailLogZero, adjacentTerrainBase, pPos, ret); -- cgit v1.1 From 766a31431e41033b9cddf5759e9b6e1b4c77682a Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 15 Oct 2013 17:02:22 -0700 Subject: BulletSim: implement the SL bug where VEHICLE_HOVER_UP_ONLY disables the vehicle buoyancy if the vehicle is above its hover height. This is a known misfeature of this vehicle flag which has been accepted since it would break too many implementations. The problem is noticed when creating a jetski-like vehicle that jumps over sand bars. A boat normally is configured with neutral buoyancy and hovering at water height. When it jumps the sandbar, it needs to have gravity applied to get back to water level. --- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 12 ++++++++++++ 1 file changed, 12 insertions(+) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index f0d17d3..7b98f9d 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -1125,7 +1125,19 @@ namespace OpenSim.Region.Physics.BulletSPlugin { // If body is already heigher, use its height as target height if (VehiclePosition.Z > m_VhoverTargetHeight) + { m_VhoverTargetHeight = VehiclePosition.Z; + + // A 'misfeature' of this flag is that if the vehicle is above it's hover height, + // the vehicle's buoyancy goes away. This is an SL bug that got used by so many + // scripts that it could not be changed. + // So, if above the height, reapply gravity if buoyancy had it turned off. + if (m_VehicleBuoyancy != 0) + { + Vector3 appliedGravity = ControllingPrim.ComputeGravity(ControllingPrim.Buoyancy) * m_vehicleMass; + VehicleAddForce(appliedGravity); + } + } } if ((m_flags & VehicleFlag.LOCK_HOVER_HEIGHT) != 0) -- cgit v1.1 From 511122834b5cd95839029d28365e479dc25eae9d Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Wed, 23 Oct 2013 16:07:03 -0700 Subject: BulletSim: change collision flags for groundplane to not interact with static objects. Reorder collision flag setting code for terrain to fit pattern used elsewhere. --- OpenSim/Region/Physics/BulletSPlugin/BSParam.cs | 5 +++++ OpenSim/Region/Physics/BulletSPlugin/BSTerrainHeightmap.cs | 5 ++--- OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs | 7 ++++--- OpenSim/Region/Physics/BulletSPlugin/BulletSimData.cs | 3 ++- 4 files changed, 13 insertions(+), 7 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs index 43aa63e..834228e 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSParam.cs @@ -120,6 +120,7 @@ public static class BSParam public static float NumberOfSolverIterations { get; private set; } public static bool UseSingleSidedMeshes { get; private set; } public static float GlobalContactBreakingThreshold { get; private set; } + public static float PhysicsUnmanLoggingFrames { get; private set; } // Avatar parameters public static float AvatarFriction { get; private set; } @@ -671,6 +672,10 @@ public static class BSParam 0f, (s) => { return GlobalContactBreakingThreshold; }, (s,v) => { GlobalContactBreakingThreshold = v; s.UnmanagedParams[0].globalContactBreakingThreshold = v; } ), + new ParameterDefn("PhysicsUnmanLoggingFrames", "If non-zero, frames between output of detailed unmanaged physics statistics", + 0f, + (s) => { return PhysicsUnmanLoggingFrames; }, + (s,v) => { PhysicsUnmanLoggingFrames = v; s.UnmanagedParams[0].physicsLoggingFrames = v; } ), new ParameterDefn("CSHullMaxDepthSplit", "CS impl: max depth to split for hull. 1-10 but > 7 is iffy", 7 ), diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainHeightmap.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainHeightmap.cs index c7deb4e..8888d6d 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainHeightmap.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainHeightmap.cs @@ -112,15 +112,14 @@ public sealed class BSTerrainHeightmap : BSTerrainPhys m_physicsScene.PE.SetRestitution(m_mapInfo.terrainBody, BSParam.TerrainRestitution); m_physicsScene.PE.SetCollisionFlags(m_mapInfo.terrainBody, CollisionFlags.CF_STATIC_OBJECT); + m_mapInfo.terrainBody.collisionType = CollisionType.Terrain; + // Return the new terrain to the world of physical objects m_physicsScene.PE.AddObjectToWorld(m_physicsScene.World, m_mapInfo.terrainBody); // redo its bounding box now that it is in the world m_physicsScene.PE.UpdateSingleAabb(m_physicsScene.World, m_mapInfo.terrainBody); - m_mapInfo.terrainBody.collisionType = CollisionType.Terrain; - m_mapInfo.terrainBody.ApplyCollisionMask(m_physicsScene); - // Make it so the terrain will not move or be considered for movement. m_physicsScene.PE.ForceActivationState(m_mapInfo.terrainBody, ActivationState.DISABLE_SIMULATION); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs index c016eed..441d2d3 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs @@ -138,13 +138,14 @@ public sealed class BSTerrainManager : IDisposable m_groundPlane = m_physicsScene.PE.CreateBodyWithDefaultMotionState(groundPlaneShape, BSScene.GROUNDPLANE_ID, Vector3.Zero, Quaternion.Identity); + // Everything collides with the ground plane. + m_groundPlane.collisionType = CollisionType.Groundplane; + m_physicsScene.PE.AddObjectToWorld(m_physicsScene.World, m_groundPlane); m_physicsScene.PE.UpdateSingleAabb(m_physicsScene.World, m_groundPlane); + // Ground plane does not move m_physicsScene.PE.ForceActivationState(m_groundPlane, ActivationState.DISABLE_SIMULATION); - // Everything collides with the ground plane. - m_groundPlane.collisionType = CollisionType.Groundplane; - m_groundPlane.ApplyCollisionMask(m_physicsScene); BSTerrainPhys initialTerrain = new BSTerrainHeightmap(m_physicsScene, Vector3.Zero, BSScene.TERRAIN_ID, DefaultRegionSize); lock (m_terrains) diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimData.cs b/OpenSim/Region/Physics/BulletSPlugin/BulletSimData.cs index d5060e3..971ff9f 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimData.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimData.cs @@ -235,7 +235,8 @@ public static Dictionary CollisionTypeM { CollisionType.Groundplane, new CollisionTypeFilterGroup(CollisionType.Groundplane, (uint)CollisionFilterGroups.BGroundPlaneGroup, - (uint)CollisionFilterGroups.BAllGroup) + // (uint)CollisionFilterGroups.BAllGroup) + (uint)(CollisionFilterGroups.BCharacterGroup | CollisionFilterGroups.BSolidGroup)) }, { CollisionType.Terrain, new CollisionTypeFilterGroup(CollisionType.Terrain, -- cgit v1.1 From 93d5d66fbd44733186439971d819f9409dac4bdd Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Sat, 26 Oct 2013 21:20:19 -0700 Subject: BulletSim: update collision flags to make sure they fit in the shorts provided. --- OpenSim/Region/Physics/BulletSPlugin/BSApiTemplate.cs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSApiTemplate.cs b/OpenSim/Region/Physics/BulletSPlugin/BSApiTemplate.cs index f7dd158..be6f152 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSApiTemplate.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSApiTemplate.cs @@ -249,7 +249,7 @@ public enum CollisionFlags : uint BS_VEHICLE_COLLISIONS = 1 << 12, // return collisions for vehicle ground checking BS_RETURN_ROOT_COMPOUND_SHAPE = 1 << 13, // return the pos/rot of the root shape in a compound shape BS_NONE = 0, - BS_ALL = 0xFFFFFFFF + BS_ALL = 0x7FFF // collision flags are a signed short }; // Values f collisions groups and masks @@ -265,14 +265,14 @@ public enum CollisionFilterGroups : uint BDebrisGroup = 1 << 3, // 0008 BSensorTrigger = 1 << 4, // 0010 BCharacterGroup = 1 << 5, // 0020 - BAllGroup = 0x000FFFFF, + BAllGroup = 0x0007FFF, // collision flags are a signed short // Filter groups defined by BulletSim - BGroundPlaneGroup = 1 << 10, // 0400 - BTerrainGroup = 1 << 11, // 0800 - BRaycastGroup = 1 << 12, // 1000 - BSolidGroup = 1 << 13, // 2000 + BGroundPlaneGroup = 1 << 8, // 0400 + BTerrainGroup = 1 << 9, // 0800 + BRaycastGroup = 1 << 10, // 1000 + BSolidGroup = 1 << 11, // 2000 // BLinksetGroup = xx // a linkset proper is either static or dynamic - BLinksetChildGroup = 1 << 14, // 4000 + BLinksetChildGroup = 1 << 12, // 4000 }; // CFM controls the 'hardness' of the constraint. 0=fixed, 0..1=violatable. Default=0 -- cgit v1.1 From f4ded3af63e4a71ffd8ee7f1a422ec600f59b845 Mon Sep 17 00:00:00 2001 From: dahlia Date: Fri, 1 Nov 2013 01:40:56 -0700 Subject: discard alpha in 4-plane sculpt textures before generating physics proxy mesh --- OpenSim/Region/Physics/Meshing/Meshmerizer.cs | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/Meshing/Meshmerizer.cs b/OpenSim/Region/Physics/Meshing/Meshmerizer.cs index fc679e7..4ad0cb1 100644 --- a/OpenSim/Region/Physics/Meshing/Meshmerizer.cs +++ b/OpenSim/Region/Physics/Meshing/Meshmerizer.cs @@ -629,21 +629,16 @@ namespace OpenSim.Region.Physics.Meshing try { - OpenMetaverse.Imaging.ManagedImage unusedData; - OpenMetaverse.Imaging.OpenJPEG.DecodeToImage(primShape.SculptData, out unusedData, out idata); + OpenMetaverse.Imaging.ManagedImage managedImage; - if (idata == null) - { - // In some cases it seems that the decode can return a null bitmap without throwing - // an exception - m_log.WarnFormat("[PHYSICS]: OpenJPEG decoded sculpt data for {0} to a null bitmap. Ignoring.", primName); - - return false; - } + OpenMetaverse.Imaging.OpenJPEG.DecodeToImage(primShape.SculptData, out managedImage); - unusedData = null; + if ((managedImage.Channels & OpenMetaverse.Imaging.ManagedImage.ImageChannels.Alpha) != 0) + managedImage.ConvertChannels(managedImage.Channels & ~OpenMetaverse.Imaging.ManagedImage.ImageChannels.Alpha); - //idata = CSJ2K.J2kImage.FromBytes(primShape.SculptData); + Bitmap imgData = OpenMetaverse.Imaging.LoadTGAClass.LoadTGA(new MemoryStream(managedImage.ExportTGA())); + idata = (Image)imgData; + managedImage = null; if (cacheSculptMaps) { -- cgit v1.1 From 7faf286d0025da04497e2b593f629c6582607c78 Mon Sep 17 00:00:00 2001 From: dahlia Date: Fri, 1 Nov 2013 13:45:09 -0700 Subject: add null check for jpeg2000 sculpt image decode failure. Note: the j2kDecodeCache folder should be cleared after updating to this revision so that sculpts containing alpha can be re-decoded and successfully meshed. --- OpenSim/Region/Physics/Meshing/Meshmerizer.cs | 9 +++++++++ 1 file changed, 9 insertions(+) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/Meshing/Meshmerizer.cs b/OpenSim/Region/Physics/Meshing/Meshmerizer.cs index 4ad0cb1..1f08b03 100644 --- a/OpenSim/Region/Physics/Meshing/Meshmerizer.cs +++ b/OpenSim/Region/Physics/Meshing/Meshmerizer.cs @@ -633,6 +633,15 @@ namespace OpenSim.Region.Physics.Meshing OpenMetaverse.Imaging.OpenJPEG.DecodeToImage(primShape.SculptData, out managedImage); + if (managedImage == null) + { + // In some cases it seems that the decode can return a null bitmap without throwing + // an exception + m_log.WarnFormat("[PHYSICS]: OpenJPEG decoded sculpt data for {0} to a null bitmap. Ignoring.", primName); + + return false; + } + if ((managedImage.Channels & OpenMetaverse.Imaging.ManagedImage.ImageChannels.Alpha) != 0) managedImage.ConvertChannels(managedImage.Channels & ~OpenMetaverse.Imaging.ManagedImage.ImageChannels.Alpha); -- cgit v1.1 From 1496de7ce99079d3d7bf046db088c3d6e2a97bcb Mon Sep 17 00:00:00 2001 From: dahlia Date: Fri, 6 Dec 2013 15:58:19 -0800 Subject: use System.IO.Compression.DeflateStream for mesh decompression in an attempt to reduce mesh asset decoding failures --- OpenSim/Region/Physics/Meshing/Meshmerizer.cs | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/Meshing/Meshmerizer.cs b/OpenSim/Region/Physics/Meshing/Meshmerizer.cs index 1f08b03..e313a30 100644 --- a/OpenSim/Region/Physics/Meshing/Meshmerizer.cs +++ b/OpenSim/Region/Physics/Meshing/Meshmerizer.cs @@ -40,7 +40,6 @@ using log4net; using Nini.Config; using System.Reflection; using System.IO; -using ComponentAce.Compression.Libs.zlib; namespace OpenSim.Region.Physics.Meshing { @@ -549,7 +548,6 @@ namespace OpenSim.Region.Physics.Meshing return true; } - /// /// decompresses a gzipped OSD object /// @@ -564,15 +562,13 @@ namespace OpenSim.Region.Physics.Meshing { using (MemoryStream outMs = new MemoryStream()) { - using (ZOutputStream zOut = new ZOutputStream(outMs)) + using (DeflateStream decompressionStream = new DeflateStream(inMs, CompressionMode.Decompress)) { byte[] readBuffer = new byte[2048]; - int readLen = 0; - while ((readLen = inMs.Read(readBuffer, 0, readBuffer.Length)) > 0) - { - zOut.Write(readBuffer, 0, readLen); - } - zOut.Flush(); + inMs.Read(readBuffer, 0, 2); // skip first 2 bytes in header + + decompressionStream.CopyTo(outMs); + outMs.Seek(0, SeekOrigin.Begin); byte[] decompressedBuf = outMs.GetBuffer(); -- cgit v1.1 From c0380d1bfe596afe33659cc69ae99a09018f9908 Mon Sep 17 00:00:00 2001 From: dahlia Date: Fri, 6 Dec 2013 16:24:44 -0800 Subject: apparently mono DeflateStream has no CopyTo method =( --- OpenSim/Region/Physics/Meshing/Meshmerizer.cs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/Meshing/Meshmerizer.cs b/OpenSim/Region/Physics/Meshing/Meshmerizer.cs index e313a30..d96de4a 100644 --- a/OpenSim/Region/Physics/Meshing/Meshmerizer.cs +++ b/OpenSim/Region/Physics/Meshing/Meshmerizer.cs @@ -566,8 +566,12 @@ namespace OpenSim.Region.Physics.Meshing { byte[] readBuffer = new byte[2048]; inMs.Read(readBuffer, 0, 2); // skip first 2 bytes in header + int readLen = 0; - decompressionStream.CopyTo(outMs); + while ((readLen = decompressionStream.Read(readBuffer, 0, readBuffer.Length)) > 0) + outMs.Write(readBuffer, 0, readLen); + + outMs.Flush(); outMs.Seek(0, SeekOrigin.Begin); -- cgit v1.1 From 54cc22976868dcdc0dd0143a0134fba7392af525 Mon Sep 17 00:00:00 2001 From: Justin Clark-Casey (justincc) Date: Sat, 14 Dec 2013 00:10:32 +0000 Subject: Fix TestSitAndStandWithNoSitTarget NPC and SP tests. These stopped working because current code calculates sit heights based on avatar physics rather than appearance data. Also changed BasicPhysics to not divide Z param of all set sizes by 2 - there's no obvious good reason for this and basicphysics is only used in tests --- OpenSim/Region/Physics/BasicPhysicsPlugin/BasicPhysicsActor.cs | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BasicPhysicsPlugin/BasicPhysicsActor.cs b/OpenSim/Region/Physics/BasicPhysicsPlugin/BasicPhysicsActor.cs index e43136a..0d17e0e 100644 --- a/OpenSim/Region/Physics/BasicPhysicsPlugin/BasicPhysicsActor.cs +++ b/OpenSim/Region/Physics/BasicPhysicsPlugin/BasicPhysicsActor.cs @@ -118,14 +118,7 @@ namespace OpenSim.Region.Physics.BasicPhysicsPlugin public override Vector3 Position { get; set; } - public override Vector3 Size - { - get { return _size; } - set { - _size = value; - _size.Z = _size.Z / 2.0f; - } - } + public override Vector3 Size { get; set; } public override PrimitiveBaseShape Shape { -- cgit v1.1 From 239b85d7cee3d8e0ae7349cbe62582d46940c732 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Fri, 10 Jan 2014 22:52:31 -0800 Subject: Fix crash in BulletSim which sometimes happens making a linkset physical (like sitting on and activating a vehicle) and crossing borders. This keeps better bookkeeping on compound shapes so BulletSim can identify them when being freed. --- OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs | 39 +++++++++++++++++++----- 1 file changed, 32 insertions(+), 7 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs index 006a9c1..fbe320b 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs @@ -71,7 +71,7 @@ public abstract class BSShape lastReferenced = DateTime.Now; } - // Called when this shape is being used again. + // Called when this shape is done being used. protected virtual void DecrementReference() { referenceCount--; @@ -866,6 +866,8 @@ public class BSShapeHull : BSShape public class BSShapeCompound : BSShape { private static string LogHeader = "[BULLETSIM SHAPE COMPOUND]"; + public static Dictionary CompoundShapes = new Dictionary(); + public BSShapeCompound(BulletShape pShape) : base(pShape) { } @@ -873,7 +875,9 @@ public class BSShapeCompound : BSShape { // Base compound shapes are not shared so this returns a raw shape. // A built compound shape can be reused in linksets. - return new BSShapeCompound(CreatePhysicalCompoundShape(physicsScene)); + BSShapeCompound ret = new BSShapeCompound(CreatePhysicalCompoundShape(physicsScene)); + CompoundShapes.Add(ret.AddrString, ret); + return ret; } public override BSShape GetReference(BSScene physicsScene, BSPhysObject prim) { @@ -911,10 +915,21 @@ public class BSShapeCompound : BSShape BulletShape childShape = physicsScene.PE.RemoveChildShapeFromCompoundShapeIndex(physShapeInfo, ii); DereferenceAnonCollisionShape(physicsScene, childShape); } + + lock (CompoundShapes) + CompoundShapes.Remove(physShapeInfo.AddrString); physicsScene.PE.DeleteCollisionShape(physicsScene.World, physShapeInfo); } } } + public static bool TryGetCompoundByPtr(BulletShape pShape, out BSShapeCompound outCompound) + { + lock (CompoundShapes) + { + string addr = pShape.AddrString; + return CompoundShapes.TryGetValue(addr, out outCompound); + } + } private static BulletShape CreatePhysicalCompoundShape(BSScene physicsScene) { BulletShape cShape = physicsScene.PE.CreateCompoundShape(physicsScene.World, false); @@ -926,10 +941,13 @@ public class BSShapeCompound : BSShape private void DereferenceAnonCollisionShape(BSScene physicsScene, BulletShape pShape) { // TODO: figure a better way to go through all the shape types and find a possible instance. + physicsScene.DetailLog("{0},BSShapeCompound.DereferenceAnonCollisionShape,shape={1}", + BSScene.DetailLogZero, pShape); BSShapeMesh meshDesc; if (BSShapeMesh.TryGetMeshByPtr(pShape, out meshDesc)) { meshDesc.Dereference(physicsScene); + // physicsScene.DetailLog("{0},BSShapeCompound.DereferenceAnonCollisionShape,foundMesh,shape={1}", BSScene.DetailLogZero, pShape); } else { @@ -937,13 +955,15 @@ public class BSShapeCompound : BSShape if (BSShapeHull.TryGetHullByPtr(pShape, out hullDesc)) { hullDesc.Dereference(physicsScene); + // physicsScene.DetailLog("{0},BSShapeCompound.DereferenceAnonCollisionShape,foundHull,shape={1}", BSScene.DetailLogZero, pShape); } else { BSShapeConvexHull chullDesc; - if (BSShapeConvexHull.TryGetHullByPtr(pShape, out chullDesc)) + if (BSShapeConvexHull.TryGetConvexHullByPtr(pShape, out chullDesc)) { chullDesc.Dereference(physicsScene); + // physicsScene.DetailLog("{0},BSShapeCompound.DereferenceAnonCollisionShape,foundConvexHull,shape={1}", BSScene.DetailLogZero, pShape); } else { @@ -951,20 +971,23 @@ public class BSShapeCompound : BSShape if (BSShapeGImpact.TryGetGImpactByPtr(pShape, out gImpactDesc)) { gImpactDesc.Dereference(physicsScene); + // physicsScene.DetailLog("{0},BSShapeCompound.DereferenceAnonCollisionShape,foundgImpact,shape={1}", BSScene.DetailLogZero, pShape); } else { // Didn't find it in the lists of specific types. It could be compound. - if (physicsScene.PE.IsCompound(pShape)) + BSShapeCompound compoundDesc; + if (BSShapeCompound.TryGetCompoundByPtr(pShape, out compoundDesc)) { - BSShapeCompound recursiveCompound = new BSShapeCompound(pShape); - recursiveCompound.Dereference(physicsScene); + compoundDesc.Dereference(physicsScene); + // physicsScene.DetailLog("{0},BSShapeCompound.DereferenceAnonCollisionShape,recursiveCompoundShape,shape={1}", BSScene.DetailLogZero, pShape); } else { // If none of the above, maybe it is a simple native shape. if (physicsScene.PE.IsNativeShape(pShape)) { + // physicsScene.DetailLog("{0},BSShapeCompound.DereferenceAnonCollisionShape,assumingNative,shape={1}", BSScene.DetailLogZero, pShape); BSShapeNative nativeShape = new BSShapeNative(pShape); nativeShape.Dereference(physicsScene); } @@ -1021,6 +1044,8 @@ public class BSShapeConvexHull : BSShape convexShape = physicsScene.PE.BuildConvexHullShapeFromMesh(physicsScene.World, baseMesh.physShapeInfo); convexShape.shapeKey = newMeshKey; ConvexHulls.Add(convexShape.shapeKey, retConvexHull); + physicsScene.DetailLog("{0},BSShapeConvexHull.GetReference,addingNewlyCreatedShape,shape={1}", + BSScene.DetailLogZero, convexShape); } // Done with the base mesh @@ -1049,7 +1074,7 @@ public class BSShapeConvexHull : BSShape } } // Loop through all the known hulls and return the description based on the physical address. - public static bool TryGetHullByPtr(BulletShape pShape, out BSShapeConvexHull outHull) + public static bool TryGetConvexHullByPtr(BulletShape pShape, out BSShapeConvexHull outHull) { bool ret = false; BSShapeConvexHull foundDesc = null; -- cgit v1.1