From 376441e5507052b36279279f64896542d44ec12a Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Wed, 15 Aug 2012 16:27:30 -0700 Subject: BulletSim: make it so objects in a linkset do not generate collisions with each other. --- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 7 +++++++ OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 10 ++++++++++ OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 12 ++++++++++-- 3 files changed, 27 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 087b9bb..1b3ba3f 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -42,6 +42,9 @@ public class BSLinkset private BSScene m_physicsScene; public BSScene PhysicsScene { get { return m_physicsScene; } } + static int m_nextLinksetID = 1; + public int LinksetID { get; private set; } + // The children under the root in this linkset private List m_children; @@ -74,6 +77,10 @@ public class BSLinkset public BSLinkset(BSScene scene, BSPrim parent) { // A simple linkset of one (no children) + LinksetID = m_nextLinksetID++; + // We create LOTS of linksets. + if (m_nextLinksetID < 0) + m_nextLinksetID = 1; m_physicsScene = scene; m_linksetRoot = parent; m_children = new List(); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 9c20004..c157669 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -1353,6 +1353,7 @@ public sealed class BSPrim : PhysicsActor } // I've collided with something + // Called at taint time from within the Step() function CollisionEventUpdate collisionCollection; public void Collide(uint collidingWith, ActorTypes type, OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth) { @@ -1366,6 +1367,15 @@ public sealed class BSPrim : PhysicsActor } // DetailLog("{0},BSPrim.Collison,call,with={1}", LocalID, collidingWith); + BSPrim collidingWithPrim; + if (_scene.Prims.TryGetValue(collidingWith, out collidingWithPrim)) + { + // prims in the same linkset cannot collide with each other + if (this.Linkset.LinksetID == collidingWithPrim.Linkset.LinksetID) + { + return; + } + } // if someone is subscribed to collision events.... if (_subscribedEventsMs != 0) { diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index a31c578..0a0e27e 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -78,10 +78,16 @@ public class BSScene : PhysicsScene, IPhysicsParameters public string BulletSimVersion = "?"; private Dictionary m_avatars = new Dictionary(); + public Dictionary Characters { get { return m_avatars; } } + private Dictionary m_prims = new Dictionary(); + public Dictionary Prims { get { return m_prims; } } + private HashSet m_avatarsWithCollisions = new HashSet(); private HashSet m_primsWithCollisions = new HashSet(); + private List m_vehicles = new List(); + private float[] m_heightMap; private float m_waterLevel; private uint m_worldID; @@ -429,13 +435,13 @@ public class BSScene : PhysicsScene, IPhysicsParameters { numSubSteps = BulletSimAPI.PhysicsStep(m_worldID, timeStep, m_maxSubSteps, m_fixedTimeStep, out updatedEntityCount, out updatedEntitiesPtr, out collidersCount, out collidersPtr); - // DetailLog("{0},Simulate,call, substeps={1}, updates={2}, colliders={3}", DetailLogZero, numSubSteps, updatedEntityCount, collidersCount); + DetailLog("{0},Simulate,call, substeps={1}, updates={2}, colliders={3}", DetailLogZero, numSubSteps, updatedEntityCount, collidersCount); } catch (Exception e) { m_log.WarnFormat("{0},PhysicsStep Exception: substeps={1}, updates={2}, colliders={3}, e={4}", LogHeader, numSubSteps, updatedEntityCount, collidersCount, e); // DetailLog("{0},PhysicsStepException,call, substeps={1}, updates={2}, colliders={3}", DetailLogZero, numSubSteps, updatedEntityCount, collidersCount); - // updatedEntityCount = 0; + updatedEntityCount = 0; collidersCount = 0; } @@ -534,6 +540,8 @@ public class BSScene : PhysicsScene, IPhysicsParameters else if (m_avatars.ContainsKey(collidingWith)) type = ActorTypes.Agent; + DetailLog("{0},BSScene.SendCollision,collide,id={1},with={2}", DetailLogZero, localID, collidingWith); + BSPrim prim; if (m_prims.TryGetValue(localID, out prim)) { prim.Collide(collidingWith, type, collidePoint, collideNormal, penitration); -- cgit v1.1 From e31e23d68d9935457ad86559bea37b2b4a63a8dc Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Wed, 15 Aug 2012 16:49:05 -0700 Subject: BulletSim: in BSDynamics, merge 'flags' and 'hoverFlags' as they are defined for the same bits and it makes the code less complicated. --- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 178 +++------------------ 1 file changed, 20 insertions(+), 158 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index 5a9f135..78bfa05 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -74,7 +74,6 @@ namespace OpenSim.Region.Physics.BulletSPlugin // HOVER_UP_ONLY // LIMIT_MOTOR_UP // LIMIT_ROLL_ONLY - private VehicleFlag m_Hoverflags = (VehicleFlag)0; private Vector3 m_BlockingEndPoint = Vector3.Zero; private Quaternion m_RollreferenceFrame = Quaternion.Identity; // Linear properties @@ -281,157 +280,20 @@ namespace OpenSim.Region.Physics.BulletSPlugin internal void ProcessVehicleFlags(int pParam, bool remove) { DetailLog("{0},ProcessVehicleFlags,param={1},remove={2}", m_prim.LocalID, pParam, remove); + VehicleFlag parm = (VehicleFlag)pParam; if (remove) { if (pParam == -1) { m_flags = (VehicleFlag)0; - m_Hoverflags = (VehicleFlag)0; - return; } - if ((pParam & (int)VehicleFlag.HOVER_GLOBAL_HEIGHT) == (int)VehicleFlag.HOVER_GLOBAL_HEIGHT) - { - if ((m_Hoverflags & VehicleFlag.HOVER_GLOBAL_HEIGHT) != (VehicleFlag)0) - m_Hoverflags &= ~(VehicleFlag.HOVER_GLOBAL_HEIGHT); - } - if ((pParam & (int)VehicleFlag.HOVER_TERRAIN_ONLY) == (int)VehicleFlag.HOVER_TERRAIN_ONLY) - { - if ((m_Hoverflags & VehicleFlag.HOVER_TERRAIN_ONLY) != (VehicleFlag)0) - m_Hoverflags &= ~(VehicleFlag.HOVER_TERRAIN_ONLY); - } - if ((pParam & (int)VehicleFlag.HOVER_UP_ONLY) == (int)VehicleFlag.HOVER_UP_ONLY) - { - if ((m_Hoverflags & VehicleFlag.HOVER_UP_ONLY) != (VehicleFlag)0) - m_Hoverflags &= ~(VehicleFlag.HOVER_UP_ONLY); - } - if ((pParam & (int)VehicleFlag.HOVER_WATER_ONLY) == (int)VehicleFlag.HOVER_WATER_ONLY) - { - if ((m_Hoverflags & VehicleFlag.HOVER_WATER_ONLY) != (VehicleFlag)0) - m_Hoverflags &= ~(VehicleFlag.HOVER_WATER_ONLY); - } - if ((pParam & (int)VehicleFlag.LIMIT_MOTOR_UP) == (int)VehicleFlag.LIMIT_MOTOR_UP) - { - if ((m_flags & VehicleFlag.LIMIT_MOTOR_UP) != (VehicleFlag)0) - m_flags &= ~(VehicleFlag.LIMIT_MOTOR_UP); - } - if ((pParam & (int)VehicleFlag.LIMIT_ROLL_ONLY) == (int)VehicleFlag.LIMIT_ROLL_ONLY) - { - if ((m_flags & VehicleFlag.LIMIT_ROLL_ONLY) != (VehicleFlag)0) - m_flags &= ~(VehicleFlag.LIMIT_ROLL_ONLY); - } - if ((pParam & (int)VehicleFlag.MOUSELOOK_BANK) == (int)VehicleFlag.MOUSELOOK_BANK) - { - if ((m_flags & VehicleFlag.MOUSELOOK_BANK) != (VehicleFlag)0) - m_flags &= ~(VehicleFlag.MOUSELOOK_BANK); - } - if ((pParam & (int)VehicleFlag.MOUSELOOK_STEER) == (int)VehicleFlag.MOUSELOOK_STEER) - { - if ((m_flags & VehicleFlag.MOUSELOOK_STEER) != (VehicleFlag)0) - m_flags &= ~(VehicleFlag.MOUSELOOK_STEER); - } - if ((pParam & (int)VehicleFlag.NO_DEFLECTION_UP) == (int)VehicleFlag.NO_DEFLECTION_UP) - { - if ((m_flags & VehicleFlag.NO_DEFLECTION_UP) != (VehicleFlag)0) - m_flags &= ~(VehicleFlag.NO_DEFLECTION_UP); - } - if ((pParam & (int)VehicleFlag.CAMERA_DECOUPLED) == (int)VehicleFlag.CAMERA_DECOUPLED) - { - if ((m_flags & VehicleFlag.CAMERA_DECOUPLED) != (VehicleFlag)0) - m_flags &= ~(VehicleFlag.CAMERA_DECOUPLED); - } - if ((pParam & (int)VehicleFlag.NO_X) == (int)VehicleFlag.NO_X) - { - if ((m_flags & VehicleFlag.NO_X) != (VehicleFlag)0) - m_flags &= ~(VehicleFlag.NO_X); - } - if ((pParam & (int)VehicleFlag.NO_Y) == (int)VehicleFlag.NO_Y) - { - if ((m_flags & VehicleFlag.NO_Y) != (VehicleFlag)0) - m_flags &= ~(VehicleFlag.NO_Y); - } - if ((pParam & (int)VehicleFlag.NO_Z) == (int)VehicleFlag.NO_Z) - { - if ((m_flags & VehicleFlag.NO_Z) != (VehicleFlag)0) - m_flags &= ~(VehicleFlag.NO_Z); - } - if ((pParam & (int)VehicleFlag.LOCK_HOVER_HEIGHT) == (int)VehicleFlag.LOCK_HOVER_HEIGHT) - { - if ((m_Hoverflags & VehicleFlag.LOCK_HOVER_HEIGHT) != (VehicleFlag)0) - m_Hoverflags &= ~(VehicleFlag.LOCK_HOVER_HEIGHT); - } - if ((pParam & (int)VehicleFlag.NO_DEFLECTION) == (int)VehicleFlag.NO_DEFLECTION) - { - if ((m_flags & VehicleFlag.NO_DEFLECTION) != (VehicleFlag)0) - m_flags &= ~(VehicleFlag.NO_DEFLECTION); - } - if ((pParam & (int)VehicleFlag.LOCK_ROTATION) == (int)VehicleFlag.LOCK_ROTATION) + else { - if ((m_flags & VehicleFlag.LOCK_ROTATION) != (VehicleFlag)0) - m_flags &= ~(VehicleFlag.LOCK_ROTATION); + m_flags &= ~parm; } } - else - { - if ((pParam & (int)VehicleFlag.HOVER_GLOBAL_HEIGHT) == (int)VehicleFlag.HOVER_GLOBAL_HEIGHT) - { - m_Hoverflags |= (VehicleFlag.HOVER_GLOBAL_HEIGHT | m_flags); - } - if ((pParam & (int)VehicleFlag.HOVER_TERRAIN_ONLY) == (int)VehicleFlag.HOVER_TERRAIN_ONLY) - { - m_Hoverflags |= (VehicleFlag.HOVER_TERRAIN_ONLY | m_flags); - } - if ((pParam & (int)VehicleFlag.HOVER_UP_ONLY) == (int)VehicleFlag.HOVER_UP_ONLY) - { - m_Hoverflags |= (VehicleFlag.HOVER_UP_ONLY | m_flags); - } - if ((pParam & (int)VehicleFlag.HOVER_WATER_ONLY) == (int)VehicleFlag.HOVER_WATER_ONLY) - { - m_Hoverflags |= (VehicleFlag.HOVER_WATER_ONLY | m_flags); - } - if ((pParam & (int)VehicleFlag.LIMIT_MOTOR_UP) == (int)VehicleFlag.LIMIT_MOTOR_UP) - { - m_flags |= (VehicleFlag.LIMIT_MOTOR_UP | m_flags); - } - if ((pParam & (int)VehicleFlag.MOUSELOOK_BANK) == (int)VehicleFlag.MOUSELOOK_BANK) - { - m_flags |= (VehicleFlag.MOUSELOOK_BANK | m_flags); - } - if ((pParam & (int)VehicleFlag.MOUSELOOK_STEER) == (int)VehicleFlag.MOUSELOOK_STEER) - { - m_flags |= (VehicleFlag.MOUSELOOK_STEER | m_flags); - } - if ((pParam & (int)VehicleFlag.NO_DEFLECTION_UP) == (int)VehicleFlag.NO_DEFLECTION_UP) - { - m_flags |= (VehicleFlag.NO_DEFLECTION_UP | m_flags); - } - if ((pParam & (int)VehicleFlag.CAMERA_DECOUPLED) == (int)VehicleFlag.CAMERA_DECOUPLED) - { - m_flags |= (VehicleFlag.CAMERA_DECOUPLED | m_flags); - } - if ((pParam & (int)VehicleFlag.NO_X) == (int)VehicleFlag.NO_X) - { - m_flags |= (VehicleFlag.NO_X); - } - if ((pParam & (int)VehicleFlag.NO_Y) == (int)VehicleFlag.NO_Y) - { - m_flags |= (VehicleFlag.NO_Y); - } - if ((pParam & (int)VehicleFlag.NO_Z) == (int)VehicleFlag.NO_Z) - { - m_flags |= (VehicleFlag.NO_Z); - } - if ((pParam & (int)VehicleFlag.LOCK_HOVER_HEIGHT) == (int)VehicleFlag.LOCK_HOVER_HEIGHT) - { - m_Hoverflags |= (VehicleFlag.LOCK_HOVER_HEIGHT); - } - if ((pParam & (int)VehicleFlag.NO_DEFLECTION) == (int)VehicleFlag.NO_DEFLECTION) - { - m_flags |= (VehicleFlag.NO_DEFLECTION); - } - if ((pParam & (int)VehicleFlag.LOCK_ROTATION) == (int)VehicleFlag.LOCK_ROTATION) - { - m_flags |= (VehicleFlag.LOCK_ROTATION); - } + else { + m_flags |= parm; } }//end ProcessVehicleFlags @@ -478,10 +340,10 @@ namespace OpenSim.Region.Physics.BulletSPlugin // m_bankingMix = 1; // m_bankingTimescale = 10; // m_referenceFrame = Quaternion.Identity; - m_Hoverflags &= + m_flags |= (VehicleFlag.NO_DEFLECTION_UP | VehicleFlag.LIMIT_ROLL_ONLY | VehicleFlag.LIMIT_MOTOR_UP); + m_flags &= ~(VehicleFlag.HOVER_WATER_ONLY | VehicleFlag.HOVER_TERRAIN_ONLY | VehicleFlag.HOVER_GLOBAL_HEIGHT | VehicleFlag.HOVER_UP_ONLY); - m_flags |= (VehicleFlag.NO_DEFLECTION_UP | VehicleFlag.LIMIT_ROLL_ONLY | VehicleFlag.LIMIT_MOTOR_UP); break; case Vehicle.TYPE_CAR: m_linearFrictionTimescale = new Vector3(100, 2, 1000); @@ -506,10 +368,10 @@ namespace OpenSim.Region.Physics.BulletSPlugin // m_bankingMix = 1; // m_bankingTimescale = 1; // m_referenceFrame = Quaternion.Identity; - m_Hoverflags &= ~(VehicleFlag.HOVER_WATER_ONLY | VehicleFlag.HOVER_TERRAIN_ONLY | VehicleFlag.HOVER_GLOBAL_HEIGHT); m_flags |= (VehicleFlag.NO_DEFLECTION_UP | VehicleFlag.LIMIT_ROLL_ONLY | VehicleFlag.LIMIT_MOTOR_UP); - m_Hoverflags |= (VehicleFlag.HOVER_UP_ONLY); + m_flags &= ~(VehicleFlag.HOVER_WATER_ONLY | VehicleFlag.HOVER_TERRAIN_ONLY | VehicleFlag.HOVER_GLOBAL_HEIGHT); + m_flags |= (VehicleFlag.HOVER_UP_ONLY); break; case Vehicle.TYPE_BOAT: m_linearFrictionTimescale = new Vector3(10, 3, 2); @@ -534,12 +396,12 @@ namespace OpenSim.Region.Physics.BulletSPlugin // m_bankingMix = 0.8f; // m_bankingTimescale = 1; // m_referenceFrame = Quaternion.Identity; - m_Hoverflags &= ~(VehicleFlag.HOVER_TERRAIN_ONLY | + m_flags &= ~(VehicleFlag.HOVER_TERRAIN_ONLY | VehicleFlag.HOVER_GLOBAL_HEIGHT | VehicleFlag.HOVER_UP_ONLY); m_flags &= ~(VehicleFlag.LIMIT_ROLL_ONLY); m_flags |= (VehicleFlag.NO_DEFLECTION_UP | VehicleFlag.LIMIT_MOTOR_UP); - m_Hoverflags |= (VehicleFlag.HOVER_WATER_ONLY); + m_flags |= (VehicleFlag.HOVER_WATER_ONLY); break; case Vehicle.TYPE_AIRPLANE: m_linearFrictionTimescale = new Vector3(200, 10, 5); @@ -564,7 +426,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin // m_bankingMix = 0.7f; // m_bankingTimescale = 2; // m_referenceFrame = Quaternion.Identity; - m_Hoverflags &= ~(VehicleFlag.HOVER_WATER_ONLY | VehicleFlag.HOVER_TERRAIN_ONLY | + m_flags &= ~(VehicleFlag.HOVER_WATER_ONLY | VehicleFlag.HOVER_TERRAIN_ONLY | VehicleFlag.HOVER_GLOBAL_HEIGHT | VehicleFlag.HOVER_UP_ONLY); m_flags &= ~(VehicleFlag.NO_DEFLECTION_UP | VehicleFlag.LIMIT_MOTOR_UP); m_flags |= (VehicleFlag.LIMIT_ROLL_ONLY); @@ -592,11 +454,11 @@ namespace OpenSim.Region.Physics.BulletSPlugin // m_bankingMix = 0.7f; // m_bankingTimescale = 5; // m_referenceFrame = Quaternion.Identity; - m_Hoverflags &= ~(VehicleFlag.HOVER_WATER_ONLY | VehicleFlag.HOVER_TERRAIN_ONLY | + m_flags &= ~(VehicleFlag.HOVER_WATER_ONLY | VehicleFlag.HOVER_TERRAIN_ONLY | VehicleFlag.HOVER_UP_ONLY); m_flags &= ~(VehicleFlag.NO_DEFLECTION_UP | VehicleFlag.LIMIT_MOTOR_UP); m_flags |= (VehicleFlag.LIMIT_ROLL_ONLY); - m_Hoverflags |= (VehicleFlag.HOVER_GLOBAL_HEIGHT); + m_flags |= (VehicleFlag.HOVER_GLOBAL_HEIGHT); break; } }//end SetDefaultsForType @@ -736,28 +598,28 @@ namespace OpenSim.Region.Physics.BulletSPlugin } // Check if hovering - if ((m_Hoverflags & (VehicleFlag.HOVER_WATER_ONLY | VehicleFlag.HOVER_TERRAIN_ONLY | VehicleFlag.HOVER_GLOBAL_HEIGHT)) != 0) + if ((m_flags & (VehicleFlag.HOVER_WATER_ONLY | VehicleFlag.HOVER_TERRAIN_ONLY | VehicleFlag.HOVER_GLOBAL_HEIGHT)) != 0) { // We should hover, get the target height - if ((m_Hoverflags & VehicleFlag.HOVER_WATER_ONLY) != 0) + if ((m_flags & VehicleFlag.HOVER_WATER_ONLY) != 0) { m_VhoverTargetHeight = m_prim.Scene.GetWaterLevel() + m_VhoverHeight; } - if ((m_Hoverflags & VehicleFlag.HOVER_TERRAIN_ONLY) != 0) + if ((m_flags & VehicleFlag.HOVER_TERRAIN_ONLY) != 0) { m_VhoverTargetHeight = m_prim.Scene.GetTerrainHeightAtXY(pos.X, pos.Y) + m_VhoverHeight; } - if ((m_Hoverflags & VehicleFlag.HOVER_GLOBAL_HEIGHT) != 0) + if ((m_flags & VehicleFlag.HOVER_GLOBAL_HEIGHT) != 0) { m_VhoverTargetHeight = m_VhoverHeight; } - if ((m_Hoverflags & VehicleFlag.HOVER_UP_ONLY) != 0) + if ((m_flags & VehicleFlag.HOVER_UP_ONLY) != 0) { // If body is aready heigher, use its height as target height if (pos.Z > m_VhoverTargetHeight) m_VhoverTargetHeight = pos.Z; } - if ((m_Hoverflags & VehicleFlag.LOCK_HOVER_HEIGHT) != 0) + if ((m_flags & VehicleFlag.LOCK_HOVER_HEIGHT) != 0) { if ((pos.Z - m_VhoverTargetHeight) > .2 || (pos.Z - m_VhoverTargetHeight) < -.2) { -- cgit v1.1 From 8eda290262bb7049aa55a7df2bdb1565bad85a99 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Fri, 17 Aug 2012 09:37:02 -0700 Subject: BulletSim: comments and parameter changes in dynamics engine. --- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 50 ++++++++++++---------- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 6 +-- 2 files changed, 30 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 78bfa05..d7213fc 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -57,6 +57,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin private int frcount = 0; // Used to limit dynamics debug output to // every 100th frame + private BSScene m_physicsScene; private BSPrim m_prim; // the prim this dynamic controller belongs to // Vehicle properties @@ -123,15 +124,16 @@ namespace OpenSim.Region.Physics.BulletSPlugin private float m_verticalAttractionEfficiency = 1.0f; // damped private float m_verticalAttractionTimescale = 500f; // Timescale > 300 means no vert attractor. - public BSDynamics(BSPrim myPrim) + public BSDynamics(BSScene myScene, BSPrim myPrim) { + m_physicsScene = myScene; m_prim = myPrim; m_type = Vehicle.TYPE_NONE; } internal void ProcessFloatVehicleParam(Vehicle pParam, float pValue, float timestep) { - DetailLog("{0},ProcessFloatVehicleParam,param={1},val={2}", m_prim.LocalID, pParam, pValue); + VDetailLog("{0},ProcessFloatVehicleParam,param={1},val={2}", m_prim.LocalID, pParam, pValue); switch (pParam) { case Vehicle.ANGULAR_DEFLECTION_EFFICIENCY: @@ -230,7 +232,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin internal void ProcessVectorVehicleParam(Vehicle pParam, Vector3 pValue, float timestep) { - DetailLog("{0},ProcessVectorVehicleParam,param={1},val={2}", m_prim.LocalID, pParam, pValue); + VDetailLog("{0},ProcessVectorVehicleParam,param={1},val={2}", m_prim.LocalID, pParam, pValue); switch (pParam) { case Vehicle.ANGULAR_FRICTION_TIMESCALE: @@ -265,7 +267,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin internal void ProcessRotationVehicleParam(Vehicle pParam, Quaternion pValue) { - DetailLog("{0},ProcessRotationalVehicleParam,param={1},val={2}", m_prim.LocalID, pParam, pValue); + VDetailLog("{0},ProcessRotationalVehicleParam,param={1},val={2}", m_prim.LocalID, pParam, pValue); switch (pParam) { case Vehicle.REFERENCE_FRAME: @@ -279,7 +281,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin internal void ProcessVehicleFlags(int pParam, bool remove) { - DetailLog("{0},ProcessVehicleFlags,param={1},remove={2}", m_prim.LocalID, pParam, remove); + VDetailLog("{0},ProcessVehicleFlags,param={1},remove={2}", m_prim.LocalID, pParam, remove); VehicleFlag parm = (VehicleFlag)pParam; if (remove) { @@ -297,9 +299,9 @@ namespace OpenSim.Region.Physics.BulletSPlugin } }//end ProcessVehicleFlags - internal void ProcessTypeChange(Vehicle pType) + internal void ProcessTypeChange(Vehicle pType, float stepSize) { - DetailLog("{0},ProcessTypeChange,type={1}", m_prim.LocalID, pType); + VDetailLog("{0},ProcessTypeChange,type={1}", m_prim.LocalID, pType); // Set Defaults For Type m_type = pType; switch (pType) @@ -475,7 +477,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin MoveAngular(pTimestep); LimitRotation(pTimestep); - DetailLog("{0},BSDynamics.Step,done,pos={1},force={2},velocity={3},angvel={4}", + VDetailLog("{0},BSDynamics.Step,done,pos={1},force={2},velocity={3},angvel={4}", m_prim.LocalID, m_prim.Position, m_prim.Force, m_prim.Velocity, m_prim.RotationalVelocity); }// end Step @@ -519,7 +521,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin */ - DetailLog("{0},MoveLinear,nonZero,origdir={1},origvel={2},add={3},decay={4},dir={5},vel={6}", + VDetailLog("{0},MoveLinear,nonZero,origdir={1},origvel={2},add={3},decay={4},dir={5},vel={6}", m_prim.LocalID, origDir, origVel, addAmount, decayfraction, m_linearMotorDirection, m_lastLinearVelocityVector); } else @@ -531,7 +533,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin m_lastLinearVelocityVector = Vector3.Zero; } - // convert requested object velocity to world-referenced vector + // convert requested object velocity to object relative vector Quaternion rotq = m_prim.Orientation; m_dir = m_lastLinearVelocityVector * rotq; @@ -584,7 +586,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin if (changed) { m_prim.Position = pos; - DetailLog("{0},MoveLinear,blockingEndPoint,block={1},origPos={2},pos={3}", + VDetailLog("{0},MoveLinear,blockingEndPoint,block={1},origPos={2},pos={3}", m_prim.LocalID, m_BlockingEndPoint, posChange, pos); } } @@ -594,7 +596,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin { pos.Z = m_prim.Scene.GetTerrainHeightAtXYZ(pos) + 2; m_prim.Position = pos; - DetailLog("{0},MoveLinear,terrainHeight,pos={1}", m_prim.LocalID, pos); + VDetailLog("{0},MoveLinear,terrainHeight,pos={1}", m_prim.LocalID, pos); } // Check if hovering @@ -641,7 +643,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin } } - DetailLog("{0},MoveLinear,hover,pos={1},dir={2},height={3},target={4}", m_prim.LocalID, pos, m_dir, m_VhoverHeight, m_VhoverTargetHeight); + VDetailLog("{0},MoveLinear,hover,pos={1},dir={2},height={3},target={4}", m_prim.LocalID, pos, m_dir, m_VhoverHeight, m_VhoverTargetHeight); // m_VhoverEfficiency = 0f; // 0=boucy, 1=Crit.damped // m_VhoverTimescale = 0f; // time to acheive height @@ -677,7 +679,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin { grav.Z = (float)(grav.Z * 1.037125); } - DetailLog("{0},MoveLinear,limitMotorUp,grav={1}", m_prim.LocalID, grav); + VDetailLog("{0},MoveLinear,limitMotorUp,grav={1}", m_prim.LocalID, grav); //End Experimental Values } if ((m_flags & (VehicleFlag.NO_X)) != 0) @@ -706,7 +708,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin Vector3 decayamount = Vector3.One / (m_linearFrictionTimescale / pTimestep); m_lastLinearVelocityVector -= m_lastLinearVelocityVector * decayamount; - DetailLog("{0},MoveLinear,done,pos={1},vel={2},force={3},decay={4}", + VDetailLog("{0},MoveLinear,done,pos={1},vel={2},force={3},decay={4}", m_prim.LocalID, m_lastPositionVector, m_dir, grav, decayamount); } // end MoveLinear() @@ -732,13 +734,13 @@ namespace OpenSim.Region.Physics.BulletSPlugin // There are m_angularMotorApply steps. Vector3 origAngularVelocity = m_angularMotorVelocity; // ramp up to new value - // current velocity += error / (time to get there / step interval) + // current velocity += error / (time to get there / step interval) // requested speed - last motor speed m_angularMotorVelocity.X += (m_angularMotorDirection.X - m_angularMotorVelocity.X) / (m_angularMotorTimescale / pTimestep); m_angularMotorVelocity.Y += (m_angularMotorDirection.Y - m_angularMotorVelocity.Y) / (m_angularMotorTimescale / pTimestep); m_angularMotorVelocity.Z += (m_angularMotorDirection.Z - m_angularMotorVelocity.Z) / (m_angularMotorTimescale / pTimestep); - DetailLog("{0},MoveAngular,angularMotorApply,apply={1},origvel={2},dir={3},vel={4}", + VDetailLog("{0},MoveAngular,angularMotorApply,apply={1},origvel={2},dir={3},vel={4}", m_prim.LocalID,m_angularMotorApply,origAngularVelocity, m_angularMotorDirection, m_angularMotorVelocity); m_angularMotorApply--; // This is done so that if script request rate is less than phys frame rate the expected @@ -749,6 +751,8 @@ namespace OpenSim.Region.Physics.BulletSPlugin // No motor recently applied, keep the body velocity // and decay the velocity m_angularMotorVelocity -= m_angularMotorVelocity / (m_angularMotorDecayTimescale / pTimestep); + if (m_angularMotorVelocity.LengthSquared() < 0.00001) + m_angularMotorVelocity = Vector3.Zero; } // end motor section // Vertical attractor section @@ -786,7 +790,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin vertattr.X += bounce * angularVelocity.X; vertattr.Y += bounce * angularVelocity.Y; - DetailLog("{0},MoveAngular,verticalAttraction,verterr={1},bounce={2},vertattr={3}", + VDetailLog("{0},MoveAngular,verticalAttraction,verterr={1},bounce={2},vertattr={3}", m_prim.LocalID, verterr, bounce, vertattr); } // else vertical attractor is off @@ -804,13 +808,13 @@ namespace OpenSim.Region.Physics.BulletSPlugin { m_lastAngularVelocity.X = 0; m_lastAngularVelocity.Y = 0; - DetailLog("{0},MoveAngular,noDeflectionUp,lastAngular={1}", m_prim.LocalID, m_lastAngularVelocity); + VDetailLog("{0},MoveAngular,noDeflectionUp,lastAngular={1}", m_prim.LocalID, m_lastAngularVelocity); } if (m_lastAngularVelocity.ApproxEquals(Vector3.Zero, 0.01f)) { m_lastAngularVelocity = Vector3.Zero; // Reduce small value to zero. - DetailLog("{0},MoveAngular,zeroSmallValues,lastAngular={1}", m_prim.LocalID, m_lastAngularVelocity); + VDetailLog("{0},MoveAngular,zeroSmallValues,lastAngular={1}", m_prim.LocalID, m_lastAngularVelocity); } // apply friction @@ -820,7 +824,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin // Apply to the body m_prim.RotationalVelocity = m_lastAngularVelocity; - DetailLog("{0},MoveAngular,done,decay={1},lastAngular={2}", m_prim.LocalID, decayamount, m_lastAngularVelocity); + VDetailLog("{0},MoveAngular,done,decay={1},lastAngular={2}", m_prim.LocalID, decayamount, m_lastAngularVelocity); } //end MoveAngular internal void LimitRotation(float timestep) @@ -867,11 +871,11 @@ namespace OpenSim.Region.Physics.BulletSPlugin if (changed) m_prim.Orientation = m_rot; - DetailLog("{0},LimitRotation,done,changed={1},orig={2},new={3}", m_prim.LocalID, changed, rotq, m_rot); + VDetailLog("{0},LimitRotation,done,changed={1},orig={2},new={3}", m_prim.LocalID, changed, rotq, m_rot); } // Invoke the detailed logger and output something if it's enabled. - private void DetailLog(string msg, params Object[] args) + private void VDetailLog(string msg, params Object[] args) { if (m_prim.Scene.VehicleLoggingEnabled) m_prim.Scene.PhysicsLogging.Write(msg, args); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index c157669..b918f84 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -141,8 +141,8 @@ public sealed class BSPrim : PhysicsActor _friction = _scene.Params.defaultFriction; // TODO: compute based on object material _density = _scene.Params.defaultDensity; // TODO: compute based on object material _restitution = _scene.Params.defaultRestitution; - _linkset = new BSLinkset(_scene, this); // a linkset of one - _vehicle = new BSDynamics(this); // add vehicleness + _linkset = new BSLinkset(Scene, this); // a linkset of one + _vehicle = new BSDynamics(Scene, this); // add vehicleness _mass = CalculateMass(); // do the actual object creation at taint time DetailLog("{0},BSPrim.constructor,call", LocalID); @@ -354,7 +354,7 @@ public sealed class BSPrim : PhysicsActor { // 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. - _vehicle.ProcessTypeChange(type); + _vehicle.ProcessTypeChange(type, Scene.LastSimulatedTimestep); // Tell the scene about the vehicle so it will get processing each frame. _scene.VehicleInSceneTypeChanged(this, type); }); -- cgit v1.1 From ccc69d66a135e149dbe9c6b70df0c8efe1265f65 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Fri, 17 Aug 2012 10:40:34 -0700 Subject: BulletSim: add parameters and functionality to specify the mesh level of detail for large meshes. Remove parameter and code for DetailLog (conditional logging into regular log file). --- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 14 ------ OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 14 +++--- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 54 +++++++++++------------ 3 files changed, 34 insertions(+), 48 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index 1b3ba3f..a075995 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -265,7 +265,6 @@ public class BSLinkset BSPrim childx = child; m_physicsScene.TaintedObject("AddChildToLinkset", delegate() { - // DebugLog("{0}: AddChildToLinkset: adding child {1} to {2}", LogHeader, child.LocalID, m_linksetRoot.LocalID); // DetailLog("{0},AddChildToLinkset,taint,child={1}", m_linksetRoot.LocalID, child.LocalID); PhysicallyLinkAChildToRoot(rootx, childx); // build the physical binding between me and the child }); @@ -294,7 +293,6 @@ public class BSLinkset BSPrim childx = child; m_physicsScene.TaintedObject("RemoveChildFromLinkset", delegate() { - // DebugLog("{0}: RemoveChildFromLinkset: Removing constraint to {1}", LogHeader, child.LocalID); // DetailLog("{0},RemoveChildFromLinkset,taint,child={1}", m_linksetRoot.LocalID, child.LocalID); PhysicallyUnlinkAChildFromRoot(rootx, childx); @@ -326,7 +324,6 @@ public class BSLinkset // create a constraint that allows no freedom of movement between the two objects // http://bulletphysics.org/Bullet/phpBB3/viewtopic.php?t=4818 - // DebugLog("{0}: CreateLinkset: Adding a constraint between root prim {1} and child prim {2}", LogHeader, LocalID, childPrim.LocalID); DetailLog("{0},PhysicallyLinkAChildToRoot,taint,root={1},child={2},rLoc={3},cLoc={4},midLoc={5}", rootPrim.LocalID, rootPrim.LocalID, childPrim.LocalID, rootPrim.Position, childPrim.Position, midPoint); BS6DofConstraint constrain = new BS6DofConstraint( @@ -350,7 +347,6 @@ public class BSLinkset // create a constraint that allows no freedom of movement between the two objects // http://bulletphysics.org/Bullet/phpBB3/viewtopic.php?t=4818 - // DebugLog("{0}: CreateLinkset: Adding a constraint between root prim {1} and child prim {2}", LogHeader, LocalID, childPrim.LocalID); DetailLog("{0},PhysicallyLinkAChildToRoot,taint,root={1},child={2}", rootPrim.LocalID, rootPrim.LocalID, childPrim.LocalID); BS6DofConstraint constrain = new BS6DofConstraint( PhysicsScene.World, rootPrim.Body, childPrim.Body, @@ -389,8 +385,6 @@ public class BSLinkset // Called at taint time! private void PhysicallyUnlinkAChildFromRoot(BSPrim rootPrim, BSPrim childPrim) { - // DebugLog("{0}: PhysicallyUnlinkAChildFromRoot: RemoveConstraint between root prim {1} and child prim {2}", - // LogHeader, rootPrim.LocalID, childPrim.LocalID); DetailLog("{0},PhysicallyUnlinkAChildFromRoot,taint,root={1},child={2}", rootPrim.LocalID, rootPrim.LocalID, childPrim.LocalID); // Find the constraint for this link and get rid of it from the overall collection and from my list @@ -404,20 +398,12 @@ public class BSLinkset // Called at taint time! private void PhysicallyUnlinkAllChildrenFromRoot(BSPrim rootPrim) { - // DebugLog("{0}: PhysicallyUnlinkAllChildren:", LogHeader); DetailLog("{0},PhysicallyUnlinkAllChildren,taint", rootPrim.LocalID); m_physicsScene.Constraints.RemoveAndDestroyConstraint(rootPrim.Body); } // Invoke the detailed logger and output something if it's enabled. - private void DebugLog(string msg, params Object[] args) - { - if (m_physicsScene.ShouldDebugLog) - m_physicsScene.Logger.DebugFormat(msg, args); - } - - // Invoke the detailed logger and output something if it's enabled. private void DetailLog(string msg, params Object[] args) { m_physicsScene.PhysicsLogging.Write(msg, args); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index b918f84..48cd89b 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -42,8 +42,6 @@ public sealed class BSPrim : PhysicsActor private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static readonly string LogHeader = "[BULLETS PRIM]"; - private void DebugLog(string mm, params Object[] xx) { if (_scene.ShouldDebugLog) m_log.DebugFormat(mm, xx); } - private IMesh _mesh; private PrimitiveBaseShape _pbs; private ShapeData.PhysicsShapeType _shapeType; @@ -232,7 +230,6 @@ public sealed class BSPrim : PhysicsActor BSPrim parent = obj as BSPrim; if (parent != null) { - DebugLog("{0}: link {1}/{2} to {3}", LogHeader, _avName, _localID, parent.LocalID); BSPrim parentBefore = _linkset.LinksetRoot; int childrenBefore = _linkset.NumberOfChildren; @@ -248,8 +245,6 @@ public sealed class BSPrim : PhysicsActor public override void delink() { // 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 - DebugLog("{0}: delink {1}/{2}. Parent={3}", LogHeader, _avName, _localID, - _linkset.LinksetRoot._avName+"/"+_linkset.LinksetRoot.LocalID.ToString()); BSPrim parentBefore = _linkset.LinksetRoot; int childrenBefore = _linkset.NumberOfChildren; @@ -1042,7 +1037,14 @@ public sealed class BSPrim : PhysicsActor // No locking here because this is done when we know physics is not simulating private void CreateGeomMesh() { - float lod = _pbs.SculptEntry ? _scene.SculptLOD : _scene.MeshLOD; + // level of detail based on size and type of the object + float lod = _scene.MeshLOD; + if (_pbs.SculptEntry) + lod = _scene.SculptLOD; + float maxAxis = Math.Max(_size.X, Math.Max(_size.Y, _size.Z)); + if (maxAxis > _scene.MeshMegaPrimThreshold) + lod = _scene.MeshMegaPrimLOD; + ulong newMeshKey = (ulong)_pbs.GetMeshKey(_size, lod); // m_log.DebugFormat("{0}: CreateGeomMesh: lID={1}, oldKey={2}, newKey={3}", LogHeader, _localID, _meshKey, newMeshKey); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index 0a0e27e..d901ff0 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -73,8 +73,6 @@ public class BSScene : PhysicsScene, IPhysicsParameters private static readonly ILog m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly string LogHeader = "[BULLETS SCENE]"; - public void DebugLog(string mm, params Object[] xx) { if (ShouldDebugLog) m_log.DebugFormat(mm, xx); } - public string BulletSimVersion = "?"; private Dictionary m_avatars = new Dictionary(); @@ -101,16 +99,11 @@ public class BSScene : PhysicsScene, IPhysicsParameters private int m_detailedStatsStep = 0; public IMesher mesher; - private float m_meshLOD; - public float MeshLOD - { - get { return m_meshLOD; } - } - private float m_sculptLOD; - public float SculptLOD - { - get { return m_sculptLOD; } - } + // Level of Detail values kept as float because that's what the Meshmerizer wants + public float MeshLOD { get; private set; } + public float MeshMegaPrimLOD { get; private set; } + public float MeshMegaPrimThreshold { get; private set; } + public float SculptLOD { get; private set; } private BulletSim m_worldSim; public BulletSim World @@ -185,8 +178,9 @@ public class BSScene : PhysicsScene, IPhysicsParameters ConfigurationParameters[] m_params; GCHandle m_paramsHandle; - public bool ShouldDebugLog { get; private set; } - + // Handle to the callback used by the unmanaged code to call into the managed code. + // Used for debug logging. + // Need to store the handle in a persistant variable so it won't be freed. private BulletSimAPI.DebugLogCallback m_DebugLogCallbackHandle; // Sometimes you just have to log everything. @@ -905,16 +899,26 @@ public class BSScene : PhysicsScene, IPhysicsParameters (s) => { return s.NumericBool(s._forceSimplePrimMeshing); }, (s,p,l,v) => { s._forceSimplePrimMeshing = s.BoolNumeric(v); } ), - new ParameterDefn("MeshLOD", "Level of detail to render meshes (32, 16, 8 or 4. 32=most detailed)", + new ParameterDefn("MeshLevelOfDetail", "Level of detail to render meshes (32, 16, 8 or 4. 32=most detailed)", 8f, - (s,cf,p,v) => { s.m_meshLOD = cf.GetInt(p, (int)v); }, - (s) => { return (float)s.m_meshLOD; }, - (s,p,l,v) => { s.m_meshLOD = (int)v; } ), - new ParameterDefn("SculptLOD", "Level of detail to render sculpties (32, 16, 8 or 4. 32=most detailed)", + (s,cf,p,v) => { s.MeshLOD = (float)cf.GetInt(p, (int)v); }, + (s) => { return s.MeshLOD; }, + (s,p,l,v) => { s.MeshLOD = v; } ), + new ParameterDefn("MeshLevelOfDetailMegaPrim", "Level of detail to render meshes larger than threshold meters", + 16f, + (s,cf,p,v) => { s.MeshMegaPrimLOD = (float)cf.GetInt(p, (int)v); }, + (s) => { return s.MeshMegaPrimLOD; }, + (s,p,l,v) => { s.MeshMegaPrimLOD = v; } ), + new ParameterDefn("MeshLevelOfDetailMegaPrimThreshold", "Size (in meters) of a mesh before using MeshMegaPrimLOD", + 10f, + (s,cf,p,v) => { s.MeshMegaPrimThreshold = (float)cf.GetInt(p, (int)v); }, + (s) => { return s.MeshMegaPrimThreshold; }, + (s,p,l,v) => { s.MeshMegaPrimThreshold = v; } ), + new ParameterDefn("SculptLevelOfDetail", "Level of detail to render sculpties (32, 16, 8 or 4. 32=most detailed)", 32f, - (s,cf,p,v) => { s.m_sculptLOD = cf.GetInt(p, (int)v); }, - (s) => { return (float)s.m_sculptLOD; }, - (s,p,l,v) => { s.m_sculptLOD = (int)v; } ), + (s,cf,p,v) => { s.SculptLOD = (float)cf.GetInt(p, (int)v); }, + (s) => { return s.SculptLOD; }, + (s,p,l,v) => { s.SculptLOD = v; } ), new ParameterDefn("MaxSubStep", "In simulation step, maximum number of substeps", 10f, @@ -1145,12 +1149,6 @@ public class BSScene : PhysicsScene, IPhysicsParameters (s,cf,p,v) => { s.m_detailedStatsStep = cf.GetInt(p, (int)v); }, (s) => { return (float)s.m_detailedStatsStep; }, (s,p,l,v) => { s.m_detailedStatsStep = (int)v; } ), - new ParameterDefn("ShouldDebugLog", "Enables detailed DEBUG log statements", - ConfigurationParameters.numericFalse, - (s,cf,p,v) => { s.ShouldDebugLog = cf.GetBoolean(p, s.BoolNumeric(v)); }, - (s) => { return s.NumericBool(s.ShouldDebugLog); }, - (s,p,l,v) => { s.ShouldDebugLog = s.BoolNumeric(v); } ), - }; // Convert a boolean to our numeric true and false values -- cgit v1.1 From 03d76e94034bbaa82d1872284d1fadbaa263411d Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Fri, 17 Aug 2012 13:30:46 -0700 Subject: BulletSim: restore most of the Detail logging statements. Will have no effect on non-logging running. Capture region name that is passed to the physics engine and use it for detail logging file name prefix. Fix problem with avatars dropping when flying across region boundries. --- .../Region/Physics/BulletSPlugin/BSCharacter.cs | 21 +++++----- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 8 ++-- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 46 +++++++++++----------- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 16 ++++++-- 4 files changed, 51 insertions(+), 40 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index e2f7af9..1b23a36 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -124,10 +124,14 @@ public class BSCharacter : PhysicsActor // do actual create at taint time _scene.TaintedObject("BSCharacter.create", delegate() { + DetailLog("{0},BSCharacter.create", _localID); BulletSimAPI.CreateObject(parent_scene.WorldID, shapeData); + // Set the buoyancy for flying. This will be refactored when all the settings happen in C# + BulletSimAPI.SetObjectBuoyancy(_scene.WorldID, LocalID, _buoyancy); + m_body = new BulletBody(LocalID, BulletSimAPI.GetBodyHandle2(_scene.World.Ptr, LocalID)); - // avatars get all collisions no matter what + // avatars get all collisions no matter what (makes walking on ground and such work) BulletSimAPI.AddToCollisionFlags2(Body.Ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); }); @@ -137,7 +141,7 @@ public class BSCharacter : PhysicsActor // called when this character is being destroyed and the resources should be released public void Destroy() { - // DetailLog("{0},BSCharacter.Destroy", LocalID); + DetailLog("{0},BSCharacter.Destroy", LocalID); _scene.TaintedObject("BSCharacter.destroy", delegate() { BulletSimAPI.DestroyObject(_scene.WorldID, _localID); @@ -319,14 +323,13 @@ public class BSCharacter : PhysicsActor public override bool Flying { get { return _flying; } set { - if (_flying != value) - { - _flying = value; - // simulate flying by changing the effect of gravity - this.Buoyancy = ComputeBuoyancyFromFlying(_flying); - } + _flying = value; + // simulate flying by changing the effect of gravity + this.Buoyancy = ComputeBuoyancyFromFlying(_flying); } } + // Flying is implimented by changing the avatar's buoyancy. + // Would this be done better with a vehicle type? private float ComputeBuoyancyFromFlying(bool ifFlying) { return ifFlying ? 1f : 0f; } @@ -488,11 +491,9 @@ public class BSCharacter : PhysicsActor // Avatars don't report their changes the usual way. Changes are checked for in the heartbeat loop. // base.RequestPhysicsterseUpdate(); - /* DetailLog("{0},BSCharacter.UpdateProperties,call,pos={1},orient={2},vel={3},accel={4},rotVel={5}", LocalID, entprop.Position, entprop.Rotation, entprop.Velocity, entprop.Acceleration, entprop.RotationalVelocity); - */ } // Called by the scene when a collision with this object is reported diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index a075995..9e3f0db 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -265,7 +265,7 @@ public class BSLinkset BSPrim childx = child; m_physicsScene.TaintedObject("AddChildToLinkset", delegate() { - // DetailLog("{0},AddChildToLinkset,taint,child={1}", m_linksetRoot.LocalID, child.LocalID); + DetailLog("{0},AddChildToLinkset,taint,child={1}", m_linksetRoot.LocalID, child.LocalID); PhysicallyLinkAChildToRoot(rootx, childx); // build the physical binding between me and the child }); } @@ -293,7 +293,7 @@ public class BSLinkset BSPrim childx = child; m_physicsScene.TaintedObject("RemoveChildFromLinkset", delegate() { - // DetailLog("{0},RemoveChildFromLinkset,taint,child={1}", m_linksetRoot.LocalID, child.LocalID); + DetailLog("{0},RemoveChildFromLinkset,taint,child={1}", m_linksetRoot.LocalID, child.LocalID); PhysicallyUnlinkAChildFromRoot(rootx, childx); }); @@ -332,10 +332,10 @@ public class BSLinkset true, true ); - /* NOTE: attempt to build constraint with full frame computation, etc. + /* NOTE: below is an attempt to build constraint with full frame computation, etc. * Using the midpoint is easier since it lets the Bullet code use the transforms * of the objects. - * Code left here as an example. + * Code left as a warning to future programmers. // ================================================================================== // relative position normalized to the root prim OMV.Quaternion invThisOrientation = OMV.Quaternion.Inverse(rootPrim.Orientation); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 48cd89b..a6bc8e2 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -191,7 +191,7 @@ public sealed class BSPrim : PhysicsActor { _mass = CalculateMass(); // changing size changes the mass BulletSimAPI.SetObjectScaleMass(_scene.WorldID, _localID, _scale, (IsPhysical ? _mass : 0f), IsPhysical); - // DetailLog("{0}: BSPrim.setSize: size={1}, mass={2}, physical={3}", LocalID, _size, _mass, IsPhysical); + DetailLog("{0}: BSPrim.setSize: size={1}, mass={2}, physical={3}", LocalID, _size, _mass, IsPhysical); RecreateGeomAndObject(); }); } @@ -275,7 +275,7 @@ public sealed class BSPrim : PhysicsActor public override void LockAngularMotion(OMV.Vector3 axis) { - // DetailLog("{0},BSPrim.LockAngularMotion,call,axis={1}", LocalID, axis); + DetailLog("{0},BSPrim.LockAngularMotion,call,axis={1}", LocalID, axis); return; } @@ -294,7 +294,7 @@ public sealed class BSPrim : PhysicsActor // TODO: what does it mean to set the position of a child prim?? Rebuild the constraint? _scene.TaintedObject("BSPrim.setPosition", delegate() { - // DetailLog("{0},BSPrim.SetPosition,taint,pos={1},orient={2}", LocalID, _position, _orientation); + DetailLog("{0},BSPrim.SetPosition,taint,pos={1},orient={2}", LocalID, _position, _orientation); BulletSimAPI.SetObjectTranslation(_scene.WorldID, _localID, _position, _orientation); }); } @@ -331,7 +331,7 @@ public sealed class BSPrim : PhysicsActor _force = value; _scene.TaintedObject("BSPrim.setForce", delegate() { - // DetailLog("{0},BSPrim.setForce,taint,force={1}", LocalID, _force); + DetailLog("{0},BSPrim.setForce,taint,force={1}", LocalID, _force); // BulletSimAPI.SetObjectForce(_scene.WorldID, _localID, _force); BulletSimAPI.SetObjectForce2(Body.Ptr, _force); }); @@ -409,7 +409,7 @@ public sealed class BSPrim : PhysicsActor _velocity = value; _scene.TaintedObject("BSPrim.setVelocity", delegate() { - // DetailLog("{0},BSPrim.SetVelocity,taint,vel={1}", LocalID, _velocity); + DetailLog("{0},BSPrim.SetVelocity,taint,vel={1}", LocalID, _velocity); BulletSimAPI.SetObjectVelocity(_scene.WorldID, LocalID, _velocity); }); } @@ -417,7 +417,7 @@ public sealed class BSPrim : PhysicsActor public override OMV.Vector3 Torque { get { return _torque; } set { _torque = value; - // DetailLog("{0},BSPrim.SetTorque,call,torque={1}", LocalID, _torque); + DetailLog("{0},BSPrim.SetTorque,call,torque={1}", LocalID, _torque); } } public override float CollisionScore { @@ -444,7 +444,7 @@ public sealed class BSPrim : PhysicsActor _scene.TaintedObject("BSPrim.setOrientation", delegate() { // _position = BulletSimAPI.GetObjectPosition(_scene.WorldID, _localID); - // DetailLog("{0},BSPrim.setOrientation,taint,pos={1},orient={2}", LocalID, _position, _orientation); + DetailLog("{0},BSPrim.setOrientation,taint,pos={1},orient={2}", LocalID, _position, _orientation); BulletSimAPI.SetObjectTranslation(_scene.WorldID, _localID, _position, _orientation); }); } @@ -496,13 +496,15 @@ public sealed class BSPrim : PhysicsActor _linkset.Refresh(this); CollisionFlags cf = BulletSimAPI.GetCollisionFlags2(Body.Ptr); - // DetailLog("{0},BSPrim.SetObjectDynamic,taint,static={1},solid={2},mass={3}, cf={4}", LocalID, IsStatic, IsSolid, mass, cf); + DetailLog("{0},BSPrim.SetObjectDynamic,taint,static={1},solid={2},mass={3}, cf={4}", LocalID, IsStatic, IsSolid, mass, cf); } // prims don't fly public override bool Flying { get { return _flying; } - set { _flying = value; } + set { + _flying = value; + } } public override bool SetAlwaysRun { get { return _setAlwaysRun; } @@ -553,7 +555,7 @@ public sealed class BSPrim : PhysicsActor // m_log.DebugFormat("{0}: RotationalVelocity={1}", LogHeader, _rotationalVelocity); _scene.TaintedObject("BSPrim.setRotationalVelocity", delegate() { - // DetailLog("{0},BSPrim.SetRotationalVel,taint,rotvel={1}", LocalID, _rotationalVelocity); + DetailLog("{0},BSPrim.SetRotationalVel,taint,rotvel={1}", LocalID, _rotationalVelocity); BulletSimAPI.SetObjectAngularVelocity(_scene.WorldID, LocalID, _rotationalVelocity); }); } @@ -570,7 +572,7 @@ public sealed class BSPrim : PhysicsActor _buoyancy = value; _scene.TaintedObject("BSPrim.setBuoyancy", delegate() { - // DetailLog("{0},BSPrim.SetBuoyancy,taint,buoy={1}", LocalID, _buoyancy); + DetailLog("{0},BSPrim.SetBuoyancy,taint,buoy={1}", LocalID, _buoyancy); BulletSimAPI.SetObjectBuoyancy(_scene.WorldID, _localID, _buoyancy); }); } @@ -633,17 +635,17 @@ public sealed class BSPrim : PhysicsActor } m_accumulatedForces.Clear(); } - // DetailLog("{0},BSPrim.AddObjectForce,taint,force={1}", LocalID, _force); + DetailLog("{0},BSPrim.AddObjectForce,taint,force={1}", LocalID, _force); BulletSimAPI.AddObjectForce2(Body.Ptr, fSum); }); } public override void AddAngularForce(OMV.Vector3 force, bool pushforce) { - // DetailLog("{0},BSPrim.AddAngularForce,call,angForce={1},push={2}", LocalID, force, pushforce); + DetailLog("{0},BSPrim.AddAngularForce,call,angForce={1},push={2}", LocalID, force, pushforce); // m_log.DebugFormat("{0}: AddAngularForce. f={1}, push={2}", LogHeader, force, pushforce); } public override void SetMomentum(OMV.Vector3 momentum) { - // DetailLog("{0},BSPrim.SetMomentum,call,mom={1}", LocalID, momentum); + DetailLog("{0},BSPrim.SetMomentum,call,mom={1}", LocalID, momentum); } public override void SubscribeEvents(int ms) { _subscribedEventsMs = ms; @@ -987,7 +989,7 @@ public sealed class BSPrim : PhysicsActor // m_log.DebugFormat("{0}: CreateGeom: Defaulting to sphere of size {1}", LogHeader, _size); if (forceRebuild || (_shapeType != ShapeData.PhysicsShapeType.SHAPE_SPHERE)) { - // DetailLog("{0},BSPrim.CreateGeom,sphere (force={1}", LocalID, forceRebuild); + DetailLog("{0},BSPrim.CreateGeom,sphere (force={1}", LocalID, forceRebuild); _shapeType = ShapeData.PhysicsShapeType.SHAPE_SPHERE; // Bullet native objects are scaled by the Bullet engine so pass the size in _scale = _size; @@ -1001,7 +1003,7 @@ public sealed class BSPrim : PhysicsActor // m_log.DebugFormat("{0}: CreateGeom: Defaulting to box. lid={1}, type={2}, size={3}", LogHeader, LocalID, _shapeType, _size); if (forceRebuild || (_shapeType != ShapeData.PhysicsShapeType.SHAPE_BOX)) { - // DetailLog("{0},BSPrim.CreateGeom,box (force={1})", LocalID, forceRebuild); + DetailLog("{0},BSPrim.CreateGeom,box (force={1})", LocalID, forceRebuild); _shapeType = ShapeData.PhysicsShapeType.SHAPE_BOX; _scale = _size; // TODO: do we need to check for and destroy a mesh or hull that might have been left from before? @@ -1051,12 +1053,12 @@ public sealed class BSPrim : PhysicsActor // if this new shape is the same as last time, don't recreate the mesh if (_meshKey == newMeshKey) return; - // DetailLog("{0},BSPrim.CreateGeomMesh,create,key={1}", LocalID, newMeshKey); + DetailLog("{0},BSPrim.CreateGeomMesh,create,key={1}", LocalID, newMeshKey); // Since we're recreating new, get rid of any previously generated shape if (_meshKey != 0) { // m_log.DebugFormat("{0}: CreateGeom: deleting old mesh. lID={1}, Key={2}", LogHeader, _localID, _meshKey); - // DetailLog("{0},BSPrim.CreateGeomMesh,deleteOld,key={1}", LocalID, _meshKey); + DetailLog("{0},BSPrim.CreateGeomMesh,deleteOld,key={1}", LocalID, _meshKey); BulletSimAPI.DestroyMesh(_scene.WorldID, _meshKey); _mesh = null; _meshKey = 0; @@ -1086,7 +1088,7 @@ public sealed class BSPrim : PhysicsActor _shapeType = ShapeData.PhysicsShapeType.SHAPE_MESH; // meshes are already scaled by the meshmerizer _scale = new OMV.Vector3(1f, 1f, 1f); - // DetailLog("{0},BSPrim.CreateGeomMesh,done", LocalID); + DetailLog("{0},BSPrim.CreateGeomMesh,done", LocalID); return; } @@ -1100,13 +1102,13 @@ public sealed class BSPrim : PhysicsActor // if the hull hasn't changed, don't rebuild it if (newHullKey == _hullKey) return; - // DetailLog("{0},BSPrim.CreateGeomHull,create,oldKey={1},newKey={2}", LocalID, _hullKey, newHullKey); + DetailLog("{0},BSPrim.CreateGeomHull,create,oldKey={1},newKey={2}", LocalID, _hullKey, newHullKey); // Since we're recreating new, get rid of any previously generated shape if (_hullKey != 0) { // m_log.DebugFormat("{0}: CreateGeom: deleting old hull. Key={1}", LogHeader, _hullKey); - // DetailLog("{0},BSPrim.CreateGeomHull,deleteOldHull,key={1}", LocalID, _hullKey); + DetailLog("{0},BSPrim.CreateGeomHull,deleteOldHull,key={1}", LocalID, _hullKey); BulletSimAPI.DestroyHull(_scene.WorldID, _hullKey); _hullKey = 0; } @@ -1200,7 +1202,7 @@ public sealed class BSPrim : PhysicsActor _shapeType = ShapeData.PhysicsShapeType.SHAPE_HULL; // meshes are already scaled by the meshmerizer _scale = new OMV.Vector3(1f, 1f, 1f); - // DetailLog("{0},BSPrim.CreateGeomHull,done", LocalID); + DetailLog("{0},BSPrim.CreateGeomHull,done", LocalID); return; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index d901ff0..56924aa 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -73,6 +73,9 @@ public class BSScene : PhysicsScene, IPhysicsParameters private static readonly ILog m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly string LogHeader = "[BULLETS SCENE]"; + // The name of the region we're working for. + public string RegionName { get; private set; } + public string BulletSimVersion = "?"; private Dictionary m_avatars = new Dictionary(); @@ -196,6 +199,8 @@ public class BSScene : PhysicsScene, IPhysicsParameters public BSScene(string identifier) { m_initialized = false; + // we are passed the name of the region we're working for. + RegionName = identifier; } public override void Initialise(IMesher meshmerizer, IConfigSource config) @@ -281,10 +286,13 @@ public class BSScene : PhysicsScene, IPhysicsParameters // Very detailed logging for physics debugging m_physicsLoggingEnabled = pConfig.GetBoolean("PhysicsLoggingEnabled", false); m_physicsLoggingDir = pConfig.GetString("PhysicsLoggingDir", "."); - m_physicsLoggingPrefix = pConfig.GetString("PhysicsLoggingPrefix", "physics-"); + m_physicsLoggingPrefix = pConfig.GetString("PhysicsLoggingPrefix", "physics-%REGIONNAME%-"); m_physicsLoggingFileMinutes = pConfig.GetInt("PhysicsLoggingFileMinutes", 5); // Very detailed logging for vehicle debugging m_vehicleLoggingEnabled = pConfig.GetBoolean("VehicleLoggingEnabled", false); + + // Do any replacements in the parameters + m_physicsLoggingPrefix = m_physicsLoggingPrefix.Replace("%REGIONNAME%", RegionName); } } } @@ -362,7 +370,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters BSPrim bsprim = prim as BSPrim; if (bsprim != null) { - // DetailLog("{0},RemovePrim,call", bsprim.LocalID); + DetailLog("{0},RemovePrim,call", bsprim.LocalID); // m_log.DebugFormat("{0}: RemovePrim. id={1}/{2}", LogHeader, bsprim.Name, bsprim.LocalID); try { @@ -388,7 +396,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters if (!m_initialized) return null; - // DetailLog("{0},AddPrimShape,call", localID); + DetailLog("{0},AddPrimShape,call", localID); BSPrim prim = new BSPrim(localID, primName, this, position, size, rotation, pbs, isPhysical); lock (m_prims) m_prims.Add(localID, prim); @@ -534,7 +542,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters else if (m_avatars.ContainsKey(collidingWith)) type = ActorTypes.Agent; - DetailLog("{0},BSScene.SendCollision,collide,id={1},with={2}", DetailLogZero, localID, collidingWith); + // DetailLog("{0},BSScene.SendCollision,collide,id={1},with={2}", DetailLogZero, localID, collidingWith); BSPrim prim; if (m_prims.TryGetValue(localID, out prim)) { -- cgit v1.1 From 7243d4f84248092eb5fe4ebe3673501bc84ce250 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Fri, 17 Aug 2012 14:45:18 -0700 Subject: BulletSim: Properly regenerate hulls when objects made physical. This fixes the problem of non-base shapes (cubes and spheres) falling through the terrain. --- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 34 +++++++++++++++++++------- 1 file changed, 25 insertions(+), 9 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index a6bc8e2..d3f1e9c 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -481,11 +481,8 @@ public sealed class BSPrim : PhysicsActor // No locking here because only called when it is safe private void SetObjectDynamic() { - // RA: remove this for the moment. - // The problem is that dynamic objects are hulls so if we are becoming physical - // the shape has to be checked and possibly built. - // Maybe a VerifyCorrectPhysicalShape() routine? - // RecreateGeomAndObject(); + // If it's becoming dynamic, it will need hullness + VerifyCorrectPhysicalShape(); // Bullet wants static objects to have a mass of zero float mass = IsStatic ? 0f : _mass; @@ -1214,6 +1211,27 @@ public sealed class BSPrim : PhysicsActor return; } + private void VerifyCorrectPhysicalShape() + { + if (IsStatic) + { + // if static, we don't need a hull so, if there is one, rebuild without it + if (_hullKey != 0) + { + RecreateGeomAndObject(); + } + } + else + { + // if not static, it will need a hull to efficiently collide with things + if (_hullKey == 0) + { + RecreateGeomAndObject(); + } + + } + } + // Create an object in Bullet if it has not already been created // No locking here because this is done when the physics engine is not simulating // Returns 'true' if an object was actually created. @@ -1338,10 +1356,8 @@ public sealed class BSPrim : PhysicsActor _acceleration = entprop.Acceleration; _rotationalVelocity = entprop.RotationalVelocity; - // m_log.DebugFormat("{0}: RequestTerseUpdate. id={1}, ch={2}, pos={3}, rot={4}, vel={5}, acc={6}, rvel={7}", - // LogHeader, LocalID, changed, _position, _orientation, _velocity, _acceleration, _rotationalVelocity); - // DetailLog("{0},BSPrim.UpdateProperties,call,pos={1},orient={2},vel={3},accel={4},rotVel={5}", - // LocalID, _position, _orientation, _velocity, _acceleration, _rotationalVelocity); + DetailLog("{0},BSPrim.UpdateProperties,call,pos={1},orient={2},vel={3},accel={4},rotVel={5}", + LocalID, _position, _orientation, _velocity, _acceleration, _rotationalVelocity); base.RequestPhysicsterseUpdate(); } -- cgit v1.1 From 0376b8ddbc4101627aa045a1deb18202fb51fffe Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Fri, 24 Aug 2012 10:10:55 -0700 Subject: BulletSim: add new interface for mesh, hull and terrain creation that will move nearly all of the logic into the C# code. --- .../Region/Physics/BulletSPlugin/BulletSimAPI.cs | 27 ++++++++++++++++------ 1 file changed, 20 insertions(+), 7 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs index 504bd3c..dab2420 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs @@ -392,23 +392,36 @@ public static extern int PhysicsStep2(IntPtr world, float timeStep, int maxSubSt [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern bool PushUpdate2(IntPtr obj); -/* +// ===================================================================================== +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern IntPtr CreateMeshShape2(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); + [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern IntPtr CreateMesh2(IntPtr world, int indicesCount, int* indices, int verticesCount, float* vertices ); +public static extern IntPtr BuildHullShape2(IntPtr world, IntPtr meshShape); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool BuildHull2(IntPtr world, IntPtr mesh); +public static extern IntPtr BuildNativeShape2(IntPtr world, + float shapeType, float collisionMargin, Vector3 scale); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool ReleaseHull2(IntPtr world, IntPtr mesh); +public static extern bool DeleteCollisionShape2(IntPtr world, IntPtr shape); +// ===================================================================================== [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool DestroyMesh2(IntPtr world, IntPtr mesh); +public static extern IntPtr CreateGroundPlaneBody2(uint id, Vector3 center, float collisionMargin); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern IntPtr CreateObject2(IntPtr world, ShapeData shapeData); -*/ +public static extern IntPtr CreateTerrainBody2(uint id, + Vector3 minCoords, Vector3 maxCoords, float collisionMargin, + [MarshalAs(UnmanagedType.LPArray)] float[] heightMap); +// ===================================================================================== [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern IntPtr Create6DofConstraint2(IntPtr world, IntPtr obj1, IntPtr obj2, Vector3 frame1loc, Quaternion frame1rot, -- cgit v1.1 From 7b6987ce83d16871f6070f3cc7d56280ad3d5dbe Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Fri, 24 Aug 2012 12:58:42 -0700 Subject: BulletSim: unify physical objects under BSPhysObjects. Now BSScene and BSLinkset only know of BSPhysObject's and there is only one list to search in BSScene. --- .../Region/Physics/BulletSPlugin/BSCharacter.cs | 31 +++-- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 50 ++++---- .../Region/Physics/BulletSPlugin/BSPhysObject.cs | 58 +++++++++ OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 84 ++++++------- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 137 +++++++++------------ 5 files changed, 200 insertions(+), 160 deletions(-) create mode 100755 OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index 1b23a36..784076d 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -34,7 +34,7 @@ using OpenSim.Region.Physics.Manager; namespace OpenSim.Region.Physics.BulletSPlugin { -public class BSCharacter : PhysicsActor +public class BSCharacter : BSPhysObject { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static readonly string LogHeader = "[BULLETS CHAR]"; @@ -74,11 +74,8 @@ public class BSCharacter : PhysicsActor private bool _kinematic; private float _buoyancy; - private BulletBody m_body; - public BulletBody Body { - get { return m_body; } - set { m_body = value; } - } + public override BulletBody Body { get; set; } + public override BSLinkset Linkset { get; set; } private int _subscribedEventsMs = 0; private int _nextCollisionOkTime = 0; @@ -108,6 +105,8 @@ public class BSCharacter : PhysicsActor _density = _scene.Params.avatarDensity; ComputeAvatarVolumeAndMass(); // set _avatarVolume and _mass based on capsule size, _density and _scale + Linkset = new BSLinkset(_scene, this); + ShapeData shapeData = new ShapeData(); shapeData.ID = _localID; shapeData.Type = ShapeData.PhysicsShapeType.SHAPE_AVATAR; @@ -130,7 +129,7 @@ public class BSCharacter : PhysicsActor // Set the buoyancy for flying. This will be refactored when all the settings happen in C# BulletSimAPI.SetObjectBuoyancy(_scene.WorldID, LocalID, _buoyancy); - m_body = new BulletBody(LocalID, BulletSimAPI.GetBodyHandle2(_scene.World.Ptr, LocalID)); + Body = new BulletBody(LocalID, BulletSimAPI.GetBodyHandle2(_scene.World.Ptr, LocalID)); // avatars get all collisions no matter what (makes walking on ground and such work) BulletSimAPI.AddToCollisionFlags2(Body.Ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); }); @@ -139,7 +138,7 @@ public class BSCharacter : PhysicsActor } // called when this character is being destroyed and the resources should be released - public void Destroy() + public override void Destroy() { DetailLog("{0},BSCharacter.Destroy", LocalID); _scene.TaintedObject("BSCharacter.destroy", delegate() @@ -245,6 +244,10 @@ public class BSCharacter : PhysicsActor return _mass; } } + + // used when we only want this prim's mass and not the linkset thing + public override float MassRaw { get {return _mass; } } + public override Vector3 Force { get { return _force; } set { @@ -448,6 +451,12 @@ public class BSCharacter : PhysicsActor }); } } + + public override void ZeroMotion() + { + return; + } + // Stop collision events public override void UnSubscribeEvents() { _subscribedEventsMs = 0; @@ -481,7 +490,7 @@ public class BSCharacter : PhysicsActor // The physics engine says that properties have updated. Update same and inform // the world that things have changed. - public void UpdateProperties(EntityProperties entprop) + public override void UpdateProperties(EntityProperties entprop) { _position = entprop.Position; _orientation = entprop.Rotation; @@ -500,7 +509,7 @@ public class BSCharacter : PhysicsActor // The collision, if it should be reported to the character, is placed in a collection // that will later be sent to the simulator when SendCollisions() is called. CollisionEventUpdate collisionCollection = null; - public void Collide(uint collidingWith, ActorTypes type, Vector3 contactPoint, Vector3 contactNormal, float pentrationDepth) + public override void Collide(uint collidingWith, BSPhysObject collidee, ActorTypes type, Vector3 contactPoint, Vector3 contactNormal, float pentrationDepth) { // m_log.DebugFormat("{0}: Collide: ms={1}, id={2}, with={3}", LogHeader, _subscribedEventsMs, LocalID, collidingWith); @@ -525,7 +534,7 @@ public class BSCharacter : PhysicsActor } } - public void SendCollisions() + public override void SendCollisions() { /* if (collisionCollection != null && collisionCollection.Count > 0) diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index 9e3f0db..b04e1b6 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -36,8 +36,8 @@ public class BSLinkset { private static string LogHeader = "[BULLETSIM LINKSET]"; - private BSPrim m_linksetRoot; - public BSPrim LinksetRoot { get { return m_linksetRoot; } } + private BSPhysObject m_linksetRoot; + public BSPhysObject LinksetRoot { get { return m_linksetRoot; } } private BSScene m_physicsScene; public BSScene PhysicsScene { get { return m_physicsScene; } } @@ -46,7 +46,7 @@ public class BSLinkset public int LinksetID { get; private set; } // The children under the root in this linkset - private List m_children; + private List m_children; // We lock the diddling of linkset classes to prevent any badness. // This locks the modification of the instances of this class. Changes @@ -74,7 +74,7 @@ public class BSLinkset get { return ComputeLinksetGeometricCenter(); } } - public BSLinkset(BSScene scene, BSPrim parent) + public BSLinkset(BSScene scene, BSPhysObject parent) { // A simple linkset of one (no children) LinksetID = m_nextLinksetID++; @@ -83,14 +83,14 @@ public class BSLinkset m_nextLinksetID = 1; m_physicsScene = scene; m_linksetRoot = parent; - m_children = new List(); + m_children = new List(); m_mass = parent.MassRaw; } // Link to a linkset where the child knows the parent. // Parent changing should not happen so do some sanity checking. // We return the parent's linkset so the child can track its membership. - public BSLinkset AddMeToLinkset(BSPrim child) + public BSLinkset AddMeToLinkset(BSPhysObject child) { lock (m_linksetActivityLock) { @@ -102,7 +102,7 @@ public class BSLinkset // Remove a child from a linkset. // Returns a new linkset for the child which is a linkset of one (just the // orphened child). - public BSLinkset RemoveMeFromLinkset(BSPrim child) + public BSLinkset RemoveMeFromLinkset(BSPhysObject child) { lock (m_linksetActivityLock) { @@ -129,7 +129,7 @@ public class BSLinkset } // Return 'true' if the passed object is the root object of this linkset - public bool IsRoot(BSPrim requestor) + public bool IsRoot(BSPhysObject requestor) { return (requestor.LocalID == m_linksetRoot.LocalID); } @@ -140,12 +140,12 @@ public class BSLinkset public bool HasAnyChildren { get { return (m_children.Count > 0); } } // Return 'true' if this child is in this linkset - public bool HasChild(BSPrim child) + public bool HasChild(BSPhysObject child) { bool ret = false; lock (m_linksetActivityLock) { - foreach (BSPrim bp in m_children) + foreach (BSPhysObject bp in m_children) { if (child.LocalID == bp.LocalID) { @@ -160,7 +160,7 @@ public class BSLinkset private float ComputeLinksetMass() { float mass = m_linksetRoot.MassRaw; - foreach (BSPrim bp in m_children) + foreach (BSPhysObject bp in m_children) { mass += bp.MassRaw; } @@ -174,7 +174,7 @@ public class BSLinkset lock (m_linksetActivityLock) { - foreach (BSPrim bp in m_children) + foreach (BSPhysObject bp in m_children) { com += bp.Position * bp.MassRaw; totalMass += bp.MassRaw; @@ -192,7 +192,7 @@ public class BSLinkset lock (m_linksetActivityLock) { - foreach (BSPrim bp in m_children) + foreach (BSPhysObject bp in m_children) { com += bp.Position * bp.MassRaw; } @@ -204,7 +204,7 @@ public class BSLinkset // When physical properties are changed the linkset needs to recalculate // its internal properties. - public void Refresh(BSPrim requestor) + public void Refresh(BSPhysObject requestor) { // If there are no children, there aren't any constraints to recompute if (!HasAnyChildren) @@ -230,7 +230,7 @@ public class BSLinkset float linksetMass = LinksetMass; lock (m_linksetActivityLock) { - foreach (BSPrim child in m_children) + foreach (BSPhysObject child in m_children) { BSConstraint constrain; if (m_physicsScene.Constraints.TryGetConstraint(LinksetRoot.Body, child.Body, out constrain)) @@ -255,14 +255,14 @@ public class BSLinkset // I am the root of a linkset and a new child is being added // Called while LinkActivity is locked. - private void AddChildToLinkset(BSPrim child) + private void AddChildToLinkset(BSPhysObject child) { if (!HasChild(child)) { m_children.Add(child); - BSPrim rootx = LinksetRoot; // capture the root as of now - BSPrim childx = child; + BSPhysObject rootx = LinksetRoot; // capture the root as of now + BSPhysObject childx = child; m_physicsScene.TaintedObject("AddChildToLinkset", delegate() { DetailLog("{0},AddChildToLinkset,taint,child={1}", m_linksetRoot.LocalID, child.LocalID); @@ -277,7 +277,7 @@ public class BSLinkset // it's still connected to the linkset. // Normal OpenSimulator operation will never do this because other SceneObjectPart information // has to be updated also (like pointer to prim's parent). - private void RemoveChildFromOtherLinkset(BSPrim pchild) + private void RemoveChildFromOtherLinkset(BSPhysObject pchild) { pchild.Linkset = new BSLinkset(m_physicsScene, pchild); RemoveChildFromLinkset(pchild); @@ -285,12 +285,12 @@ public 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. - private void RemoveChildFromLinkset(BSPrim child) + private void RemoveChildFromLinkset(BSPhysObject child) { if (m_children.Remove(child)) { - BSPrim rootx = LinksetRoot; // capture the root as of now - BSPrim childx = child; + BSPhysObject rootx = LinksetRoot; // capture the root as of now + BSPhysObject childx = child; m_physicsScene.TaintedObject("RemoveChildFromLinkset", delegate() { DetailLog("{0},RemoveChildFromLinkset,taint,child={1}", m_linksetRoot.LocalID, child.LocalID); @@ -310,7 +310,7 @@ public class BSLinkset // Create a constraint between me (root of linkset) and the passed prim (the child). // Called at taint time! - private void PhysicallyLinkAChildToRoot(BSPrim rootPrim, BSPrim childPrim) + private void PhysicallyLinkAChildToRoot(BSPhysObject rootPrim, BSPhysObject childPrim) { // Zero motion for children so they don't interpolate childPrim.ZeroMotion(); @@ -383,7 +383,7 @@ public class BSLinkset // Remove linkage between myself and a particular child // Called at taint time! - private void PhysicallyUnlinkAChildFromRoot(BSPrim rootPrim, BSPrim childPrim) + private void PhysicallyUnlinkAChildFromRoot(BSPhysObject rootPrim, BSPhysObject childPrim) { DetailLog("{0},PhysicallyUnlinkAChildFromRoot,taint,root={1},child={2}", rootPrim.LocalID, rootPrim.LocalID, childPrim.LocalID); @@ -396,7 +396,7 @@ public class BSLinkset // Remove linkage between myself and any possible children I might have // Called at taint time! - private void PhysicallyUnlinkAllChildrenFromRoot(BSPrim rootPrim) + private void PhysicallyUnlinkAllChildrenFromRoot(BSPhysObject rootPrim) { DetailLog("{0},PhysicallyUnlinkAllChildren,taint", rootPrim.LocalID); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs new file mode 100755 index 0000000..6e205a9 --- /dev/null +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -0,0 +1,58 @@ +/* + * 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 OMV = OpenMetaverse; +using OpenSim.Framework; +using OpenSim.Region.Physics.Manager; + +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. +public abstract class BSPhysObject : PhysicsActor +{ + public abstract BSLinkset Linkset { get; set; } + + public abstract void Collide(uint collidingWith, BSPhysObject collidee, ActorTypes type, + OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth); + public abstract void SendCollisions(); + + // Return the object mass without calculating it or side effects + public abstract float MassRaw { get; } + + public abstract BulletBody Body { get; set; } + public abstract void ZeroMotion(); + + public abstract void UpdateProperties(EntityProperties entprop); + + public abstract void Destroy(); +} +} diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index d3f1e9c..036fd4f 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -37,7 +37,7 @@ using OpenSim.Region.Physics.ConvexDecompositionDotNet; namespace OpenSim.Region.Physics.BulletSPlugin { [Serializable] -public sealed class BSPrim : PhysicsActor +public sealed class BSPrim : BSPhysObject { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static readonly string LogHeader = "[BULLETS PRIM]"; @@ -88,23 +88,14 @@ public sealed class BSPrim : PhysicsActor private float _buoyancy; // Membership in a linkset is controlled by this class. - private BSLinkset _linkset; - public BSLinkset Linkset - { - get { return _linkset; } - set { _linkset = value; } - } + public override BSLinkset Linkset { get; set; } private int _subscribedEventsMs = 0; private int _nextCollisionOkTime = 0; long _collidingStep; long _collidingGroundStep; - private BulletBody m_body; - public BulletBody Body { - get { return m_body; } - set { m_body = value; } - } + public override BulletBody Body { get; set; } private BSDynamics _vehicle; @@ -139,7 +130,7 @@ public sealed class BSPrim : PhysicsActor _friction = _scene.Params.defaultFriction; // TODO: compute based on object material _density = _scene.Params.defaultDensity; // TODO: compute based on object material _restitution = _scene.Params.defaultRestitution; - _linkset = new BSLinkset(Scene, this); // a linkset of one + Linkset = new BSLinkset(Scene, this); // a linkset of one _vehicle = new BSDynamics(Scene, this); // add vehicleness _mass = CalculateMass(); // do the actual object creation at taint time @@ -151,23 +142,23 @@ public sealed class BSPrim : PhysicsActor // Get the pointer to the physical body for this object. // At the moment, we're still letting BulletSim manage the creation and destruction // of the object. Someday we'll move that into the C# code. - m_body = new BulletBody(LocalID, BulletSimAPI.GetBodyHandle2(_scene.World.Ptr, LocalID)); + Body = new BulletBody(LocalID, BulletSimAPI.GetBodyHandle2(_scene.World.Ptr, LocalID)); }); } // called when this prim is being destroyed and we should free all the resources - public void Destroy() + public override void Destroy() { // m_log.DebugFormat("{0}: Destroy, id={1}", LogHeader, LocalID); // Undo any links between me and any other object - BSPrim parentBefore = _linkset.LinksetRoot; - int childrenBefore = _linkset.NumberOfChildren; + BSPhysObject parentBefore = Linkset.LinksetRoot; + int childrenBefore = Linkset.NumberOfChildren; - _linkset = _linkset.RemoveMeFromLinkset(this); + Linkset = Linkset.RemoveMeFromLinkset(this); DetailLog("{0},BSPrim.Destroy,call,parentBefore={1},childrenBefore={2},parentAfter={3},childrenAfter={4}", - LocalID, parentBefore.LocalID, childrenBefore, _linkset.LinksetRoot.LocalID, _linkset.NumberOfChildren); + LocalID, parentBefore.LocalID, childrenBefore, Linkset.LinksetRoot.LocalID, Linkset.NumberOfChildren); // Undo any vehicle properties this.VehicleType = (int)Vehicle.TYPE_NONE; @@ -230,13 +221,13 @@ public sealed class BSPrim : PhysicsActor BSPrim parent = obj as BSPrim; if (parent != null) { - BSPrim parentBefore = _linkset.LinksetRoot; - int childrenBefore = _linkset.NumberOfChildren; + BSPhysObject parentBefore = Linkset.LinksetRoot; + int childrenBefore = Linkset.NumberOfChildren; - _linkset = parent.Linkset.AddMeToLinkset(this); + Linkset = parent.Linkset.AddMeToLinkset(this); DetailLog("{0},BSPrim.link,call,parentBefore={1}, childrenBefore=={2}, parentAfter={3}, childrenAfter={4}", - LocalID, parentBefore.LocalID, childrenBefore, _linkset.LinksetRoot.LocalID, _linkset.NumberOfChildren); + LocalID, parentBefore.LocalID, childrenBefore, Linkset.LinksetRoot.LocalID, Linkset.NumberOfChildren); } return; } @@ -246,13 +237,13 @@ public sealed class BSPrim : PhysicsActor // 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 - BSPrim parentBefore = _linkset.LinksetRoot; - int childrenBefore = _linkset.NumberOfChildren; + BSPhysObject parentBefore = Linkset.LinksetRoot; + int childrenBefore = Linkset.NumberOfChildren; - _linkset = _linkset.RemoveMeFromLinkset(this); + Linkset = Linkset.RemoveMeFromLinkset(this); DetailLog("{0},BSPrim.delink,parentBefore={1},childrenBefore={2},parentAfter={3},childrenAfter={4}, ", - LocalID, parentBefore.LocalID, childrenBefore, _linkset.LinksetRoot.LocalID, _linkset.NumberOfChildren); + LocalID, parentBefore.LocalID, childrenBefore, Linkset.LinksetRoot.LocalID, Linkset.NumberOfChildren); return; } @@ -260,7 +251,7 @@ public sealed class BSPrim : PhysicsActor // Do it to the properties so the values get set in the physics engine. // Push the setting of the values to the viewer. // Called at taint time! - public void ZeroMotion() + public override void ZeroMotion() { _velocity = OMV.Vector3.Zero; _acceleration = OMV.Vector3.Zero; @@ -281,7 +272,7 @@ public sealed class BSPrim : PhysicsActor public override OMV.Vector3 Position { get { - if (!_linkset.IsRoot(this)) + if (!Linkset.IsRoot(this)) // child prims move around based on their parent. Need to get the latest location _position = BulletSimAPI.GetObjectPosition(_scene.WorldID, _localID); @@ -306,23 +297,23 @@ public sealed class BSPrim : PhysicsActor { get { - return _linkset.LinksetMass; + return Linkset.LinksetMass; } } // used when we only want this prim's mass and not the linkset thing - public float MassRaw { get { return _mass; } } + public override float MassRaw { get { return _mass; } } // Is this used? public override OMV.Vector3 CenterOfMass { - get { return _linkset.CenterOfMass; } + get { return Linkset.CenterOfMass; } } // Is this used? public override OMV.Vector3 GeometricCenter { - get { return _linkset.GeometricCenter; } + get { return Linkset.GeometricCenter; } } public override OMV.Vector3 Force { @@ -431,7 +422,7 @@ public sealed class BSPrim : PhysicsActor } public override OMV.Quaternion Orientation { get { - if (!_linkset.IsRoot(this)) + if (!Linkset.IsRoot(this)) { // Children move around because tied to parent. Get a fresh value. _orientation = BulletSimAPI.GetObjectOrientation(_scene.WorldID, LocalID); @@ -490,7 +481,7 @@ public sealed class BSPrim : PhysicsActor BulletSimAPI.SetObjectProperties(_scene.WorldID, LocalID, IsStatic, IsSolid, SubscribedEvents(), mass); // recompute any linkset parameters - _linkset.Refresh(this); + Linkset.Refresh(this); CollisionFlags cf = BulletSimAPI.GetCollisionFlags2(Body.Ptr); DetailLog("{0},BSPrim.SetObjectDynamic,taint,static={1},solid={2},mass={3}, cf={4}", LocalID, IsStatic, IsSolid, mass, cf); @@ -1299,7 +1290,7 @@ public sealed class BSPrim : PhysicsActor const float ACCELERATION_TOLERANCE = 0.01f; const float ROTATIONAL_VELOCITY_TOLERANCE = 0.01f; - public void UpdateProperties(EntityProperties entprop) + public override void UpdateProperties(EntityProperties entprop) { /* UpdatedProperties changed = 0; @@ -1347,7 +1338,7 @@ public sealed class BSPrim : PhysicsActor // Don't check for damping here -- it's done in BulletSim and SceneObjectPart. // Updates only for individual prims and for the root object of a linkset. - if (_linkset.IsRoot(this)) + if (Linkset.IsRoot(this)) { // Assign to the local variables so the normal set action does not happen _position = entprop.Position; @@ -1375,7 +1366,7 @@ public sealed class BSPrim : PhysicsActor // I've collided with something // Called at taint time from within the Step() function CollisionEventUpdate collisionCollection; - public void Collide(uint collidingWith, ActorTypes type, OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth) + public override void Collide(uint collidingWith, BSPhysObject collidee, ActorTypes type, OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth) { // m_log.DebugFormat("{0}: Collide: ms={1}, id={2}, with={3}", LogHeader, _subscribedEventsMs, LocalID, collidingWith); @@ -1387,18 +1378,15 @@ public sealed class BSPrim : PhysicsActor } // DetailLog("{0},BSPrim.Collison,call,with={1}", LocalID, collidingWith); - BSPrim collidingWithPrim; - if (_scene.Prims.TryGetValue(collidingWith, out collidingWithPrim)) + + // prims in the same linkset cannot collide with each other + if (collidee != null && (this.Linkset.LinksetID == collidee.Linkset.LinksetID)) { - // prims in the same linkset cannot collide with each other - if (this.Linkset.LinksetID == collidingWithPrim.Linkset.LinksetID) - { - return; - } + return; } - // if someone is subscribed to collision events.... - if (_subscribedEventsMs != 0) { + // if someone has subscribed for collision events.... + if (SubscribedEvents()) { // throttle the collisions to the number of milliseconds specified in the subscription int nowTime = _scene.SimulationNowTime; if (nowTime >= _nextCollisionOkTime) { @@ -1412,7 +1400,7 @@ public sealed class BSPrim : PhysicsActor } // The scene is telling us it's time to pass our collected collisions into the simulator - public void SendCollisions() + public override void SendCollisions() { if (collisionCollection != null && collisionCollection.Count > 0) { diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index 56924aa..ce64b9b 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -78,14 +78,12 @@ public class BSScene : PhysicsScene, IPhysicsParameters public string BulletSimVersion = "?"; - private Dictionary m_avatars = new Dictionary(); - public Dictionary Characters { get { return m_avatars; } } - - private Dictionary m_prims = new Dictionary(); - public Dictionary Prims { get { return m_prims; } } + public Dictionary PhysObjects = new Dictionary(); + private HashSet m_objectsWithCollisions = new HashSet(); + // Following is a kludge and can be removed when avatar animation updating is + // moved to a better place. private HashSet m_avatarsWithCollisions = new HashSet(); - private HashSet m_primsWithCollisions = new HashSet(); private List m_vehicles = new List(); @@ -235,7 +233,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters // BulletSimVersion = BulletSimAPI.GetVersion(); // m_log.WarnFormat("{0}: BulletSim.dll version='{1}'", LogHeader, BulletSimVersion); - // if Debug, enable logging from the unmanaged code + // If Debug logging level, enable logging from the unmanaged code if (m_log.IsDebugEnabled || PhysicsLogging.Enabled) { m_log.DebugFormat("{0}: Initialize: Setting debug callback for unmanaged code", LogHeader); @@ -243,13 +241,14 @@ public class BSScene : PhysicsScene, IPhysicsParameters m_DebugLogCallbackHandle = new BulletSimAPI.DebugLogCallback(BulletLoggerPhysLog); else m_DebugLogCallbackHandle = new BulletSimAPI.DebugLogCallback(BulletLogger); - // the handle is saved in a variable to make sure it doesn't get freed after this call + // The handle is saved in a variable to make sure it doesn't get freed after this call BulletSimAPI.SetDebugLogCallback(m_DebugLogCallbackHandle); } _taintedObjects = new List(); mesher = meshmerizer; + // The bounding box for the simulated world Vector3 worldExtent = new Vector3(Constants.RegionSize, Constants.RegionSize, 8192f); @@ -337,7 +336,11 @@ public class BSScene : PhysicsScene, IPhysicsParameters if (!m_initialized) return null; BSCharacter actor = new BSCharacter(localID, avName, this, position, size, isFlying); - lock (m_avatars) m_avatars.Add(localID, actor); + lock (PhysObjects) PhysObjects.Add(localID, actor); + + // Remove kludge someday + lock (m_avatarsWithCollisions) m_avatarsWithCollisions.Add(actor); + return actor; } @@ -352,7 +355,9 @@ public class BSScene : PhysicsScene, IPhysicsParameters { try { - lock (m_avatars) m_avatars.Remove(actor.LocalID); + lock (PhysObjects) PhysObjects.Remove(actor.LocalID); + // Remove kludge someday + lock (m_avatarsWithCollisions) m_avatarsWithCollisions.Remove(bsactor); } catch (Exception e) { @@ -374,7 +379,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters // m_log.DebugFormat("{0}: RemovePrim. id={1}/{2}", LogHeader, bsprim.Name, bsprim.LocalID); try { - lock (m_prims) m_prims.Remove(bsprim.LocalID); + lock (PhysObjects) PhysObjects.Remove(bsprim.LocalID); } catch (Exception e) { @@ -399,7 +404,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters DetailLog("{0},AddPrimShape,call", localID); BSPrim prim = new BSPrim(localID, primName, this, position, size, rotation, pbs, isPhysical); - lock (m_prims) m_prims.Add(localID, prim); + lock (PhysObjects) PhysObjects.Add(localID, prim); return prim; } @@ -470,19 +475,16 @@ public class BSScene : PhysicsScene, IPhysicsParameters // The above SendCollision's batch up the collisions on the objects. // Now push the collisions into the simulator. - foreach (BSPrim bsp in m_primsWithCollisions) + foreach (BSPhysObject bsp in m_objectsWithCollisions) bsp.SendCollisions(); - m_primsWithCollisions.Clear(); + m_objectsWithCollisions.Clear(); // This is a kludge to get avatar movement updated. - // Don't send collisions only if there were collisions -- send everytime. // ODE sends collisions even if there are none and this is used to update // avatar animations and stuff. - // foreach (BSCharacter bsc in m_avatarsWithCollisions) - // bsc.SendCollisions(); - foreach (KeyValuePair kvp in m_avatars) - kvp.Value.SendCollisions(); - m_avatarsWithCollisions.Clear(); + foreach (BSPhysObject bpo in m_avatarsWithCollisions) + bpo.SendCollisions(); + // m_avatarsWithCollisions.Clear(); // If any of the objects had updated properties, tell the object it has been changed by the physics engine if (updatedEntityCount > 0) @@ -490,16 +492,10 @@ public class BSScene : PhysicsScene, IPhysicsParameters for (int ii = 0; ii < updatedEntityCount; ii++) { EntityProperties entprop = m_updateArray[ii]; - BSPrim prim; - if (m_prims.TryGetValue(entprop.ID, out prim)) - { - prim.UpdateProperties(entprop); - continue; - } - BSCharacter actor; - if (m_avatars.TryGetValue(entprop.ID, out actor)) + BSPhysObject pobj; + if (PhysObjects.TryGetValue(entprop.ID, out pobj)) { - actor.UpdateProperties(entprop); + pobj.UpdateProperties(entprop); continue; } } @@ -529,33 +525,36 @@ public class BSScene : PhysicsScene, IPhysicsParameters } // Something has collided - private void SendCollision(uint localID, uint collidingWith, Vector3 collidePoint, Vector3 collideNormal, float penitration) + private void SendCollision(uint localID, uint collidingWith, Vector3 collidePoint, Vector3 collideNormal, float penetration) { if (localID == TERRAIN_ID || localID == GROUNDPLANE_ID) { return; // don't send collisions to the terrain } + BSPhysObject collider = PhysObjects[localID]; + // TODO: as of this code, terrain was not in the physical object list. + // When BSTerrain is created and it will be in the list, we can remove + // the possibility that it's not there and just fetch the collidee. + BSPhysObject collidee = null; + ActorTypes type = ActorTypes.Prim; if (collidingWith == TERRAIN_ID || collidingWith == GROUNDPLANE_ID) + { type = ActorTypes.Ground; - else if (m_avatars.ContainsKey(collidingWith)) - type = ActorTypes.Agent; + } + else + { + collidee = PhysObjects[collidingWith]; + if (collidee is BSCharacter) + type = ActorTypes.Agent; + } // DetailLog("{0},BSScene.SendCollision,collide,id={1},with={2}", DetailLogZero, localID, collidingWith); - BSPrim prim; - if (m_prims.TryGetValue(localID, out prim)) { - prim.Collide(collidingWith, type, collidePoint, collideNormal, penitration); - m_primsWithCollisions.Add(prim); - return; - } - BSCharacter actor; - if (m_avatars.TryGetValue(localID, out actor)) { - actor.Collide(collidingWith, type, collidePoint, collideNormal, penitration); - m_avatarsWithCollisions.Add(actor); - return; - } + collider.Collide(collidingWith, collidee, type, collidePoint, collideNormal, penetration); + m_objectsWithCollisions.Add(collider); + return; } @@ -605,17 +604,11 @@ public class BSScene : PhysicsScene, IPhysicsParameters // make sure no stepping happens while we're deleting stuff m_initialized = false; - foreach (KeyValuePair kvp in m_avatars) - { - kvp.Value.Destroy(); - } - m_avatars.Clear(); - - foreach (KeyValuePair kvp in m_prims) + foreach (KeyValuePair kvp in PhysObjects) { kvp.Value.Destroy(); } - m_prims.Clear(); + PhysObjects.Clear(); // Now that the prims are all cleaned up, there should be no constraints left if (m_constraintCollection != null) @@ -996,42 +989,42 @@ public class BSScene : PhysicsScene, IPhysicsParameters 0f, (s,cf,p,v) => { s.m_params[0].linearDamping = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].linearDamping; }, - (s,p,l,v) => { s.UpdateParameterPrims(ref s.m_params[0].linearDamping, p, l, v); } ), + (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].linearDamping, p, l, v); } ), new ParameterDefn("AngularDamping", "Factor to damp angular movement per second (0.0 - 1.0)", 0f, (s,cf,p,v) => { s.m_params[0].angularDamping = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].angularDamping; }, - (s,p,l,v) => { s.UpdateParameterPrims(ref s.m_params[0].angularDamping, p, l, v); } ), + (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].angularDamping, p, l, v); } ), new ParameterDefn("DeactivationTime", "Seconds before considering an object potentially static", 0.2f, (s,cf,p,v) => { s.m_params[0].deactivationTime = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].deactivationTime; }, - (s,p,l,v) => { s.UpdateParameterPrims(ref s.m_params[0].deactivationTime, p, l, v); } ), + (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].deactivationTime, p, l, v); } ), new ParameterDefn("LinearSleepingThreshold", "Seconds to measure linear movement before considering static", 0.8f, (s,cf,p,v) => { s.m_params[0].linearSleepingThreshold = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].linearSleepingThreshold; }, - (s,p,l,v) => { s.UpdateParameterPrims(ref s.m_params[0].linearSleepingThreshold, p, l, v); } ), + (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].linearSleepingThreshold, p, l, v); } ), new ParameterDefn("AngularSleepingThreshold", "Seconds to measure angular movement before considering static", 1.0f, (s,cf,p,v) => { s.m_params[0].angularSleepingThreshold = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].angularSleepingThreshold; }, - (s,p,l,v) => { s.UpdateParameterPrims(ref s.m_params[0].angularSleepingThreshold, p, l, v); } ), + (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].angularSleepingThreshold, p, l, v); } ), new ParameterDefn("CcdMotionThreshold", "Continuious collision detection threshold (0 means no CCD)" , 0f, // set to zero to disable (s,cf,p,v) => { s.m_params[0].ccdMotionThreshold = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].ccdMotionThreshold; }, - (s,p,l,v) => { s.UpdateParameterPrims(ref s.m_params[0].ccdMotionThreshold, p, l, v); } ), + (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].ccdMotionThreshold, p, l, v); } ), new ParameterDefn("CcdSweptSphereRadius", "Continuious collision detection test radius" , 0f, (s,cf,p,v) => { s.m_params[0].ccdSweptSphereRadius = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].ccdSweptSphereRadius; }, - (s,p,l,v) => { s.UpdateParameterPrims(ref s.m_params[0].ccdSweptSphereRadius, p, l, v); } ), + (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].ccdSweptSphereRadius, p, l, v); } ), new ParameterDefn("ContactProcessingThreshold", "Distance between contacts before doing collision check" , 0.1f, (s,cf,p,v) => { s.m_params[0].contactProcessingThreshold = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].contactProcessingThreshold; }, - (s,p,l,v) => { s.UpdateParameterPrims(ref s.m_params[0].contactProcessingThreshold, p, l, v); } ), + (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].contactProcessingThreshold, p, l, v); } ), new ParameterDefn("TerrainFriction", "Factor to reduce movement against terrain surface" , 0.5f, @@ -1052,32 +1045,32 @@ public class BSScene : PhysicsScene, IPhysicsParameters 0.5f, (s,cf,p,v) => { s.m_params[0].avatarFriction = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].avatarFriction; }, - (s,p,l,v) => { s.UpdateParameterAvatars(ref s.m_params[0].avatarFriction, p, l, v); } ), + (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].avatarFriction, p, l, v); } ), new ParameterDefn("AvatarDensity", "Density of an avatar. Changed on avatar recreation.", 60f, (s,cf,p,v) => { s.m_params[0].avatarDensity = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].avatarDensity; }, - (s,p,l,v) => { s.UpdateParameterAvatars(ref s.m_params[0].avatarDensity, p, l, v); } ), + (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].avatarDensity, p, l, v); } ), new ParameterDefn("AvatarRestitution", "Bouncyness. Changed on avatar recreation.", 0f, (s,cf,p,v) => { s.m_params[0].avatarRestitution = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].avatarRestitution; }, - (s,p,l,v) => { s.UpdateParameterAvatars(ref s.m_params[0].avatarRestitution, p, l, v); } ), + (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].avatarRestitution, p, l, v); } ), new ParameterDefn("AvatarCapsuleRadius", "Radius of space around an avatar", 0.37f, (s,cf,p,v) => { s.m_params[0].avatarCapsuleRadius = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].avatarCapsuleRadius; }, - (s,p,l,v) => { s.UpdateParameterAvatars(ref s.m_params[0].avatarCapsuleRadius, p, l, v); } ), + (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].avatarCapsuleRadius, p, l, v); } ), new ParameterDefn("AvatarCapsuleHeight", "Default height of space around avatar", 1.5f, (s,cf,p,v) => { s.m_params[0].avatarCapsuleHeight = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].avatarCapsuleHeight; }, - (s,p,l,v) => { s.UpdateParameterAvatars(ref s.m_params[0].avatarCapsuleHeight, p, l, v); } ), + (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].avatarCapsuleHeight, p, l, v); } ), new ParameterDefn("AvatarContactProcessingThreshold", "Distance from capsule to check for collisions", 0.1f, (s,cf,p,v) => { s.m_params[0].avatarContactProcessingThreshold = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].avatarContactProcessingThreshold; }, - (s,p,l,v) => { s.UpdateParameterAvatars(ref s.m_params[0].avatarContactProcessingThreshold, p, l, v); } ), + (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].avatarContactProcessingThreshold, p, l, v); } ), new ParameterDefn("MaxPersistantManifoldPoolSize", "Number of manifolds pooled (0 means default of 4096)", @@ -1264,18 +1257,10 @@ public class BSScene : PhysicsScene, IPhysicsParameters } // check to see if we are updating a parameter for a particular or all of the prims - protected void UpdateParameterPrims(ref float loc, string parm, uint localID, float val) - { - List operateOn; - lock (m_prims) operateOn = new List(m_prims.Keys); - UpdateParameterSet(operateOn, ref loc, parm, localID, val); - } - - // check to see if we are updating a parameter for a particular or all of the avatars - protected void UpdateParameterAvatars(ref float loc, string parm, uint localID, float val) + protected void UpdateParameterObject(ref float loc, string parm, uint localID, float val) { List operateOn; - lock (m_avatars) operateOn = new List(m_avatars.Keys); + lock (PhysObjects) operateOn = new List(PhysObjects.Keys); UpdateParameterSet(operateOn, ref loc, parm, localID, val); } -- cgit v1.1 From 7c140570db3b01eb83efc0d42a47715d3047e376 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Sat, 25 Aug 2012 23:18:46 -0700 Subject: BulletSim: Changes to terrain storage and management so mega-regions work. Moved all terrain code out of BSScene and into new BSTerrainManager. Added logic to manage multiple terrains for mega-regions. Added new functions to BulletSimAPI to match the library. Moved all of the terrain creation and setup logic from C++ code to C# code. The unused code has not yet been removed from either place. Soon. Moved checks for avatar above ground and in bounds into BSCharacter. --- .../Region/Physics/BulletSPlugin/BSCharacter.cs | 37 ++- .../Region/Physics/BulletSPlugin/BSConstraint.cs | 3 +- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 9 +- .../Region/Physics/BulletSPlugin/BSPhysObject.cs | 118 ++++---- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 2 +- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 245 ++++++++-------- .../Physics/BulletSPlugin/BSTerrainManager.cs | 307 +++++++++++++++++++++ .../Region/Physics/BulletSPlugin/BulletSimAPI.cs | 61 +++- 8 files changed, 597 insertions(+), 185 deletions(-) create mode 100755 OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index 784076d..e76d8a4 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -226,16 +226,37 @@ public class BSCharacter : BSPhysObject bool ret = false; // If below the ground, move the avatar up - float terrainHeight = Scene.GetTerrainHeightAtXYZ(_position); - if (_position.Z < terrainHeight) + float terrainHeight = Scene.TerrainManager.GetTerrainHeightAtXYZ(_position); + if (Position.Z < terrainHeight) { - DetailLog("{0},BSCharacter.PositionAdjustUnderGround,call,pos={1},orient={2}", LocalID, _position, _orientation); - _position.Z = terrainHeight + 2.0f; + DetailLog("{0},BSCharacter.PositionAdjustUnderGround,call,pos={1},terrain={2}", LocalID, _position, terrainHeight); + Vector3 newPos = _position; + newPos.Z = terrainHeight + 2.0f; + _position = newPos; ret = true; } // TODO: check for out of bounds + return ret; + } + // A version of the sanity check that also makes sure a new position value is + // pushed back to the physics engine. This routine would be used by anyone + // who is not already pushing the value. + private bool PositionSanityCheck2() + { + bool ret = false; + if (PositionSanityCheck()) + { + // The new position value must be pushed into the physics engine but we can't + // just assign to "Position" because of potential call loops. + _scene.TaintedObject("BSCharacter.PositionSanityCheck", delegate() + { + DetailLog("{0},BSCharacter.PositionSanityCheck,taint,pos={1},orient={2}", LocalID, _position, _orientation); + BulletSimAPI.SetObjectTranslation(_scene.WorldID, _localID, _position, _orientation); + }); + ret = true; + } return ret; } @@ -500,9 +521,13 @@ public class BSCharacter : BSPhysObject // Avatars don't report their changes the usual way. Changes are checked for in the heartbeat loop. // base.RequestPhysicsterseUpdate(); - DetailLog("{0},BSCharacter.UpdateProperties,call,pos={1},orient={2},vel={3},accel={4},rotVel={5}", + // Do some sanity checking for the avatar. Make sure it's above ground and inbounds. + PositionSanityCheck2(); + + float heightHere = Scene.TerrainManager.GetTerrainHeightAtXYZ(_position); // just for debug + DetailLog("{0},BSCharacter.UpdateProperties,call,pos={1},orient={2},vel={3},accel={4},rotVel={5},terrain={6}", LocalID, entprop.Position, entprop.Rotation, entprop.Velocity, - entprop.Acceleration, entprop.RotationalVelocity); + entprop.Acceleration, entprop.RotationalVelocity, heightHere); } // Called by the scene when a collision with this object is reported diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs b/OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs index 25084d8..d9270d1 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs @@ -48,11 +48,10 @@ public abstract class BSConstraint : IDisposable { if (m_enabled) { - // BulletSimAPI.RemoveConstraint(m_world.ID, m_body1.ID, m_body2.ID); + m_enabled = false; bool success = BulletSimAPI.DestroyConstraint2(m_world.Ptr, m_constraint.Ptr); m_world.scene.DetailLog("{0},BSConstraint.Dispose,taint,body1={1},body2={2},success={3}", BSScene.DetailLogZero, m_body1.ID, m_body2.ID, success); m_constraint.Ptr = System.IntPtr.Zero; - m_enabled = false; } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index d7213fc..8169e99 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -465,6 +465,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin } }//end SetDefaultsForType + // One step of the vehicle properties for the next 'pTimestep' seconds. internal void Step(float pTimestep) { if (m_type == Vehicle.TYPE_NONE) return; @@ -592,9 +593,9 @@ namespace OpenSim.Region.Physics.BulletSPlugin } // If below the terrain, move us above the ground a little. - if (pos.Z < m_prim.Scene.GetTerrainHeightAtXYZ(pos)) + if (pos.Z < m_prim.Scene.TerrainManager.GetTerrainHeightAtXYZ(pos)) { - pos.Z = m_prim.Scene.GetTerrainHeightAtXYZ(pos) + 2; + pos.Z = m_prim.Scene.TerrainManager.GetTerrainHeightAtXYZ(pos) + 2; m_prim.Position = pos; VDetailLog("{0},MoveLinear,terrainHeight,pos={1}", m_prim.LocalID, pos); } @@ -609,7 +610,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin } if ((m_flags & VehicleFlag.HOVER_TERRAIN_ONLY) != 0) { - m_VhoverTargetHeight = m_prim.Scene.GetTerrainHeightAtXY(pos.X, pos.Y) + m_VhoverHeight; + m_VhoverTargetHeight = m_prim.Scene.TerrainManager.GetTerrainHeightAtXY(pos.X, pos.Y) + m_VhoverHeight; } if ((m_flags & VehicleFlag.HOVER_GLOBAL_HEIGHT) != 0) { @@ -673,7 +674,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin { grav.Z = (float)(grav.Z * 1.125); } - float terraintemp = m_prim.Scene.GetTerrainHeightAtXYZ(pos); + float terraintemp = m_prim.Scene.TerrainManager.GetTerrainHeightAtXYZ(pos); float postemp = (pos.Z - terraintemp); if (postemp > 2.5f) { diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index 6e205a9..ef463ca 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -1,58 +1,60 @@ -/* - * 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 OMV = OpenMetaverse; -using OpenSim.Framework; -using OpenSim.Region.Physics.Manager; - -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. -public abstract class BSPhysObject : PhysicsActor -{ - public abstract BSLinkset Linkset { get; set; } - - public abstract void Collide(uint collidingWith, BSPhysObject collidee, ActorTypes type, - OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth); - public abstract void SendCollisions(); - - // Return the object mass without calculating it or side effects - public abstract float MassRaw { get; } - - public abstract BulletBody Body { get; set; } - public abstract void ZeroMotion(); - - public abstract void UpdateProperties(EntityProperties entprop); - - public abstract void Destroy(); -} -} +/* + * 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 OMV = OpenMetaverse; +using OpenSim.Framework; +using OpenSim.Region.Physics.Manager; + +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. +public abstract class BSPhysObject : PhysicsActor +{ + public abstract BSLinkset Linkset { get; set; } + + public abstract void Collide(uint collidingWith, BSPhysObject collidee, ActorTypes type, + OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth); + public abstract void SendCollisions(); + + // Return the object mass without calculating it or side effects + public abstract float MassRaw { get; } + + public abstract BulletBody Body { get; set; } + public abstract void ZeroMotion(); + + public virtual void StepVehicle(float timeStep) { } + + public abstract void UpdateProperties(EntityProperties entprop); + + public abstract void Destroy(); +} +} diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 036fd4f..6bfce5c 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -377,7 +377,7 @@ public sealed class BSPrim : BSPhysObject // Called each simulation step to advance vehicle characteristics. // Called from Scene when doing simulation step so we're in taint processing time. - public void StepVehicle(float timeStep) + public override void StepVehicle(float timeStep) { if (IsPhysical) _vehicle.Step(timeStep); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index ce64b9b..f80304d 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -39,8 +39,6 @@ using log4net; using OpenMetaverse; // TODOs for BulletSim (for BSScene, BSPrim, BSCharacter and BulletSim) -// Debug linkset -// Test with multiple regions in one simulator // Adjust character capsule size when height is adjusted (ScenePresence.SetHeight) // Test sculpties // Compute physics FPS reasonably @@ -54,10 +52,8 @@ using OpenMetaverse; // Use collision masks for collision with terrain and phantom objects // Check out llVolumeDetect. Must do something for that. // Should prim.link() and prim.delink() membership checking happen at taint time? -// changing the position and orientation of a linked prim must rebuild the constraint with the root. // Mesh sharing. Use meshHash to tell if we already have a hull of that shape and only create once // Do attachments need to be handled separately? Need collision events. Do not collide with VolumeDetect -// Implement the genCollisions feature in BulletSim::SetObjectProperties (don't pass up unneeded collisions) // Implement LockAngularMotion // Decide if clearing forces is the right thing to do when setting position (BulletSim::SetObjectTranslation) // Does NeedsMeshing() really need to exclude all the different shapes? @@ -85,18 +81,15 @@ public class BSScene : PhysicsScene, IPhysicsParameters // moved to a better place. private HashSet m_avatarsWithCollisions = new HashSet(); - private List m_vehicles = new List(); - - private float[] m_heightMap; - private float m_waterLevel; - private uint m_worldID; - public uint WorldID { get { return m_worldID; } } + // List of all the objects that have vehicle properties and should be called + // to update each physics step. + private List m_vehicles = new List(); // let my minuions use my logger public ILog Logger { get { return m_log; } } - private bool m_initialized = false; - + // If non-zero, the number of simulation steps between calls to the physics + // engine to output detailed physics stats. Debug logging level must be on also. private int m_detailedStatsStep = 0; public IMesher mesher; @@ -106,29 +99,31 @@ public class BSScene : PhysicsScene, IPhysicsParameters public float MeshMegaPrimThreshold { get; private set; } public float SculptLOD { get; private set; } - private BulletSim m_worldSim; - public BulletSim World - { - get { return m_worldSim; } - } - private BSConstraintCollection m_constraintCollection; - public BSConstraintCollection Constraints - { - get { return m_constraintCollection; } - } + public uint WorldID { get; private set; } + public BulletSim World { get; private set; } + + // All the constraints that have been allocated in this instance. + public BSConstraintCollection Constraints { get; private set; } + // Simulation parameters private int m_maxSubSteps; private float m_fixedTimeStep; private long m_simulationStep = 0; public long SimulationStep { get { return m_simulationStep; } } + // The length of the last timestep we were asked to simulate. + // This is used by the vehicle code. Since the vehicle code is called + // once per simulation step, its constants need to be scaled by this. public float LastSimulatedTimestep { get; private set; } // 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 - private int m_simulationNowTime; - public int SimulationNowTime { get { return m_simulationNowTime; } } + // Set to 'now' just before all the prims and actors are called for collisions and updates + public int SimulationNowTime { get; private set; } + + // True if initialized and ready to do simulation steps + private bool m_initialized = false; + // Pinned memory used to pass step information between managed and unmanaged private int m_maxCollisionsPerFrame; private CollisionDesc[] m_collisionArray; private GCHandle m_collisionArrayPinnedHandle; @@ -145,6 +140,10 @@ public class BSScene : PhysicsScene, IPhysicsParameters public const uint TERRAIN_ID = 0; // OpenSim senses terrain with a localID of zero public const uint GROUNDPLANE_ID = 1; + public const uint CHILDTERRAIN_ID = 2; // Terrain allocated based on our mega-prim childre start here + + private float m_waterLevel; + public BSTerrainManager TerrainManager { get; private set; } public ConfigurationParameters Params { @@ -155,12 +154,12 @@ public class BSScene : PhysicsScene, IPhysicsParameters get { return new Vector3(0f, 0f, Params.gravity); } } - private float m_maximumObjectMass; - public float MaximumObjectMass - { - get { return m_maximumObjectMass; } - } + public float MaximumObjectMass { get; private set; } + // When functions in the unmanaged code must be called, it is only + // done at a known time just before the simulation step. The taint + // system saves all these function calls and executes them in + // order before the simulation. public delegate void TaintCallback(); private struct TaintCallbackEntry { @@ -176,6 +175,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters private Object _taintLock = new Object(); // A pointer to an instance if this structure is passed to the C++ code + // Used to pass basic configuration values to the unmanaged code. ConfigurationParameters[] m_params; GCHandle m_paramsHandle; @@ -189,11 +189,11 @@ public class BSScene : PhysicsScene, IPhysicsParameters private bool m_physicsLoggingEnabled; private string m_physicsLoggingDir; private string m_physicsLoggingPrefix; - private int m_physicsLoggingFileMinutes; - - private bool m_vehicleLoggingEnabled; - public bool VehicleLoggingEnabled { get { return m_vehicleLoggingEnabled; } } + private int m_physicsLoggingFileMinutes; + // 'true' of the vehicle code is to log lots of details + public bool VehicleLoggingEnabled { get; private set; } + #region Construction and Initialization public BSScene(string identifier) { m_initialized = false; @@ -216,6 +216,9 @@ public class BSScene : PhysicsScene, IPhysicsParameters m_updateArray = new EntityProperties[m_maxUpdatesPerFrame]; m_updateArrayPinnedHandle = GCHandle.Alloc(m_updateArray, GCHandleType.Pinned); + mesher = meshmerizer; + _taintedObjects = new List(); + // Enable very detailed logging. // By creating an empty logger when not logging, the log message invocation code // can be left in and every call doesn't have to check for null. @@ -228,11 +231,6 @@ public class BSScene : PhysicsScene, IPhysicsParameters PhysicsLogging = new Logging.LogWriter(); } - // Get the version of the DLL - // TODO: this doesn't work yet. Something wrong with marshaling the returned string. - // BulletSimVersion = BulletSimAPI.GetVersion(); - // m_log.WarnFormat("{0}: BulletSim.dll version='{1}'", LogHeader, BulletSimVersion); - // If Debug logging level, enable logging from the unmanaged code if (m_log.IsDebugEnabled || PhysicsLogging.Enabled) { @@ -245,22 +243,32 @@ public class BSScene : PhysicsScene, IPhysicsParameters BulletSimAPI.SetDebugLogCallback(m_DebugLogCallbackHandle); } - _taintedObjects = new List(); - - mesher = meshmerizer; + // Get the version of the DLL + // TODO: this doesn't work yet. Something wrong with marshaling the returned string. + // BulletSimVersion = BulletSimAPI.GetVersion(); + // m_log.WarnFormat("{0}: BulletSim.dll version='{1}'", LogHeader, BulletSimVersion); - // The bounding box for the simulated world + // The bounding box for the simulated world. The origin is 0,0,0 unless we're + // a child in a mega-region. + // Turns out that Bullet really doesn't care about the extents of the simulated + // area. It tracks active objects no matter where they are. Vector3 worldExtent = new Vector3(Constants.RegionSize, Constants.RegionSize, 8192f); // m_log.DebugFormat("{0}: Initialize: Calling BulletSimAPI.Initialize.", LogHeader); - m_worldID = BulletSimAPI.Initialize(worldExtent, m_paramsHandle.AddrOfPinnedObject(), + WorldID = BulletSimAPI.Initialize(worldExtent, m_paramsHandle.AddrOfPinnedObject(), m_maxCollisionsPerFrame, m_collisionArrayPinnedHandle.AddrOfPinnedObject(), m_maxUpdatesPerFrame, m_updateArrayPinnedHandle.AddrOfPinnedObject()); // Initialization to support the transition to a new API which puts most of the logic // into the C# code so it is easier to modify and add to. - m_worldSim = new BulletSim(m_worldID, this, BulletSimAPI.GetSimHandle2(m_worldID)); - m_constraintCollection = new BSConstraintCollection(World); + World = new BulletSim(WorldID, this, BulletSimAPI.GetSimHandle2(WorldID)); + + Constraints = new BSConstraintCollection(World); + + // Note: choose one of the two following lines + // BulletSimAPI.CreateInitialGroundPlaneAndTerrain(WorldID); + TerrainManager = new BSTerrainManager(this); + TerrainManager.CreateInitialGroundPlaneAndTerrain(); m_initialized = true; } @@ -288,7 +296,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters m_physicsLoggingPrefix = pConfig.GetString("PhysicsLoggingPrefix", "physics-%REGIONNAME%-"); m_physicsLoggingFileMinutes = pConfig.GetInt("PhysicsLoggingFileMinutes", 5); // Very detailed logging for vehicle debugging - m_vehicleLoggingEnabled = pConfig.GetBoolean("VehicleLoggingEnabled", false); + VehicleLoggingEnabled = pConfig.GetBoolean("VehicleLoggingEnabled", false); // Do any replacements in the parameters m_physicsLoggingPrefix = m_physicsLoggingPrefix.Replace("%REGIONNAME%", RegionName); @@ -323,6 +331,38 @@ public class BSScene : PhysicsScene, IPhysicsParameters PhysicsLogging.Write("[BULLETS UNMANAGED]:" + msg); } + public override void Dispose() + { + // m_log.DebugFormat("{0}: Dispose()", LogHeader); + + // make sure no stepping happens while we're deleting stuff + m_initialized = false; + + TerrainManager.ReleaseGroundPlaneAndTerrain(); + + foreach (KeyValuePair kvp in PhysObjects) + { + kvp.Value.Destroy(); + } + PhysObjects.Clear(); + + // Now that the prims are all cleaned up, there should be no constraints left + if (Constraints != null) + { + Constraints.Dispose(); + Constraints = null; + } + + // Anything left in the unmanaged code should be cleaned out + BulletSimAPI.Shutdown(WorldID); + + // Not logging any more + PhysicsLogging.Close(); + } + #endregion // Construction and Initialization + + #region Prim and Avatar addition and removal + public override PhysicsActor AddAvatar(string avName, Vector3 position, Vector3 size, bool isFlying) { m_log.ErrorFormat("{0}: CALL TO AddAvatar in BSScene. NOT IMPLEMENTED", LogHeader); @@ -413,6 +453,9 @@ public class BSScene : PhysicsScene, IPhysicsParameters // information call is not needed. public override void AddPhysicsActorTaint(PhysicsActor prim) { } + #endregion // Prim and Avatar addition and removal + + #region Simulation // Simulate one timestep public override float Simulate(float timeStep) { @@ -428,7 +471,8 @@ public class BSScene : PhysicsScene, IPhysicsParameters int simulateStartTime = Util.EnvironmentTickCount(); - // update the prim states while we know the physics engine is not busy + // update the prim states while we know the physics engine is not busy + int numTaints = _taintedObjects.Count; ProcessTaints(); // Some of the prims operate with special vehicle properties @@ -440,14 +484,17 @@ public class BSScene : PhysicsScene, IPhysicsParameters int numSubSteps = 0; try { - numSubSteps = BulletSimAPI.PhysicsStep(m_worldID, timeStep, m_maxSubSteps, m_fixedTimeStep, + numSubSteps = BulletSimAPI.PhysicsStep(WorldID, timeStep, m_maxSubSteps, m_fixedTimeStep, out updatedEntityCount, out updatedEntitiesPtr, out collidersCount, out collidersPtr); - DetailLog("{0},Simulate,call, substeps={1}, updates={2}, colliders={3}", DetailLogZero, numSubSteps, updatedEntityCount, collidersCount); + DetailLog("{0},Simulate,call, nTaints= {1}, substeps={2}, updates={3}, colliders={4}", + DetailLogZero, numTaints, numSubSteps, updatedEntityCount, collidersCount); } catch (Exception e) { - m_log.WarnFormat("{0},PhysicsStep Exception: substeps={1}, updates={2}, colliders={3}, e={4}", LogHeader, numSubSteps, updatedEntityCount, collidersCount, e); - // DetailLog("{0},PhysicsStepException,call, substeps={1}, updates={2}, colliders={3}", DetailLogZero, numSubSteps, updatedEntityCount, collidersCount); + m_log.WarnFormat("{0},PhysicsStep Exception: nTaints={1}, substeps={2}, updates={3}, colliders={4}, e={5}", + LogHeader, numTaints, numSubSteps, updatedEntityCount, collidersCount, e); + DetailLog("{0},PhysicsStepException,call, nTaints={1}, substeps={2}, updates={3}, colliders={4}", + DetailLogZero, numTaints, numSubSteps, updatedEntityCount, collidersCount); updatedEntityCount = 0; collidersCount = 0; } @@ -456,7 +503,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters // Don't have to use the pointers passed back since we know it is the same pinned memory we passed in // Get a value for 'now' so all the collision and update routines don't have to get their own - m_simulationNowTime = Util.EnvironmentTickCount(); + SimulationNowTime = Util.EnvironmentTickCount(); // If there were collisions, process them by sending the event to the prim. // Collisions must be processed before updates. @@ -527,7 +574,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters // Something has collided private void SendCollision(uint localID, uint collidingWith, Vector3 collidePoint, Vector3 collideNormal, float penetration) { - if (localID == TERRAIN_ID || localID == GROUNDPLANE_ID) + if (localID <= TerrainManager.HighestTerrainID) { return; // don't send collisions to the terrain } @@ -539,7 +586,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters BSPhysObject collidee = null; ActorTypes type = ActorTypes.Prim; - if (collidingWith == TERRAIN_ID || collidingWith == GROUNDPLANE_ID) + if (collidingWith <= TerrainManager.HighestTerrainID) { type = ActorTypes.Ground; } @@ -558,28 +605,14 @@ public class BSScene : PhysicsScene, IPhysicsParameters return; } + #endregion // Simulation + public override void GetResults() { } - public override void SetTerrain(float[] heightMap) { - m_heightMap = heightMap; - this.TaintedObject("BSScene.SetTerrain", delegate() - { - BulletSimAPI.SetHeightmap(m_worldID, m_heightMap); - }); - } + #region Terrain - // Someday we will have complex terrain with caves and tunnels - // For the moment, it's flat and convex - public float GetTerrainHeightAtXYZ(Vector3 loc) - { - return GetTerrainHeightAtXY(loc.X, loc.Y); - } - - public float GetTerrainHeightAtXY(float tX, float tY) - { - if (tX < 0 || tX >= Constants.RegionSize || tY < 0 || tY >= Constants.RegionSize) - return 30; - return m_heightMap[((int)tX) * Constants.RegionSize + ((int)tY)]; + public override void SetTerrain(float[] heightMap) { + TerrainManager.SetTerrain(heightMap); } public override void SetWaterLevel(float baseheight) @@ -595,35 +628,29 @@ public class BSScene : PhysicsScene, IPhysicsParameters public override void DeleteTerrain() { // m_log.DebugFormat("{0}: DeleteTerrain()", LogHeader); + } + + // Although no one seems to check this, I do support combining. + public override bool SupportsCombining() + { + return TerrainManager.SupportsCombining(); } - - public override void Dispose() - { - // m_log.DebugFormat("{0}: Dispose()", LogHeader); - - // make sure no stepping happens while we're deleting stuff - m_initialized = false; - - foreach (KeyValuePair kvp in PhysObjects) - { - kvp.Value.Destroy(); - } - PhysObjects.Clear(); - - // Now that the prims are all cleaned up, there should be no constraints left - if (m_constraintCollection != null) - { - m_constraintCollection.Dispose(); - m_constraintCollection = null; - } - - // Anything left in the unmanaged code should be cleaned out - BulletSimAPI.Shutdown(WorldID); - - // Not logging any more - PhysicsLogging.Close(); + // This call says I am a child to region zero in a mega-region. 'pScene' is that + // of region zero, 'offset' is my offset from regions zero's origin, and + // 'extents' is the largest XY that is handled in my region. + public override void Combine(PhysicsScene pScene, Vector3 offset, Vector3 extents) + { + TerrainManager.Combine(pScene, offset, extents); + } + + // Unhook all the combining that I know about. + public override void UnCombine(PhysicsScene pScene) + { + TerrainManager.UnCombine(pScene); } + #endregion // Terrain + public override Dictionary GetTopColliders() { return new Dictionary(); @@ -833,14 +860,14 @@ public class BSScene : PhysicsScene, IPhysicsParameters // no locking because only called when physics engine is not busy private void ProcessVehicles(float timeStep) { - foreach (BSPrim prim in m_vehicles) + foreach (BSPhysObject pobj in m_vehicles) { - prim.StepVehicle(timeStep); + pobj.StepVehicle(timeStep); } } #endregion Vehicles - #region Parameters + #region INI and command line parameter processing delegate void ParamUser(BSScene scene, IConfig conf, string paramName, float val); delegate float ParamGet(BSScene scene); @@ -943,9 +970,9 @@ public class BSScene : PhysicsScene, IPhysicsParameters (s,p,l,v) => { s.m_maxUpdatesPerFrame = (int)v; } ), new ParameterDefn("MaxObjectMass", "Maximum object mass (10000.01)", 10000.01f, - (s,cf,p,v) => { s.m_maximumObjectMass = cf.GetFloat(p, v); }, - (s) => { return (float)s.m_maximumObjectMass; }, - (s,p,l,v) => { s.m_maximumObjectMass = v; } ), + (s,cf,p,v) => { s.MaximumObjectMass = cf.GetFloat(p, v); }, + (s) => { return (float)s.MaximumObjectMass; }, + (s,p,l,v) => { s.MaximumObjectMass = v; } ), new ParameterDefn("PID_D", "Derivitive factor for motion smoothing", 2200f, @@ -1207,6 +1234,8 @@ public class BSScene : PhysicsScene, IPhysicsParameters private PhysParameterEntry[] SettableParameters = new PhysParameterEntry[1]; + // This creates an array in the correct format for returning the list of + // parameters. This is used by the 'list' option of the 'physics' command. private void BuildParameterTable() { if (SettableParameters.Length < ParameterDefinitions.Length) @@ -1283,7 +1312,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters TaintedObject("BSScene.UpdateParameterSet", delegate() { foreach (uint lID in objectIDs) { - BulletSimAPI.UpdateParameter(m_worldID, lID, xparm, xval); + BulletSimAPI.UpdateParameter(WorldID, lID, xparm, xval); } }); break; @@ -1301,7 +1330,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters string xparm = parm.ToLower(); float xval = val; TaintedObject("BSScene.TaintedUpdateParameter", delegate() { - BulletSimAPI.UpdateParameter(m_worldID, xlocalID, xparm, xval); + BulletSimAPI.UpdateParameter(WorldID, xlocalID, xparm, xval); }); } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs new file mode 100755 index 0000000..28c1940 --- /dev/null +++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs @@ -0,0 +1,307 @@ +/* + * 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 OpenSim.Framework; +using OpenSim.Region.Framework; +using OpenSim.Region.CoreModules; +using OpenSim.Region.Physics.Manager; + +using Nini.Config; +using log4net; + +using OpenMetaverse; + +namespace OpenSim.Region.Physics.BulletSPlugin +{ +public class BSTerrainManager +{ + static string LogHeader = "[BULLETSIM TERRAIN MANAGER]"; + + BSScene m_physicsScene; + + private BulletBody m_groundPlane; + + // If doing mega-regions, if we're region zero we will be managing multiple + // region terrains since region zero does the physics for the whole mega-region. + private Dictionary m_terrains; + private Dictionary m_heightMaps; + + // If we are doing mega-regions, terrains are added from TERRAIN_ID to m_terrainCount. + // This is incremented before assigning to new region so it is the last ID allocated. + private uint m_terrainCount = BSScene.CHILDTERRAIN_ID - 1; + public uint HighestTerrainID { get {return m_terrainCount; } } + + // If doing mega-regions, this holds our offset from region zero of + // the mega-regions. "parentScene" points to the PhysicsScene of region zero. + private Vector3 m_worldOffset = Vector3.Zero; + public Vector2 WorldExtents = new Vector2((int)Constants.RegionSize, (int)Constants.RegionSize); + private PhysicsScene m_parentScene = null; + + public BSTerrainManager(BSScene physicsScene) + { + m_physicsScene = physicsScene; + m_terrains = new Dictionary(); + m_heightMaps = new Dictionary(); + } + + // Create the initial instance of terrain and the underlying ground plane. + // The objects are allocated in the unmanaged space and the pointers are tracked + // by the managed code. + // The terrains and the groundPlane are not added to the list of PhysObjects. + // This is called from the initialization routine so we presume it is + // safe to call Bullet in real time. We hope no one is moving around prim yet. + public void CreateInitialGroundPlaneAndTerrain() + { + // The ground plane is here to catch things that are trying to drop to negative infinity + m_groundPlane = new BulletBody(BSScene.GROUNDPLANE_ID, + BulletSimAPI.CreateGroundPlaneBody2(BSScene.GROUNDPLANE_ID, 1f, 0.4f)); + BulletSimAPI.AddObjectToWorld2(m_physicsScene.World.Ptr, m_groundPlane.Ptr); + + Vector3 minTerrainCoords = new Vector3(0f, 0f, 24f); + Vector3 maxTerrainCoords = new Vector3(Constants.RegionSize, Constants.RegionSize, 25f); + int totalHeights = (int)maxTerrainCoords.X * (int)maxTerrainCoords.Y; + float[] initialMap = new float[totalHeights]; + for (int ii = 0; ii < totalHeights; ii++) + { + initialMap[ii] = 25f; + } + CreateNewTerrainSegment(BSScene.TERRAIN_ID, initialMap, minTerrainCoords, maxTerrainCoords); + } + + public void ReleaseGroundPlaneAndTerrain() + { + if (BulletSimAPI.RemoveObjectFromWorld2(m_physicsScene.World.Ptr, m_groundPlane.Ptr)) + { + BulletSimAPI.DestroyObject2(m_physicsScene.World.Ptr, m_groundPlane.Ptr); + } + m_groundPlane.Ptr = IntPtr.Zero; + + foreach (KeyValuePair kvp in m_terrains) + { + if (BulletSimAPI.RemoveObjectFromWorld2(m_physicsScene.World.Ptr, kvp.Value.Ptr)) + { + BulletSimAPI.DestroyObject2(m_physicsScene.World.Ptr, kvp.Value.Ptr); + BulletSimAPI.ReleaseHeightmapInfo2(m_heightMaps[kvp.Key].Ptr); + } + } + m_terrains.Clear(); + m_heightMaps.Clear(); + } + + // Create a new terrain description. This is used for mega-regions where + // the children of region zero give region zero all of the terrain + // segments since region zero does all the physics for the mega-region. + // Call at taint time!! + public void CreateNewTerrainSegment(uint id, float[] heightMap, Vector3 minCoords, Vector3 maxCoords) + { + // The Z coordinates are recalculated to be the min and max height of the terrain + // itself. The caller may have passed us the real region extent. + float minZ = float.MaxValue; + float maxZ = float.MinValue; + int hSize = heightMap.Length; + for (int ii = 0; ii < hSize; ii++) + { + minZ = heightMap[ii] < minZ ? heightMap[ii] : minZ; + maxZ = heightMap[ii] > maxZ ? heightMap[ii] : maxZ; + } + minCoords.Z = minZ; + maxCoords.Z = maxZ; + // If the terrain is flat, make a difference so we get a good bounding box + if (minZ == maxZ) + minZ -= 0.2f; + Vector2 terrainRegionBase = new Vector2(minCoords.X, minCoords.Y); + + // Create the heightmap data structure in the unmanaged space + BulletHeightMapInfo mapInfo = new BulletHeightMapInfo( + BulletSimAPI.CreateHeightmap2(minCoords, maxCoords, heightMap), heightMap); + mapInfo.terrainRegionBase = terrainRegionBase; + mapInfo.maxRegionExtent = maxCoords; + mapInfo.minZ = minZ; + mapInfo.maxZ = maxZ; + mapInfo.sizeX = maxCoords.X - minCoords.X; + mapInfo.sizeY = maxCoords.Y - minCoords.Y; + + DetailLog("{0},BSScene.CreateNewTerrainSegment,call,minZ={1},maxZ={2},hMapPtr={3},minC={4},maxC={5}", + BSScene.DetailLogZero, minZ, maxZ, mapInfo.Ptr, minCoords, maxCoords); + // Create the terrain body from that heightmap + BulletBody terrainBody = new BulletBody(id, BulletSimAPI.CreateTerrainBody2(id, mapInfo.Ptr, 0.01f)); + + BulletSimAPI.SetFriction2(terrainBody.Ptr, m_physicsScene.Params.terrainFriction); + BulletSimAPI.SetHitFraction2(terrainBody.Ptr, m_physicsScene.Params.terrainHitFraction); + BulletSimAPI.SetRestitution2(terrainBody.Ptr, m_physicsScene.Params.terrainRestitution); + BulletSimAPI.SetCollisionFlags2(terrainBody.Ptr, CollisionFlags.CF_STATIC_OBJECT); + BulletSimAPI.Activate2(terrainBody.Ptr, true); + + // Add the new terrain to the dynamics world + BulletSimAPI.AddObjectToWorld2(m_physicsScene.World.Ptr, terrainBody.Ptr); + BulletSimAPI.UpdateSingleAabb2(m_physicsScene.World.Ptr, terrainBody.Ptr); + + + // Add the created terrain to the management set. If we are doing mega-regions, + // the terrains of our children will be added. + m_terrains.Add(terrainRegionBase, terrainBody); + m_heightMaps.Add(terrainRegionBase, mapInfo); + } + + public void SetTerrain(float[] heightMap) { + if (m_worldOffset != Vector3.Zero && m_parentScene != null) + { + // If doing the mega-prim stuff and we are the child of the zero region, + // the terrain is really added to our parent + if (m_parentScene is BSScene) + { + ((BSScene)m_parentScene).TerrainManager.SetTerrain(heightMap, m_worldOffset); + } + } + else + { + // if not doing the mega-prim thing, just change the terrain + SetTerrain(heightMap, m_worldOffset); + } + } + + private void SetTerrain(float[] heightMap, Vector3 tOffset) + { + float minZ = float.MaxValue; + float maxZ = float.MinValue; + + // Copy heightMap local and compute some statistics. + // Not really sure if we need to do this deep copy but, given + // the magic that happens to make the closure for taint + // below, I don't want there to be any problem with sharing + // locations of there are multiple calls to this routine + // within one tick. + int heightMapSize = heightMap.Length; + float[] localHeightMap = new float[heightMapSize]; + for (int ii = 0; ii < heightMapSize; ii++) + { + float height = heightMap[ii]; + if (height < minZ) minZ = height; + if (height > maxZ) maxZ = height; + localHeightMap[ii] = height; + } + + Vector2 terrainRegionBase = new Vector2(tOffset.X, tOffset.Y); + BulletHeightMapInfo mapInfo; + if (m_heightMaps.TryGetValue(terrainRegionBase, out mapInfo)) + { + // If this is terrain we know about, it's easy to update + mapInfo.heightMap = localHeightMap; + m_physicsScene.TaintedObject("BSScene.SetTerrain:UpdateExisting", delegate() + { + DetailLog("{0},SetTerrain:UpdateExisting,baseX={1},baseY={2},minZ={3},maxZ={4}", + BSScene.DetailLogZero, tOffset.X, tOffset.Y, minZ, maxZ); + BulletSimAPI.UpdateHeightMap2(m_physicsScene.World.Ptr, mapInfo.Ptr, mapInfo.heightMap); + }); + } + else + { + // Our mega-prim child is giving us a new terrain to add to the phys world + uint newTerrainID = ++m_terrainCount; + + Vector3 minCoords = tOffset; + minCoords.Z = minZ; + Vector3 maxCoords = new Vector3(tOffset.X + Constants.RegionSize, + tOffset.Y + Constants.RegionSize, + maxZ); + m_physicsScene.TaintedObject("BSScene.SetTerrain:NewTerrain", delegate() + { + DetailLog("{0},SetTerrain:NewTerrain,baseX={1},baseY={2}", BSScene.DetailLogZero, tOffset.X, tOffset.Y); + CreateNewTerrainSegment(newTerrainID, heightMap, minCoords, maxCoords); + }); + } + } + + // Someday we will have complex terrain with caves and tunnels + // For the moment, it's flat and convex + public float GetTerrainHeightAtXYZ(Vector3 loc) + { + return GetTerrainHeightAtXY(loc.X, loc.Y); + } + + // Given an X and Y, find the height of the terrain. + // Since we could be handling multiple terrains for a mega-region, + // the base of the region is calcuated assuming all regions are + // the same size and that is the default. + // Once the heightMapInfo is found, we have all the information to + // compute the offset into the array. + public float GetTerrainHeightAtXY(float tX, float tY) + { + float ret = 30f; + + int offsetX = ((int)(tX / (int)Constants.RegionSize)) * (int)Constants.RegionSize; + int offsetY = ((int)(tY / (int)Constants.RegionSize)) * (int)Constants.RegionSize; + Vector2 terrainBaseXY = new Vector2(offsetX, offsetY); + + BulletHeightMapInfo mapInfo; + if (m_heightMaps.TryGetValue(terrainBaseXY, out mapInfo)) + { + float regionX = tX - offsetX; + float regionY = tY - offsetY; + regionX = regionX > mapInfo.sizeX ? 0 : regionX; + regionY = regionY > mapInfo.sizeY ? 0 : regionY; + ret = mapInfo.heightMap[(int)(regionX * mapInfo.sizeX + regionY)]; + } + else + { + m_physicsScene.Logger.ErrorFormat("{0} GetTerrainHeightAtXY: terrain not found: x={1}, y={2}", + LogHeader, tX, tY); + } + return ret; + } + + // Although no one seems to check this, I do support combining. + public bool SupportsCombining() + { + return true; + } + // This call says I am a child to region zero in a mega-region. 'pScene' is that + // of region zero, 'offset' is my offset from regions zero's origin, and + // 'extents' is the largest XY that is handled in my region. + public void Combine(PhysicsScene pScene, Vector3 offset, Vector3 extents) + { + m_worldOffset = offset; + WorldExtents = new Vector2(extents.X, extents.Y); + m_parentScene = pScene; + } + + // Unhook all the combining that I know about. + public void UnCombine(PhysicsScene pScene) + { + // Just like ODE, for the moment a NOP + } + + + private void DetailLog(string msg, params Object[] args) + { + m_physicsScene.PhysicsLogging.Write(msg, args); + } +} +} diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs index dab2420..3b319fb 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs @@ -33,6 +33,9 @@ using OpenMetaverse; namespace OpenSim.Region.Physics.BulletSPlugin { // Classes to allow some type checking for the API +// These hold pointers to allocated objects in the unmanaged space. + +// The physics engine controller class created at initialization public struct BulletSim { public BulletSim(uint id, BSScene bss, IntPtr xx) { ID = id; scene = bss; Ptr = xx; } @@ -42,6 +45,7 @@ public struct BulletSim public IntPtr Ptr; } +// An allocated Bullet btRigidBody public struct BulletBody { public BulletBody(uint id, IntPtr xx) { ID = id; Ptr = xx; } @@ -49,12 +53,35 @@ public struct BulletBody public uint ID; } +// An allocated Bullet btConstraint public struct BulletConstraint { public BulletConstraint(IntPtr xx) { Ptr = xx; } public IntPtr Ptr; } +// An allocated HeightMapThing which hold various heightmap info +// Made a class rather than a struct so there would be only one +// instance of this and C# will pass around pointers rather +// than making copies. +public class BulletHeightMapInfo +{ + public BulletHeightMapInfo(IntPtr xx, float[] hm) { + Ptr = xx; + heightMap = hm; + terrainRegionBase = new Vector2(0f, 0f); + maxRegionExtent = new Vector3(100f, 100f, 25f); + minZ = maxZ = 0f; + sizeX = sizeY = 256f; + } + public IntPtr Ptr; + public float[] heightMap; + public Vector2 terrainRegionBase; + public Vector3 maxRegionExtent; + public float sizeX, sizeY; + public float minZ, maxZ; +} + // =============================================================================== [StructLayout(LayoutKind.Sequential)] public struct ConvexHull @@ -231,6 +258,9 @@ public static extern uint Initialize(Vector3 maxPosition, IntPtr parms, int maxUpdates, IntPtr updateArray); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void CreateInitialGroundPlaneAndTerrain(uint worldID); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern void SetHeightmap(uint worldID, [MarshalAs(UnmanagedType.LPArray)] float[] heightMap); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] @@ -414,12 +444,23 @@ public static extern bool DeleteCollisionShape2(IntPtr world, IntPtr shape); // ===================================================================================== [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern IntPtr CreateGroundPlaneBody2(uint id, Vector3 center, float collisionMargin); +public static extern IntPtr CreateGroundPlaneBody2(uint id, float height, float collisionMargin); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern IntPtr CreateTerrainBody2(uint id, - Vector3 minCoords, Vector3 maxCoords, float collisionMargin, - [MarshalAs(UnmanagedType.LPArray)] float[] heightMap); + IntPtr heightMapInfo, + float collisionMargin); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern IntPtr CreateHeightmap2(Vector3 minCoords, Vector3 maxCoords, + [MarshalAs(UnmanagedType.LPArray)] float[] heightMap); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern bool ReleaseHeightmapInfo2(IntPtr heightMapInfo); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void UpdateHeightMap2(IntPtr world, IntPtr heightMapInfo, + [MarshalAs(UnmanagedType.LPArray)] float[] heightMap); // ===================================================================================== [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] @@ -473,11 +514,16 @@ public static extern bool SetConstraintParam2(IntPtr constrain, ConstraintParams [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern bool DestroyConstraint2(IntPtr world, IntPtr constrain); +// ===================================================================================== [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern Vector3 AddObjectToWorld2(IntPtr world, IntPtr obj); +public static extern bool AddObjectToWorld2(IntPtr world, IntPtr obj); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern Vector3 RemoveObjectFromWorld2(IntPtr world, IntPtr obj); +public static extern bool RemoveObjectFromWorld2(IntPtr world, IntPtr obj); + +// ===================================================================================== +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void Activate2(IntPtr obj, bool forceActivation); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern Vector3 GetPosition2(IntPtr obj); @@ -522,6 +568,9 @@ public static extern bool SetContactProcessingThreshold2(IntPtr obj, float val); public static extern bool SetFriction2(IntPtr obj, float val); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern bool SetHitFraction2(IntPtr obj, float val); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern bool SetRestitution2(IntPtr obj, float val); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] @@ -564,7 +613,7 @@ public static extern bool SetMargin2(IntPtr obj, float val); public static extern bool UpdateSingleAabb2(IntPtr world, IntPtr obj); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool DestroyObject2(IntPtr world, uint id); +public static extern bool DestroyObject2(IntPtr world, IntPtr obj); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern void DumpPhysicsStatistics2(IntPtr sim); -- cgit v1.1 From d3adf9b2b3bd8e0e76168cd6eb6414f3123c5f02 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Sat, 25 Aug 2012 23:25:29 -0700 Subject: BulletSim: fix line endings. --- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 44 ++++++++++++------------- 1 file changed, 22 insertions(+), 22 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index f80304d..7b4802e 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -102,7 +102,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters public uint WorldID { get; private set; } public BulletSim World { get; private set; } - // All the constraints that have been allocated in this instance. + // All the constraints that have been allocated in this instance. public BSConstraintCollection Constraints { get; private set; } // Simulation parameters @@ -117,7 +117,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters public float LastSimulatedTimestep { get; private set; } // 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 + // Set to 'now' just before all the prims and actors are called for collisions and updates public int SimulationNowTime { get; private set; } // True if initialized and ready to do simulation steps @@ -140,8 +140,8 @@ public class BSScene : PhysicsScene, IPhysicsParameters public const uint TERRAIN_ID = 0; // OpenSim senses terrain with a localID of zero public const uint GROUNDPLANE_ID = 1; - public const uint CHILDTERRAIN_ID = 2; // Terrain allocated based on our mega-prim childre start here - + public const uint CHILDTERRAIN_ID = 2; // Terrain allocated based on our mega-prim childre start here + private float m_waterLevel; public BSTerrainManager TerrainManager { get; private set; } @@ -189,8 +189,8 @@ public class BSScene : PhysicsScene, IPhysicsParameters private bool m_physicsLoggingEnabled; private string m_physicsLoggingDir; private string m_physicsLoggingPrefix; - private int m_physicsLoggingFileMinutes; - // 'true' of the vehicle code is to log lots of details + private int m_physicsLoggingFileMinutes; + // 'true' of the vehicle code is to log lots of details public bool VehicleLoggingEnabled { get; private set; } #region Construction and Initialization @@ -266,7 +266,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters Constraints = new BSConstraintCollection(World); // Note: choose one of the two following lines - // BulletSimAPI.CreateInitialGroundPlaneAndTerrain(WorldID); + // BulletSimAPI.CreateInitialGroundPlaneAndTerrain(WorldID); TerrainManager = new BSTerrainManager(this); TerrainManager.CreateInitialGroundPlaneAndTerrain(); @@ -471,7 +471,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters int simulateStartTime = Util.EnvironmentTickCount(); - // update the prim states while we know the physics engine is not busy + // update the prim states while we know the physics engine is not busy int numTaints = _taintedObjects.Count; ProcessTaints(); @@ -611,7 +611,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters #region Terrain - public override void SetTerrain(float[] heightMap) { + public override void SetTerrain(float[] heightMap) { TerrainManager.SetTerrain(heightMap); } @@ -628,25 +628,25 @@ public class BSScene : PhysicsScene, IPhysicsParameters public override void DeleteTerrain() { // m_log.DebugFormat("{0}: DeleteTerrain()", LogHeader); - } - - // Although no one seems to check this, I do support combining. - public override bool SupportsCombining() - { - return TerrainManager.SupportsCombining(); + } + + // Although no one seems to check this, I do support combining. + public override bool SupportsCombining() + { + return TerrainManager.SupportsCombining(); } // This call says I am a child to region zero in a mega-region. 'pScene' is that // of region zero, 'offset' is my offset from regions zero's origin, and // 'extents' is the largest XY that is handled in my region. public override void Combine(PhysicsScene pScene, Vector3 offset, Vector3 extents) - { + { TerrainManager.Combine(pScene, offset, extents); - } - - // Unhook all the combining that I know about. - public override void UnCombine(PhysicsScene pScene) - { - TerrainManager.UnCombine(pScene); + } + + // Unhook all the combining that I know about. + public override void UnCombine(PhysicsScene pScene) + { + TerrainManager.UnCombine(pScene); } #endregion // Terrain -- cgit v1.1 From ae852bb8738c7bce60c8fee9fbf6038288bd9363 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Wed, 29 Aug 2012 09:20:09 -0700 Subject: BulletSim: clean up some variable naming for consistancy. Update DLL API for new terrain and shape/body pattern methods. Terrain creation and modification uses new shape/body pattern. Move debug logging callback set to initialization call so logging is per physics engine. --- .../Region/Physics/BulletSPlugin/BSCharacter.cs | 78 ++++++------ OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 13 +- .../Physics/BulletSPlugin/BSTerrainManager.cs | 139 +++++++++++++++------ .../Region/Physics/BulletSPlugin/BulletSimAPI.cs | 55 +++++--- 4 files changed, 183 insertions(+), 102 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index e76d8a4..fa21233 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -39,8 +39,7 @@ public class BSCharacter : BSPhysObject private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static readonly string LogHeader = "[BULLETS CHAR]"; - private BSScene _scene; - public BSScene Scene { get { return _scene; } } + public BSScene Scene { get; private set; } private String _avName; // private bool _stopped; private Vector3 _size; @@ -92,7 +91,7 @@ public class BSCharacter : BSPhysObject { _localID = localID; _avName = avName; - _scene = parent_scene; + Scene = parent_scene; _position = pos; _size = size; _flying = isFlying; @@ -101,11 +100,11 @@ public class BSCharacter : BSPhysObject _buoyancy = ComputeBuoyancyFromFlying(isFlying); // The dimensions of the avatar capsule are kept in the scale. // Physics creates a unit capsule which is scaled by the physics engine. - _scale = new Vector3(_scene.Params.avatarCapsuleRadius, _scene.Params.avatarCapsuleRadius, size.Z); - _density = _scene.Params.avatarDensity; + _scale = new Vector3(Scene.Params.avatarCapsuleRadius, Scene.Params.avatarCapsuleRadius, size.Z); + _density = Scene.Params.avatarDensity; ComputeAvatarVolumeAndMass(); // set _avatarVolume and _mass based on capsule size, _density and _scale - Linkset = new BSLinkset(_scene, this); + Linkset = new BSLinkset(Scene, this); ShapeData shapeData = new ShapeData(); shapeData.ID = _localID; @@ -117,19 +116,19 @@ public class BSCharacter : BSPhysObject shapeData.Mass = _mass; shapeData.Buoyancy = _buoyancy; shapeData.Static = ShapeData.numericFalse; - shapeData.Friction = _scene.Params.avatarFriction; - shapeData.Restitution = _scene.Params.avatarRestitution; + shapeData.Friction = Scene.Params.avatarFriction; + shapeData.Restitution = Scene.Params.avatarRestitution; // do actual create at taint time - _scene.TaintedObject("BSCharacter.create", delegate() + Scene.TaintedObject("BSCharacter.create", delegate() { DetailLog("{0},BSCharacter.create", _localID); - BulletSimAPI.CreateObject(parent_scene.WorldID, shapeData); + BulletSimAPI.CreateObject(Scene.WorldID, shapeData); // Set the buoyancy for flying. This will be refactored when all the settings happen in C# - BulletSimAPI.SetObjectBuoyancy(_scene.WorldID, LocalID, _buoyancy); + BulletSimAPI.SetObjectBuoyancy(Scene.WorldID, LocalID, _buoyancy); - Body = new BulletBody(LocalID, BulletSimAPI.GetBodyHandle2(_scene.World.Ptr, LocalID)); + Body = new BulletBody(LocalID, BulletSimAPI.GetBodyHandle2(Scene.World.Ptr, LocalID)); // avatars get all collisions no matter what (makes walking on ground and such work) BulletSimAPI.AddToCollisionFlags2(Body.Ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); }); @@ -141,9 +140,9 @@ public class BSCharacter : BSPhysObject public override void Destroy() { DetailLog("{0},BSCharacter.Destroy", LocalID); - _scene.TaintedObject("BSCharacter.destroy", delegate() + Scene.TaintedObject("BSCharacter.destroy", delegate() { - BulletSimAPI.DestroyObject(_scene.WorldID, _localID); + BulletSimAPI.DestroyObject(Scene.WorldID, _localID); }); } @@ -172,9 +171,9 @@ public class BSCharacter : BSPhysObject ComputeAvatarVolumeAndMass(); - _scene.TaintedObject("BSCharacter.setSize", delegate() + Scene.TaintedObject("BSCharacter.setSize", delegate() { - BulletSimAPI.SetObjectScaleMass(_scene.WorldID, LocalID, _scale, _mass, true); + BulletSimAPI.SetObjectScaleMass(Scene.WorldID, LocalID, _scale, _mass, true); }); } @@ -203,17 +202,17 @@ public class BSCharacter : BSPhysObject public override Vector3 Position { get { - // _position = BulletSimAPI.GetObjectPosition(_scene.WorldID, _localID); + // _position = BulletSimAPI.GetObjectPosition(Scene.WorldID, _localID); return _position; } set { _position = value; PositionSanityCheck(); - _scene.TaintedObject("BSCharacter.setPosition", delegate() + Scene.TaintedObject("BSCharacter.setPosition", delegate() { DetailLog("{0},BSCharacter.SetPosition,taint,pos={1},orient={2}", LocalID, _position, _orientation); - BulletSimAPI.SetObjectTranslation(_scene.WorldID, _localID, _position, _orientation); + BulletSimAPI.SetObjectTranslation(Scene.WorldID, _localID, _position, _orientation); }); } } @@ -229,10 +228,8 @@ public class BSCharacter : BSPhysObject float terrainHeight = Scene.TerrainManager.GetTerrainHeightAtXYZ(_position); if (Position.Z < terrainHeight) { - DetailLog("{0},BSCharacter.PositionAdjustUnderGround,call,pos={1},terrain={2}", LocalID, _position, terrainHeight); - Vector3 newPos = _position; - newPos.Z = terrainHeight + 2.0f; - _position = newPos; + DetailLog("{0},BSCharacter.PositionAdjustUnderGround,call,pos={1},terrain={2}", LocalID, _position, terrainHeight); + _position.Z = terrainHeight + 2.0f; ret = true; } @@ -250,10 +247,10 @@ public 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. - _scene.TaintedObject("BSCharacter.PositionSanityCheck", delegate() + Scene.TaintedObject("BSCharacter.PositionSanityCheck", delegate() { DetailLog("{0},BSCharacter.PositionSanityCheck,taint,pos={1},orient={2}", LocalID, _position, _orientation); - BulletSimAPI.SetObjectTranslation(_scene.WorldID, _localID, _position, _orientation); + BulletSimAPI.SetObjectTranslation(Scene.WorldID, _localID, _position, _orientation); }); ret = true; } @@ -301,10 +298,10 @@ public class BSCharacter : BSPhysObject set { _velocity = value; // m_log.DebugFormat("{0}: set velocity = {1}", LogHeader, _velocity); - _scene.TaintedObject("BSCharacter.setVelocity", delegate() + Scene.TaintedObject("BSCharacter.setVelocity", delegate() { DetailLog("{0},BSCharacter.setVelocity,taint,vel={1}", LocalID, _velocity); - BulletSimAPI.SetObjectVelocity(_scene.WorldID, _localID, _velocity); + BulletSimAPI.SetObjectVelocity(Scene.WorldID, _localID, _velocity); }); } } @@ -327,10 +324,10 @@ public class BSCharacter : BSPhysObject set { _orientation = value; // m_log.DebugFormat("{0}: set orientation to {1}", LogHeader, _orientation); - _scene.TaintedObject("BSCharacter.setOrientation", delegate() + Scene.TaintedObject("BSCharacter.setOrientation", delegate() { - // _position = BulletSimAPI.GetObjectPosition(_scene.WorldID, _localID); - BulletSimAPI.SetObjectTranslation(_scene.WorldID, _localID, _position, _orientation); + // _position = BulletSimAPI.GetObjectPosition(Scene.WorldID, _localID); + BulletSimAPI.SetObjectTranslation(Scene.WorldID, _localID, _position, _orientation); }); } } @@ -367,11 +364,11 @@ public class BSCharacter : BSPhysObject set { _throttleUpdates = value; } } public override bool IsColliding { - get { return (_collidingStep == _scene.SimulationStep); } + get { return (_collidingStep == Scene.SimulationStep); } set { _isColliding = value; } } public override bool CollidingGround { - get { return (_collidingGroundStep == _scene.SimulationStep); } + get { return (_collidingGroundStep == Scene.SimulationStep); } set { _collidingGround = value; } } public override bool CollidingObj { @@ -393,10 +390,10 @@ public class BSCharacter : BSPhysObject public override float Buoyancy { get { return _buoyancy; } set { _buoyancy = value; - _scene.TaintedObject("BSCharacter.setBuoyancy", delegate() + Scene.TaintedObject("BSCharacter.setBuoyancy", delegate() { DetailLog("{0},BSCharacter.setBuoyancy,taint,buoy={1}", LocalID, _buoyancy); - BulletSimAPI.SetObjectBuoyancy(_scene.WorldID, LocalID, _buoyancy); + BulletSimAPI.SetObjectBuoyancy(Scene.WorldID, LocalID, _buoyancy); }); } } @@ -440,7 +437,7 @@ public class BSCharacter : BSPhysObject _force.Y += force.Y; _force.Z += force.Z; // m_log.DebugFormat("{0}: AddForce. adding={1}, newForce={2}", LogHeader, force, _force); - _scene.TaintedObject("BSCharacter.AddForce", delegate() + Scene.TaintedObject("BSCharacter.AddForce", delegate() { DetailLog("{0},BSCharacter.setAddForce,taint,addedForce={1}", LocalID, _force); BulletSimAPI.AddObjectForce2(Body.Ptr, _force); @@ -524,10 +521,9 @@ public class BSCharacter : BSPhysObject // Do some sanity checking for the avatar. Make sure it's above ground and inbounds. PositionSanityCheck2(); - float heightHere = Scene.TerrainManager.GetTerrainHeightAtXYZ(_position); // just for debug + float heightHere = Scene.TerrainManager.GetTerrainHeightAtXYZ(_position); // only for debug DetailLog("{0},BSCharacter.UpdateProperties,call,pos={1},orient={2},vel={3},accel={4},rotVel={5},terrain={6}", - LocalID, entprop.Position, entprop.Rotation, entprop.Velocity, - entprop.Acceleration, entprop.RotationalVelocity, heightHere); + LocalID, _position, _orientation, _velocity, _acceleration, _rotationalVelocity, heightHere); } // Called by the scene when a collision with this object is reported @@ -539,16 +535,16 @@ public class BSCharacter : BSPhysObject // m_log.DebugFormat("{0}: Collide: ms={1}, id={2}, with={3}", LogHeader, _subscribedEventsMs, LocalID, collidingWith); // The following makes IsColliding() and IsCollidingGround() work - _collidingStep = _scene.SimulationStep; + _collidingStep = Scene.SimulationStep; if (collidingWith == BSScene.TERRAIN_ID || collidingWith == BSScene.GROUNDPLANE_ID) { - _collidingGroundStep = _scene.SimulationStep; + _collidingGroundStep = Scene.SimulationStep; } // DetailLog("{0},BSCharacter.Collison,call,with={1}", LocalID, collidingWith); // throttle collisions to the rate specified in the subscription if (_subscribedEventsMs != 0) { - int nowTime = _scene.SimulationNowTime; + int nowTime = Scene.SimulationNowTime; if (nowTime >= _nextCollisionOkTime) { _nextCollisionOkTime = nowTime + _subscribedEventsMs; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index 7b4802e..2f55ba4 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -232,15 +232,15 @@ public class BSScene : PhysicsScene, IPhysicsParameters } // If Debug logging level, enable logging from the unmanaged code + m_DebugLogCallbackHandle = null; if (m_log.IsDebugEnabled || PhysicsLogging.Enabled) { m_log.DebugFormat("{0}: Initialize: Setting debug callback for unmanaged code", LogHeader); if (PhysicsLogging.Enabled) + // The handle is saved in a variable to make sure it doesn't get freed after this call m_DebugLogCallbackHandle = new BulletSimAPI.DebugLogCallback(BulletLoggerPhysLog); else m_DebugLogCallbackHandle = new BulletSimAPI.DebugLogCallback(BulletLogger); - // The handle is saved in a variable to make sure it doesn't get freed after this call - BulletSimAPI.SetDebugLogCallback(m_DebugLogCallbackHandle); } // Get the version of the DLL @@ -257,7 +257,8 @@ public class BSScene : PhysicsScene, IPhysicsParameters // m_log.DebugFormat("{0}: Initialize: Calling BulletSimAPI.Initialize.", LogHeader); WorldID = BulletSimAPI.Initialize(worldExtent, m_paramsHandle.AddrOfPinnedObject(), m_maxCollisionsPerFrame, m_collisionArrayPinnedHandle.AddrOfPinnedObject(), - m_maxUpdatesPerFrame, m_updateArrayPinnedHandle.AddrOfPinnedObject()); + m_maxUpdatesPerFrame, m_updateArrayPinnedHandle.AddrOfPinnedObject(), + m_DebugLogCallbackHandle); // Initialization to support the transition to a new API which puts most of the logic // into the C# code so it is easier to modify and add to. @@ -265,8 +266,6 @@ public class BSScene : PhysicsScene, IPhysicsParameters Constraints = new BSConstraintCollection(World); - // Note: choose one of the two following lines - // BulletSimAPI.CreateInitialGroundPlaneAndTerrain(WorldID); TerrainManager = new BSTerrainManager(this); TerrainManager.CreateInitialGroundPlaneAndTerrain(); @@ -378,7 +377,9 @@ public class BSScene : PhysicsScene, IPhysicsParameters BSCharacter actor = new BSCharacter(localID, avName, this, position, size, isFlying); lock (PhysObjects) PhysObjects.Add(localID, actor); - // Remove kludge someday + // TODO: Remove kludge someday. + // We must generate a collision for avatars whether they collide or not. + // This is required by OpenSim to update avatar animations, etc. lock (m_avatarsWithCollisions) m_avatarsWithCollisions.Add(actor); return actor; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs index 28c1940..733d9c2 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs @@ -44,8 +44,22 @@ public class BSTerrainManager { static string LogHeader = "[BULLETSIM TERRAIN MANAGER]"; + // These height values are fractional so the odd values will be + // noticable when debugging. + public const float HEIGHT_INITIALIZATION = 24.987f; + public const float HEIGHT_INITIAL_LASTHEIGHT = 24.876f; + public const float HEIGHT_GETHEIGHT_RET = 24.765f; + + // If the min and max height are equal, we reduce the min by this + // amount to make sure that a bounding box is built for the terrain. + public const float HEIGHT_EQUAL_FUDGE = 0.2f; + + public const float TERRAIN_COLLISION_MARGIN = 0.2f; + + // The scene that I am part of BSScene m_physicsScene; + // The ground plane created to keep thing from falling to infinity. private BulletBody m_groundPlane; // If doing mega-regions, if we're region zero we will be managing multiple @@ -53,6 +67,10 @@ public class BSTerrainManager private Dictionary m_terrains; private Dictionary m_heightMaps; + // True of the terrain has been modified. + // Used to force recalculation of terrain height after terrain has been modified + private bool m_terrainModified; + // If we are doing mega-regions, terrains are added from TERRAIN_ID to m_terrainCount. // This is incremented before assigning to new region so it is the last ID allocated. private uint m_terrainCount = BSScene.CHILDTERRAIN_ID - 1; @@ -69,6 +87,7 @@ public class BSTerrainManager m_physicsScene = physicsScene; m_terrains = new Dictionary(); m_heightMaps = new Dictionary(); + m_terrainModified = false; } // Create the initial instance of terrain and the underlying ground plane. @@ -80,17 +99,18 @@ public class BSTerrainManager public void CreateInitialGroundPlaneAndTerrain() { // The ground plane is here to catch things that are trying to drop to negative infinity + BulletShape groundPlaneShape = new BulletShape(BulletSimAPI.CreateGroundPlaneShape2(BSScene.GROUNDPLANE_ID, 1f, TERRAIN_COLLISION_MARGIN)); m_groundPlane = new BulletBody(BSScene.GROUNDPLANE_ID, - BulletSimAPI.CreateGroundPlaneBody2(BSScene.GROUNDPLANE_ID, 1f, 0.4f)); + BulletSimAPI.CreateBodyWithDefaultMotionState2(groundPlaneShape.Ptr, Vector3.Zero, Quaternion.Identity)); BulletSimAPI.AddObjectToWorld2(m_physicsScene.World.Ptr, m_groundPlane.Ptr); - Vector3 minTerrainCoords = new Vector3(0f, 0f, 24f); - Vector3 maxTerrainCoords = new Vector3(Constants.RegionSize, Constants.RegionSize, 25f); + Vector3 minTerrainCoords = new Vector3(0f, 0f, HEIGHT_INITIALIZATION - HEIGHT_EQUAL_FUDGE); + Vector3 maxTerrainCoords = new Vector3(Constants.RegionSize, Constants.RegionSize, HEIGHT_INITIALIZATION); int totalHeights = (int)maxTerrainCoords.X * (int)maxTerrainCoords.Y; float[] initialMap = new float[totalHeights]; for (int ii = 0; ii < totalHeights; ii++) { - initialMap[ii] = 25f; + initialMap[ii] = HEIGHT_INITIALIZATION; } CreateNewTerrainSegment(BSScene.TERRAIN_ID, initialMap, minTerrainCoords, maxTerrainCoords); } @@ -108,7 +128,7 @@ public class BSTerrainManager if (BulletSimAPI.RemoveObjectFromWorld2(m_physicsScene.World.Ptr, kvp.Value.Ptr)) { BulletSimAPI.DestroyObject2(m_physicsScene.World.Ptr, kvp.Value.Ptr); - BulletSimAPI.ReleaseHeightmapInfo2(m_heightMaps[kvp.Key].Ptr); + BulletSimAPI.ReleaseHeightMapInfo2(m_heightMaps[kvp.Key].Ptr); } } m_terrains.Clear(); @@ -128,30 +148,41 @@ public class BSTerrainManager int hSize = heightMap.Length; for (int ii = 0; ii < hSize; ii++) { - minZ = heightMap[ii] < minZ ? heightMap[ii] : minZ; - maxZ = heightMap[ii] > maxZ ? heightMap[ii] : maxZ; + float height = heightMap[ii]; + if (height < minZ) minZ = height; + if (height > maxZ) maxZ = height; } + // If the terrain is flat, make a difference so we get a bounding box + if (minZ == maxZ) + minZ -= HEIGHT_EQUAL_FUDGE; + minCoords.Z = minZ; maxCoords.Z = maxZ; - // If the terrain is flat, make a difference so we get a good bounding box - if (minZ == maxZ) - minZ -= 0.2f; Vector2 terrainRegionBase = new Vector2(minCoords.X, minCoords.Y); // Create the heightmap data structure in the unmanaged space - BulletHeightMapInfo mapInfo = new BulletHeightMapInfo( - BulletSimAPI.CreateHeightmap2(minCoords, maxCoords, heightMap), heightMap); + BulletHeightMapInfo mapInfo = new BulletHeightMapInfo(id, heightMap, + BulletSimAPI.CreateHeightMapInfo2(id, minCoords, maxCoords, heightMap, TERRAIN_COLLISION_MARGIN)); mapInfo.terrainRegionBase = terrainRegionBase; - mapInfo.maxRegionExtent = maxCoords; + mapInfo.minCoords = minCoords; + mapInfo.maxCoords = maxCoords; mapInfo.minZ = minZ; mapInfo.maxZ = maxZ; mapInfo.sizeX = maxCoords.X - minCoords.X; mapInfo.sizeY = maxCoords.Y - minCoords.Y; + Vector3 centerPos; + centerPos.X = minCoords.X + (mapInfo.sizeX / 2f); + centerPos.Y = minCoords.Y + (mapInfo.sizeY / 2f); + centerPos.Z = minZ + (maxZ - minZ) / 2f; + DetailLog("{0},BSScene.CreateNewTerrainSegment,call,minZ={1},maxZ={2},hMapPtr={3},minC={4},maxC={5}", BSScene.DetailLogZero, minZ, maxZ, mapInfo.Ptr, minCoords, maxCoords); - // Create the terrain body from that heightmap - BulletBody terrainBody = new BulletBody(id, BulletSimAPI.CreateTerrainBody2(id, mapInfo.Ptr, 0.01f)); + // Create the terrain shape from the mapInfo + BulletShape terrainShape = new BulletShape(BulletSimAPI.CreateTerrainShape2(mapInfo.Ptr)); + + BulletBody terrainBody = new BulletBody(id, BulletSimAPI.CreateBodyWithDefaultMotionState2(terrainShape.Ptr, + centerPos, Quaternion.Identity)); BulletSimAPI.SetFriction2(terrainBody.Ptr, m_physicsScene.Params.terrainFriction); BulletSimAPI.SetHitFraction2(terrainBody.Ptr, m_physicsScene.Params.terrainHitFraction); @@ -163,11 +194,12 @@ public class BSTerrainManager BulletSimAPI.AddObjectToWorld2(m_physicsScene.World.Ptr, terrainBody.Ptr); BulletSimAPI.UpdateSingleAabb2(m_physicsScene.World.Ptr, terrainBody.Ptr); - // Add the created terrain to the management set. If we are doing mega-regions, // the terrains of our children will be added. m_terrains.Add(terrainRegionBase, terrainBody); m_heightMaps.Add(terrainRegionBase, mapInfo); + + m_terrainModified = true; } public void SetTerrain(float[] heightMap) { @@ -191,34 +223,57 @@ public class BSTerrainManager { float minZ = float.MaxValue; float maxZ = float.MinValue; + Vector2 terrainRegionBase = new Vector2(tOffset.X, tOffset.Y); - // Copy heightMap local and compute some statistics. - // Not really sure if we need to do this deep copy but, given - // the magic that happens to make the closure for taint - // below, I don't want there to be any problem with sharing - // locations of there are multiple calls to this routine - // within one tick. int heightMapSize = heightMap.Length; - float[] localHeightMap = new float[heightMapSize]; for (int ii = 0; ii < heightMapSize; ii++) { float height = heightMap[ii]; if (height < minZ) minZ = height; if (height > maxZ) maxZ = height; - localHeightMap[ii] = height; } - Vector2 terrainRegionBase = new Vector2(tOffset.X, tOffset.Y); + // The shape of the terrain is from its base to its extents. + Vector3 minCoords, maxCoords; + minCoords = tOffset; + minCoords.Z = minZ; + maxCoords = tOffset; + maxCoords.X += Constants.RegionSize; + maxCoords.Y += Constants.RegionSize; + maxCoords.Z = maxZ; + + BulletBody terrainBody; BulletHeightMapInfo mapInfo; if (m_heightMaps.TryGetValue(terrainRegionBase, out mapInfo)) { + terrainBody = m_terrains[terrainRegionBase]; + // Copy heightMap local and compute some statistics. + for (int ii = 0; ii < heightMapSize; ii++) + { + mapInfo.heightMap[ii] = heightMap[ii]; + } + // If this is terrain we know about, it's easy to update - mapInfo.heightMap = localHeightMap; m_physicsScene.TaintedObject("BSScene.SetTerrain:UpdateExisting", delegate() { DetailLog("{0},SetTerrain:UpdateExisting,baseX={1},baseY={2},minZ={3},maxZ={4}", BSScene.DetailLogZero, tOffset.X, tOffset.Y, minZ, maxZ); - BulletSimAPI.UpdateHeightMap2(m_physicsScene.World.Ptr, mapInfo.Ptr, mapInfo.heightMap); + // Fill the existing height map info with the new location and size information + BulletSimAPI.FillHeightMapInfo2(mapInfo.Ptr, mapInfo.ID, minCoords, maxCoords, mapInfo.heightMap, TERRAIN_COLLISION_MARGIN); + + // Create a terrain shape based on the new info + BulletShape terrainShape = new BulletShape(BulletSimAPI.CreateTerrainShape2(mapInfo.Ptr)); + + // Swap the shape in the terrain body (this also deletes the old shape) + bool success = BulletSimAPI.ReplaceBodyShape2(m_physicsScene.World.Ptr, terrainBody.Ptr, terrainShape.Ptr); + + if (!success) + { + DetailLog("{0},SetTerrain:UpdateExisting,Failed", BSScene.DetailLogZero); + m_physicsScene.Logger.ErrorFormat("{0} Failed updating terrain heightmap. Region={1}", + LogHeader, m_physicsScene.RegionName); + + } }); } else @@ -226,11 +281,6 @@ public class BSTerrainManager // Our mega-prim child is giving us a new terrain to add to the phys world uint newTerrainID = ++m_terrainCount; - Vector3 minCoords = tOffset; - minCoords.Z = minZ; - Vector3 maxCoords = new Vector3(tOffset.X + Constants.RegionSize, - tOffset.Y + Constants.RegionSize, - maxZ); m_physicsScene.TaintedObject("BSScene.SetTerrain:NewTerrain", delegate() { DetailLog("{0},SetTerrain:NewTerrain,baseX={1},baseY={2}", BSScene.DetailLogZero, tOffset.X, tOffset.Y); @@ -240,9 +290,9 @@ public class BSTerrainManager } // Someday we will have complex terrain with caves and tunnels - // For the moment, it's flat and convex public float GetTerrainHeightAtXYZ(Vector3 loc) { + // For the moment, it's flat and convex return GetTerrainHeightAtXY(loc.X, loc.Y); } @@ -252,9 +302,19 @@ public class BSTerrainManager // the same size and that is the default. // Once the heightMapInfo is found, we have all the information to // compute the offset into the array. + private float lastHeightTX = 999999f; + private float lastHeightTY = 999999f; + private float lastHeight = HEIGHT_INITIAL_LASTHEIGHT; public float GetTerrainHeightAtXY(float tX, float tY) { - float ret = 30f; + // You'd be surprized at the number of times this routine is called + // with the same parameters as last time. + if (!m_terrainModified && lastHeightTX == tX && lastHeightTY == tY) + return lastHeight; + + lastHeightTX = tX; + lastHeightTY = tY; + float ret = HEIGHT_GETHEIGHT_RET; int offsetX = ((int)(tX / (int)Constants.RegionSize)) * (int)Constants.RegionSize; int offsetY = ((int)(tY / (int)Constants.RegionSize)) * (int)Constants.RegionSize; @@ -265,15 +325,20 @@ public class BSTerrainManager { float regionX = tX - offsetX; float regionY = tY - offsetY; - regionX = regionX > mapInfo.sizeX ? 0 : regionX; - regionY = regionY > mapInfo.sizeY ? 0 : regionY; - ret = mapInfo.heightMap[(int)(regionX * mapInfo.sizeX + regionY)]; + if (regionX > mapInfo.sizeX) regionX = 0; + if (regionY > mapInfo.sizeY) regionY = 0; + int mapIndex = (int)regionY * (int)mapInfo.sizeY + (int)regionX; + ret = mapInfo.heightMap[mapIndex]; + m_terrainModified = false; + DetailLog("{0},BSTerrainManager.GetTerrainHeightAtXY,bX={1},baseY={2},szX={3},szY={4},regX={5},regY={6},index={7},ht={8}", + BSScene.DetailLogZero, offsetX, offsetY, mapInfo.sizeX, mapInfo.sizeY, regionX, regionY, mapIndex, ret); } else { m_physicsScene.Logger.ErrorFormat("{0} GetTerrainHeightAtXY: terrain not found: x={1}, y={2}", LogHeader, tX, tY); } + lastHeight = ret; return ret; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs index 3b319fb..804d2ea 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs @@ -38,13 +38,19 @@ namespace OpenSim.Region.Physics.BulletSPlugin { // The physics engine controller class created at initialization public struct BulletSim { - public BulletSim(uint id, BSScene bss, IntPtr xx) { ID = id; scene = bss; Ptr = xx; } - public uint ID; + public BulletSim(uint worldId, BSScene bss, IntPtr xx) { worldID = worldId; scene = bss; Ptr = xx; } + public uint worldID; // The scene is only in here so very low level routines have a handle to print debug/error messages public BSScene scene; public IntPtr Ptr; } +public struct BulletShape +{ + public BulletShape(IntPtr xx) { Ptr = xx; } + public IntPtr Ptr; +} + // An allocated Bullet btRigidBody public struct BulletBody { @@ -66,18 +72,22 @@ public struct BulletConstraint // than making copies. public class BulletHeightMapInfo { - public BulletHeightMapInfo(IntPtr xx, float[] hm) { + public BulletHeightMapInfo(uint id, float[] hm, IntPtr xx) { + ID = id; Ptr = xx; heightMap = hm; terrainRegionBase = new Vector2(0f, 0f); - maxRegionExtent = new Vector3(100f, 100f, 25f); + minCoords = new Vector3(100f, 100f, 25f); + maxCoords = new Vector3(101f, 101f, 26f); minZ = maxZ = 0f; sizeX = sizeY = 256f; } + public uint ID; public IntPtr Ptr; public float[] heightMap; public Vector2 terrainRegionBase; - public Vector3 maxRegionExtent; + public Vector3 minCoords; + public Vector3 maxCoords; public float sizeX, sizeY; public float minZ, maxZ; } @@ -248,6 +258,10 @@ public enum ConstraintParamAxis : int // =============================================================================== static class BulletSimAPI { +// Link back to the managed code for outputting log messages +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +public delegate void DebugLogCallback([MarshalAs(UnmanagedType.LPStr)]string msg); + [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.LPStr)] public static extern string GetVersion(); @@ -255,7 +269,8 @@ public static extern string GetVersion(); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern uint Initialize(Vector3 maxPosition, IntPtr parms, int maxCollisions, IntPtr collisionArray, - int maxUpdates, IntPtr updateArray); + int maxUpdates, IntPtr updateArray, + DebugLogCallback logRoutine); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern void CreateInitialGroundPlaneAndTerrain(uint worldID); @@ -372,8 +387,6 @@ public static extern Vector3 RecoverFromPenetration(uint worldID, uint id); public static extern void DumpBulletStatistics(); // Log a debug message -[UnmanagedFunctionPointer(CallingConvention.Cdecl)] -public delegate void DebugLogCallback([MarshalAs(UnmanagedType.LPStr)]string msg); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern void SetDebugLogCallback(DebugLogCallback callback); @@ -407,7 +420,7 @@ public static extern IntPtr Initialize2(Vector3 maxPosition, IntPtr parms, public static extern bool UpdateParameter2(IntPtr world, uint localID, String parm, float value); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern void SetHeightmap2(IntPtr world, float[] heightmap); +public static extern void SetHeightMap2(IntPtr world, float[] heightmap); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern void Shutdown2(IntPtr sim); @@ -442,25 +455,31 @@ public static extern IntPtr BuildNativeShape2(IntPtr world, [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern bool DeleteCollisionShape2(IntPtr world, IntPtr shape); +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern IntPtr CreateBodyFromShape2(IntPtr sim, IntPtr shape, Vector3 pos, Quaternion rot); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern IntPtr CreateBodyWithDefaultMotionState2(IntPtr shape, Vector3 pos, Quaternion rot); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern bool ReplaceBodyShape2(IntPtr sim, IntPtr obj, IntPtr shape); // ===================================================================================== [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern IntPtr CreateGroundPlaneBody2(uint id, float height, float collisionMargin); +public static extern IntPtr CreateHeightMapInfo2(uint id, Vector3 minCoords, Vector3 maxCoords, + [MarshalAs(UnmanagedType.LPArray)] float[] heightMap, float collisionMargin); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern IntPtr CreateTerrainBody2(uint id, - IntPtr heightMapInfo, - float collisionMargin); +public static extern IntPtr FillHeightMapInfo2(IntPtr mapInfo, uint id, Vector3 minCoords, Vector3 maxCoords, + [MarshalAs(UnmanagedType.LPArray)] float[] heightMap, float collisionMargin); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern IntPtr CreateHeightmap2(Vector3 minCoords, Vector3 maxCoords, - [MarshalAs(UnmanagedType.LPArray)] float[] heightMap); +public static extern bool ReleaseHeightMapInfo2(IntPtr heightMapInfo); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool ReleaseHeightmapInfo2(IntPtr heightMapInfo); +public static extern IntPtr CreateGroundPlaneShape2(uint id, float height, float collisionMargin); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern void UpdateHeightMap2(IntPtr world, IntPtr heightMapInfo, - [MarshalAs(UnmanagedType.LPArray)] float[] heightMap); +public static extern IntPtr CreateTerrainShape2(IntPtr mapInfo); // ===================================================================================== [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -- cgit v1.1 From ffdc7987207de279116a077e2042ed3a1f381a5f Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Fri, 31 Aug 2012 11:33:36 -0700 Subject: BulletSim: Update BulletSimAPI to match the DLL interface. Major rework of terrain management which finally makes mega-regions work. Update heightmap of terrain by rebuilding the terrain's body and shape. There is a problem with just replacing the shape so this workaround will do for the moment but it will need to be resolved for mesh and hull switching. --- .../Region/Physics/BulletSPlugin/BSCharacter.cs | 2 +- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 2 +- .../Physics/BulletSPlugin/BSTerrainManager.cs | 356 +++++++++++++-------- .../Region/Physics/BulletSPlugin/BulletSimAPI.cs | 8 +- 4 files changed, 231 insertions(+), 137 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index fa21233..747ae71 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -228,7 +228,7 @@ public class BSCharacter : BSPhysObject float terrainHeight = Scene.TerrainManager.GetTerrainHeightAtXYZ(_position); if (Position.Z < terrainHeight) { - DetailLog("{0},BSCharacter.PositionAdjustUnderGround,call,pos={1},terrain={2}", LocalID, _position, terrainHeight); + DetailLog("{0},BSCharacter.PositionAdjustUnderGround,call,pos={1},terrain={2}", LocalID, _position, terrainHeight); _position.Z = terrainHeight + 2.0f; ret = true; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index 2f55ba4..4a468af 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -1070,7 +1070,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters (s) => { return s.m_params[0].terrainRestitution; }, (s,p,l,v) => { s.m_params[0].terrainRestitution = v; s.TaintedUpdateParameter(p,l,v); } ), new ParameterDefn("AvatarFriction", "Factor to reduce movement against an avatar. Changed on avatar recreation.", - 0.5f, + 0.2f, (s,cf,p,v) => { s.m_params[0].avatarFriction = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].avatarFriction; }, (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].avatarFriction, p, l, v); } ), diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs index 733d9c2..ab45f8f 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs @@ -54,17 +54,19 @@ public class BSTerrainManager // amount to make sure that a bounding box is built for the terrain. public const float HEIGHT_EQUAL_FUDGE = 0.2f; - public const float TERRAIN_COLLISION_MARGIN = 0.2f; + public const float TERRAIN_COLLISION_MARGIN = 0.0f; + + // Until the whole simulator is changed to pass us the region size, we rely on constants. + public Vector3 DefaultRegionSize = new Vector3(Constants.RegionSize, Constants.RegionSize, 0f); // The scene that I am part of - BSScene m_physicsScene; + private BSScene m_physicsScene; // The ground plane created to keep thing from falling to infinity. private BulletBody m_groundPlane; // If doing mega-regions, if we're region zero we will be managing multiple // region terrains since region zero does the physics for the whole mega-region. - private Dictionary m_terrains; private Dictionary m_heightMaps; // True of the terrain has been modified. @@ -78,16 +80,22 @@ public class BSTerrainManager // If doing mega-regions, this holds our offset from region zero of // the mega-regions. "parentScene" points to the PhysicsScene of region zero. - private Vector3 m_worldOffset = Vector3.Zero; - public Vector2 WorldExtents = new Vector2((int)Constants.RegionSize, (int)Constants.RegionSize); - private PhysicsScene m_parentScene = null; + private Vector3 m_worldOffset; + // If the parent region (region 0), this is the extent of the combined regions + // relative to the origin of region zero + private Vector3 m_worldMax; + private PhysicsScene m_parentScene; public BSTerrainManager(BSScene physicsScene) { m_physicsScene = physicsScene; - m_terrains = new Dictionary(); m_heightMaps = new Dictionary(); m_terrainModified = false; + + // Assume one region of default size + m_worldOffset = Vector3.Zero; + m_worldMax = new Vector3(DefaultRegionSize.X, DefaultRegionSize.Y, 4096f); + m_parentScene = null; } // Create the initial instance of terrain and the underlying ground plane. @@ -95,7 +103,7 @@ public class BSTerrainManager // by the managed code. // The terrains and the groundPlane are not added to the list of PhysObjects. // This is called from the initialization routine so we presume it is - // safe to call Bullet in real time. We hope no one is moving around prim yet. + // safe to call Bullet in real time. We hope no one is moving prims around yet. public void CreateInitialGroundPlaneAndTerrain() { // The ground plane is here to catch things that are trying to drop to negative infinity @@ -105,125 +113,91 @@ public class BSTerrainManager BulletSimAPI.AddObjectToWorld2(m_physicsScene.World.Ptr, m_groundPlane.Ptr); Vector3 minTerrainCoords = new Vector3(0f, 0f, HEIGHT_INITIALIZATION - HEIGHT_EQUAL_FUDGE); - Vector3 maxTerrainCoords = new Vector3(Constants.RegionSize, Constants.RegionSize, HEIGHT_INITIALIZATION); + Vector3 maxTerrainCoords = new Vector3(DefaultRegionSize.X, DefaultRegionSize.Y, HEIGHT_INITIALIZATION); int totalHeights = (int)maxTerrainCoords.X * (int)maxTerrainCoords.Y; float[] initialMap = new float[totalHeights]; for (int ii = 0; ii < totalHeights; ii++) { initialMap[ii] = HEIGHT_INITIALIZATION; } - CreateNewTerrainSegment(BSScene.TERRAIN_ID, initialMap, minTerrainCoords, maxTerrainCoords); + UpdateOrCreateTerrain(BSScene.TERRAIN_ID, initialMap, minTerrainCoords, maxTerrainCoords, true); } + // Release all the terrain structures we might have allocated public void ReleaseGroundPlaneAndTerrain() { - if (BulletSimAPI.RemoveObjectFromWorld2(m_physicsScene.World.Ptr, m_groundPlane.Ptr)) + if (m_groundPlane.Ptr != IntPtr.Zero) { - BulletSimAPI.DestroyObject2(m_physicsScene.World.Ptr, m_groundPlane.Ptr); - } - m_groundPlane.Ptr = IntPtr.Zero; - - foreach (KeyValuePair kvp in m_terrains) - { - if (BulletSimAPI.RemoveObjectFromWorld2(m_physicsScene.World.Ptr, kvp.Value.Ptr)) + if (BulletSimAPI.RemoveObjectFromWorld2(m_physicsScene.World.Ptr, m_groundPlane.Ptr)) { - BulletSimAPI.DestroyObject2(m_physicsScene.World.Ptr, kvp.Value.Ptr); - BulletSimAPI.ReleaseHeightMapInfo2(m_heightMaps[kvp.Key].Ptr); + BulletSimAPI.DestroyObject2(m_physicsScene.World.Ptr, m_groundPlane.Ptr); } + m_groundPlane.Ptr = IntPtr.Zero; } - m_terrains.Clear(); - m_heightMaps.Clear(); + + ReleaseTerrain(); } - // Create a new terrain description. This is used for mega-regions where - // the children of region zero give region zero all of the terrain - // segments since region zero does all the physics for the mega-region. - // Call at taint time!! - public void CreateNewTerrainSegment(uint id, float[] heightMap, Vector3 minCoords, Vector3 maxCoords) + // Release all the terrain we have allocated + public void ReleaseTerrain() { - // The Z coordinates are recalculated to be the min and max height of the terrain - // itself. The caller may have passed us the real region extent. - float minZ = float.MaxValue; - float maxZ = float.MinValue; - int hSize = heightMap.Length; - for (int ii = 0; ii < hSize; ii++) + foreach (KeyValuePair kvp in m_heightMaps) { - float height = heightMap[ii]; - if (height < minZ) minZ = height; - if (height > maxZ) maxZ = height; + if (BulletSimAPI.RemoveObjectFromWorld2(m_physicsScene.World.Ptr, kvp.Value.terrainBody.Ptr)) + { + BulletSimAPI.DestroyObject2(m_physicsScene.World.Ptr, kvp.Value.terrainBody.Ptr); + BulletSimAPI.ReleaseHeightMapInfo2(kvp.Value.Ptr); + } } - // If the terrain is flat, make a difference so we get a bounding box - if (minZ == maxZ) - minZ -= HEIGHT_EQUAL_FUDGE; - - minCoords.Z = minZ; - maxCoords.Z = maxZ; - Vector2 terrainRegionBase = new Vector2(minCoords.X, minCoords.Y); - - // Create the heightmap data structure in the unmanaged space - BulletHeightMapInfo mapInfo = new BulletHeightMapInfo(id, heightMap, - BulletSimAPI.CreateHeightMapInfo2(id, minCoords, maxCoords, heightMap, TERRAIN_COLLISION_MARGIN)); - mapInfo.terrainRegionBase = terrainRegionBase; - mapInfo.minCoords = minCoords; - mapInfo.maxCoords = maxCoords; - mapInfo.minZ = minZ; - mapInfo.maxZ = maxZ; - mapInfo.sizeX = maxCoords.X - minCoords.X; - mapInfo.sizeY = maxCoords.Y - minCoords.Y; - - Vector3 centerPos; - centerPos.X = minCoords.X + (mapInfo.sizeX / 2f); - centerPos.Y = minCoords.Y + (mapInfo.sizeY / 2f); - centerPos.Z = minZ + (maxZ - minZ) / 2f; - - DetailLog("{0},BSScene.CreateNewTerrainSegment,call,minZ={1},maxZ={2},hMapPtr={3},minC={4},maxC={5}", - BSScene.DetailLogZero, minZ, maxZ, mapInfo.Ptr, minCoords, maxCoords); - // Create the terrain shape from the mapInfo - BulletShape terrainShape = new BulletShape(BulletSimAPI.CreateTerrainShape2(mapInfo.Ptr)); - - BulletBody terrainBody = new BulletBody(id, BulletSimAPI.CreateBodyWithDefaultMotionState2(terrainShape.Ptr, - centerPos, Quaternion.Identity)); - - BulletSimAPI.SetFriction2(terrainBody.Ptr, m_physicsScene.Params.terrainFriction); - BulletSimAPI.SetHitFraction2(terrainBody.Ptr, m_physicsScene.Params.terrainHitFraction); - BulletSimAPI.SetRestitution2(terrainBody.Ptr, m_physicsScene.Params.terrainRestitution); - BulletSimAPI.SetCollisionFlags2(terrainBody.Ptr, CollisionFlags.CF_STATIC_OBJECT); - BulletSimAPI.Activate2(terrainBody.Ptr, true); - - // Add the new terrain to the dynamics world - BulletSimAPI.AddObjectToWorld2(m_physicsScene.World.Ptr, terrainBody.Ptr); - BulletSimAPI.UpdateSingleAabb2(m_physicsScene.World.Ptr, terrainBody.Ptr); - - // Add the created terrain to the management set. If we are doing mega-regions, - // the terrains of our children will be added. - m_terrains.Add(terrainRegionBase, terrainBody); - m_heightMaps.Add(terrainRegionBase, mapInfo); - - m_terrainModified = true; + m_heightMaps.Clear(); } + // The simulator wants to set a new heightmap for the terrain. public void SetTerrain(float[] heightMap) { if (m_worldOffset != Vector3.Zero && m_parentScene != null) { + // If a child of a mega-region, we shouldn't have any terrain allocated for us + ReleaseGroundPlaneAndTerrain(); // If doing the mega-prim stuff and we are the child of the zero region, - // the terrain is really added to our parent + // the terrain is added to our parent if (m_parentScene is BSScene) { - ((BSScene)m_parentScene).TerrainManager.SetTerrain(heightMap, m_worldOffset); + DetailLog("{0},SetTerrain.ToParent,offset={1},worldMax={2}", + BSScene.DetailLogZero, m_worldOffset, m_worldMax); + ((BSScene)m_parentScene).TerrainManager.UpdateOrCreateTerrain(BSScene.CHILDTERRAIN_ID, + heightMap, m_worldOffset, m_worldOffset+DefaultRegionSize, false); } } else { - // if not doing the mega-prim thing, just change the terrain - SetTerrain(heightMap, m_worldOffset); + // If not doing the mega-prim thing, just change the terrain + DetailLog("{0},SetTerrain.Existing", BSScene.DetailLogZero); + + UpdateOrCreateTerrain(BSScene.TERRAIN_ID, heightMap, m_worldOffset, m_worldOffset+DefaultRegionSize, false); } } - private void SetTerrain(float[] heightMap, Vector3 tOffset) + // If called with no mapInfo for the terrain, this will create a new mapInfo and terrain + // based on the passed information. The 'id' should be either the terrain id or + // BSScene.CHILDTERRAIN_ID. If the latter, a new child terrain ID will be allocated and used. + // The latter feature is for creating child terrains for mega-regions. + // If called with a mapInfo in m_heightMaps but the terrain has no body yet (mapInfo.terrainBody.Ptr == 0) + // then a new body and shape is created and the mapInfo is filled. + // This call is used for doing the initial terrain creation. + // If called with a mapInfo in m_heightMaps and there is an existing terrain body, a new + // terrain shape is created and added to the body. + // This call is most often used to update the heightMap and parameters of the terrain. + // The 'doNow' boolean says whether to do all the unmanaged activities right now (like when + // calling this routine from initialization or taint-time routines) or whether to delay + // all the unmanaged activities to taint-time. + private void UpdateOrCreateTerrain(uint id, float[] heightMap, Vector3 minCoords, Vector3 maxCoords, bool doNow) { + DetailLog("{0},BSTerrainManager.UpdateOrCreateTerrain,call,minC={1},maxC={2},doNow={3}", + BSScene.DetailLogZero, minCoords, maxCoords, doNow); + float minZ = float.MaxValue; float maxZ = float.MinValue; - Vector2 terrainRegionBase = new Vector2(tOffset.X, tOffset.Y); + Vector2 terrainRegionBase = new Vector2(minCoords.X, minCoords.Y); int heightMapSize = heightMap.Length; for (int ii = 0; ii < heightMapSize; ii++) @@ -234,58 +208,162 @@ public class BSTerrainManager } // The shape of the terrain is from its base to its extents. - Vector3 minCoords, maxCoords; - minCoords = tOffset; minCoords.Z = minZ; - maxCoords = tOffset; - maxCoords.X += Constants.RegionSize; - maxCoords.Y += Constants.RegionSize; maxCoords.Z = maxZ; - BulletBody terrainBody; BulletHeightMapInfo mapInfo; if (m_heightMaps.TryGetValue(terrainRegionBase, out mapInfo)) { - terrainBody = m_terrains[terrainRegionBase]; - // Copy heightMap local and compute some statistics. - for (int ii = 0; ii < heightMapSize; ii++) - { - mapInfo.heightMap[ii] = heightMap[ii]; - } - // If this is terrain we know about, it's easy to update - m_physicsScene.TaintedObject("BSScene.SetTerrain:UpdateExisting", delegate() + + mapInfo.heightMap = heightMap; + mapInfo.minCoords = minCoords; + mapInfo.maxCoords = maxCoords; + mapInfo.minZ = minZ; + mapInfo.maxZ = maxZ; + mapInfo.sizeX = maxCoords.X - minCoords.X; + mapInfo.sizeY = maxCoords.Y - minCoords.Y; + DetailLog("{0},UpdateOrCreateTerrain:UpdateExisting,call,terrainBase={1},minC={2}, maxC={3}, szX={4}, szY={5}", + BSScene.DetailLogZero, terrainRegionBase, mapInfo.minCoords, mapInfo.maxCoords, mapInfo.sizeX, mapInfo.sizeY); + + BSScene.TaintCallback rebuildOperation = delegate() { - DetailLog("{0},SetTerrain:UpdateExisting,baseX={1},baseY={2},minZ={3},maxZ={4}", - BSScene.DetailLogZero, tOffset.X, tOffset.Y, minZ, maxZ); - // Fill the existing height map info with the new location and size information - BulletSimAPI.FillHeightMapInfo2(mapInfo.Ptr, mapInfo.ID, minCoords, maxCoords, mapInfo.heightMap, TERRAIN_COLLISION_MARGIN); + if (m_parentScene != null) + { + // It's possible that Combine() was called after this code was queued. + // If we are a child of combined regions, we don't create any terrain for us. + DetailLog("{0},UpdateOrCreateTerrain:AmACombineChild,taint", BSScene.DetailLogZero); - // Create a terrain shape based on the new info - BulletShape terrainShape = new BulletShape(BulletSimAPI.CreateTerrainShape2(mapInfo.Ptr)); + // Get rid of any terrain that may have been allocated for us. + ReleaseGroundPlaneAndTerrain(); - // Swap the shape in the terrain body (this also deletes the old shape) - bool success = BulletSimAPI.ReplaceBodyShape2(m_physicsScene.World.Ptr, terrainBody.Ptr, terrainShape.Ptr); + // I hate doing this, but just bail + return; + } - if (!success) + if (mapInfo.terrainBody.Ptr != IntPtr.Zero) { - DetailLog("{0},SetTerrain:UpdateExisting,Failed", BSScene.DetailLogZero); - m_physicsScene.Logger.ErrorFormat("{0} Failed updating terrain heightmap. Region={1}", - LogHeader, m_physicsScene.RegionName); - + // Updating an existing terrain. + DetailLog("{0},UpdateOrCreateTerrain:UpdateExisting,taint,terrainBase={1},minC={2}, maxC={3}, szX={4}, szY={5}", + BSScene.DetailLogZero, terrainRegionBase, mapInfo.minCoords, mapInfo.maxCoords, mapInfo.sizeX, mapInfo.sizeY); + + // Remove from the dynamics world because we're going to mangle this object + BulletSimAPI.RemoveObjectFromWorld2(m_physicsScene.World.Ptr, mapInfo.terrainBody.Ptr); + + // Get rid of the old terrain + BulletSimAPI.DestroyObject2(m_physicsScene.World.Ptr, mapInfo.terrainBody.Ptr); + BulletSimAPI.ReleaseHeightMapInfo2(mapInfo.Ptr); + mapInfo.Ptr = IntPtr.Zero; + + /* + // NOTE: This routine is half here because I can't get the terrain shape replacement + // to work. In the short term, the above three lines completely delete the old + // terrain and the code below recreates one from scratch. + // Hopefully the Bullet community will help me out on this one. + + // First, release the old collision shape (there is only one terrain) + BulletSimAPI.DeleteCollisionShape2(m_physicsScene.World.Ptr, mapInfo.terrainShape.Ptr); + + // Fill the existing height map info with the new location and size information + BulletSimAPI.FillHeightMapInfo2(m_physicsScene.World.Ptr, mapInfo.Ptr, mapInfo.ID, + mapInfo.minCoords, mapInfo.maxCoords, mapInfo.heightMap, TERRAIN_COLLISION_MARGIN); + + // Create a terrain shape based on the new info + mapInfo.terrainShape = new BulletShape(BulletSimAPI.CreateTerrainShape2(mapInfo.Ptr)); + + // Stuff the shape into the existing terrain body + BulletSimAPI.SetBodyShape2(m_physicsScene.World.Ptr, mapInfo.terrainBody.Ptr, mapInfo.terrainShape.Ptr); + */ } - }); + // else + { + // Creating a new terrain. + DetailLog("{0},UpdateOrCreateTerrain:CreateNewTerrain,taint,baseX={1},baseY={2},minZ={3},maxZ={4}", + BSScene.DetailLogZero, mapInfo.minCoords.X, mapInfo.minCoords.Y, minZ, maxZ); + + mapInfo.ID = id; + mapInfo.Ptr = BulletSimAPI.CreateHeightMapInfo2(m_physicsScene.World.Ptr, mapInfo.ID, + mapInfo.minCoords, mapInfo.maxCoords, mapInfo.heightMap, TERRAIN_COLLISION_MARGIN); + + // The terrain object initial position is at the center of the object + Vector3 centerPos; + centerPos.X = minCoords.X + (mapInfo.sizeX / 2f); + centerPos.Y = minCoords.Y + (mapInfo.sizeY / 2f); + centerPos.Z = minZ + ((maxZ - minZ) / 2f); + + // Create the terrain shape from the mapInfo + mapInfo.terrainShape = new BulletShape(BulletSimAPI.CreateTerrainShape2(mapInfo.Ptr)); + + mapInfo.terrainBody = new BulletBody(mapInfo.ID, + BulletSimAPI.CreateBodyWithDefaultMotionState2(mapInfo.terrainShape.Ptr, + centerPos, Quaternion.Identity)); + } + + // Make sure the entry is in the heightmap table + m_heightMaps[terrainRegionBase] = mapInfo; + + // Set current terrain attributes + BulletSimAPI.SetFriction2(mapInfo.terrainBody.Ptr, m_physicsScene.Params.terrainFriction); + BulletSimAPI.SetHitFraction2(mapInfo.terrainBody.Ptr, m_physicsScene.Params.terrainHitFraction); + BulletSimAPI.SetRestitution2(mapInfo.terrainBody.Ptr, m_physicsScene.Params.terrainRestitution); + BulletSimAPI.SetCollisionFlags2(mapInfo.terrainBody.Ptr, CollisionFlags.CF_STATIC_OBJECT); + + BulletSimAPI.SetMassProps2(mapInfo.terrainBody.Ptr, 0f, Vector3.Zero); + BulletSimAPI.UpdateInertiaTensor2(mapInfo.terrainBody.Ptr); + + // Return the new terrain to the world of physical objects + BulletSimAPI.AddObjectToWorld2(m_physicsScene.World.Ptr, mapInfo.terrainBody.Ptr); + + // redo its bounding box now that it is in the world + BulletSimAPI.UpdateSingleAabb2(m_physicsScene.World.Ptr, mapInfo.terrainBody.Ptr); + + // Make sure the new shape is processed. + BulletSimAPI.Activate2(mapInfo.terrainBody.Ptr, true); + }; + + // There is the option to do the changes now (we're already in 'taint time'), or + // to do the Bullet operations later. + if (doNow) + rebuildOperation(); + else + m_physicsScene.TaintedObject("BSScene.UpdateOrCreateTerrain:UpdateExisting", rebuildOperation); } else { - // Our mega-prim child is giving us a new terrain to add to the phys world - uint newTerrainID = ++m_terrainCount; + // We don't know about this terrain so either we are creating a new terrain or + // our mega-prim child is giving us a new terrain to add to the phys world - m_physicsScene.TaintedObject("BSScene.SetTerrain:NewTerrain", delegate() + // if this is a child terrain, calculate a unique terrain id + uint newTerrainID = id; + if (newTerrainID >= BSScene.CHILDTERRAIN_ID) + newTerrainID = ++m_terrainCount; + + float[] heightMapX = heightMap; + Vector3 minCoordsX = minCoords; + Vector3 maxCoordsX = maxCoords; + + DetailLog("{0},UpdateOrCreateTerrain:NewTerrain,call,id={1}, minC={2}, maxC={3}", + BSScene.DetailLogZero, newTerrainID, minCoords, minCoords); + + // Code that must happen at taint-time + BSScene.TaintCallback createOperation = delegate() { - DetailLog("{0},SetTerrain:NewTerrain,baseX={1},baseY={2}", BSScene.DetailLogZero, tOffset.X, tOffset.Y); - CreateNewTerrainSegment(newTerrainID, heightMap, minCoords, maxCoords); - }); + DetailLog("{0},UpdateOrCreateTerrain:NewTerrain,taint,baseX={1},baseY={2}", BSScene.DetailLogZero, minCoords.X, minCoords.Y); + // Create a new mapInfo that will be filled with the new info + mapInfo = new BulletHeightMapInfo(id, heightMapX, + BulletSimAPI.CreateHeightMapInfo2(m_physicsScene.World.Ptr, newTerrainID, + minCoordsX, maxCoordsX, heightMapX, TERRAIN_COLLISION_MARGIN)); + // Put the unfilled heightmap info into the collection of same + m_heightMaps.Add(terrainRegionBase, mapInfo); + // Build the terrain + UpdateOrCreateTerrain(newTerrainID, heightMap, minCoords, maxCoords, true); + }; + + // If already in taint-time, just call Bullet. Otherwise queue the operations for the safe time. + if (doNow) + createOperation(); + else + m_physicsScene.TaintedObject("BSScene.UpdateOrCreateTerrain:NewTerrain", createOperation); } } @@ -316,8 +394,8 @@ public class BSTerrainManager lastHeightTY = tY; float ret = HEIGHT_GETHEIGHT_RET; - int offsetX = ((int)(tX / (int)Constants.RegionSize)) * (int)Constants.RegionSize; - int offsetY = ((int)(tY / (int)Constants.RegionSize)) * (int)Constants.RegionSize; + int offsetX = ((int)(tX / (int)DefaultRegionSize.X)) * (int)DefaultRegionSize.X; + int offsetY = ((int)(tY / (int)DefaultRegionSize.Y)) * (int)DefaultRegionSize.Y; Vector2 terrainBaseXY = new Vector2(offsetX, offsetY); BulletHeightMapInfo mapInfo; @@ -335,8 +413,8 @@ public class BSTerrainManager } else { - m_physicsScene.Logger.ErrorFormat("{0} GetTerrainHeightAtXY: terrain not found: x={1}, y={2}", - LogHeader, tX, tY); + m_physicsScene.Logger.ErrorFormat("{0} GetTerrainHeightAtXY: terrain not found: region={1}, x={2}, y={3}", + LogHeader, m_physicsScene.RegionName, tX, tY); } lastHeight = ret; return ret; @@ -347,20 +425,34 @@ public class BSTerrainManager { return true; } - // This call says I am a child to region zero in a mega-region. 'pScene' is that - // of region zero, 'offset' is my offset from regions zero's origin, and - // 'extents' is the largest XY that is handled in my region. + + // This routine is called two ways: + // One with 'offset' and 'pScene' zero and null but 'extents' giving the maximum + // extent of the combined regions. This is to inform the parent of the size + // of the combined regions. + // and one with 'offset' as the offset of the child region to the base region, + // 'pScene' pointing to the parent and 'extents' of zero. This informs the + // child of its relative base and new parent. public void Combine(PhysicsScene pScene, Vector3 offset, Vector3 extents) { m_worldOffset = offset; - WorldExtents = new Vector2(extents.X, extents.Y); + m_worldMax = extents; m_parentScene = pScene; + if (pScene != null) + { + // We are a child. + // We want m_worldMax to be the highest coordinate of our piece of terrain. + m_worldMax = offset + DefaultRegionSize; + } + DetailLog("{0},BSTerrainManager.Combine,offset={1},extents={2},wOffset={3},wMax={4}", + BSScene.DetailLogZero, offset, extents, m_worldOffset, m_worldMax); } // Unhook all the combining that I know about. public void UnCombine(PhysicsScene pScene) { // Just like ODE, for the moment a NOP + DetailLog("{0},BSTerrainManager.UnCombine", BSScene.DetailLogZero); } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs index 804d2ea..a0bad3a 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs @@ -90,6 +90,8 @@ public class BulletHeightMapInfo public Vector3 maxCoords; public float sizeX, sizeY; public float minZ, maxZ; + public BulletShape terrainShape; + public BulletBody terrainBody; } // =============================================================================== @@ -462,14 +464,14 @@ public static extern IntPtr CreateBodyFromShape2(IntPtr sim, IntPtr shape, Vecto public static extern IntPtr CreateBodyWithDefaultMotionState2(IntPtr shape, Vector3 pos, Quaternion rot); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool ReplaceBodyShape2(IntPtr sim, IntPtr obj, IntPtr shape); +public static extern bool SetBodyShape2(IntPtr sim, IntPtr obj, IntPtr shape); // ===================================================================================== [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern IntPtr CreateHeightMapInfo2(uint id, Vector3 minCoords, Vector3 maxCoords, +public static extern IntPtr CreateHeightMapInfo2(IntPtr sim, uint id, Vector3 minCoords, Vector3 maxCoords, [MarshalAs(UnmanagedType.LPArray)] float[] heightMap, float collisionMargin); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern IntPtr FillHeightMapInfo2(IntPtr mapInfo, uint id, Vector3 minCoords, Vector3 maxCoords, +public static extern IntPtr FillHeightMapInfo2(IntPtr sim, IntPtr mapInfo, uint id, Vector3 minCoords, Vector3 maxCoords, [MarshalAs(UnmanagedType.LPArray)] float[] heightMap, float collisionMargin); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -- cgit v1.1 From 76dc29dc379036aa44f1ef78782f7ac94760a80f Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Fri, 31 Aug 2012 13:32:22 -0700 Subject: BulletSim: Modify collision flag calls to return the current flags. Track current collision flags in BSPrim. Add BulletSimAPI calls for saving and restoring rigidBodies using construction information structure. --- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 9 +++++---- OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs | 16 +++++++++++++--- 2 files changed, 18 insertions(+), 7 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 6bfce5c..6fcd416 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -94,6 +94,7 @@ public sealed class BSPrim : BSPhysObject private int _nextCollisionOkTime = 0; long _collidingStep; long _collidingGroundStep; + CollisionFlags m_currentCollisionFlags = 0; public override BulletBody Body { get; set; } @@ -143,6 +144,7 @@ public sealed class BSPrim : BSPhysObject // At the moment, we're still letting BulletSim manage the creation and destruction // of the object. Someday we'll move that into the C# code. Body = new BulletBody(LocalID, BulletSimAPI.GetBodyHandle2(_scene.World.Ptr, LocalID)); + m_currentCollisionFlags = BulletSimAPI.GetCollisionFlags2(Body.Ptr); }); } @@ -483,8 +485,7 @@ public sealed class BSPrim : BSPhysObject // recompute any linkset parameters Linkset.Refresh(this); - CollisionFlags cf = BulletSimAPI.GetCollisionFlags2(Body.Ptr); - DetailLog("{0},BSPrim.SetObjectDynamic,taint,static={1},solid={2},mass={3}, cf={4}", LocalID, IsStatic, IsSolid, mass, cf); + DetailLog("{0},BSPrim.SetObjectDynamic,taint,static={1},solid={2},mass={3}, cf={4}", LocalID, IsStatic, IsSolid, mass, m_currentCollisionFlags); } // prims don't fly @@ -644,7 +645,7 @@ public sealed class BSPrim : BSPhysObject Scene.TaintedObject("BSPrim.SubscribeEvents", delegate() { - BulletSimAPI.AddToCollisionFlags2(Body.Ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); + m_currentCollisionFlags = BulletSimAPI.AddToCollisionFlags2(Body.Ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); }); } } @@ -652,7 +653,7 @@ public sealed class BSPrim : BSPhysObject _subscribedEventsMs = 0; Scene.TaintedObject("BSPrim.UnSubscribeEvents", delegate() { - BulletSimAPI.RemoveFromCollisionFlags2(Body.Ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); + m_currentCollisionFlags = BulletSimAPI.RemoveFromCollisionFlags2(Body.Ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); }); } public override bool SubscribedEvents() { diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs index a0bad3a..d28c14b 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs @@ -461,10 +461,20 @@ public static extern bool DeleteCollisionShape2(IntPtr world, IntPtr shape); public static extern IntPtr CreateBodyFromShape2(IntPtr sim, IntPtr shape, Vector3 pos, Quaternion rot); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern IntPtr CreateBodyFromShapeAndInfo2(IntPtr sim, IntPtr shape, IntPtr constructionInfo); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern IntPtr CreateBodyWithDefaultMotionState2(IntPtr shape, Vector3 pos, Quaternion rot); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern bool SetBodyShape2(IntPtr sim, IntPtr obj, IntPtr shape); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern IntPtr AllocateBodyInfo2(IntPtr obj); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void ReleaseBodyInfo2(IntPtr obj); + // ===================================================================================== [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern IntPtr CreateHeightMapInfo2(IntPtr sim, uint id, Vector3 minCoords, Vector3 maxCoords, @@ -604,13 +614,13 @@ public static extern bool SetInterpolation2(IntPtr obj, Vector3 lin, Vector3 ang public static extern CollisionFlags GetCollisionFlags2(IntPtr obj); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern IntPtr SetCollisionFlags2(IntPtr obj, CollisionFlags flags); +public static extern CollisionFlags SetCollisionFlags2(IntPtr obj, CollisionFlags flags); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern IntPtr AddToCollisionFlags2(IntPtr obj, CollisionFlags flags); +public static extern CollisionFlags AddToCollisionFlags2(IntPtr obj, CollisionFlags flags); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern IntPtr RemoveFromCollisionFlags2(IntPtr obj, CollisionFlags flags); +public static extern CollisionFlags RemoveFromCollisionFlags2(IntPtr obj, CollisionFlags flags); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern bool SetMassProps2(IntPtr obj, float mass, Vector3 inertia); -- cgit v1.1 From 189f51233e48026347a3443628350044e4b6fe8a Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Fri, 31 Aug 2012 13:39:29 -0700 Subject: BulletSim: PhysicsActorType() now returns the correct value rather than 'unknown'. --- OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs | 1 + OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 4 ++-- 2 files changed, 3 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 747ae71..dc2b595 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -92,6 +92,7 @@ public class BSCharacter : BSPhysObject _localID = localID; _avName = avName; Scene = parent_scene; + _physicsActorType = (int)ActorTypes.Agent; _position = pos; _size = size; _flying = isFlying; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 6fcd416..de182f8 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -114,6 +114,7 @@ public sealed class BSPrim : BSPhysObject // m_log.DebugFormat("{0}: BSPrim creation of {1}, id={2}", LogHeader, primName, localID); _localID = localID; _avName = primName; + _physicsActorType = (int)ActorTypes.Prim; _scene = parent_scene; _position = pos; _size = size; @@ -444,8 +445,7 @@ public sealed class BSPrim : BSPhysObject } public override int PhysicsActorType { get { return _physicsActorType; } - set { _physicsActorType = value; - } + set { _physicsActorType = value; } } public override bool IsPhysical { get { return _isPhysical; } -- cgit v1.1 From 3c097cb7a9634f711fffb56c0a6912487694aa53 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Thu, 6 Sep 2012 08:05:53 -0700 Subject: BulletSim: Add some comments (gasp) and log messages. --- OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs | 4 ++++ OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 4 ++-- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 5 +++++ OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs | 4 ++-- 4 files changed, 13 insertions(+), 4 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs b/OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs index d9270d1..2e15ced 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs @@ -98,6 +98,10 @@ public abstract class BSConstraint : IDisposable { // m_world.scene.PhysicsLogging.Write("{0},BSConstraint.RecomputeConstraintVariables,taint,enabling,A={1},B={2}", // BSScene.DetailLogZero, Body1.ID, Body2.ID); + + // Setting an object's mass to zero (making it static like when it's selected) + // automatically disables the constraints. + // If enabled, be sure to set the constraint itself to enabled. BulletSimAPI.SetConstraintEnable2(m_constraint.Ptr, m_world.scene.NumericBool(true)); } else diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index b04e1b6..3111258 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -245,8 +245,8 @@ public class BSLinkset // their constraints have not been created yet. // Caused by the fact that m_children is built at run time but building constraints // happens at taint time. - // m_physicsScene.Logger.ErrorFormat("[BULLETSIM LINKSET] RecomputeLinksetConstraintVariables: constraint not found for root={0}, child={1}", - // m_linksetRoot.Body.ID, child.Body.ID); + // m_physicsScene.Logger.ErrorFormat("{0} RecomputeLinksetConstraintVariables: constraint not found for root={1}, child={2}", + // LogHeader, m_linksetRoot.Body.ID, child.Body.ID); } } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index de182f8..01f231b 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -472,6 +472,10 @@ public sealed class BSPrim : BSPhysObject // Make gravity work if the object is physical and not selected // No locking here because only called when it is safe + // There are three flags we're interested in: + // IsStatic: Object does not move, otherwise the object has mass and moves + // isSolid: other objects bounce off of this object + // collisionEvents: whether this object returns collision events private void SetObjectDynamic() { // If it's becoming dynamic, it will need hullness @@ -481,6 +485,7 @@ public sealed class BSPrim : BSPhysObject float mass = IsStatic ? 0f : _mass; BulletSimAPI.SetObjectProperties(_scene.WorldID, LocalID, IsStatic, IsSolid, SubscribedEvents(), mass); + m_currentCollisionFlags = BulletSimAPI.GetCollisionFlags2(Body.Ptr); // recompute any linkset parameters Linkset.Refresh(this); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs index ab45f8f..4285073 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs @@ -408,8 +408,8 @@ public class BSTerrainManager int mapIndex = (int)regionY * (int)mapInfo.sizeY + (int)regionX; ret = mapInfo.heightMap[mapIndex]; m_terrainModified = false; - DetailLog("{0},BSTerrainManager.GetTerrainHeightAtXY,bX={1},baseY={2},szX={3},szY={4},regX={5},regY={6},index={7},ht={8}", - BSScene.DetailLogZero, offsetX, offsetY, mapInfo.sizeX, mapInfo.sizeY, regionX, regionY, mapIndex, ret); + // DetailLog("{0},BSTerrainManager.GetTerrainHeightAtXY,bX={1},baseY={2},szX={3},szY={4},regX={5},regY={6},index={7},ht={8}", + // BSScene.DetailLogZero, offsetX, offsetY, mapInfo.sizeX, mapInfo.sizeY, regionX, regionY, mapIndex, ret); } else { -- cgit v1.1 From 126eae71009001c5455e4896cf12317422bbac51 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Fri, 7 Sep 2012 15:46:14 -0700 Subject: BulletSim: Add Bullet body and shape to BSPhysObject and rename 'Body' to 'BSBody' for disambiguation when reading code. Complete the API2 interface so nearly all methods on bullet classes are available to the managed code. The efficient single call simulation step is kept in place while all other creation/destruction/parameterization can be done in the managed code. --- .../Region/Physics/BulletSPlugin/BSCharacter.cs | 11 +- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 10 +- .../Region/Physics/BulletSPlugin/BSPhysObject.cs | 6 +- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 96 ++++- .../Physics/BulletSPlugin/BSTerrainManager.cs | 4 +- .../Region/Physics/BulletSPlugin/BulletSimAPI.cs | 440 +++++++++++++++++++-- 6 files changed, 505 insertions(+), 62 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index dc2b595..fa22c78 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -73,7 +73,8 @@ public class BSCharacter : BSPhysObject private bool _kinematic; private float _buoyancy; - public override BulletBody Body { get; set; } + public override BulletBody BSBody { get; set; } + public override BulletShape BSShape { get; set; } public override BSLinkset Linkset { get; set; } private int _subscribedEventsMs = 0; @@ -129,9 +130,9 @@ public class BSCharacter : BSPhysObject // Set the buoyancy for flying. This will be refactored when all the settings happen in C# BulletSimAPI.SetObjectBuoyancy(Scene.WorldID, LocalID, _buoyancy); - Body = new BulletBody(LocalID, BulletSimAPI.GetBodyHandle2(Scene.World.Ptr, LocalID)); + BSBody = new BulletBody(LocalID, BulletSimAPI.GetBodyHandle2(Scene.World.Ptr, LocalID)); // avatars get all collisions no matter what (makes walking on ground and such work) - BulletSimAPI.AddToCollisionFlags2(Body.Ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); + BulletSimAPI.AddToCollisionFlags2(BSBody.Ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); }); return; @@ -441,7 +442,7 @@ public class BSCharacter : BSPhysObject Scene.TaintedObject("BSCharacter.AddForce", delegate() { DetailLog("{0},BSCharacter.setAddForce,taint,addedForce={1}", LocalID, _force); - BulletSimAPI.AddObjectForce2(Body.Ptr, _force); + BulletSimAPI.SetObjectForce2(BSBody.Ptr, _force); }); } else @@ -466,7 +467,7 @@ public class BSCharacter : BSPhysObject Scene.TaintedObject("BSCharacter.SubscribeEvents", delegate() { - BulletSimAPI.AddToCollisionFlags2(Body.Ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); + BulletSimAPI.AddToCollisionFlags2(BSBody.Ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); }); } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index 3111258..5f6601d 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -233,7 +233,7 @@ public class BSLinkset foreach (BSPhysObject child in m_children) { BSConstraint constrain; - if (m_physicsScene.Constraints.TryGetConstraint(LinksetRoot.Body, child.Body, out constrain)) + if (m_physicsScene.Constraints.TryGetConstraint(LinksetRoot.BSBody, child.BSBody, out constrain)) { // DetailLog("{0},BSLinkset.RecomputeLinksetConstraintVariables,taint,child={1},mass={2},A={3},B={4}", // LinksetRoot.LocalID, child.LocalID, linksetMass, constrain.Body1.ID, constrain.Body2.ID); @@ -327,7 +327,7 @@ public class BSLinkset DetailLog("{0},PhysicallyLinkAChildToRoot,taint,root={1},child={2},rLoc={3},cLoc={4},midLoc={5}", rootPrim.LocalID, rootPrim.LocalID, childPrim.LocalID, rootPrim.Position, childPrim.Position, midPoint); BS6DofConstraint constrain = new BS6DofConstraint( - m_physicsScene.World, rootPrim.Body, childPrim.Body, + m_physicsScene.World, rootPrim.BSBody, childPrim.BSBody, midPoint, true, true @@ -388,10 +388,10 @@ public class BSLinkset DetailLog("{0},PhysicallyUnlinkAChildFromRoot,taint,root={1},child={2}", rootPrim.LocalID, rootPrim.LocalID, childPrim.LocalID); // Find the constraint for this link and get rid of it from the overall collection and from my list - m_physicsScene.Constraints.RemoveAndDestroyConstraint(rootPrim.Body, childPrim.Body); + m_physicsScene.Constraints.RemoveAndDestroyConstraint(rootPrim.BSBody, childPrim.BSBody); // Make the child refresh its location - BulletSimAPI.PushUpdate2(childPrim.Body.Ptr); + BulletSimAPI.PushUpdate2(childPrim.BSBody.Ptr); } // Remove linkage between myself and any possible children I might have @@ -400,7 +400,7 @@ public class BSLinkset { DetailLog("{0},PhysicallyUnlinkAllChildren,taint", rootPrim.LocalID); - m_physicsScene.Constraints.RemoveAndDestroyConstraint(rootPrim.Body); + m_physicsScene.Constraints.RemoveAndDestroyConstraint(rootPrim.BSBody); } // Invoke the detailed logger and output something if it's enabled. diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index ef463ca..e411fcb 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -48,7 +48,11 @@ public abstract class BSPhysObject : PhysicsActor // Return the object mass without calculating it or side effects public abstract float MassRaw { get; } - public abstract BulletBody Body { get; set; } + // Reference to the physical body (btCollisionObject) of this object + public abstract BulletBody BSBody { get; set; } + // Reference to the physical shape (btCollisionShape) of this object + public abstract BulletShape BSShape { get; set; } + public abstract void ZeroMotion(); public virtual void StepVehicle(float timeStep) { } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 01f231b..6d0af63 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -96,7 +96,8 @@ public sealed class BSPrim : BSPhysObject long _collidingGroundStep; CollisionFlags m_currentCollisionFlags = 0; - public override BulletBody Body { get; set; } + public override BulletBody BSBody { get; set; } + public override BulletShape BSShape { get; set; } private BSDynamics _vehicle; @@ -144,8 +145,9 @@ public sealed class BSPrim : BSPhysObject // Get the pointer to the physical body for this object. // At the moment, we're still letting BulletSim manage the creation and destruction // of the object. Someday we'll move that into the C# code. - Body = new BulletBody(LocalID, BulletSimAPI.GetBodyHandle2(_scene.World.Ptr, LocalID)); - m_currentCollisionFlags = BulletSimAPI.GetCollisionFlags2(Body.Ptr); + BSBody = new BulletBody(LocalID, BulletSimAPI.GetBodyHandle2(_scene.World.Ptr, LocalID)); + BSShape = new BulletShape(BulletSimAPI.GetCollisionShape2(BSBody.Ptr)); + m_currentCollisionFlags = BulletSimAPI.GetCollisionFlags2(BSBody.Ptr); }); } @@ -261,10 +263,10 @@ public sealed class BSPrim : BSPhysObject _rotationalVelocity = OMV.Vector3.Zero; // Zero some other properties directly into the physics engine - BulletSimAPI.SetVelocity2(Body.Ptr, OMV.Vector3.Zero); - BulletSimAPI.SetAngularVelocity2(Body.Ptr, OMV.Vector3.Zero); - BulletSimAPI.SetInterpolation2(Body.Ptr, OMV.Vector3.Zero, OMV.Vector3.Zero); - BulletSimAPI.ClearForces2(Body.Ptr); + BulletSimAPI.SetLinearVelocity2(BSBody.Ptr, OMV.Vector3.Zero); + BulletSimAPI.SetAngularVelocity2(BSBody.Ptr, OMV.Vector3.Zero); + BulletSimAPI.SetInterpolationVelocity2(BSBody.Ptr, OMV.Vector3.Zero, OMV.Vector3.Zero); + BulletSimAPI.ClearForces2(BSBody.Ptr); } public override void LockAngularMotion(OMV.Vector3 axis) @@ -327,7 +329,7 @@ public sealed class BSPrim : BSPhysObject { DetailLog("{0},BSPrim.setForce,taint,force={1}", LocalID, _force); // BulletSimAPI.SetObjectForce(_scene.WorldID, _localID, _force); - BulletSimAPI.SetObjectForce2(Body.Ptr, _force); + BulletSimAPI.SetObjectForce2(BSBody.Ptr, _force); }); } } @@ -472,10 +474,11 @@ public sealed class BSPrim : BSPhysObject // Make gravity work if the object is physical and not selected // No locking here because only called when it is safe - // There are three flags we're interested in: - // IsStatic: Object does not move, otherwise the object has mass and moves - // isSolid: other objects bounce off of this object - // collisionEvents: whether this object returns collision events + // There are four flags we're interested in: + // IsStatic: Object does not move, otherwise the object has mass and moves + // isSolid: other objects bounce off of this object + // isVolumeDetect: other objects pass through but can generate collisions + // collisionEvents: whether this object returns collision events private void SetObjectDynamic() { // If it's becoming dynamic, it will need hullness @@ -485,14 +488,68 @@ public sealed class BSPrim : BSPhysObject float mass = IsStatic ? 0f : _mass; BulletSimAPI.SetObjectProperties(_scene.WorldID, LocalID, IsStatic, IsSolid, SubscribedEvents(), mass); - m_currentCollisionFlags = BulletSimAPI.GetCollisionFlags2(Body.Ptr); + /* + BulletSimAPI.RemoveObjectFromWorld2(Scene.World.Ptr, BSBody.Ptr); + + // Set up the object physicalness (static or dynamic) + MakeDynamic(); + + // Make solid or not and arrange for collisions, etc + MakeSolid(); - // recompute any linkset parameters + m_currentCollisionFlags = BulletSimAPI.GetCollisionFlags2(BSBody.Ptr); + + BulletSimAPI.AddObjectToWorld2(Scene.World.Ptr, BSBody.Ptr); + */ + + // Recompute any linkset parameters. + // When going from non-physical to physical, this re-enables the constraints that + // had been automatically disabled when the mass was set to zero. Linkset.Refresh(this); DetailLog("{0},BSPrim.SetObjectDynamic,taint,static={1},solid={2},mass={3}, cf={4}", LocalID, IsStatic, IsSolid, mass, m_currentCollisionFlags); } + // "Making dynamic" means changing to and from static. + // When static, gravity does not effect the object and it is fixed in space. + // When dynamic, the object can fall and be pushed by others. + // This is independent of its 'solidness' which controls what passes through + // this object and what interacts with it. + private void MakeDynamic() + { + if (IsStatic) + { + // Become a Bullet 'static' object type + BulletSimAPI.AddToCollisionFlags2(BSBody.Ptr, CollisionFlags.CF_STATIC_OBJECT); + // Stop all movement + BulletSimAPI.ClearAllForces2(BSBody.Ptr); + // Mass is zero which disables a bunch of physics stuff in Bullet + BulletSimAPI.SetMassProps2(BSBody.Ptr, 0f, OMV.Vector3.Zero); + // There is no inertia in a static object + BulletSimAPI.UpdateInertiaTensor2(BSBody.Ptr); + // The activation state is 'sleeping' so Bullet will not try to act on it + BulletSimAPI.ForceActivationState2(BSBody.Ptr, ActivationState.ISLAND_SLEEPING); + } + else + { + // Not a Bullet static object + BulletSimAPI.RemoveFromCollisionFlags2(BSBody.Ptr, CollisionFlags.CF_STATIC_OBJECT); + // A dynamic object has mass + BulletSimAPI.SetMassProps2(BSBody.Ptr, _mass, OMV.Vector3.Zero); + // The shape is interesting and has mass and a center of gravity + IntPtr collisionShapePtr = BulletSimAPI.GetCollisionShape2(BSBody.Ptr); + BulletSimAPI.CalculateLocalInertia2(collisionShapePtr, _mass, OMV.Vector3.Zero); + // Inertia is based on our new mass + BulletSimAPI.UpdateInertiaTensor2(BSBody.Ptr); + // Force activation of the object so Bullet will act on it. + BulletSimAPI.Activate2(BSBody.Ptr, true); + } + } + + private void MakeSolid() + { + } + // prims don't fly public override bool Flying { get { return _flying; } @@ -615,7 +672,7 @@ public sealed class BSPrim : BSPhysObject } else { - m_log.WarnFormat("{0}: Got a NaN force applied to a Character", LogHeader); + m_log.WarnFormat("{0}: Got a NaN force applied to a prim. LocalID={1}", LogHeader, LocalID); return; } _scene.TaintedObject("BSPrim.AddForce", delegate() @@ -630,7 +687,8 @@ public sealed class BSPrim : BSPhysObject m_accumulatedForces.Clear(); } DetailLog("{0},BSPrim.AddObjectForce,taint,force={1}", LocalID, _force); - BulletSimAPI.AddObjectForce2(Body.Ptr, fSum); + // For unknown reason, "ApplyCentralForce" is really additive. + BulletSimAPI.ApplyCentralForce2(BSBody.Ptr, fSum); }); } @@ -650,7 +708,7 @@ public sealed class BSPrim : BSPhysObject Scene.TaintedObject("BSPrim.SubscribeEvents", delegate() { - m_currentCollisionFlags = BulletSimAPI.AddToCollisionFlags2(Body.Ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); + m_currentCollisionFlags = BulletSimAPI.AddToCollisionFlags2(BSBody.Ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); }); } } @@ -658,7 +716,7 @@ public sealed class BSPrim : BSPhysObject _subscribedEventsMs = 0; Scene.TaintedObject("BSPrim.UnSubscribeEvents", delegate() { - m_currentCollisionFlags = BulletSimAPI.RemoveFromCollisionFlags2(Body.Ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); + m_currentCollisionFlags = BulletSimAPI.RemoveFromCollisionFlags2(BSBody.Ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); }); } public override bool SubscribedEvents() { @@ -1243,7 +1301,7 @@ public sealed class BSPrim : BSPhysObject bool ret = BulletSimAPI.CreateObject(_scene.WorldID, shape); // the CreateObject() may have recreated the rigid body. Make sure we have the latest. - Body = new BulletBody(LocalID, BulletSimAPI.GetBodyHandle2(_scene.World.Ptr, LocalID)); + BSBody = new BulletBody(LocalID, BulletSimAPI.GetBodyHandle2(_scene.World.Ptr, LocalID)); return ret; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs index 4285073..47d7199 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs @@ -403,8 +403,8 @@ public class BSTerrainManager { float regionX = tX - offsetX; float regionY = tY - offsetY; - if (regionX > mapInfo.sizeX) regionX = 0; - if (regionY > mapInfo.sizeY) regionY = 0; + if (regionX >= mapInfo.sizeX || regionX < 0f) regionX = 0; + if (regionY >= mapInfo.sizeY || regionY < 0f) regionY = 0; int mapIndex = (int)regionY * (int)mapInfo.sizeY + (int)regionX; ret = mapInfo.heightMap[mapIndex]; m_terrainModified = false; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs index d28c14b..e579cf2 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs @@ -218,7 +218,20 @@ public struct ConfigurationParameters public const float numericFalse = 0f; } -// Values used by Bullet and BulletSim to control collisions + +// The states a bullet collision object can have +public enum ActivationState : uint +{ + ACTIVE_TAG = 1, + ISLAND_SLEEPING, + WANTS_DEACTIVATION, + DISABLE_DEACTIVATION, + DISABLE_SIMULATION +} + +// Values used by Bullet and BulletSim to control object properties. +// Bullet's "CollisionFlags" has more to do with operations on the +// object (if collisions happen, if gravity effects it, ...). public enum CollisionFlags : uint { CF_STATIC_OBJECT = 1 << 0, @@ -233,8 +246,75 @@ public enum CollisionFlags : uint BS_VOLUME_DETECT_OBJECT = 1 << 11, BS_PHANTOM_OBJECT = 1 << 12, BS_PHYSICAL_OBJECT = 1 << 13, + BS_TERRAIN_OBJECT = 1 << 14, + BS_NONE = 0, + BS_ALL = 0xFFFFFFFF +}; + +// Values for collisions groups and masks +public enum CollisionFilterGroups : uint +{ + NoneFilter = 0, + DefaultFilter = 1 << 0, + StaticFilter = 1 << 1, + KinematicFilter = 1 << 2, + DebrisFilter = 1 << 3, + SensorTrigger = 1 << 4, + CharacterFilter = 1 << 5, + AllFilter = 0xFFFFFFFF, + // Filter groups defined by BulletSim + GroundPlaneFilter = 1 << 10, + TerrainFilter = 1 << 11, + RaycastFilter = 1 << 12, + SolidFilter = 1 << 13, }; + // For each type, we first clear and then set the collision flags +public enum ClearCollisionFlag : uint +{ + Terrain = CollisionFlags.BS_ALL, + Phantom = CollisionFlags.BS_ALL, + VolumeDetect = CollisionFlags.BS_ALL, + PhysicalObject = CollisionFlags.BS_ALL, + StaticObject = CollisionFlags.BS_ALL +} + +public enum SetCollisionFlag : uint +{ + Terrain = CollisionFlags.CF_STATIC_OBJECT + | CollisionFlags.BS_TERRAIN_OBJECT, + Phantom = CollisionFlags.CF_STATIC_OBJECT + | CollisionFlags.BS_PHANTOM_OBJECT + | CollisionFlags.CF_NO_CONTACT_RESPONSE, + VolumeDetect = CollisionFlags.CF_STATIC_OBJECT + | CollisionFlags.BS_VOLUME_DETECT_OBJECT + | CollisionFlags.CF_NO_CONTACT_RESPONSE, + PhysicalObject = CollisionFlags.BS_PHYSICAL_OBJECT, + StaticObject = CollisionFlags.CF_STATIC_OBJECT, +} + +// Collision filters used for different types of objects +public enum SetCollisionFilter : uint +{ + Terrain = CollisionFilterGroups.AllFilter, + Phantom = CollisionFilterGroups.GroundPlaneFilter + | CollisionFilterGroups.TerrainFilter, + VolumeDetect = CollisionFilterGroups.AllFilter, + PhysicalObject = CollisionFilterGroups.AllFilter, + StaticObject = CollisionFilterGroups.AllFilter, +} + +// Collision masks used for different types of objects +public enum SetCollisionMask : uint +{ + Terrain = CollisionFilterGroups.AllFilter, + Phantom = CollisionFilterGroups.GroundPlaneFilter + | CollisionFilterGroups.TerrainFilter, + VolumeDetect = CollisionFilterGroups.AllFilter, + PhysicalObject = CollisionFilterGroups.AllFilter, + StaticObject = CollisionFilterGroups.AllFilter +} + // CFM controls the 'hardness' of the constraint. 0=fixed, 0..1=violatable. Default=0 // ERP controls amount of correction per tick. Usable range=0.1..0.8. Default=0.2. public enum ConstraintParams : int @@ -347,6 +427,7 @@ public static extern bool SetObjectVelocity(uint worldID, uint id, Vector3 veloc [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern bool SetObjectAngularVelocity(uint worldID, uint id, Vector3 angularVelocity); +// Set the current force acting on the object [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern bool SetObjectForce(uint worldID, uint id, Vector3 force); @@ -403,6 +484,7 @@ public static extern void SetDebugLogCallback(DebugLogCallback callback); // The names have a "2" tacked on. This will be removed as the C# code gets rebuilt // and the old code is removed. +// Functions use while converting from API1 to API2. Can be removed when totally converted. [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern IntPtr GetSimHandle2(uint worldID); @@ -413,6 +495,7 @@ public static extern IntPtr GetBodyHandleWorldID2(uint worldID, uint id); public static extern IntPtr GetBodyHandle2(IntPtr world, uint id); // =============================================================================== +// Initialization and simulation [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern IntPtr Initialize2(Vector3 maxPosition, IntPtr parms, int maxCollisions, IntPtr collisionArray, @@ -438,6 +521,7 @@ public static extern int PhysicsStep2(IntPtr world, float timeStep, int maxSubSt public static extern bool PushUpdate2(IntPtr obj); // ===================================================================================== +// Mesh, hull, shape and body creation helper routines [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern IntPtr CreateMeshShape2(IntPtr world, int indicesCount, [MarshalAs(UnmanagedType.LPArray)] int[] indices, @@ -467,15 +551,19 @@ public static extern IntPtr CreateBodyFromShapeAndInfo2(IntPtr sim, IntPtr shape public static extern IntPtr CreateBodyWithDefaultMotionState2(IntPtr shape, Vector3 pos, Quaternion rot); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool SetBodyShape2(IntPtr sim, IntPtr obj, IntPtr shape); - -[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern IntPtr AllocateBodyInfo2(IntPtr obj); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern void ReleaseBodyInfo2(IntPtr obj); +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void DestroyObject2(IntPtr sim, IntPtr obj); + // ===================================================================================== +// Terrain creation and helper routines +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void DumpMapInfo(IntPtr sim, IntPtr manInfo); + [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern IntPtr CreateHeightMapInfo2(IntPtr sim, uint id, Vector3 minCoords, Vector3 maxCoords, [MarshalAs(UnmanagedType.LPArray)] float[] heightMap, float collisionMargin); @@ -494,6 +582,7 @@ public static extern IntPtr CreateGroundPlaneShape2(uint id, float height, float public static extern IntPtr CreateTerrainShape2(IntPtr mapInfo); // ===================================================================================== +// Constraint creation and helper routines [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern IntPtr Create6DofConstraint2(IntPtr world, IntPtr obj1, IntPtr obj2, Vector3 frame1loc, Quaternion frame1rot, @@ -546,69 +635,145 @@ public static extern bool SetConstraintParam2(IntPtr constrain, ConstraintParams public static extern bool DestroyConstraint2(IntPtr world, IntPtr constrain); // ===================================================================================== +// btCollisionWorld entries +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void UpdateSingleAabb2(IntPtr world, IntPtr obj); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void UpdateAabbs2(IntPtr world); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern bool GetForceUpdateAllAabbs2(IntPtr world); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void SetForceUpdateAllAabbs2(IntPtr world, bool force); + +// ===================================================================================== +// btDynamicsWorld entries [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern bool AddObjectToWorld2(IntPtr world, IntPtr obj); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern bool RemoveObjectFromWorld2(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] +public static extern bool RemoveConstraintFromWorld2(IntPtr world, IntPtr constrain); // ===================================================================================== +// btCollisionObject entries +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern Vector3 GetAnisotripicFriction2(IntPtr constrain); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern Vector3 SetAnisotripicFriction2(IntPtr constrain, Vector3 frict); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern bool HasAnisotripicFriction2(IntPtr constrain); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void SetContactProcessingThreshold2(IntPtr obj, float val); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern float GetContactProcessingThreshold2(IntPtr obj); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern bool IsStaticObject2(IntPtr obj); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern bool IsKinematicObject2(IntPtr obj); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern bool IsStaticOrKinematicObject2(IntPtr obj); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern bool HasContactResponse2(IntPtr obj); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void SetCollisionShape2(IntPtr sim, IntPtr obj, IntPtr shape); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern IntPtr GetCollisionShape2(IntPtr obj); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern int GetActivationState2(IntPtr obj); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void SetActivationState2(IntPtr obj, int state); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void SetDeactivationTime2(IntPtr obj, float dtime); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern float GetDeactivationTime2(IntPtr obj); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void ForceActivationState2(IntPtr obj, ActivationState state); + [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern void Activate2(IntPtr obj, bool forceActivation); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern Vector3 GetPosition2(IntPtr obj); +public static extern bool IsActive2(IntPtr obj); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern Quaternion GetOrientation2(IntPtr obj); +public static extern void SetRestitution2(IntPtr obj, float val); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool SetTranslation2(IntPtr obj, Vector3 position, Quaternion rotation); +public static extern float GetRestitution2(IntPtr obj); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool SetVelocity2(IntPtr obj, Vector3 velocity); +public static extern void SetFriction2(IntPtr obj, float val); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool SetAngularVelocity2(IntPtr obj, Vector3 angularVelocity); +public static extern float GetFriction2(IntPtr obj); + /* Haven't defined the type 'Transform' [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool SetObjectForce2(IntPtr obj, Vector3 force); +public static extern Transform GetWorldTransform2(IntPtr obj); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool AddObjectForce2(IntPtr obj, Vector3 force); +public static extern void setWorldTransform2(IntPtr obj, Transform trans); + */ [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool SetCcdMotionThreshold2(IntPtr obj, float val); +public static extern Vector3 GetPosition2(IntPtr obj); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool SetCcdSweepSphereRadius2(IntPtr obj, float val); +public static extern Quaternion GetOrientation2(IntPtr obj); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool SetDamping2(IntPtr obj, float lin_damping, float ang_damping); +public static extern void SetTranslation2(IntPtr obj, Vector3 position, Quaternion rotation); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool SetDeactivationTime2(IntPtr obj, float val); +public static extern IntPtr GetBroadphaseHandle2(IntPtr obj); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool SetSleepingThresholds2(IntPtr obj, float lin_threshold, float ang_threshold); +public static extern void SetBroadphaseHandle2(IntPtr obj, IntPtr handle); + /* [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool SetContactProcessingThreshold2(IntPtr obj, float val); +public static extern Transform GetInterpolationWorldTransform2(IntPtr obj); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool SetFriction2(IntPtr obj, float val); +public static extern void SetInterpolationWorldTransform2(IntPtr obj, Transform trans); + */ [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool SetHitFraction2(IntPtr obj, float val); +public static extern void SetInterpolationLinearVelocity2(IntPtr obj, Vector3 vel); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool SetRestitution2(IntPtr obj, float val); +public static extern void SetInterpolationAngularVelocity2(IntPtr obj, Vector3 vel); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool SetLinearVelocity2(IntPtr obj, Vector3 val); +public static extern void SetInterpolationVelocity2(IntPtr obj, Vector3 linearVel, Vector3 angularVel); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool SetInterpolation2(IntPtr obj, Vector3 lin, Vector3 ang); +public static extern float GetHitFraction2(IntPtr obj); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void SetHitFraction2(IntPtr obj, float val); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern CollisionFlags GetCollisionFlags2(IntPtr obj); @@ -623,30 +788,245 @@ public static extern CollisionFlags AddToCollisionFlags2(IntPtr obj, CollisionFl public static extern CollisionFlags RemoveFromCollisionFlags2(IntPtr obj, CollisionFlags flags); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool SetMassProps2(IntPtr obj, float mass, Vector3 inertia); +public static extern float GetCcdMotionThreshold2(IntPtr obj); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void SetCcdMotionThreshold2(IntPtr obj, float val); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern float GetCcdSweepSphereRadius2(IntPtr obj); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void SetCcdSweepSphereRadius2(IntPtr obj, float val); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern IntPtr GetUserPointer2(IntPtr obj); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void SetUserPointer2(IntPtr obj, IntPtr val); + +// ===================================================================================== +// btRigidBody entries +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void ApplyGravity2(IntPtr obj); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void SetGravity2(IntPtr obj, Vector3 val); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern Vector3 GetGravity2(IntPtr obj); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void SetDamping2(IntPtr obj, float lin_damping, float ang_damping); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern float GetLinearDamping2(IntPtr obj); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern float GetAngularDamping2(IntPtr obj); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern float GetLinearSleepingThreshold2(IntPtr obj); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern float GetAngularSleepingThreshold2(IntPtr obj); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void ApplyDamping2(IntPtr obj, float timeStep); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void SetMassProps2(IntPtr obj, float mass, Vector3 inertia); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool UpdateInertiaTensor2(IntPtr obj); +public static extern Vector3 GetLinearFactor2(IntPtr obj); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool SetGravity2(IntPtr obj, Vector3 val); +public static extern void SetLinearFactor2(IntPtr obj, Vector3 factor); + /* [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern IntPtr ClearForces2(IntPtr obj); +public static extern void SetCenterOfMassTransform2(IntPtr obj, Transform trans); + */ [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern IntPtr ClearAllForces2(IntPtr obj); +public static extern void SetCenterOfMassByPosRot2(IntPtr obj, Vector3 pos, Quaternion rot); +// Add a force to the object as if its mass is one. [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool SetMargin2(IntPtr obj, float val); +public static extern void ApplyCentralForce2(IntPtr obj, Vector3 force); +// Set the force being applied to the object as if its mass is one. [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool UpdateSingleAabb2(IntPtr world, IntPtr obj); +public static extern void SetObjectForce2(IntPtr obj, Vector3 force); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool DestroyObject2(IntPtr world, IntPtr obj); +public static extern Vector3 GetTotalForce2(IntPtr obj); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern Vector3 GetTotalTorque2(IntPtr obj); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern Vector3 GetInvInertiaDiagLocal2(IntPtr obj); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void SetInvInertiaDiagLocal2(IntPtr obj, Vector3 inert); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void SetSleepingThresholds2(IntPtr obj, float lin_threshold, float ang_threshold); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void ApplyTorque2(IntPtr obj, Vector3 torque); + +// Apply force at the given point. Will add torque to the object. +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void ApplyForce2(IntPtr obj, Vector3 force, Vector3 pos); + +// Apply impulse to the object. Same as "ApplycentralForce" but force scaled by object's mass. +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void ApplyCentralImpulse2(IntPtr obj, Vector3 imp); + +// Apply impulse to the object's torque. Force is scaled by object's mass. +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void ApplyTorqueImpulse2(IntPtr obj, Vector3 imp); + +// Apply impulse at the point given. For is scaled by object's mass and effects both linear and angular forces. +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void ApplyImpulse2(IntPtr obj, Vector3 imp, Vector3 pos); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void ClearForces2(IntPtr obj); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void ClearAllForces2(IntPtr obj); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void UpdateInertiaTensor2(IntPtr obj); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern Vector3 GetCenterOfMassPosition2(IntPtr obj); + + /* +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern Transform GetCenterOfMassTransform2(IntPtr obj); + */ + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern Vector3 GetLinearVelocity2(IntPtr obj); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern Vector3 GetAngularVelocity2(IntPtr obj); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void SetLinearVelocity2(IntPtr obj, Vector3 val); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void SetAngularVelocity2(IntPtr obj, Vector3 angularVelocity); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern Vector3 GetVelocityInLocalPoint2(IntPtr obj, Vector3 pos); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void Translate2(IntPtr obj, Vector3 trans); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void UpdateDeactivation2(IntPtr obj, float timeStep); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern bool WantsSleeping2(IntPtr obj); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void SetAngularFactor2(IntPtr obj, float factor); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void SetAngularFactorV2(IntPtr obj, Vector3 factor); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern Vector3 GetAngularFactor2(IntPtr obj); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern bool IsInWorld2(IntPtr obj); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void AddConstraintRef2(IntPtr obj, IntPtr constrain); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void RemoveConstraintRef2(IntPtr obj, IntPtr constrain); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern IntPtr GetConstraintRef2(IntPtr obj, int index); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern int GetNumConstraintRefs2(IntPtr obj); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern Vector3 GetDeltaLinearVelocity2(IntPtr obj); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern Vector3 GetDeltaAngularVelocity2(IntPtr obj); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern Vector3 GetPushVelocity2(IntPtr obj); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern Vector3 GetTurnVelocity2(IntPtr obj); + +// ===================================================================================== +// btCollisionShape entries + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern float GetAngularMotionDisc2(IntPtr shape); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern float GetContactBreakingThreshold2(IntPtr shape, float defaultFactor); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern bool IsPolyhedral2(IntPtr shape); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern bool IsConvex2d2(IntPtr shape); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern bool IsConvex2(IntPtr shape); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern bool IsNonMoving2(IntPtr shape); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern bool IsConcave2(IntPtr shape); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern bool IsCompound2(IntPtr shape); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern bool IsSoftBody2(IntPtr shape); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern bool IsInfinite2(IntPtr shape); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void SetLocalScaling2(IntPtr shape, Vector3 scale); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern Vector3 GetLocalScaling2(IntPtr shape); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void CalculateLocalInertia2(IntPtr shape, float mass, Vector3 inertia); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern int GetShapeType2(IntPtr shape); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void SetMargin2(IntPtr shape, float val); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern float GetMargin2(IntPtr shape); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void SetCollisionFilterMask(IntPtr shape, uint filter, uint mask); + +// ===================================================================================== +// Debugging +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern void DumpPhysicsStatistics2(IntPtr sim); } -- cgit v1.1 From 2c5ff9399063080276a23bcd06fb696d653bef2e Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Thu, 13 Sep 2012 08:11:54 -0700 Subject: BulletSim: Way too many changes in one commit. Many changes to BSDynamic for readability and commentary. Linkset hacking for vehicles: don't over mass the root prim. Add parameter for link constraint solver iterations. Correct uses of timestep in timescale calculations for vehicles. Reorganize code/logic for making objects static and dynamic for readability and use of API2. Changed most calls in BSPrim to use API2 calls (the new way). Avatars do not generate default Bullet collision events but do call up to the simulator for every avatar. Reduces overhead. Objects added to collision list only if they are processing collisions. Reduces overhead especially for large numbers of avatars. Generalize call for water height to GetWaterHeightAtXYZ(). Catch and correct exception getting terrain height when out of bounds. Correct race condition in Terrain Manager where creation wasn't at taint-time. Add API calls for constructing compound shapes. Move NeedsMeshing() logic into object class. Reorganize logic for object meshing to reduce rebuilding of meshs/hulls. --- .../Region/Physics/BulletSPlugin/BSCharacter.cs | 17 +- .../Region/Physics/BulletSPlugin/BSConstraint.cs | 16 +- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 218 +++++++++------------ OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 32 ++- .../Region/Physics/BulletSPlugin/BSPhysObject.cs | 2 +- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 196 ++++++++++-------- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 67 ++++--- .../Physics/BulletSPlugin/BSTerrainManager.cs | 60 +++--- .../Region/Physics/BulletSPlugin/BulletSimAPI.cs | 29 ++- 9 files changed, 351 insertions(+), 286 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index fa22c78..a9b1365 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -131,8 +131,6 @@ public class BSCharacter : BSPhysObject BulletSimAPI.SetObjectBuoyancy(Scene.WorldID, LocalID, _buoyancy); BSBody = new BulletBody(LocalID, BulletSimAPI.GetBodyHandle2(Scene.World.Ptr, LocalID)); - // avatars get all collisions no matter what (makes walking on ground and such work) - BulletSimAPI.AddToCollisionFlags2(BSBody.Ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); }); return; @@ -480,11 +478,10 @@ public class BSCharacter : BSPhysObject // Stop collision events public override void UnSubscribeEvents() { _subscribedEventsMs = 0; - // Avatars get all their collision events - // Scene.TaintedObject("BSCharacter.UnSubscribeEvents", delegate() - // { - // BulletSimAPI.RemoveFromCollisionFlags2(Body.Ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); - // }); + Scene.TaintedObject("BSCharacter.UnSubscribeEvents", delegate() + { + BulletSimAPI.RemoveFromCollisionFlags2(BSBody.Ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); + }); } // Return 'true' if someone has subscribed to events public override bool SubscribedEvents() { @@ -532,10 +529,12 @@ public class BSCharacter : BSPhysObject // The collision, if it should be reported to the character, is placed in a collection // that will later be sent to the simulator when SendCollisions() is called. CollisionEventUpdate collisionCollection = null; - public override void Collide(uint collidingWith, BSPhysObject collidee, ActorTypes type, Vector3 contactPoint, Vector3 contactNormal, float pentrationDepth) + public override bool Collide(uint collidingWith, BSPhysObject collidee, ActorTypes type, Vector3 contactPoint, Vector3 contactNormal, float pentrationDepth) { // m_log.DebugFormat("{0}: Collide: ms={1}, id={2}, with={3}", LogHeader, _subscribedEventsMs, LocalID, collidingWith); + bool ret = false; + // The following makes IsColliding() and IsCollidingGround() work _collidingStep = Scene.SimulationStep; if (collidingWith == BSScene.TERRAIN_ID || collidingWith == BSScene.GROUNDPLANE_ID) @@ -553,8 +552,10 @@ public class BSCharacter : BSPhysObject if (collisionCollection == null) collisionCollection = new CollisionEventUpdate(); collisionCollection.AddCollider(collidingWith, new ContactPoint(contactPoint, contactNormal, pentrationDepth)); + ret = true; } } + return ret; } public override void SendCollisions() diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs b/OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs index 2e15ced..1376a29 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs @@ -74,6 +74,17 @@ public abstract class BSConstraint : IDisposable return ret; } + public virtual bool SetSolverIterations(float cnt) + { + bool ret = false; + if (m_enabled) + { + BulletSimAPI.SetConstraintNumSolverIterations2(m_constraint.Ptr, cnt); + ret = true; + } + return ret; + } + public virtual bool CalculateTransforms() { bool ret = false; @@ -96,12 +107,9 @@ public abstract class BSConstraint : IDisposable ret = CalculateTransforms(); if (ret) { - // m_world.scene.PhysicsLogging.Write("{0},BSConstraint.RecomputeConstraintVariables,taint,enabling,A={1},B={2}", - // BSScene.DetailLogZero, Body1.ID, Body2.ID); - // Setting an object's mass to zero (making it static like when it's selected) // automatically disables the constraints. - // If enabled, be sure to set the constraint itself to enabled. + // If the link is enabled, be sure to set the constraint itself to enabled. BulletSimAPI.SetConstraintEnable2(m_constraint.Ptr, m_world.scene.NumericBool(true)); } else diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index 8169e99..098fea7 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -80,7 +80,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin // Linear properties private Vector3 m_linearMotorDirection = Vector3.Zero; // velocity requested by LSL, decayed by time private Vector3 m_linearMotorDirectionLASTSET = Vector3.Zero; // velocity requested by LSL - private Vector3 m_dir = Vector3.Zero; // velocity applied to body + private Vector3 m_newVelocity = Vector3.Zero; // velocity computed to be applied to body private Vector3 m_linearFrictionTimescale = Vector3.Zero; private float m_linearMotorDecayTimescale = 0; private float m_linearMotorTimescale = 0; @@ -475,32 +475,33 @@ namespace OpenSim.Region.Physics.BulletSPlugin frcount = 0; MoveLinear(pTimestep); - MoveAngular(pTimestep); + // MoveAngular(pTimestep); LimitRotation(pTimestep); + // remember the position so next step we can limit absolute movement effects + m_lastPositionVector = m_prim.Position; + VDetailLog("{0},BSDynamics.Step,done,pos={1},force={2},velocity={3},angvel={4}", m_prim.LocalID, m_prim.Position, m_prim.Force, m_prim.Velocity, m_prim.RotationalVelocity); }// end Step private void MoveLinear(float pTimestep) { - // requested m_linearMotorDirection is significant - // if (!m_linearMotorDirection.ApproxEquals(Vector3.Zero, 0.01f)) - if (m_linearMotorDirection.LengthSquared() > 0.0001f) + // m_linearMotorDirection is the direction we are moving relative to the vehicle coordinates + // m_lastLinearVelocityVector is the speed we are moving in that direction + if (m_linearMotorDirection.LengthSquared() > 0.001f) { Vector3 origDir = m_linearMotorDirection; Vector3 origVel = m_lastLinearVelocityVector; // add drive to body - // Vector3 addAmount = m_linearMotorDirection/(m_linearMotorTimescale/pTimestep); - Vector3 addAmount = m_linearMotorDirection/(m_linearMotorTimescale); - // lastLinearVelocityVector is the current body velocity vector? + // Vector3 addAmount = m_linearMotorDirection/(m_linearMotorTimescale / pTimestep); + Vector3 addAmount = (m_linearMotorDirection - m_lastLinearVelocityVector)/(m_linearMotorTimescale / pTimestep); + // lastLinearVelocityVector is the current body velocity vector // RA: Not sure what the *10 is for. A correction for pTimestep? // m_lastLinearVelocityVector += (addAmount*10); m_lastLinearVelocityVector += addAmount; - // This will work temporarily, but we really need to compare speed on an axis - // KF: Limit body velocity to applied velocity? // Limit the velocity vector to less than the last set linear motor direction if (Math.Abs(m_lastLinearVelocityVector.X) > Math.Abs(m_linearMotorDirectionLASTSET.X)) m_lastLinearVelocityVector.X = m_linearMotorDirectionLASTSET.X; @@ -509,34 +510,29 @@ namespace OpenSim.Region.Physics.BulletSPlugin if (Math.Abs(m_lastLinearVelocityVector.Z) > Math.Abs(m_linearMotorDirectionLASTSET.Z)) m_lastLinearVelocityVector.Z = m_linearMotorDirectionLASTSET.Z; + /* // decay applied velocity - Vector3 decayfraction = ((Vector3.One/(m_linearMotorDecayTimescale/pTimestep))); + Vector3 decayfraction = Vector3.One/(m_linearMotorDecayTimescale / pTimestep); + // (RA: do not know where the 0.5f comes from) m_linearMotorDirection -= m_linearMotorDirection * decayfraction * 0.5f; - - /* - Vector3 addAmount = (m_linearMotorDirection - m_lastLinearVelocityVector)/m_linearMotorTimescale; - m_lastLinearVelocityVector += addAmount; - - float decayfraction = (1.0f - 1.0f / m_linearMotorDecayTimescale); - m_linearMotorDirection *= decayfraction; - */ + float keepfraction = 1.0f - (1.0f / (m_linearMotorDecayTimescale / pTimestep)); + m_linearMotorDirection *= keepfraction; - VDetailLog("{0},MoveLinear,nonZero,origdir={1},origvel={2},add={3},decay={4},dir={5},vel={6}", - m_prim.LocalID, origDir, origVel, addAmount, decayfraction, m_linearMotorDirection, m_lastLinearVelocityVector); + VDetailLog("{0},MoveLinear,nonZero,origdir={1},origvel={2},add={3},notDecay={4},dir={5},vel={6}", + m_prim.LocalID, origDir, origVel, addAmount, keepfraction, m_linearMotorDirection, m_lastLinearVelocityVector); } else { - // if what remains of applied is small, zero it. - // if (m_lastLinearVelocityVector.ApproxEquals(Vector3.Zero, 0.01f)) - // m_lastLinearVelocityVector = Vector3.Zero; + // if what remains of direction is very small, zero it. m_linearMotorDirection = Vector3.Zero; m_lastLinearVelocityVector = Vector3.Zero; + VDetailLog("{0},MoveLinear,zeroed", m_prim.LocalID); } // convert requested object velocity to object relative vector Quaternion rotq = m_prim.Orientation; - m_dir = m_lastLinearVelocityVector * rotq; + m_newVelocity = m_lastLinearVelocityVector * rotq; // Add the various forces into m_dir which will be our new direction vector (velocity) @@ -544,60 +540,31 @@ namespace OpenSim.Region.Physics.BulletSPlugin // KF: So far I have found no good method to combine a script-requested // .Z velocity and gravity. Therefore only 0g will used script-requested // .Z velocity. >0g (m_VehicleBuoyancy < 1) will used modified gravity only. - Vector3 grav = Vector3.Zero; // There is some gravity, make a gravity force vector that is applied after object velocity. // m_VehicleBuoyancy: -1=2g; 0=1g; 1=0g; - grav.Z = m_prim.Scene.DefaultGravity.Z * m_prim.Mass * (1f - m_VehicleBuoyancy); + Vector3 grav = m_prim.Scene.DefaultGravity * (m_prim.Mass * (1f - m_VehicleBuoyancy)); + + /* + * RA: Not sure why one would do this // Preserve the current Z velocity Vector3 vel_now = m_prim.Velocity; m_dir.Z = vel_now.Z; // Preserve the accumulated falling velocity + */ Vector3 pos = m_prim.Position; - Vector3 posChange = pos; // Vector3 accel = new Vector3(-(m_dir.X - m_lastLinearVelocityVector.X / 0.1f), -(m_dir.Y - m_lastLinearVelocityVector.Y / 0.1f), m_dir.Z - m_lastLinearVelocityVector.Z / 0.1f); - double Zchange = Math.Abs(posChange.Z); - if (m_BlockingEndPoint != Vector3.Zero) - { - bool changed = false; - if (pos.X >= (m_BlockingEndPoint.X - (float)1)) - { - pos.X -= posChange.X + 1; - changed = true; - } - if (pos.Y >= (m_BlockingEndPoint.Y - (float)1)) - { - pos.Y -= posChange.Y + 1; - changed = true; - } - if (pos.Z >= (m_BlockingEndPoint.Z - (float)1)) - { - pos.Z -= posChange.Z + 1; - changed = true; - } - if (pos.X <= 0) - { - pos.X += posChange.X + 1; - changed = true; - } - if (pos.Y <= 0) - { - pos.Y += posChange.Y + 1; - changed = true; - } - if (changed) - { - m_prim.Position = pos; - VDetailLog("{0},MoveLinear,blockingEndPoint,block={1},origPos={2},pos={3}", - m_prim.LocalID, m_BlockingEndPoint, posChange, pos); - } - } // If below the terrain, move us above the ground a little. - if (pos.Z < m_prim.Scene.TerrainManager.GetTerrainHeightAtXYZ(pos)) + float terrainHeight = m_prim.Scene.TerrainManager.GetTerrainHeightAtXYZ(pos); + // Taking the rotated size doesn't work here because m_prim.Size is the size of the root prim and not the linkset. + // Need to add a m_prim.LinkSet.Size similar to m_prim.LinkSet.Mass. + // Vector3 rotatedSize = m_prim.Size * m_prim.Orientation; + // if (rotatedSize.Z < terrainHeight) + if (pos.Z < terrainHeight) { - pos.Z = m_prim.Scene.TerrainManager.GetTerrainHeightAtXYZ(pos) + 2; + pos.Z = terrainHeight + 2; m_prim.Position = pos; - VDetailLog("{0},MoveLinear,terrainHeight,pos={1}", m_prim.LocalID, pos); + VDetailLog("{0},MoveLinear,terrainHeight,terrainHeight={1},pos={2}", m_prim.LocalID, terrainHeight, pos); } // Check if hovering @@ -606,11 +573,11 @@ namespace OpenSim.Region.Physics.BulletSPlugin // We should hover, get the target height if ((m_flags & VehicleFlag.HOVER_WATER_ONLY) != 0) { - m_VhoverTargetHeight = m_prim.Scene.GetWaterLevel() + m_VhoverHeight; + m_VhoverTargetHeight = m_prim.Scene.GetWaterLevelAtXYZ(pos) + m_VhoverHeight; } if ((m_flags & VehicleFlag.HOVER_TERRAIN_ONLY) != 0) { - m_VhoverTargetHeight = m_prim.Scene.TerrainManager.GetTerrainHeightAtXY(pos.X, pos.Y) + m_VhoverHeight; + m_VhoverTargetHeight = terrainHeight + m_VhoverHeight; } if ((m_flags & VehicleFlag.HOVER_GLOBAL_HEIGHT) != 0) { @@ -635,82 +602,92 @@ namespace OpenSim.Region.Physics.BulletSPlugin // Replace Vertical speed with correction figure if significant if (Math.Abs(herr0) > 0.01f) { - m_dir.Z = -((herr0 * pTimestep * 50.0f) / m_VhoverTimescale); + m_newVelocity.Z = -((herr0 * pTimestep * 50.0f) / m_VhoverTimescale); //KF: m_VhoverEfficiency is not yet implemented } else { - m_dir.Z = 0f; + m_newVelocity.Z = 0f; } } - VDetailLog("{0},MoveLinear,hover,pos={1},dir={2},height={3},target={4}", m_prim.LocalID, pos, m_dir, m_VhoverHeight, m_VhoverTargetHeight); + VDetailLog("{0},MoveLinear,hover,pos={1},dir={2},height={3},target={4}", m_prim.LocalID, pos, m_newVelocity, m_VhoverHeight, m_VhoverTargetHeight); + } -// m_VhoverEfficiency = 0f; // 0=boucy, 1=Crit.damped -// m_VhoverTimescale = 0f; // time to acheive height -// pTimestep is time since last frame,in secs + Vector3 posChange = pos - m_lastPositionVector; + if (m_BlockingEndPoint != Vector3.Zero) + { + bool changed = false; + if (pos.X >= (m_BlockingEndPoint.X - (float)1)) + { + pos.X -= posChange.X + 1; + changed = true; + } + if (pos.Y >= (m_BlockingEndPoint.Y - (float)1)) + { + pos.Y -= posChange.Y + 1; + changed = true; + } + if (pos.Z >= (m_BlockingEndPoint.Z - (float)1)) + { + pos.Z -= posChange.Z + 1; + changed = true; + } + if (pos.X <= 0) + { + pos.X += posChange.X + 1; + changed = true; + } + if (pos.Y <= 0) + { + pos.Y += posChange.Y + 1; + changed = true; + } + if (changed) + { + m_prim.Position = pos; + VDetailLog("{0},MoveLinear,blockingEndPoint,block={1},origPos={2},pos={3}", + m_prim.LocalID, m_BlockingEndPoint, posChange, pos); + } } + float Zchange = Math.Abs(posChange.Z); if ((m_flags & (VehicleFlag.LIMIT_MOTOR_UP)) != 0) { - //Start Experimental Values if (Zchange > .3) - { grav.Z = (float)(grav.Z * 3); - } if (Zchange > .15) - { grav.Z = (float)(grav.Z * 2); - } if (Zchange > .75) - { grav.Z = (float)(grav.Z * 1.5); - } if (Zchange > .05) - { grav.Z = (float)(grav.Z * 1.25); - } if (Zchange > .025) - { grav.Z = (float)(grav.Z * 1.125); - } - float terraintemp = m_prim.Scene.TerrainManager.GetTerrainHeightAtXYZ(pos); - float postemp = (pos.Z - terraintemp); + float postemp = (pos.Z - terrainHeight); if (postemp > 2.5f) - { grav.Z = (float)(grav.Z * 1.037125); - } VDetailLog("{0},MoveLinear,limitMotorUp,grav={1}", m_prim.LocalID, grav); - //End Experimental Values } if ((m_flags & (VehicleFlag.NO_X)) != 0) - { - m_dir.X = 0; - } + m_newVelocity.X = 0; if ((m_flags & (VehicleFlag.NO_Y)) != 0) - { - m_dir.Y = 0; - } + m_newVelocity.Y = 0; if ((m_flags & (VehicleFlag.NO_Z)) != 0) - { - m_dir.Z = 0; - } - - m_lastPositionVector = m_prim.Position; + m_newVelocity.Z = 0; // Apply velocity - m_prim.Velocity = m_dir; + m_prim.Velocity = m_newVelocity; // apply gravity force // Why is this set here? The physics engine already does gravity. // m_prim.AddForce(grav, false); - // m_prim.Force = grav; // Apply friction - Vector3 decayamount = Vector3.One / (m_linearFrictionTimescale / pTimestep); - m_lastLinearVelocityVector -= m_lastLinearVelocityVector * decayamount; + Vector3 keepFraction = Vector3.One - (Vector3.One / (m_linearFrictionTimescale / pTimestep)); + m_lastLinearVelocityVector *= keepFraction; - VDetailLog("{0},MoveLinear,done,pos={1},vel={2},force={3},decay={4}", - m_prim.LocalID, m_lastPositionVector, m_dir, grav, decayamount); + VDetailLog("{0},MoveLinear,done,lmDir={1},lmVel={2},newVel={3},grav={4},1Mdecay={5}", + m_prim.LocalID, m_linearMotorDirection, m_lastLinearVelocityVector, m_newVelocity, grav, keepFraction); } // end MoveLinear() @@ -735,17 +712,18 @@ namespace OpenSim.Region.Physics.BulletSPlugin // There are m_angularMotorApply steps. Vector3 origAngularVelocity = m_angularMotorVelocity; // ramp up to new value - // current velocity += error / (time to get there / step interval) - // requested speed - last motor speed + // current velocity += error / ( time to get there / step interval) + // requested speed - last motor speed m_angularMotorVelocity.X += (m_angularMotorDirection.X - m_angularMotorVelocity.X) / (m_angularMotorTimescale / pTimestep); m_angularMotorVelocity.Y += (m_angularMotorDirection.Y - m_angularMotorVelocity.Y) / (m_angularMotorTimescale / pTimestep); m_angularMotorVelocity.Z += (m_angularMotorDirection.Z - m_angularMotorVelocity.Z) / (m_angularMotorTimescale / pTimestep); - VDetailLog("{0},MoveAngular,angularMotorApply,apply={1},origvel={2},dir={3},vel={4}", - m_prim.LocalID,m_angularMotorApply,origAngularVelocity, m_angularMotorDirection, m_angularMotorVelocity); + VDetailLog("{0},MoveAngular,angularMotorApply,apply={1},angTScale={2},timeStep={3},origvel={4},dir={5},vel={6}", + m_prim.LocalID, m_angularMotorApply, m_angularMotorTimescale, pTimestep, origAngularVelocity, m_angularMotorDirection, m_angularMotorVelocity); - m_angularMotorApply--; // This is done so that if script request rate is less than phys frame rate the expected - // velocity may still be acheived. + // This is done so that if script request rate is less than phys frame rate the expected + // velocity may still be acheived. + m_angularMotorApply--; } else { @@ -760,7 +738,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin Vector3 vertattr = Vector3.Zero; if (m_verticalAttractionTimescale < 300) { - float VAservo = 0.2f / (m_verticalAttractionTimescale * pTimestep); + float VAservo = 0.2f / (m_verticalAttractionTimescale / pTimestep); // get present body rotation Quaternion rotq = m_prim.Orientation; // make a vector pointing up @@ -863,16 +841,12 @@ namespace OpenSim.Region.Physics.BulletSPlugin m_rot.Y = 0; changed = true; } - if ((m_flags & VehicleFlag.LOCK_ROTATION) != 0) - { - m_rot.X = 0; - m_rot.Y = 0; - changed = true; - } if (changed) + { m_prim.Orientation = m_rot; + VDetailLog("{0},LimitRotation,done,orig={1},new={2}", m_prim.LocalID, rotq, m_rot); + } - VDetailLog("{0},LimitRotation,done,changed={1},orig={2},new={3}", m_prim.LocalID, changed, rotq, m_rot); } // Invoke the detailed logger and output something if it's enabled. diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index 5f6601d..dc1de6c 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -206,7 +206,7 @@ public class BSLinkset // its internal properties. public void Refresh(BSPhysObject requestor) { - // If there are no children, there aren't any constraints to recompute + // If there are no children, there can't be any constraints to recompute if (!HasAnyChildren) return; @@ -225,11 +225,12 @@ public class BSLinkset // from a linkset to make sure the constraints know about the new mass and // geometry. // Must only be called at taint time!! - private bool RecomputeLinksetConstraintVariables() + private void RecomputeLinksetConstraintVariables() { float linksetMass = LinksetMass; lock (m_linksetActivityLock) { + bool somethingMissing = false; foreach (BSPhysObject child in m_children) { BSConstraint constrain; @@ -241,16 +242,29 @@ public class BSLinkset } else { - // Non-fatal error that can happen when children are being added to the linkset but + // Non-fatal error that happens when children are being added to the linkset but // their constraints have not been created yet. // Caused by the fact that m_children is built at run time but building constraints // happens at taint time. - // m_physicsScene.Logger.ErrorFormat("{0} RecomputeLinksetConstraintVariables: constraint not found for root={1}, child={2}", - // LogHeader, m_linksetRoot.Body.ID, child.Body.ID); + somethingMissing = true; + break; } } + + // If the whole linkset is not here, doesn't make sense to recompute the root prim now. + if (!somethingMissing) + { + // The root prim takes on the weight of the whole linkset + /* + OMV.Vector3 inertia = BulletSimAPI.CalculateLocalInertia2(LinksetRoot.BSShape.Ptr, linksetMass); + BulletSimAPI.SetMassProps2(LinksetRoot.BSBody.Ptr, linksetMass, inertia); + OMV.Vector3 centerOfMass = ComputeLinksetCenterOfMass(); + BulletSimAPI.SetCenterOfMassByPosRot2(LinksetRoot.BSBody.Ptr, centerOfMass, OMV.Quaternion.Identity); + BulletSimAPI.UpdateInertiaTensor2(LinksetRoot.BSBody.Ptr); + */ + } } - return false; + return; } // I am the root of a linkset and a new child is being added @@ -296,9 +310,9 @@ public class BSLinkset DetailLog("{0},RemoveChildFromLinkset,taint,child={1}", m_linksetRoot.LocalID, child.LocalID); PhysicallyUnlinkAChildFromRoot(rootx, childx); + RecomputeLinksetConstraintVariables(); }); - RecomputeLinksetConstraintVariables(); } else { @@ -377,6 +391,10 @@ public class BSLinkset PhysicsScene.Params.linkConstraintTransMotorMaxVel, PhysicsScene.Params.linkConstraintTransMotorMaxForce); constrain.SetCFMAndERP(PhysicsScene.Params.linkConstraintCFM, PhysicsScene.Params.linkConstraintERP); + if (PhysicsScene.Params.linkConstraintSolverIterations != 0f) + { + constrain.SetSolverIterations(PhysicsScene.Params.linkConstraintSolverIterations); + } RecomputeLinksetConstraintVariables(); } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index e411fcb..969c53e 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -41,7 +41,7 @@ public abstract class BSPhysObject : PhysicsActor { public abstract BSLinkset Linkset { get; set; } - public abstract void Collide(uint collidingWith, BSPhysObject collidee, ActorTypes type, + public abstract bool Collide(uint collidingWith, BSPhysObject collidee, ActorTypes type, OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth); public abstract void SendCollisions(); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 6d0af63..481a8db 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -136,11 +136,11 @@ public sealed class BSPrim : BSPhysObject Linkset = new BSLinkset(Scene, this); // a linkset of one _vehicle = new BSDynamics(Scene, this); // add vehicleness _mass = CalculateMass(); - // do the actual object creation at taint time DetailLog("{0},BSPrim.constructor,call", LocalID); + // do the actual object creation at taint time _scene.TaintedObject("BSPrim.create", delegate() { - RecreateGeomAndObject(); + CreateGeomAndObject(true); // Get the pointer to the physical body for this object. // At the moment, we're still letting BulletSim manage the creation and destruction @@ -186,9 +186,10 @@ public sealed class BSPrim : BSPhysObject _scene.TaintedObject("BSPrim.setSize", delegate() { _mass = CalculateMass(); // changing size changes the mass - BulletSimAPI.SetObjectScaleMass(_scene.WorldID, _localID, _scale, (IsPhysical ? _mass : 0f), IsPhysical); - DetailLog("{0}: BSPrim.setSize: size={1}, mass={2}, physical={3}", LocalID, _size, _mass, IsPhysical); - RecreateGeomAndObject(); + // Since _size changed, the mesh needs to be rebuilt. If rebuilt, all the correct + // scale and margins are set. + CreateGeomAndObject(true); + DetailLog("{0}: BSPrim.setSize: size={1}, scale={2}, mass={3}, physical={4}", LocalID, _size, _scale, _mass, IsPhysical); }); } } @@ -198,7 +199,7 @@ public sealed class BSPrim : BSPhysObject _scene.TaintedObject("BSPrim.setShape", delegate() { _mass = CalculateMass(); // changing the shape changes the mass - RecreateGeomAndObject(); + CreateGeomAndObject(false); }); } } @@ -279,7 +280,7 @@ public sealed class BSPrim : BSPhysObject get { if (!Linkset.IsRoot(this)) // child prims move around based on their parent. Need to get the latest location - _position = BulletSimAPI.GetObjectPosition(_scene.WorldID, _localID); + _position = BulletSimAPI.GetPosition2(BSBody.Ptr); // don't do the GetObjectPosition for root elements because this function is called a zillion times // _position = BulletSimAPI.GetObjectPosition(_scene.WorldID, _localID); @@ -291,7 +292,7 @@ public sealed class BSPrim : BSPhysObject _scene.TaintedObject("BSPrim.setPosition", delegate() { DetailLog("{0},BSPrim.SetPosition,taint,pos={1},orient={2}", LocalID, _position, _orientation); - BulletSimAPI.SetObjectTranslation(_scene.WorldID, _localID, _position, _orientation); + BulletSimAPI.SetTranslation2(BSBody.Ptr, _position, _orientation); }); } } @@ -302,7 +303,8 @@ public sealed class BSPrim : BSPhysObject { get { - return Linkset.LinksetMass; + // return Linkset.LinksetMass; + return _mass; } } @@ -328,7 +330,6 @@ public sealed class BSPrim : BSPhysObject _scene.TaintedObject("BSPrim.setForce", delegate() { DetailLog("{0},BSPrim.setForce,taint,force={1}", LocalID, _force); - // BulletSimAPI.SetObjectForce(_scene.WorldID, _localID, _force); BulletSimAPI.SetObjectForce2(BSBody.Ptr, _force); }); } @@ -406,7 +407,7 @@ public sealed class BSPrim : BSPhysObject _scene.TaintedObject("BSPrim.setVelocity", delegate() { DetailLog("{0},BSPrim.SetVelocity,taint,vel={1}", LocalID, _velocity); - BulletSimAPI.SetObjectVelocity(_scene.WorldID, LocalID, _velocity); + BulletSimAPI.SetLinearVelocity2(BSBody.Ptr, _velocity); }); } } @@ -430,7 +431,7 @@ public sealed class BSPrim : BSPhysObject if (!Linkset.IsRoot(this)) { // Children move around because tied to parent. Get a fresh value. - _orientation = BulletSimAPI.GetObjectOrientation(_scene.WorldID, LocalID); + _orientation = BulletSimAPI.GetOrientation2(BSBody.Ptr); } return _orientation; } @@ -441,7 +442,7 @@ public sealed class BSPrim : BSPhysObject { // _position = BulletSimAPI.GetObjectPosition(_scene.WorldID, _localID); DetailLog("{0},BSPrim.setOrientation,taint,pos={1},orient={2}", LocalID, _position, _orientation); - BulletSimAPI.SetObjectTranslation(_scene.WorldID, _localID, _position, _orientation); + BulletSimAPI.SetTranslation2(BSBody.Ptr, _position, _orientation); }); } } @@ -483,31 +484,37 @@ public sealed class BSPrim : BSPhysObject { // If it's becoming dynamic, it will need hullness VerifyCorrectPhysicalShape(); + UpdatePhysicalParameters(); + } + private void UpdatePhysicalParameters() + { + /* // Bullet wants static objects to have a mass of zero float mass = IsStatic ? 0f : _mass; BulletSimAPI.SetObjectProperties(_scene.WorldID, LocalID, IsStatic, IsSolid, SubscribedEvents(), mass); - /* + */ BulletSimAPI.RemoveObjectFromWorld2(Scene.World.Ptr, BSBody.Ptr); - // Set up the object physicalness (static or dynamic) - MakeDynamic(); + // Set up the object physicalness (does gravity and collisions move this object) + MakeDynamic(IsStatic); - // Make solid or not and arrange for collisions, etc - MakeSolid(); + // Make solid or not (do things bounce off or pass through this object) + MakeSolid(IsSolid); - m_currentCollisionFlags = BulletSimAPI.GetCollisionFlags2(BSBody.Ptr); + // Arrange for collisions events if the simulator wants them + EnableCollisions(SubscribedEvents()); BulletSimAPI.AddObjectToWorld2(Scene.World.Ptr, BSBody.Ptr); - */ // Recompute any linkset parameters. // When going from non-physical to physical, this re-enables the constraints that // had been automatically disabled when the mass was set to zero. Linkset.Refresh(this); - DetailLog("{0},BSPrim.SetObjectDynamic,taint,static={1},solid={2},mass={3}, cf={4}", LocalID, IsStatic, IsSolid, mass, m_currentCollisionFlags); + DetailLog("{0},BSPrim.UpdatePhysicalParameters,taint,static={1},solid={2},mass={3}, cf={4}", + LocalID, IsStatic, IsSolid, _mass, m_currentCollisionFlags); } // "Making dynamic" means changing to and from static. @@ -515,12 +522,12 @@ public sealed class BSPrim : BSPhysObject // When dynamic, the object can fall and be pushed by others. // This is independent of its 'solidness' which controls what passes through // this object and what interacts with it. - private void MakeDynamic() + private void MakeDynamic(bool makeStatic) { - if (IsStatic) + if (makeStatic) { // Become a Bullet 'static' object type - BulletSimAPI.AddToCollisionFlags2(BSBody.Ptr, CollisionFlags.CF_STATIC_OBJECT); + m_currentCollisionFlags = BulletSimAPI.AddToCollisionFlags2(BSBody.Ptr, CollisionFlags.CF_STATIC_OBJECT); // Stop all movement BulletSimAPI.ClearAllForces2(BSBody.Ptr); // Mass is zero which disables a bunch of physics stuff in Bullet @@ -533,12 +540,11 @@ public sealed class BSPrim : BSPhysObject else { // Not a Bullet static object - BulletSimAPI.RemoveFromCollisionFlags2(BSBody.Ptr, CollisionFlags.CF_STATIC_OBJECT); + m_currentCollisionFlags = BulletSimAPI.RemoveFromCollisionFlags2(BSBody.Ptr, CollisionFlags.CF_STATIC_OBJECT); // A dynamic object has mass - BulletSimAPI.SetMassProps2(BSBody.Ptr, _mass, OMV.Vector3.Zero); - // The shape is interesting and has mass and a center of gravity IntPtr collisionShapePtr = BulletSimAPI.GetCollisionShape2(BSBody.Ptr); - BulletSimAPI.CalculateLocalInertia2(collisionShapePtr, _mass, OMV.Vector3.Zero); + OMV.Vector3 inertia = BulletSimAPI.CalculateLocalInertia2(collisionShapePtr, _mass); + BulletSimAPI.SetMassProps2(BSBody.Ptr, _mass, inertia); // Inertia is based on our new mass BulletSimAPI.UpdateInertiaTensor2(BSBody.Ptr); // Force activation of the object so Bullet will act on it. @@ -546,8 +552,31 @@ public sealed class BSPrim : BSPhysObject } } - private void MakeSolid() + // "Making solid" means that other object will not pass through this object. + private void MakeSolid(bool makeSolid) { + if (makeSolid) + { + // Easy in Bullet -- just remove the object flag that controls collision response + m_currentCollisionFlags = BulletSimAPI.RemoveFromCollisionFlags2(BSBody.Ptr, CollisionFlags.CF_NO_CONTACT_RESPONSE); + } + else + { + m_currentCollisionFlags = BulletSimAPI.AddToCollisionFlags2(BSBody.Ptr, CollisionFlags.CF_NO_CONTACT_RESPONSE); + } + } + + // Turn on or off the flag controlling whether collision events are returned to the simulator. + private void EnableCollisions(bool wantsCollisionEvents) + { + if (wantsCollisionEvents) + { + m_currentCollisionFlags = BulletSimAPI.AddToCollisionFlags2(BSBody.Ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); + } + else + { + m_currentCollisionFlags = BulletSimAPI.RemoveFromCollisionFlags2(BSBody.Ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); + } } // prims don't fly @@ -607,7 +636,7 @@ public sealed class BSPrim : BSPhysObject _scene.TaintedObject("BSPrim.setRotationalVelocity", delegate() { DetailLog("{0},BSPrim.SetRotationalVel,taint,rotvel={1}", LocalID, _rotationalVelocity); - BulletSimAPI.SetObjectAngularVelocity(_scene.WorldID, LocalID, _rotationalVelocity); + BulletSimAPI.SetAngularVelocity2(BSBody.Ptr, _rotationalVelocity); }); } } @@ -624,7 +653,10 @@ public sealed class BSPrim : BSPhysObject _scene.TaintedObject("BSPrim.setBuoyancy", delegate() { DetailLog("{0},BSPrim.SetBuoyancy,taint,buoy={1}", LocalID, _buoyancy); - BulletSimAPI.SetObjectBuoyancy(_scene.WorldID, _localID, _buoyancy); + // Buoyancy is faked by changing the gravity applied to the object + float grav = Scene.Params.gravity * (1f - _buoyancy); + BulletSimAPI.SetGravity2(BSBody.Ptr, new OMV.Vector3(0f, 0f, grav)); + // BulletSimAPI.SetObjectBuoyancy(_scene.WorldID, _localID, _buoyancy); }); } } @@ -686,8 +718,8 @@ public sealed class BSPrim : BSPhysObject } m_accumulatedForces.Clear(); } - DetailLog("{0},BSPrim.AddObjectForce,taint,force={1}", LocalID, _force); - // For unknown reason, "ApplyCentralForce" is really additive. + DetailLog("{0},BSPrim.AddObjectForce,taint,force={1}", LocalID, fSum); + // For unknown reasons, "ApplyCentralForce" adds this force to the total force on the object. BulletSimAPI.ApplyCentralForce2(BSBody.Ptr, fSum); }); } @@ -1030,29 +1062,36 @@ public sealed class BSPrim : BSPhysObject // Returns 'true' if the geometry was rebuilt private bool CreateGeom(bool forceRebuild) { - // the mesher thought this was too simple to mesh. Use a native Bullet collision shape. bool ret = false; - if (!_scene.NeedsMeshing(_pbs)) + bool haveShape = false; + + // If the prim attributes are simple, this could be a simple Bullet native shape + if ((_pbs.SculptEntry && !Scene.ShouldMeshSculptedPrim) + || (_pbs.ProfileBegin == 0 && _pbs.ProfileEnd == 0 + && _pbs.ProfileHollow == 0 + && _pbs.PathTwist == 0 && _pbs.PathTwistBegin == 0 + && _pbs.PathBegin == 0 && _pbs.PathEnd == 0 + && _pbs.PathTaperX == 0 && _pbs.PathTaperY == 0 + && _pbs.PathScaleX == 100 && _pbs.PathScaleY == 100 + && _pbs.PathShearX == 0 && _pbs.PathShearY == 0) ) { if (_pbs.ProfileShape == ProfileShape.HalfCircle && _pbs.PathCurve == (byte)Extrusion.Curve1) { - // if (_size.X == _size.Y && _size.Y == _size.Z && _size.X == _size.Z) - // { - // m_log.DebugFormat("{0}: CreateGeom: Defaulting to sphere of size {1}", LogHeader, _size); - if (forceRebuild || (_shapeType != ShapeData.PhysicsShapeType.SHAPE_SPHERE)) - { - DetailLog("{0},BSPrim.CreateGeom,sphere (force={1}", LocalID, forceRebuild); - _shapeType = ShapeData.PhysicsShapeType.SHAPE_SPHERE; - // Bullet native objects are scaled by the Bullet engine so pass the size in - _scale = _size; - // TODO: do we need to check for and destroy a mesh or hull that might have been left from before? - ret = true; - } - // } + haveShape = true; + if (forceRebuild || (_shapeType != ShapeData.PhysicsShapeType.SHAPE_SPHERE)) + { + DetailLog("{0},BSPrim.CreateGeom,sphere (force={1}", LocalID, forceRebuild); + _shapeType = ShapeData.PhysicsShapeType.SHAPE_SPHERE; + // Bullet native objects are scaled by the Bullet engine so pass the size in + _scale = _size; + // TODO: do we need to check for and destroy a mesh or hull that might have been left from before? + ret = true; + } } else { // m_log.DebugFormat("{0}: CreateGeom: Defaulting to box. lid={1}, type={2}, size={3}", LogHeader, LocalID, _shapeType, _size); + haveShape = true; if (forceRebuild || (_shapeType != ShapeData.PhysicsShapeType.SHAPE_BOX)) { DetailLog("{0},BSPrim.CreateGeom,box (force={1})", LocalID, forceRebuild); @@ -1063,16 +1102,16 @@ public sealed class BSPrim : BSPhysObject } } } - else + // If a simple shape isn't happening, create a mesh and possibly a hull + if (!haveShape) { if (IsPhysical) { if (forceRebuild || _hullKey == 0) { // physical objects require a hull for interaction. - // This will create the mesh if it doesn't already exist - CreateGeomHull(); - ret = true; + // This also creates the mesh if it doesn't already exist + ret = CreateGeomHull(); } } else @@ -1080,8 +1119,7 @@ public sealed class BSPrim : BSPhysObject if (forceRebuild || _meshKey == 0) { // Static (non-physical) objects only need a mesh for bumping into - CreateGeomMesh(); - ret = true; + ret = CreateGeomMesh(); } } } @@ -1089,7 +1127,8 @@ public sealed class BSPrim : BSPhysObject } // No locking here because this is done when we know physics is not simulating - private void CreateGeomMesh() + // Returns 'true' of a mesh was actually rebuild (we could also have one of these specs). + private bool CreateGeomMesh() { // level of detail based on size and type of the object float lod = _scene.MeshLOD; @@ -1103,7 +1142,7 @@ public sealed class BSPrim : BSPhysObject // m_log.DebugFormat("{0}: CreateGeomMesh: lID={1}, oldKey={2}, newKey={3}", LogHeader, _localID, _meshKey, newMeshKey); // if this new shape is the same as last time, don't recreate the mesh - if (_meshKey == newMeshKey) return; + if (_meshKey == newMeshKey) return false; DetailLog("{0},BSPrim.CreateGeomMesh,create,key={1}", LocalID, newMeshKey); // Since we're recreating new, get rid of any previously generated shape @@ -1140,19 +1179,19 @@ public sealed class BSPrim : BSPhysObject _shapeType = ShapeData.PhysicsShapeType.SHAPE_MESH; // meshes are already scaled by the meshmerizer _scale = new OMV.Vector3(1f, 1f, 1f); - DetailLog("{0},BSPrim.CreateGeomMesh,done", LocalID); - return; + return true; } // No locking here because this is done when we know physics is not simulating - private void CreateGeomHull() + // Returns 'true' of a mesh was actually rebuild (we could also have one of these specs). + private bool CreateGeomHull() { float lod = _pbs.SculptEntry ? _scene.SculptLOD : _scene.MeshLOD; ulong newHullKey = (ulong)_pbs.GetMeshKey(_size, lod); // m_log.DebugFormat("{0}: CreateGeomHull: lID={1}, oldKey={2}, newKey={3}", LogHeader, _localID, _hullKey, newHullKey); // if the hull hasn't changed, don't rebuild it - if (newHullKey == _hullKey) return; + if (newHullKey == _hullKey) return false; DetailLog("{0},BSPrim.CreateGeomHull,create,oldKey={1},newKey={2}", LocalID, _hullKey, newHullKey); @@ -1255,7 +1294,7 @@ public sealed class BSPrim : BSPhysObject // meshes are already scaled by the meshmerizer _scale = new OMV.Vector3(1f, 1f, 1f); DetailLog("{0},BSPrim.CreateGeomHull,done", LocalID); - return; + return true; } // Callback from convex hull creater with a newly created hull. @@ -1268,20 +1307,12 @@ public sealed class BSPrim : BSPhysObject private void VerifyCorrectPhysicalShape() { - if (IsStatic) - { - // if static, we don't need a hull so, if there is one, rebuild without it - if (_hullKey != 0) - { - RecreateGeomAndObject(); - } - } - else + if (!IsStatic) { // if not static, it will need a hull to efficiently collide with things if (_hullKey == 0) { - RecreateGeomAndObject(); + CreateGeomAndObject(false); } } @@ -1300,8 +1331,9 @@ public sealed class BSPrim : BSPhysObject // m_log.DebugFormat("{0}: CreateObject: lID={1}, shape={2}", LogHeader, _localID, shape.Type); bool ret = BulletSimAPI.CreateObject(_scene.WorldID, shape); - // the CreateObject() may have recreated the rigid body. Make sure we have the latest. + // the CreateObject() may have recreated the rigid body. Make sure we have the latest address. BSBody = new BulletBody(LocalID, BulletSimAPI.GetBodyHandle2(_scene.World.Ptr, LocalID)); + BSShape = new BulletShape(BulletSimAPI.GetCollisionShape2(BSBody.Ptr)); return ret; } @@ -1325,15 +1357,20 @@ public sealed class BSPrim : BSPhysObject shape.Static = _isPhysical ? ShapeData.numericFalse : ShapeData.numericTrue; } - // Rebuild the geometry and object. // This is called when the shape changes so we need to recreate the mesh/hull. // No locking here because this is done when the physics engine is not simulating - private void RecreateGeomAndObject() + private void CreateGeomAndObject(bool forceRebuild) { - // m_log.DebugFormat("{0}: RecreateGeomAndObject. lID={1}", LogHeader, _localID); - if (CreateGeom(true)) + // m_log.DebugFormat("{0}: CreateGeomAndObject. lID={1}, force={2}", LogHeader, _localID, forceRebuild); + // Create the geometry that will make up the object + if (CreateGeom(forceRebuild)) + { + // Create the object and place it into the world CreateObject(); + // Make sure the properties are set on the new object + UpdatePhysicalParameters(); + } return; } @@ -1430,9 +1467,10 @@ public sealed class BSPrim : BSPhysObject // I've collided with something // Called at taint time from within the Step() function CollisionEventUpdate collisionCollection; - public override void Collide(uint collidingWith, BSPhysObject collidee, ActorTypes type, OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth) + public override bool Collide(uint collidingWith, BSPhysObject collidee, ActorTypes type, OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth) { // m_log.DebugFormat("{0}: Collide: ms={1}, id={2}, with={3}", LogHeader, _subscribedEventsMs, LocalID, collidingWith); + bool ret = false; // The following lines make IsColliding() and IsCollidingGround() work _collidingStep = _scene.SimulationStep; @@ -1446,7 +1484,7 @@ public sealed class BSPrim : BSPhysObject // prims in the same linkset cannot collide with each other if (collidee != null && (this.Linkset.LinksetID == collidee.Linkset.LinksetID)) { - return; + return ret; } // if someone has subscribed for collision events.... @@ -1459,8 +1497,10 @@ public sealed class BSPrim : BSPhysObject if (collisionCollection == null) collisionCollection = new CollisionEventUpdate(); collisionCollection.AddCollider(collidingWith, new ContactPoint(contactPoint, contactNormal, pentrationDepth)); + ret = true; } } + return ret; } // The scene is telling us it's time to pass our collected collisions into the simulator diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index 4a468af..eea899f 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -79,7 +79,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters private HashSet m_objectsWithCollisions = new HashSet(); // Following is a kludge and can be removed when avatar animation updating is // moved to a better place. - private HashSet m_avatarsWithCollisions = new HashSet(); + private HashSet m_avatarsWithCollisions = new HashSet(); // List of all the objects that have vehicle properties and should be called // to update each physics step. @@ -132,8 +132,8 @@ public class BSScene : PhysicsScene, IPhysicsParameters private EntityProperties[] m_updateArray; private GCHandle m_updateArrayPinnedHandle; - private bool _meshSculptedPrim = true; // cause scuplted prims to get meshed - private bool _forceSimplePrimMeshing = false; // if a cube or sphere, let Bullet do internal shapes + public bool ShouldMeshSculptedPrim { get; private set; } // cause scuplted prims to get meshed + public bool ShouldForceSimplePrimMeshing { get; private set; } // if a cube or sphere, let Bullet do internal shapes public float PID_D { get; private set; } // derivative public float PID_P { get; private set; } // proportional @@ -153,6 +153,11 @@ public class BSScene : PhysicsScene, IPhysicsParameters { get { return new Vector3(0f, 0f, Params.gravity); } } + // Just the Z value of the gravity + public float DefaultGravityZ + { + get { return Params.gravity; } + } public float MaximumObjectMass { get; private set; } @@ -171,8 +176,8 @@ public class BSScene : PhysicsScene, IPhysicsParameters callback = c; } } + private Object _taintLock = new Object(); // lock for using the next object private List _taintedObjects; - private Object _taintLock = new Object(); // A pointer to an instance if this structure is passed to the C++ code // Used to pass basic configuration values to the unmanaged code. @@ -478,6 +483,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters // Some of the prims operate with special vehicle properties ProcessVehicles(timeStep); + numTaints += _taintedObjects.Count; ProcessTaints(); // the vehicles might have added taints // step the physical world one interval @@ -506,6 +512,12 @@ public class BSScene : PhysicsScene, IPhysicsParameters // Get a value for 'now' so all the collision and update routines don't have to get their own SimulationNowTime = Util.EnvironmentTickCount(); + // This is a kludge to get avatar movement updates. + // ODE sends collisions for avatars even if there are have been no collisions. This updates + // avatar animations and stuff. + // If you fix avatar animation updates, remove this overhead and let collisions happen. + m_objectsWithCollisions = new HashSet(m_avatarsWithCollisions); + // If there were collisions, process them by sending the event to the prim. // Collisions must be processed before updates. if (collidersCount > 0) @@ -527,13 +539,6 @@ public class BSScene : PhysicsScene, IPhysicsParameters bsp.SendCollisions(); m_objectsWithCollisions.Clear(); - // This is a kludge to get avatar movement updated. - // ODE sends collisions even if there are none and this is used to update - // avatar animations and stuff. - foreach (BSPhysObject bpo in m_avatarsWithCollisions) - bpo.SendCollisions(); - // m_avatarsWithCollisions.Clear(); - // If any of the objects had updated properties, tell the object it has been changed by the physics engine if (updatedEntityCount > 0) { @@ -544,7 +549,6 @@ public class BSScene : PhysicsScene, IPhysicsParameters if (PhysObjects.TryGetValue(entprop.ID, out pobj)) { pobj.UpdateProperties(entprop); - continue; } } } @@ -600,8 +604,11 @@ public class BSScene : PhysicsScene, IPhysicsParameters // DetailLog("{0},BSScene.SendCollision,collide,id={1},with={2}", DetailLogZero, localID, collidingWith); - collider.Collide(collidingWith, collidee, type, collidePoint, collideNormal, penetration); - m_objectsWithCollisions.Add(collider); + if (collider.Collide(collidingWith, collidee, type, collidePoint, collideNormal, penetration)) + { + // If a collision was posted, remember to send it to the simulator + m_objectsWithCollisions.Add(collider); + } return; } @@ -619,9 +626,9 @@ public class BSScene : PhysicsScene, IPhysicsParameters public override void SetWaterLevel(float baseheight) { m_waterLevel = baseheight; - // TODO: pass to physics engine so things will float? } - public float GetWaterLevel() + // Someday.... + public float GetWaterLevelAtXYZ(Vector3 loc) { return m_waterLevel; } @@ -672,7 +679,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters // int iPropertiesNotSupportedDefault = 0; - if (pbs.SculptEntry && !_meshSculptedPrim) + if (pbs.SculptEntry && !ShouldMeshSculptedPrim) { // Render sculpties as boxes return false; @@ -680,7 +687,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters // if it's a standard box or sphere with no cuts, hollows, twist or top shear, return false since Bullet // can use an internal representation for the prim - if (!_forceSimplePrimMeshing) + if (!ShouldForceSimplePrimMeshing) { if ((pbs.ProfileShape == ProfileShape.Square && pbs.PathCurve == (byte)Extrusion.Straight) || (pbs.ProfileShape == ProfileShape.HalfCircle && pbs.PathCurve == (byte)Extrusion.Curve1 @@ -782,7 +789,10 @@ public class BSScene : PhysicsScene, IPhysicsParameters if (!m_initialized) return; lock (_taintLock) + { _taintedObjects.Add(new TaintCallbackEntry(ident, callback)); + } + return; } @@ -919,14 +929,14 @@ public class BSScene : PhysicsScene, IPhysicsParameters { new ParameterDefn("MeshSculptedPrim", "Whether to create meshes for sculpties", ConfigurationParameters.numericTrue, - (s,cf,p,v) => { s._meshSculptedPrim = cf.GetBoolean(p, s.BoolNumeric(v)); }, - (s) => { return s.NumericBool(s._meshSculptedPrim); }, - (s,p,l,v) => { s._meshSculptedPrim = s.BoolNumeric(v); } ), + (s,cf,p,v) => { s.ShouldMeshSculptedPrim = cf.GetBoolean(p, s.BoolNumeric(v)); }, + (s) => { return s.NumericBool(s.ShouldMeshSculptedPrim); }, + (s,p,l,v) => { s.ShouldMeshSculptedPrim = s.BoolNumeric(v); } ), new ParameterDefn("ForceSimplePrimMeshing", "If true, only use primitive meshes for objects", ConfigurationParameters.numericFalse, - (s,cf,p,v) => { s._forceSimplePrimMeshing = cf.GetBoolean(p, s.BoolNumeric(v)); }, - (s) => { return s.NumericBool(s._forceSimplePrimMeshing); }, - (s,p,l,v) => { s._forceSimplePrimMeshing = s.BoolNumeric(v); } ), + (s,cf,p,v) => { s.ShouldForceSimplePrimMeshing = cf.GetBoolean(p, s.BoolNumeric(v)); }, + (s) => { return s.NumericBool(s.ShouldForceSimplePrimMeshing); }, + (s,p,l,v) => { s.ShouldForceSimplePrimMeshing = s.BoolNumeric(v); } ), new ParameterDefn("MeshLevelOfDetail", "Level of detail to render meshes (32, 16, 8 or 4. 32=most detailed)", 8f, @@ -1162,8 +1172,8 @@ public class BSScene : PhysicsScene, IPhysicsParameters (s,cf,p,v) => { s.m_params[0].linkConstraintTransMotorMaxForce = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].linkConstraintTransMotorMaxForce; }, (s,p,l,v) => { s.m_params[0].linkConstraintTransMotorMaxForce = v; } ), - new ParameterDefn("LinkConstraintCFM", "Amount constraint can be violated. 0=none, 1=all. Default=0", - 0.0f, + new ParameterDefn("LinkConstraintCFM", "Amount constraint can be violated. 0=no violation, 1=infinite. Default=0.1", + 0.1f, (s,cf,p,v) => { s.m_params[0].linkConstraintCFM = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].linkConstraintCFM; }, (s,p,l,v) => { s.m_params[0].linkConstraintCFM = v; } ), @@ -1172,6 +1182,11 @@ public class BSScene : PhysicsScene, IPhysicsParameters (s,cf,p,v) => { s.m_params[0].linkConstraintERP = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].linkConstraintERP; }, (s,p,l,v) => { s.m_params[0].linkConstraintERP = v; } ), + new ParameterDefn("LinkConstraintSolverIterations", "Number of solver iterations when computing constraint. (0 = Bullet default)", + 40, + (s,cf,p,v) => { s.m_params[0].linkConstraintSolverIterations = cf.GetFloat(p, v); }, + (s) => { return s.m_params[0].linkConstraintSolverIterations; }, + (s,p,l,v) => { s.m_params[0].linkConstraintSolverIterations = v; } ), new ParameterDefn("DetailedStats", "Frames between outputting detailed phys stats. (0 is off)", 0f, diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs index 47d7199..d48462e 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs @@ -154,27 +154,31 @@ public class BSTerrainManager // The simulator wants to set a new heightmap for the terrain. public void SetTerrain(float[] heightMap) { - if (m_worldOffset != Vector3.Zero && m_parentScene != null) + float[] localHeightMap = heightMap; + m_physicsScene.TaintedObject("TerrainManager.SetTerrain", delegate() { - // If a child of a mega-region, we shouldn't have any terrain allocated for us - ReleaseGroundPlaneAndTerrain(); - // If doing the mega-prim stuff and we are the child of the zero region, - // the terrain is added to our parent - if (m_parentScene is BSScene) + if (m_worldOffset != Vector3.Zero && m_parentScene != null) { - DetailLog("{0},SetTerrain.ToParent,offset={1},worldMax={2}", - BSScene.DetailLogZero, m_worldOffset, m_worldMax); - ((BSScene)m_parentScene).TerrainManager.UpdateOrCreateTerrain(BSScene.CHILDTERRAIN_ID, - heightMap, m_worldOffset, m_worldOffset+DefaultRegionSize, false); + // If a child of a mega-region, we shouldn't have any terrain allocated for us + ReleaseGroundPlaneAndTerrain(); + // If doing the mega-prim stuff and we are the child of the zero region, + // the terrain is added to our parent + if (m_parentScene is BSScene) + { + DetailLog("{0},SetTerrain.ToParent,offset={1},worldMax={2}", + BSScene.DetailLogZero, m_worldOffset, m_worldMax); + ((BSScene)m_parentScene).TerrainManager.UpdateOrCreateTerrain(BSScene.CHILDTERRAIN_ID, + localHeightMap, m_worldOffset, m_worldOffset + DefaultRegionSize, true); + } } - } - else - { - // If not doing the mega-prim thing, just change the terrain - DetailLog("{0},SetTerrain.Existing", BSScene.DetailLogZero); + else + { + // If not doing the mega-prim thing, just change the terrain + DetailLog("{0},SetTerrain.Existing", BSScene.DetailLogZero); - UpdateOrCreateTerrain(BSScene.TERRAIN_ID, heightMap, m_worldOffset, m_worldOffset+DefaultRegionSize, false); - } + UpdateOrCreateTerrain(BSScene.TERRAIN_ID, localHeightMap, m_worldOffset, m_worldOffset + DefaultRegionSize, true); + } + }); } // If called with no mapInfo for the terrain, this will create a new mapInfo and terrain @@ -319,6 +323,8 @@ public class BSTerrainManager // Make sure the new shape is processed. BulletSimAPI.Activate2(mapInfo.terrainBody.Ptr, true); + + m_terrainModified = true; }; // There is the option to do the changes now (we're already in 'taint time'), or @@ -357,6 +363,8 @@ public class BSTerrainManager m_heightMaps.Add(terrainRegionBase, mapInfo); // Build the terrain UpdateOrCreateTerrain(newTerrainID, heightMap, minCoords, maxCoords, true); + + m_terrainModified = true; }; // If already in taint-time, just call Bullet. Otherwise queue the operations for the safe time. @@ -383,7 +391,7 @@ public class BSTerrainManager private float lastHeightTX = 999999f; private float lastHeightTY = 999999f; private float lastHeight = HEIGHT_INITIAL_LASTHEIGHT; - public float GetTerrainHeightAtXY(float tX, float tY) + private float GetTerrainHeightAtXY(float tX, float tY) { // You'd be surprized at the number of times this routine is called // with the same parameters as last time. @@ -403,11 +411,18 @@ public class BSTerrainManager { float regionX = tX - offsetX; float regionY = tY - offsetY; - if (regionX >= mapInfo.sizeX || regionX < 0f) regionX = 0; - if (regionY >= mapInfo.sizeY || regionY < 0f) regionY = 0; int mapIndex = (int)regionY * (int)mapInfo.sizeY + (int)regionX; - ret = mapInfo.heightMap[mapIndex]; - m_terrainModified = false; + try + { + ret = mapInfo.heightMap[mapIndex]; + } + catch + { + // Sometimes they give us wonky values of X and Y. Give a warning and return something. + m_physicsScene.Logger.WarnFormat("{0} Bad request for terrain height. terrainBase={1}, x={2}, y={3}", + LogHeader, terrainBaseXY, regionX, regionY); + ret = HEIGHT_GETHEIGHT_RET; + } // DetailLog("{0},BSTerrainManager.GetTerrainHeightAtXY,bX={1},baseY={2},szX={3},szY={4},regX={5},regY={6},index={7},ht={8}", // BSScene.DetailLogZero, offsetX, offsetY, mapInfo.sizeX, mapInfo.sizeY, regionX, regionY, mapIndex, ret); } @@ -416,6 +431,7 @@ public class BSTerrainManager m_physicsScene.Logger.ErrorFormat("{0} GetTerrainHeightAtXY: terrain not found: region={1}, x={2}, y={3}", LogHeader, m_physicsScene.RegionName, tX, tY); } + m_terrainModified = false; lastHeight = ret; return ret; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs index e579cf2..043423e 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs @@ -213,6 +213,7 @@ public struct ConfigurationParameters public float linkConstraintTransMotorMaxForce; public float linkConstraintERP; public float linkConstraintCFM; + public float linkConstraintSolverIterations; public const float numericTrue = 1f; public const float numericFalse = 0f; @@ -395,23 +396,6 @@ public static extern bool DestroyMesh(uint worldID, System.UInt64 meshKey); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern bool CreateObject(uint worldID, ShapeData shapeData); -/* Remove old functionality -[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern void CreateLinkset(uint worldID, int objectCount, ShapeData[] shapeDatas); - -[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern void AddConstraint(uint worldID, uint id1, uint id2, - Vector3 frame1, Quaternion frame1rot, - Vector3 frame2, Quaternion frame2rot, - Vector3 lowLinear, Vector3 hiLinear, Vector3 lowAngular, Vector3 hiAngular); - -[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool RemoveConstraintByID(uint worldID, uint id1); - -[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool RemoveConstraint(uint worldID, uint id1, uint id2); - */ - [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern Vector3 GetObjectPosition(uint WorldID, uint id); @@ -545,6 +529,15 @@ public static extern bool DeleteCollisionShape2(IntPtr world, IntPtr shape); public static extern IntPtr CreateBodyFromShape2(IntPtr sim, IntPtr shape, Vector3 pos, Quaternion rot); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern IntPtr CreateCompoundShape2(IntPtr sim); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void AddChildToCompoundShape2(IntPtr cShape, IntPtr addShape, Vector3 pos, Quaternion rot); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void RemoveChildFromCompoundShape2(IntPtr cShape, IntPtr removeShape); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern IntPtr CreateBodyFromShapeAndInfo2(IntPtr sim, IntPtr shape, IntPtr constructionInfo); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] @@ -1010,7 +1003,7 @@ public static extern void SetLocalScaling2(IntPtr shape, Vector3 scale); public static extern Vector3 GetLocalScaling2(IntPtr shape); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern void CalculateLocalInertia2(IntPtr shape, float mass, Vector3 inertia); +public static extern Vector3 CalculateLocalInertia2(IntPtr shape, float mass); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern int GetShapeType2(IntPtr shape); -- cgit v1.1 From c0fec70b1ad3047b8e543558a6aaee2916bd7b3f Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Thu, 13 Sep 2012 10:10:29 -0700 Subject: BulletSim: Add 'IsNativeShape2' call --- OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs index 043423e..087c61b 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs @@ -523,10 +523,7 @@ public static extern IntPtr BuildNativeShape2(IntPtr world, float shapeType, float collisionMargin, Vector3 scale); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool DeleteCollisionShape2(IntPtr world, IntPtr shape); - -[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern IntPtr CreateBodyFromShape2(IntPtr sim, IntPtr shape, Vector3 pos, Quaternion rot); +public static extern bool IsNativeShape2(IntPtr shape); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern IntPtr CreateCompoundShape2(IntPtr sim); @@ -541,6 +538,12 @@ public static extern void RemoveChildFromCompoundShape2(IntPtr cShape, IntPtr re public static extern IntPtr CreateBodyFromShapeAndInfo2(IntPtr sim, IntPtr shape, IntPtr constructionInfo); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern bool DeleteCollisionShape2(IntPtr world, IntPtr shape); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern IntPtr CreateBodyFromShape2(IntPtr sim, IntPtr shape, Vector3 pos, Quaternion rot); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern IntPtr CreateBodyWithDefaultMotionState2(IntPtr shape, Vector3 pos, Quaternion rot); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -- cgit v1.1 From d86cbe637943acde05528d0bce6dc61a77257cc0 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Thu, 13 Sep 2012 10:11:25 -0700 Subject: BulletSim: remove unused NeedsMeshing() code from BSScene. --- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 116 ------------------------ 1 file changed, 116 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index eea899f..9c958d5 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -56,7 +56,6 @@ using OpenMetaverse; // Do attachments need to be handled separately? Need collision events. Do not collide with VolumeDetect // Implement LockAngularMotion // Decide if clearing forces is the right thing to do when setting position (BulletSim::SetObjectTranslation) -// Does NeedsMeshing() really need to exclude all the different shapes? // Remove mesh and Hull stuff. Use mesh passed to bullet and use convexdecom from bullet. // Add PID movement operations. What does ScenePresence.MoveToTarget do? // Check terrain size. 128 or 127? @@ -666,121 +665,6 @@ public class BSScene : PhysicsScene, IPhysicsParameters public override bool IsThreaded { get { return false; } } - /// - /// Routine to figure out if we need to mesh this prim with our mesher - /// - /// - /// true if the prim needs meshing - public bool NeedsMeshing(PrimitiveBaseShape pbs) - { - // most of this is redundant now as the mesher will return null if it cant mesh a prim - // but we still need to check for sculptie meshing being enabled so this is the most - // convenient place to do it for now... - - // int iPropertiesNotSupportedDefault = 0; - - if (pbs.SculptEntry && !ShouldMeshSculptedPrim) - { - // Render sculpties as boxes - return false; - } - - // if it's a standard box or sphere with no cuts, hollows, twist or top shear, return false since Bullet - // can use an internal representation for the prim - if (!ShouldForceSimplePrimMeshing) - { - if ((pbs.ProfileShape == ProfileShape.Square && pbs.PathCurve == (byte)Extrusion.Straight) - || (pbs.ProfileShape == ProfileShape.HalfCircle && pbs.PathCurve == (byte)Extrusion.Curve1 - && pbs.Scale.X == pbs.Scale.Y && pbs.Scale.Y == pbs.Scale.Z)) - { - - if (pbs.ProfileBegin == 0 && pbs.ProfileEnd == 0 - && pbs.ProfileHollow == 0 - && pbs.PathTwist == 0 && pbs.PathTwistBegin == 0 - && pbs.PathBegin == 0 && pbs.PathEnd == 0 - && pbs.PathTaperX == 0 && pbs.PathTaperY == 0 - && pbs.PathScaleX == 100 && pbs.PathScaleY == 100 - && pbs.PathShearX == 0 && pbs.PathShearY == 0) - { - return false; - } - } - } - - /* TODO: verify that the mesher will now do all these shapes - if (pbs.ProfileHollow != 0) - iPropertiesNotSupportedDefault++; - - if ((pbs.PathBegin != 0) || pbs.PathEnd != 0) - iPropertiesNotSupportedDefault++; - - if ((pbs.PathTwistBegin != 0) || (pbs.PathTwist != 0)) - iPropertiesNotSupportedDefault++; - - if ((pbs.ProfileBegin != 0) || pbs.ProfileEnd != 0) - iPropertiesNotSupportedDefault++; - - if ((pbs.PathScaleX != 100) || (pbs.PathScaleY != 100)) - iPropertiesNotSupportedDefault++; - - if ((pbs.PathShearX != 0) || (pbs.PathShearY != 0)) - iPropertiesNotSupportedDefault++; - - if (pbs.ProfileShape == ProfileShape.Circle && pbs.PathCurve == (byte)Extrusion.Straight) - iPropertiesNotSupportedDefault++; - - if (pbs.ProfileShape == ProfileShape.HalfCircle && pbs.PathCurve == (byte)Extrusion.Curve1 && (pbs.Scale.X != pbs.Scale.Y || pbs.Scale.Y != pbs.Scale.Z || pbs.Scale.Z != pbs.Scale.X)) - iPropertiesNotSupportedDefault++; - - if (pbs.ProfileShape == ProfileShape.HalfCircle && pbs.PathCurve == (byte) Extrusion.Curve1) - iPropertiesNotSupportedDefault++; - - // test for torus - if ((pbs.ProfileCurve & 0x07) == (byte)ProfileShape.Square) - { - if (pbs.PathCurve == (byte)Extrusion.Curve1) - { - iPropertiesNotSupportedDefault++; - } - } - else if ((pbs.ProfileCurve & 0x07) == (byte)ProfileShape.Circle) - { - if (pbs.PathCurve == (byte)Extrusion.Straight) - { - iPropertiesNotSupportedDefault++; - } - // ProfileCurve seems to combine hole shape and profile curve so we need to only compare against the lower 3 bits - else if (pbs.PathCurve == (byte)Extrusion.Curve1) - { - iPropertiesNotSupportedDefault++; - } - } - else if ((pbs.ProfileCurve & 0x07) == (byte)ProfileShape.HalfCircle) - { - if (pbs.PathCurve == (byte)Extrusion.Curve1 || pbs.PathCurve == (byte)Extrusion.Curve2) - { - iPropertiesNotSupportedDefault++; - } - } - else if ((pbs.ProfileCurve & 0x07) == (byte)ProfileShape.EquilateralTriangle) - { - if (pbs.PathCurve == (byte)Extrusion.Straight) - { - iPropertiesNotSupportedDefault++; - } - else if (pbs.PathCurve == (byte)Extrusion.Curve1) - { - iPropertiesNotSupportedDefault++; - } - } - if (iPropertiesNotSupportedDefault == 0) - { - return false; - } - */ - return true; - } - // 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. -- cgit v1.1 From 7c347f4c5c966848669b979b367e1bc3912621d5 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Thu, 13 Sep 2012 10:11:39 -0700 Subject: BulletSim: Add calls to linkset class when object going static or dynamic. Reset center of mass on an object when going dynamic. --- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 20 ++++++++++++++++++-- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 20 ++++++++++++++------ 2 files changed, 32 insertions(+), 8 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index dc1de6c..3d73887 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -202,6 +202,24 @@ public class BSLinkset return com; } + // The object is going dynamic (physical). Do any setup necessary + // for a dynamic linkset. + // Return 'true' if any properties updated on the passed object. + // Called at taint-time! + public bool MakeDynamic(BSPhysObject child) + { + return false; + } + + // The object is going static (non-physical). Do any setup necessary + // for a static linkset. + // Return 'true' if any properties updated on the passed object. + // Called at taint-time! + public bool MakeStatic(BSPhysObject child) + { + return false; + } + // When physical properties are changed the linkset needs to recalculate // its internal properties. public void Refresh(BSPhysObject requestor) @@ -255,13 +273,11 @@ public class BSLinkset if (!somethingMissing) { // The root prim takes on the weight of the whole linkset - /* OMV.Vector3 inertia = BulletSimAPI.CalculateLocalInertia2(LinksetRoot.BSShape.Ptr, linksetMass); BulletSimAPI.SetMassProps2(LinksetRoot.BSBody.Ptr, linksetMass, inertia); OMV.Vector3 centerOfMass = ComputeLinksetCenterOfMass(); BulletSimAPI.SetCenterOfMassByPosRot2(LinksetRoot.BSBody.Ptr, centerOfMass, OMV.Quaternion.Identity); BulletSimAPI.UpdateInertiaTensor2(LinksetRoot.BSBody.Ptr); - */ } } return; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 481a8db..04b7be5 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -530,10 +530,14 @@ public sealed class BSPrim : BSPhysObject m_currentCollisionFlags = BulletSimAPI.AddToCollisionFlags2(BSBody.Ptr, CollisionFlags.CF_STATIC_OBJECT); // Stop all movement BulletSimAPI.ClearAllForces2(BSBody.Ptr); + // Center of mass is at the center of the object + BulletSimAPI.SetCenterOfMassByPosRot2(Linkset.LinksetRoot.BSBody.Ptr, _position, _orientation); // Mass is zero which disables a bunch of physics stuff in Bullet BulletSimAPI.SetMassProps2(BSBody.Ptr, 0f, OMV.Vector3.Zero); // There is no inertia in a static object BulletSimAPI.UpdateInertiaTensor2(BSBody.Ptr); + // There can be special things needed for implementing linksets + Linkset.MakeStatic(this); // The activation state is 'sleeping' so Bullet will not try to act on it BulletSimAPI.ForceActivationState2(BSBody.Ptr, ActivationState.ISLAND_SLEEPING); } @@ -543,10 +547,12 @@ public sealed class BSPrim : BSPhysObject m_currentCollisionFlags = BulletSimAPI.RemoveFromCollisionFlags2(BSBody.Ptr, CollisionFlags.CF_STATIC_OBJECT); // A dynamic object has mass IntPtr collisionShapePtr = BulletSimAPI.GetCollisionShape2(BSBody.Ptr); - OMV.Vector3 inertia = BulletSimAPI.CalculateLocalInertia2(collisionShapePtr, _mass); + OMV.Vector3 inertia = BulletSimAPI.CalculateLocalInertia2(collisionShapePtr, Linkset.LinksetMass); BulletSimAPI.SetMassProps2(BSBody.Ptr, _mass, inertia); // Inertia is based on our new mass BulletSimAPI.UpdateInertiaTensor2(BSBody.Ptr); + // There can be special things needed for implementing linksets + Linkset.MakeDynamic(this); // Force activation of the object so Bullet will act on it. BulletSimAPI.Activate2(BSBody.Ptr, true); } @@ -1055,11 +1061,12 @@ public sealed class BSPrim : BSPhysObject }// end CalculateMass #endregion Mass Calculation - // Create the geometry information in Bullet for later use - // The objects needs a hull if it's physical otherwise a mesh is enough - // No locking here because this is done when we know physics is not simulating - // if 'forceRebuild' is true, the geometry is rebuilt. Otherwise a previously built version is used - // Returns 'true' if the geometry was rebuilt + // Create the geometry information in Bullet for later use. + // The objects needs a hull if it's physical otherwise a mesh is enough. + // No locking here because this is done when we know physics is not simulating. + // if 'forceRebuild' is true, the geometry is rebuilt. Otherwise a previously built version is used. + // Returns 'true' if the geometry was rebuilt. + // Called at taint-time! private bool CreateGeom(bool forceRebuild) { bool ret = false; @@ -1128,6 +1135,7 @@ public sealed class BSPrim : BSPhysObject // No locking here because this is done when we know physics is not simulating // Returns 'true' of a mesh was actually rebuild (we could also have one of these specs). + // Called at taint-time! private bool CreateGeomMesh() { // level of detail based on size and type of the object -- cgit v1.1 From f0a098924e8a3f64692de5d3326bfbdfb2b208a2 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Thu, 13 Sep 2012 13:51:28 -0700 Subject: BulletSim: set all linkset objects center of mass to the whole linkset's center of mass --- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 17 +++++++++++++++-- 1 file changed, 15 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 3d73887..7e784eb 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -204,11 +204,14 @@ public class BSLinkset // The object is going dynamic (physical). Do any setup necessary // for a dynamic linkset. + // Only the state of the passed object can be modified. The rest of the linkset + // has not yet been fully constructed. // Return 'true' if any properties updated on the passed object. // Called at taint-time! public bool MakeDynamic(BSPhysObject child) { - return false; + bool ret = false; + return ret; } // The object is going static (non-physical). Do any setup necessary @@ -217,6 +220,7 @@ public class BSLinkset // Called at taint-time! public bool MakeStatic(BSPhysObject child) { + // What is done for each object in BSPrim is what we want. return false; } @@ -269,15 +273,24 @@ public class BSLinkset } } - // If the whole linkset is not here, doesn't make sense to recompute the root prim now. + // If the whole linkset is not here, doesn't make sense to recompute linkset wide values if (!somethingMissing) { + // If this is a multiple object linkset, set everybody's center of mass to the set's center of mass + OMV.Vector3 centerOfMass = ComputeLinksetCenterOfMass(); + BulletSimAPI.SetCenterOfMassByPosRot2(LinksetRoot.BSBody.Ptr, centerOfMass, OMV.Quaternion.Identity); + foreach (BSPhysObject child in m_children) + { + BulletSimAPI.SetCenterOfMassByPosRot2(child.BSBody.Ptr, centerOfMass, OMV.Quaternion.Identity); + } + /* // The root prim takes on the weight of the whole linkset OMV.Vector3 inertia = BulletSimAPI.CalculateLocalInertia2(LinksetRoot.BSShape.Ptr, linksetMass); BulletSimAPI.SetMassProps2(LinksetRoot.BSBody.Ptr, linksetMass, inertia); OMV.Vector3 centerOfMass = ComputeLinksetCenterOfMass(); BulletSimAPI.SetCenterOfMassByPosRot2(LinksetRoot.BSBody.Ptr, centerOfMass, OMV.Quaternion.Identity); BulletSimAPI.UpdateInertiaTensor2(LinksetRoot.BSBody.Ptr); + */ } } return; -- cgit v1.1 From 6632eb7c051e2638ea1c58c2876e7d6825398556 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Thu, 13 Sep 2012 13:51:42 -0700 Subject: BulletSim: Remove calculation and passing of unused collied object type. Fix collision code to properly sense mega-region children regions as terrain. When setting an object physical, reset all the physical properties (friction, ...). --- .../Region/Physics/BulletSPlugin/BSCharacter.cs | 8 +++---- .../Region/Physics/BulletSPlugin/BSPhysObject.cs | 2 +- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 28 +++++++++++++++++----- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 26 ++++++++------------ 4 files changed, 36 insertions(+), 28 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index a9b1365..526dbad 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -529,22 +529,20 @@ public class BSCharacter : BSPhysObject // The collision, if it should be reported to the character, is placed in a collection // that will later be sent to the simulator when SendCollisions() is called. CollisionEventUpdate collisionCollection = null; - public override bool Collide(uint collidingWith, BSPhysObject collidee, ActorTypes type, Vector3 contactPoint, Vector3 contactNormal, float pentrationDepth) + public override bool Collide(uint collidingWith, BSPhysObject collidee, Vector3 contactPoint, Vector3 contactNormal, float pentrationDepth) { - // m_log.DebugFormat("{0}: Collide: ms={1}, id={2}, with={3}", LogHeader, _subscribedEventsMs, LocalID, collidingWith); - bool ret = false; // The following makes IsColliding() and IsCollidingGround() work _collidingStep = Scene.SimulationStep; - if (collidingWith == BSScene.TERRAIN_ID || collidingWith == BSScene.GROUNDPLANE_ID) + if (collidingWith <= Scene.TerrainManager.HighestTerrainID) { _collidingGroundStep = Scene.SimulationStep; } // DetailLog("{0},BSCharacter.Collison,call,with={1}", LocalID, collidingWith); // throttle collisions to the rate specified in the subscription - if (_subscribedEventsMs != 0) { + if (SubscribedEvents()) { int nowTime = Scene.SimulationNowTime; if (nowTime >= _nextCollisionOkTime) { _nextCollisionOkTime = nowTime + _subscribedEventsMs; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index 969c53e..3fe71e1 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -41,7 +41,7 @@ public abstract class BSPhysObject : PhysicsActor { public abstract BSLinkset Linkset { get; set; } - public abstract bool Collide(uint collidingWith, BSPhysObject collidee, ActorTypes type, + public abstract bool Collide(uint collidingWith, BSPhysObject collidee, OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth); public abstract void SendCollisions(); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 04b7be5..6827be0 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -545,14 +545,31 @@ public sealed class BSPrim : BSPhysObject { // Not a Bullet static object m_currentCollisionFlags = BulletSimAPI.RemoveFromCollisionFlags2(BSBody.Ptr, CollisionFlags.CF_STATIC_OBJECT); + + // Set various physical properties so internal things will get computed correctly as they are set + BulletSimAPI.SetFriction2(BSBody.Ptr, Scene.Params.defaultFriction); + BulletSimAPI.SetRestitution2(BSBody.Ptr, Scene.Params.defaultRestitution); + // per http://www.bulletphysics.org/Bullet/phpBB3/viewtopic.php?t=3382 + BulletSimAPI.SetInterpolationLinearVelocity2(BSBody.Ptr, OMV.Vector3.Zero); + BulletSimAPI.SetInterpolationAngularVelocity2(BSBody.Ptr, OMV.Vector3.Zero); + BulletSimAPI.SetInterpolationVelocity2(BSBody.Ptr, OMV.Vector3.Zero, OMV.Vector3.Zero); + // A dynamic object has mass IntPtr collisionShapePtr = BulletSimAPI.GetCollisionShape2(BSBody.Ptr); OMV.Vector3 inertia = BulletSimAPI.CalculateLocalInertia2(collisionShapePtr, Linkset.LinksetMass); BulletSimAPI.SetMassProps2(BSBody.Ptr, _mass, inertia); // Inertia is based on our new mass BulletSimAPI.UpdateInertiaTensor2(BSBody.Ptr); + + // Various values for simulation limits + BulletSimAPI.SetDamping2(BSBody.Ptr, Scene.Params.linearDamping, Scene.Params.angularDamping); + BulletSimAPI.SetDeactivationTime2(BSBody.Ptr, Scene.Params.deactivationTime); + BulletSimAPI.SetSleepingThresholds2(BSBody.Ptr, Scene.Params.linearSleepingThreshold, Scene.Params.angularSleepingThreshold); + BulletSimAPI.SetContactProcessingThreshold2(BSBody.Ptr, Scene.Params.contactProcessingThreshold); + // There can be special things needed for implementing linksets Linkset.MakeDynamic(this); + // Force activation of the object so Bullet will act on it. BulletSimAPI.Activate2(BSBody.Ptr, true); } @@ -1475,16 +1492,15 @@ public sealed class BSPrim : BSPhysObject // I've collided with something // Called at taint time from within the Step() function CollisionEventUpdate collisionCollection; - public override bool Collide(uint collidingWith, BSPhysObject collidee, ActorTypes type, OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth) + public override bool Collide(uint collidingWith, BSPhysObject collidee, OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth) { - // m_log.DebugFormat("{0}: Collide: ms={1}, id={2}, with={3}", LogHeader, _subscribedEventsMs, LocalID, collidingWith); bool ret = false; // The following lines make IsColliding() and IsCollidingGround() work - _collidingStep = _scene.SimulationStep; - if (collidingWith == BSScene.TERRAIN_ID || collidingWith == BSScene.GROUNDPLANE_ID) + _collidingStep = Scene.SimulationStep; + if (collidingWith <= Scene.TerrainManager.HighestTerrainID) { - _collidingGroundStep = _scene.SimulationStep; + _collidingGroundStep = Scene.SimulationStep; } // DetailLog("{0},BSPrim.Collison,call,with={1}", LocalID, collidingWith); @@ -1498,7 +1514,7 @@ public sealed class BSPrim : BSPhysObject // if someone has subscribed for collision events.... if (SubscribedEvents()) { // throttle the collisions to the number of milliseconds specified in the subscription - int nowTime = _scene.SimulationNowTime; + int nowTime = Scene.SimulationNowTime; if (nowTime >= _nextCollisionOkTime) { _nextCollisionOkTime = nowTime + _subscribedEventsMs; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index 9c958d5..c38867f 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -583,27 +583,21 @@ public class BSScene : PhysicsScene, IPhysicsParameters return; // don't send collisions to the terrain } - BSPhysObject collider = PhysObjects[localID]; - // TODO: as of this code, terrain was not in the physical object list. - // When BSTerrain is created and it will be in the list, we can remove - // the possibility that it's not there and just fetch the collidee. - BSPhysObject collidee = null; - - ActorTypes type = ActorTypes.Prim; - if (collidingWith <= TerrainManager.HighestTerrainID) + BSPhysObject collider; + if (!PhysObjects.TryGetValue(localID, out collider)) { - type = ActorTypes.Ground; - } - else - { - collidee = PhysObjects[collidingWith]; - if (collidee is BSCharacter) - type = ActorTypes.Agent; + // If the object that is colliding cannot be found, just ignore the collision. + return; } + // 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); + // DetailLog("{0},BSScene.SendCollision,collide,id={1},with={2}", DetailLogZero, localID, collidingWith); - if (collider.Collide(collidingWith, collidee, type, collidePoint, collideNormal, penetration)) + if (collider.Collide(collidingWith, collidee, collidePoint, collideNormal, penetration)) { // If a collision was posted, remember to send it to the simulator m_objectsWithCollisions.Add(collider); -- cgit v1.1 From dcb94b8a242dff0f3a33f084565af49d6582f663 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Fri, 14 Sep 2012 11:11:43 -0700 Subject: BulletSim: remove timeStep parameter from calls for vehicle parameter setting. There is no reason these should be using the simulation time interval for parameter calculation. --- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 9 +++------ OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 6 +++--- 2 files changed, 6 insertions(+), 9 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index 098fea7..5f62b12 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -131,7 +131,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin m_type = Vehicle.TYPE_NONE; } - internal void ProcessFloatVehicleParam(Vehicle pParam, float pValue, float timestep) + internal void ProcessFloatVehicleParam(Vehicle pParam, float pValue) { VDetailLog("{0},ProcessFloatVehicleParam,param={1},val={2}", m_prim.LocalID, pParam, pValue); switch (pParam) @@ -230,7 +230,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin } }//end ProcessFloatVehicleParam - internal void ProcessVectorVehicleParam(Vehicle pParam, Vector3 pValue, float timestep) + internal void ProcessVectorVehicleParam(Vehicle pParam, Vector3 pValue) { VDetailLog("{0},ProcessVectorVehicleParam,param={1},val={2}", m_prim.LocalID, pParam, pValue); switch (pParam) @@ -299,7 +299,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin } }//end ProcessVehicleFlags - internal void ProcessTypeChange(Vehicle pType, float stepSize) + internal void ProcessTypeChange(Vehicle pType) { VDetailLog("{0},ProcessTypeChange,type={1}", m_prim.LocalID, pType); // Set Defaults For Type @@ -537,9 +537,6 @@ namespace OpenSim.Region.Physics.BulletSPlugin // Add the various forces into m_dir which will be our new direction vector (velocity) // add Gravity and Buoyancy - // KF: So far I have found no good method to combine a script-requested - // .Z velocity and gravity. Therefore only 0g will used script-requested - // .Z velocity. >0g (m_VehicleBuoyancy < 1) will used modified gravity only. // There is some gravity, make a gravity force vector that is applied after object velocity. // m_VehicleBuoyancy: -1=2g; 0=1g; 1=0g; Vector3 grav = m_prim.Scene.DefaultGravity * (m_prim.Mass * (1f - m_VehicleBuoyancy)); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 6827be0..d97231c 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -346,7 +346,7 @@ public sealed class BSPrim : BSPhysObject { // 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. - _vehicle.ProcessTypeChange(type, Scene.LastSimulatedTimestep); + _vehicle.ProcessTypeChange(type); // Tell the scene about the vehicle so it will get processing each frame. _scene.VehicleInSceneTypeChanged(this, type); }); @@ -356,14 +356,14 @@ public sealed class BSPrim : BSPhysObject { _scene.TaintedObject("BSPrim.VehicleFloatParam", delegate() { - _vehicle.ProcessFloatVehicleParam((Vehicle)param, value, _scene.LastSimulatedTimestep); + _vehicle.ProcessFloatVehicleParam((Vehicle)param, value); }); } public override void VehicleVectorParam(int param, OMV.Vector3 value) { _scene.TaintedObject("BSPrim.VehicleVectorParam", delegate() { - _vehicle.ProcessVectorVehicleParam((Vehicle)param, value, _scene.LastSimulatedTimestep); + _vehicle.ProcessVectorVehicleParam((Vehicle)param, value); }); } public override void VehicleRotationParam(int param, OMV.Quaternion rotation) -- cgit v1.1 From f35bd6eb7d5b0eb1a6d385f5f1d0147acfc3c8ef Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Fri, 14 Sep 2012 11:12:23 -0700 Subject: BulletSim: another attempt at computing physics FPS correctly. --- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 29 +++++-------------------- 1 file changed, 6 insertions(+), 23 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index c38867f..52997dd 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -110,11 +110,6 @@ public class BSScene : PhysicsScene, IPhysicsParameters private long m_simulationStep = 0; public long SimulationStep { get { return m_simulationStep; } } - // The length of the last timestep we were asked to simulate. - // This is used by the vehicle code. Since the vehicle code is called - // once per simulation step, its constants need to be scaled by this. - public float LastSimulatedTimestep { get; private set; } - // 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; } @@ -469,12 +464,8 @@ public class BSScene : PhysicsScene, IPhysicsParameters int collidersCount = 0; IntPtr collidersPtr; - LastSimulatedTimestep = timeStep; - // prevent simulation until we've been initialized - if (!m_initialized) return 10.0f; - - int simulateStartTime = Util.EnvironmentTickCount(); + if (!m_initialized) return 5.0f; // update the prim states while we know the physics engine is not busy int numTaints = _taintedObjects.Count; @@ -514,7 +505,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters // This is a kludge to get avatar movement updates. // ODE sends collisions for avatars even if there are have been no collisions. This updates // avatar animations and stuff. - // If you fix avatar animation updates, remove this overhead and let collisions happen. + // If you fix avatar animation updates, remove this overhead and let normal collision processing happen. m_objectsWithCollisions = new HashSet(m_avatarsWithCollisions); // If there were collisions, process them by sending the event to the prim. @@ -561,18 +552,10 @@ public class BSScene : PhysicsScene, IPhysicsParameters } } - // this is a waste since the outside routine also calcuates the physics simulation - // period. TODO: There should be a way of computing physics frames from simulator computation. - // long simulateTotalTime = Util.EnvironmentTickCountSubtract(simulateStartTime); - // return (timeStep * (float)simulateTotalTime); - - // TODO: FIX THIS: fps calculation possibly wrong. - // This calculation says 1/timeStep is the ideal frame rate. Any time added to - // that by the physics simulation gives a slower frame rate. - long totalSimulationTime = Util.EnvironmentTickCountSubtract(simulateStartTime); - if (totalSimulationTime >= timeStep) - return 0; - return 1f / (timeStep + totalSimulationTime); + // 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. + // Since Bullet normally does 5 or 6 substeps, this will normally sum to about 60 FPS. + return numSubSteps * m_fixedTimeStep; } // Something has collided -- cgit v1.1 From 1826b2b18e8d82a91ca34787e17cf4ef0d1f46a6 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Fri, 14 Sep 2012 11:13:05 -0700 Subject: BulletSim: add the debugging routine DumpRigidBody2() to API2. --- OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs index 087c61b..9221cdb 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs @@ -558,9 +558,6 @@ public static extern void DestroyObject2(IntPtr sim, IntPtr obj); // ===================================================================================== // Terrain creation and helper routines [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern void DumpMapInfo(IntPtr sim, IntPtr manInfo); - -[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern IntPtr CreateHeightMapInfo2(IntPtr sim, uint id, Vector3 minCoords, Vector3 maxCoords, [MarshalAs(UnmanagedType.LPArray)] float[] heightMap, float collisionMargin); @@ -1023,6 +1020,12 @@ public static extern void SetCollisionFilterMask(IntPtr shape, uint filter, uint // ===================================================================================== // Debugging [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void DumpRigidBody2(IntPtr sim, IntPtr collisionObject); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void DumpMapInfo2(IntPtr sim, IntPtr manInfo); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern void DumpPhysicsStatistics2(IntPtr sim); } -- cgit v1.1 From c77be802d2879c0504438905359c1b865a92d3a1 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Sat, 15 Sep 2012 15:23:54 -0700 Subject: BulletSim: some debugging prints in BSPrim for tracking changes in linkset children. --- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 4 +++- 1 file changed, 3 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 d97231c..26a581f 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -1476,12 +1476,14 @@ public sealed class BSPrim : BSPhysObject DetailLog("{0},BSPrim.UpdateProperties,call,pos={1},orient={2},vel={3},accel={4},rotVel={5}", LocalID, _position, _orientation, _velocity, _acceleration, _rotationalVelocity); + // BulletSimAPI.DumpRigidBody2(Scene.World.Ptr, BSBody.Ptr); + base.RequestPhysicsterseUpdate(); } /* else { - // For debugging, we also report the movement of children + // For debugging, we can also 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); -- cgit v1.1 From b602b476adafe8e6eab9ec257db029a3d05db224 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Sat, 15 Sep 2012 15:36:13 -0700 Subject: BulletSim: update DLLs and SOs and remove some debugging code. --- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index 5f62b12..61006f0 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -475,7 +475,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin frcount = 0; MoveLinear(pTimestep); - // MoveAngular(pTimestep); + MoveAngular(pTimestep); LimitRotation(pTimestep); // remember the position so next step we can limit absolute movement effects -- cgit v1.1 From ee7cda261cbbc9dcd558c35eabc070cc0bf45644 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 18 Sep 2012 08:39:52 -0700 Subject: BulletSim: move a bunch of common logic out of BSPrim and BSCharacter and into the parent class BSPhysObject. Rework collision logic to enable extra collision after done colliding. Rename 'Scene' to 'PhysicsScene' to differentiate it from the simulator 'Scene'. --- .../Region/Physics/BulletSPlugin/BSCharacter.cs | 238 +++++++-------------- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 10 +- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 42 ++-- .../Region/Physics/BulletSPlugin/BSPhysObject.cs | 138 +++++++++++- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 232 +++++++------------- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 60 ++++-- .../Region/Physics/BulletSPlugin/BulletSimAPI.cs | 57 +---- 7 files changed, 361 insertions(+), 416 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index 526dbad..57d5726 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -28,7 +28,7 @@ using System; using System.Collections.Generic; using System.Reflection; using log4net; -using OpenMetaverse; +using OMV = OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Physics.Manager; @@ -39,25 +39,24 @@ public class BSCharacter : BSPhysObject private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static readonly string LogHeader = "[BULLETS CHAR]"; - public BSScene Scene { get; private set; } private String _avName; // private bool _stopped; - private Vector3 _size; - private Vector3 _scale; + private OMV.Vector3 _size; + private OMV.Vector3 _scale; private PrimitiveBaseShape _pbs; private uint _localID = 0; private bool _grabbed; private bool _selected; - private Vector3 _position; + private OMV.Vector3 _position; private float _mass; public float _density; public float _avatarVolume; - private Vector3 _force; - private Vector3 _velocity; - private Vector3 _torque; + private OMV.Vector3 _force; + private OMV.Vector3 _velocity; + private OMV.Vector3 _torque; private float _collisionScore; - private Vector3 _acceleration; - private Quaternion _orientation; + private OMV.Vector3 _acceleration; + private OMV.Quaternion _orientation; private int _physicsActorType; private bool _isPhysical; private bool _flying; @@ -69,18 +68,14 @@ public class BSCharacter : BSPhysObject private long _collidingGroundStep; private bool _collidingObj; private bool _floatOnWater; - private Vector3 _rotationalVelocity; + private OMV.Vector3 _rotationalVelocity; private bool _kinematic; private float _buoyancy; - public override BulletBody BSBody { get; set; } - public override BulletShape BSShape { get; set; } - public override BSLinkset Linkset { get; set; } - private int _subscribedEventsMs = 0; private int _nextCollisionOkTime = 0; - private Vector3 _PIDTarget; + private OMV.Vector3 _PIDTarget; private bool _usePID; private float _PIDTau; private bool _useHoverPID; @@ -88,26 +83,24 @@ public class BSCharacter : BSPhysObject private PIDHoverType _PIDHoverType; private float _PIDHoverTao; - public BSCharacter(uint localID, String avName, BSScene parent_scene, Vector3 pos, Vector3 size, bool isFlying) + public BSCharacter(uint localID, String avName, BSScene parent_scene, OMV.Vector3 pos, OMV.Vector3 size, bool isFlying) { + base.BaseInitialize(parent_scene); _localID = localID; _avName = avName; - Scene = parent_scene; _physicsActorType = (int)ActorTypes.Agent; _position = pos; _size = size; _flying = isFlying; - _orientation = Quaternion.Identity; - _velocity = Vector3.Zero; + _orientation = OMV.Quaternion.Identity; + _velocity = OMV.Vector3.Zero; _buoyancy = ComputeBuoyancyFromFlying(isFlying); // The dimensions of the avatar capsule are kept in the scale. // Physics creates a unit capsule which is scaled by the physics engine. - _scale = new Vector3(Scene.Params.avatarCapsuleRadius, Scene.Params.avatarCapsuleRadius, size.Z); - _density = Scene.Params.avatarDensity; + _scale = new OMV.Vector3(PhysicsScene.Params.avatarCapsuleRadius, PhysicsScene.Params.avatarCapsuleRadius, size.Z); + _density = PhysicsScene.Params.avatarDensity; ComputeAvatarVolumeAndMass(); // set _avatarVolume and _mass based on capsule size, _density and _scale - Linkset = new BSLinkset(Scene, this); - ShapeData shapeData = new ShapeData(); shapeData.ID = _localID; shapeData.Type = ShapeData.PhysicsShapeType.SHAPE_AVATAR; @@ -118,19 +111,19 @@ public class BSCharacter : BSPhysObject shapeData.Mass = _mass; shapeData.Buoyancy = _buoyancy; shapeData.Static = ShapeData.numericFalse; - shapeData.Friction = Scene.Params.avatarFriction; - shapeData.Restitution = Scene.Params.avatarRestitution; + shapeData.Friction = PhysicsScene.Params.avatarFriction; + shapeData.Restitution = PhysicsScene.Params.avatarRestitution; // do actual create at taint time - Scene.TaintedObject("BSCharacter.create", delegate() + PhysicsScene.TaintedObject("BSCharacter.create", delegate() { DetailLog("{0},BSCharacter.create", _localID); - BulletSimAPI.CreateObject(Scene.WorldID, shapeData); + BulletSimAPI.CreateObject(PhysicsScene.WorldID, shapeData); // Set the buoyancy for flying. This will be refactored when all the settings happen in C# - BulletSimAPI.SetObjectBuoyancy(Scene.WorldID, LocalID, _buoyancy); + BulletSimAPI.SetObjectBuoyancy(PhysicsScene.WorldID, LocalID, _buoyancy); - BSBody = new BulletBody(LocalID, BulletSimAPI.GetBodyHandle2(Scene.World.Ptr, LocalID)); + BSBody = new BulletBody(LocalID, BulletSimAPI.GetBodyHandle2(PhysicsScene.World.Ptr, LocalID)); }); return; @@ -140,9 +133,9 @@ public class BSCharacter : BSPhysObject public override void Destroy() { DetailLog("{0},BSCharacter.Destroy", LocalID); - Scene.TaintedObject("BSCharacter.destroy", delegate() + PhysicsScene.TaintedObject("BSCharacter.destroy", delegate() { - BulletSimAPI.DestroyObject(Scene.WorldID, _localID); + BulletSimAPI.DestroyObject(PhysicsScene.WorldID, _localID); }); } @@ -154,11 +147,11 @@ public class BSCharacter : BSPhysObject public override bool Stopped { get { return false; } } - public override Vector3 Size { + public override OMV.Vector3 Size { get { // Avatar capsule size is kept in the scale parameter. - return new Vector3(_scale.X * 2, _scale.Y * 2, _scale.Z); + return new OMV.Vector3(_scale.X * 2, _scale.Y * 2, _scale.Z); } set { @@ -171,9 +164,9 @@ public class BSCharacter : BSPhysObject ComputeAvatarVolumeAndMass(); - Scene.TaintedObject("BSCharacter.setSize", delegate() + PhysicsScene.TaintedObject("BSCharacter.setSize", delegate() { - BulletSimAPI.SetObjectScaleMass(Scene.WorldID, LocalID, _scale, _mass, true); + BulletSimAPI.SetObjectScaleMass(PhysicsScene.WorldID, LocalID, _scale, _mass, true); }); } @@ -198,9 +191,27 @@ public class BSCharacter : BSPhysObject public override void CrossingFailure() { return; } public override void link(PhysicsActor obj) { return; } public override void delink() { return; } - public override void LockAngularMotion(Vector3 axis) { return; } - public override Vector3 Position { + // Set motion values to zero. + // Do it to the properties so the values get set in the physics engine. + // Push the setting of the values to the viewer. + // Called at taint time! + public override void ZeroMotion() + { + _velocity = OMV.Vector3.Zero; + _acceleration = OMV.Vector3.Zero; + _rotationalVelocity = OMV.Vector3.Zero; + + // Zero some other properties directly into the physics engine + BulletSimAPI.SetLinearVelocity2(BSBody.Ptr, OMV.Vector3.Zero); + BulletSimAPI.SetAngularVelocity2(BSBody.Ptr, OMV.Vector3.Zero); + BulletSimAPI.SetInterpolationVelocity2(BSBody.Ptr, OMV.Vector3.Zero, OMV.Vector3.Zero); + BulletSimAPI.ClearForces2(BSBody.Ptr); + } + + public override void LockAngularMotion(OMV.Vector3 axis) { return; } + + public override OMV.Vector3 Position { get { // _position = BulletSimAPI.GetObjectPosition(Scene.WorldID, _localID); return _position; @@ -209,10 +220,10 @@ public class BSCharacter : BSPhysObject _position = value; PositionSanityCheck(); - Scene.TaintedObject("BSCharacter.setPosition", delegate() + PhysicsScene.TaintedObject("BSCharacter.setPosition", delegate() { DetailLog("{0},BSCharacter.SetPosition,taint,pos={1},orient={2}", LocalID, _position, _orientation); - BulletSimAPI.SetObjectTranslation(Scene.WorldID, _localID, _position, _orientation); + BulletSimAPI.SetObjectTranslation(PhysicsScene.WorldID, _localID, _position, _orientation); }); } } @@ -225,7 +236,7 @@ public class BSCharacter : BSPhysObject bool ret = false; // If below the ground, move the avatar up - float terrainHeight = Scene.TerrainManager.GetTerrainHeightAtXYZ(_position); + float terrainHeight = PhysicsScene.TerrainManager.GetTerrainHeightAtXYZ(_position); if (Position.Z < terrainHeight) { DetailLog("{0},BSCharacter.PositionAdjustUnderGround,call,pos={1},terrain={2}", LocalID, _position, terrainHeight); @@ -247,10 +258,10 @@ public 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. - Scene.TaintedObject("BSCharacter.PositionSanityCheck", delegate() + PhysicsScene.TaintedObject("BSCharacter.PositionSanityCheck", delegate() { DetailLog("{0},BSCharacter.PositionSanityCheck,taint,pos={1},orient={2}", LocalID, _position, _orientation); - BulletSimAPI.SetObjectTranslation(Scene.WorldID, _localID, _position, _orientation); + BulletSimAPI.SetObjectTranslation(PhysicsScene.WorldID, _localID, _position, _orientation); }); ret = true; } @@ -266,15 +277,15 @@ public class BSCharacter : BSPhysObject // used when we only want this prim's mass and not the linkset thing public override float MassRaw { get {return _mass; } } - public override Vector3 Force { + public override OMV.Vector3 Force { get { return _force; } set { _force = value; // m_log.DebugFormat("{0}: Force = {1}", LogHeader, _force); - Scene.TaintedObject("BSCharacter.SetForce", delegate() + PhysicsScene.TaintedObject("BSCharacter.SetForce", delegate() { DetailLog("{0},BSCharacter.setForce,taint,force={1}", LocalID, _force); - BulletSimAPI.SetObjectForce(Scene.WorldID, LocalID, _force); + BulletSimAPI.SetObjectForce(PhysicsScene.WorldID, LocalID, _force); }); } } @@ -284,28 +295,28 @@ public class BSCharacter : BSPhysObject set { return; } } public override void VehicleFloatParam(int param, float value) { } - public override void VehicleVectorParam(int param, Vector3 value) {} - public override void VehicleRotationParam(int param, Quaternion rotation) { } + public override void VehicleVectorParam(int param, OMV.Vector3 value) {} + public override void VehicleRotationParam(int param, OMV.Quaternion rotation) { } public override void VehicleFlags(int param, bool remove) { } // Allows the detection of collisions with inherently non-physical prims. see llVolumeDetect for more public override void SetVolumeDetect(int param) { return; } - public override Vector3 GeometricCenter { get { return Vector3.Zero; } } - public override Vector3 CenterOfMass { get { return Vector3.Zero; } } - public override Vector3 Velocity { + public override OMV.Vector3 GeometricCenter { get { return OMV.Vector3.Zero; } } + public override OMV.Vector3 CenterOfMass { get { return OMV.Vector3.Zero; } } + public override OMV.Vector3 Velocity { get { return _velocity; } set { _velocity = value; // m_log.DebugFormat("{0}: set velocity = {1}", LogHeader, _velocity); - Scene.TaintedObject("BSCharacter.setVelocity", delegate() + PhysicsScene.TaintedObject("BSCharacter.setVelocity", delegate() { DetailLog("{0},BSCharacter.setVelocity,taint,vel={1}", LocalID, _velocity); - BulletSimAPI.SetObjectVelocity(Scene.WorldID, _localID, _velocity); + BulletSimAPI.SetObjectVelocity(PhysicsScene.WorldID, _localID, _velocity); }); } } - public override Vector3 Torque { + public override OMV.Vector3 Torque { get { return _torque; } set { _torque = value; } @@ -315,19 +326,19 @@ public class BSCharacter : BSPhysObject set { _collisionScore = value; } } - public override Vector3 Acceleration { + public override OMV.Vector3 Acceleration { get { return _acceleration; } set { _acceleration = value; } } - public override Quaternion Orientation { + public override OMV.Quaternion Orientation { get { return _orientation; } set { _orientation = value; // m_log.DebugFormat("{0}: set orientation to {1}", LogHeader, _orientation); - Scene.TaintedObject("BSCharacter.setOrientation", delegate() + PhysicsScene.TaintedObject("BSCharacter.setOrientation", delegate() { // _position = BulletSimAPI.GetObjectPosition(Scene.WorldID, _localID); - BulletSimAPI.SetObjectTranslation(Scene.WorldID, _localID, _position, _orientation); + BulletSimAPI.SetObjectTranslation(PhysicsScene.WorldID, _localID, _position, _orientation); }); } } @@ -364,11 +375,11 @@ public class BSCharacter : BSPhysObject set { _throttleUpdates = value; } } public override bool IsColliding { - get { return (_collidingStep == Scene.SimulationStep); } + get { return (_collidingStep == PhysicsScene.SimulationStep); } set { _isColliding = value; } } public override bool CollidingGround { - get { return (_collidingGroundStep == Scene.SimulationStep); } + get { return (_collidingGroundStep == PhysicsScene.SimulationStep); } set { _collidingGround = value; } } public override bool CollidingObj { @@ -378,7 +389,7 @@ public class BSCharacter : BSPhysObject public override bool FloatOnWater { set { _floatOnWater = value; } } - public override Vector3 RotationalVelocity { + public override OMV.Vector3 RotationalVelocity { get { return _rotationalVelocity; } set { _rotationalVelocity = value; } } @@ -390,16 +401,16 @@ public class BSCharacter : BSPhysObject public override float Buoyancy { get { return _buoyancy; } set { _buoyancy = value; - Scene.TaintedObject("BSCharacter.setBuoyancy", delegate() + PhysicsScene.TaintedObject("BSCharacter.setBuoyancy", delegate() { DetailLog("{0},BSCharacter.setBuoyancy,taint,buoy={1}", LocalID, _buoyancy); - BulletSimAPI.SetObjectBuoyancy(Scene.WorldID, LocalID, _buoyancy); + BulletSimAPI.SetObjectBuoyancy(PhysicsScene.WorldID, LocalID, _buoyancy); }); } } // Used for MoveTo - public override Vector3 PIDTarget { + public override OMV.Vector3 PIDTarget { set { _PIDTarget = value; } } public override bool PIDActive { @@ -425,19 +436,19 @@ public class BSCharacter : BSPhysObject } // For RotLookAt - public override Quaternion APIDTarget { set { return; } } + 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(Vector3 force, bool pushforce) { + public override void AddForce(OMV.Vector3 force, bool pushforce) { if (force.IsFinite()) { _force.X += force.X; _force.Y += force.Y; _force.Z += force.Z; // m_log.DebugFormat("{0}: AddForce. adding={1}, newForce={2}", LogHeader, force, _force); - Scene.TaintedObject("BSCharacter.AddForce", delegate() + PhysicsScene.TaintedObject("BSCharacter.AddForce", delegate() { DetailLog("{0},BSCharacter.setAddForce,taint,addedForce={1}", LocalID, _force); BulletSimAPI.SetObjectForce2(BSBody.Ptr, _force); @@ -450,42 +461,9 @@ public class BSCharacter : BSPhysObject //m_lastUpdateSent = false; } - public override void AddAngularForce(Vector3 force, bool pushforce) { - } - public override void SetMomentum(Vector3 momentum) { - } - - // Turn on collision events at a rate no faster than one every the given milliseconds - public override void SubscribeEvents(int ms) { - _subscribedEventsMs = ms; - if (ms > 0) - { - // make sure first collision happens - _nextCollisionOkTime = Util.EnvironmentTickCount() - _subscribedEventsMs; - - Scene.TaintedObject("BSCharacter.SubscribeEvents", delegate() - { - BulletSimAPI.AddToCollisionFlags2(BSBody.Ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); - }); - } + public override void AddAngularForce(OMV.Vector3 force, bool pushforce) { } - - public override void ZeroMotion() - { - return; - } - - // Stop collision events - public override void UnSubscribeEvents() { - _subscribedEventsMs = 0; - Scene.TaintedObject("BSCharacter.UnSubscribeEvents", delegate() - { - BulletSimAPI.RemoveFromCollisionFlags2(BSBody.Ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); - }); - } - // Return 'true' if someone has subscribed to events - public override bool SubscribedEvents() { - return (_subscribedEventsMs > 0); + public override void SetMomentum(OMV.Vector3 momentum) { } // set _avatarVolume and _mass based on capsule size, _density and _scale @@ -520,67 +498,15 @@ public class BSCharacter : BSPhysObject // Do some sanity checking for the avatar. Make sure it's above ground and inbounds. PositionSanityCheck2(); - float heightHere = Scene.TerrainManager.GetTerrainHeightAtXYZ(_position); // only for debug + float heightHere = PhysicsScene.TerrainManager.GetTerrainHeightAtXYZ(_position); // only for debug DetailLog("{0},BSCharacter.UpdateProperties,call,pos={1},orient={2},vel={3},accel={4},rotVel={5},terrain={6}", LocalID, _position, _orientation, _velocity, _acceleration, _rotationalVelocity, heightHere); } - // Called by the scene when a collision with this object is reported - // The collision, if it should be reported to the character, is placed in a collection - // that will later be sent to the simulator when SendCollisions() is called. - CollisionEventUpdate collisionCollection = null; - public override bool Collide(uint collidingWith, BSPhysObject collidee, Vector3 contactPoint, Vector3 contactNormal, float pentrationDepth) - { - bool ret = false; - - // The following makes IsColliding() and IsCollidingGround() work - _collidingStep = Scene.SimulationStep; - if (collidingWith <= Scene.TerrainManager.HighestTerrainID) - { - _collidingGroundStep = Scene.SimulationStep; - } - // DetailLog("{0},BSCharacter.Collison,call,with={1}", LocalID, collidingWith); - - // throttle collisions to the rate specified in the subscription - if (SubscribedEvents()) { - int nowTime = Scene.SimulationNowTime; - if (nowTime >= _nextCollisionOkTime) { - _nextCollisionOkTime = nowTime + _subscribedEventsMs; - - if (collisionCollection == null) - collisionCollection = new CollisionEventUpdate(); - collisionCollection.AddCollider(collidingWith, new ContactPoint(contactPoint, contactNormal, pentrationDepth)); - ret = true; - } - } - return ret; - } - - public override void SendCollisions() - { - /* - if (collisionCollection != null && collisionCollection.Count > 0) - { - base.SendCollisionUpdate(collisionCollection); - collisionCollection = null; - } - */ - // Kludge to make a collision call even if there are no collisions. - // This causes the avatar animation to get updated. - if (collisionCollection == null) - collisionCollection = new CollisionEventUpdate(); - base.SendCollisionUpdate(collisionCollection); - // If there were any collisions in the collection, make sure we don't use the - // same instance next time. - if (collisionCollection.Count > 0) - collisionCollection = null; - // End kludge - } - // Invoke the detailed logger and output something if it's enabled. private void DetailLog(string msg, params Object[] args) { - Scene.PhysicsLogging.Write(msg, args); + PhysicsScene.PhysicsLogging.Write(msg, args); } } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index 61006f0..2da2331 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -539,7 +539,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin // add Gravity and Buoyancy // There is some gravity, make a gravity force vector that is applied after object velocity. // m_VehicleBuoyancy: -1=2g; 0=1g; 1=0g; - Vector3 grav = m_prim.Scene.DefaultGravity * (m_prim.Mass * (1f - m_VehicleBuoyancy)); + Vector3 grav = m_prim.PhysicsScene.DefaultGravity * (m_prim.Mass * (1f - m_VehicleBuoyancy)); /* * RA: Not sure why one would do this @@ -552,7 +552,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin // Vector3 accel = new Vector3(-(m_dir.X - m_lastLinearVelocityVector.X / 0.1f), -(m_dir.Y - m_lastLinearVelocityVector.Y / 0.1f), m_dir.Z - m_lastLinearVelocityVector.Z / 0.1f); // If below the terrain, move us above the ground a little. - float terrainHeight = m_prim.Scene.TerrainManager.GetTerrainHeightAtXYZ(pos); + float terrainHeight = m_prim.PhysicsScene.TerrainManager.GetTerrainHeightAtXYZ(pos); // Taking the rotated size doesn't work here because m_prim.Size is the size of the root prim and not the linkset. // Need to add a m_prim.LinkSet.Size similar to m_prim.LinkSet.Mass. // Vector3 rotatedSize = m_prim.Size * m_prim.Orientation; @@ -570,7 +570,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin // We should hover, get the target height if ((m_flags & VehicleFlag.HOVER_WATER_ONLY) != 0) { - m_VhoverTargetHeight = m_prim.Scene.GetWaterLevelAtXYZ(pos) + m_VhoverHeight; + m_VhoverTargetHeight = m_prim.PhysicsScene.GetWaterLevelAtXYZ(pos) + m_VhoverHeight; } if ((m_flags & VehicleFlag.HOVER_TERRAIN_ONLY) != 0) { @@ -849,8 +849,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 (m_prim.Scene.VehicleLoggingEnabled) - m_prim.Scene.PhysicsLogging.Write(msg, args); + if (m_prim.PhysicsScene.VehicleLoggingEnabled) + m_prim.PhysicsScene.PhysicsLogging.Write(msg, args); } } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index 7e784eb..005a758 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -36,11 +36,9 @@ public class BSLinkset { private static string LogHeader = "[BULLETSIM LINKSET]"; - private BSPhysObject m_linksetRoot; - public BSPhysObject LinksetRoot { get { return m_linksetRoot; } } + public BSPhysObject LinksetRoot { get; protected set; } - private BSScene m_physicsScene; - public BSScene PhysicsScene { get { return m_physicsScene; } } + public BSScene PhysicsScene { get; private set; } static int m_nextLinksetID = 1; public int LinksetID { get; private set; } @@ -81,8 +79,8 @@ public class BSLinkset // We create LOTS of linksets. if (m_nextLinksetID < 0) m_nextLinksetID = 1; - m_physicsScene = scene; - m_linksetRoot = parent; + PhysicsScene = scene; + LinksetRoot = parent; m_children = new List(); m_mass = parent.MassRaw; } @@ -131,7 +129,7 @@ public class BSLinkset // Return 'true' if the passed object is the root object of this linkset public bool IsRoot(BSPhysObject requestor) { - return (requestor.LocalID == m_linksetRoot.LocalID); + return (requestor.LocalID == LinksetRoot.LocalID); } public int NumberOfChildren { get { return m_children.Count; } } @@ -159,7 +157,7 @@ public class BSLinkset private float ComputeLinksetMass() { - float mass = m_linksetRoot.MassRaw; + float mass = LinksetRoot.MassRaw; foreach (BSPhysObject bp in m_children) { mass += bp.MassRaw; @@ -169,8 +167,8 @@ public class BSLinkset private OMV.Vector3 ComputeLinksetCenterOfMass() { - OMV.Vector3 com = m_linksetRoot.Position * m_linksetRoot.MassRaw; - float totalMass = m_linksetRoot.MassRaw; + OMV.Vector3 com = LinksetRoot.Position * LinksetRoot.MassRaw; + float totalMass = LinksetRoot.MassRaw; lock (m_linksetActivityLock) { @@ -188,7 +186,7 @@ public class BSLinkset private OMV.Vector3 ComputeLinksetGeometricCenter() { - OMV.Vector3 com = m_linksetRoot.Position; + OMV.Vector3 com = LinksetRoot.Position; lock (m_linksetActivityLock) { @@ -256,7 +254,7 @@ public class BSLinkset foreach (BSPhysObject child in m_children) { BSConstraint constrain; - if (m_physicsScene.Constraints.TryGetConstraint(LinksetRoot.BSBody, child.BSBody, out constrain)) + if (PhysicsScene.Constraints.TryGetConstraint(LinksetRoot.BSBody, child.BSBody, out constrain)) { // DetailLog("{0},BSLinkset.RecomputeLinksetConstraintVariables,taint,child={1},mass={2},A={3},B={4}", // LinksetRoot.LocalID, child.LocalID, linksetMass, constrain.Body1.ID, constrain.Body2.ID); @@ -306,9 +304,9 @@ public class BSLinkset BSPhysObject rootx = LinksetRoot; // capture the root as of now BSPhysObject childx = child; - m_physicsScene.TaintedObject("AddChildToLinkset", delegate() + PhysicsScene.TaintedObject("AddChildToLinkset", delegate() { - DetailLog("{0},AddChildToLinkset,taint,child={1}", m_linksetRoot.LocalID, child.LocalID); + DetailLog("{0},AddChildToLinkset,taint,child={1}", LinksetRoot.LocalID, child.LocalID); PhysicallyLinkAChildToRoot(rootx, childx); // build the physical binding between me and the child }); } @@ -322,7 +320,7 @@ public class BSLinkset // has to be updated also (like pointer to prim's parent). private void RemoveChildFromOtherLinkset(BSPhysObject pchild) { - pchild.Linkset = new BSLinkset(m_physicsScene, pchild); + pchild.Linkset = new BSLinkset(PhysicsScene, pchild); RemoveChildFromLinkset(pchild); } @@ -334,9 +332,9 @@ public class BSLinkset { BSPhysObject rootx = LinksetRoot; // capture the root as of now BSPhysObject childx = child; - m_physicsScene.TaintedObject("RemoveChildFromLinkset", delegate() + PhysicsScene.TaintedObject("RemoveChildFromLinkset", delegate() { - DetailLog("{0},RemoveChildFromLinkset,taint,child={1}", m_linksetRoot.LocalID, child.LocalID); + DetailLog("{0},RemoveChildFromLinkset,taint,child={1}", LinksetRoot.LocalID, child.LocalID); PhysicallyUnlinkAChildFromRoot(rootx, childx); RecomputeLinksetConstraintVariables(); @@ -370,7 +368,7 @@ public class BSLinkset DetailLog("{0},PhysicallyLinkAChildToRoot,taint,root={1},child={2},rLoc={3},cLoc={4},midLoc={5}", rootPrim.LocalID, rootPrim.LocalID, childPrim.LocalID, rootPrim.Position, childPrim.Position, midPoint); BS6DofConstraint constrain = new BS6DofConstraint( - m_physicsScene.World, rootPrim.BSBody, childPrim.BSBody, + PhysicsScene.World, rootPrim.BSBody, childPrim.BSBody, midPoint, true, true @@ -408,7 +406,7 @@ public class BSLinkset // ================================================================================== */ - m_physicsScene.Constraints.AddConstraint(constrain); + 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); @@ -435,7 +433,7 @@ public class BSLinkset DetailLog("{0},PhysicallyUnlinkAChildFromRoot,taint,root={1},child={2}", rootPrim.LocalID, rootPrim.LocalID, childPrim.LocalID); // Find the constraint for this link and get rid of it from the overall collection and from my list - m_physicsScene.Constraints.RemoveAndDestroyConstraint(rootPrim.BSBody, childPrim.BSBody); + PhysicsScene.Constraints.RemoveAndDestroyConstraint(rootPrim.BSBody, childPrim.BSBody); // Make the child refresh its location BulletSimAPI.PushUpdate2(childPrim.BSBody.Ptr); @@ -447,13 +445,13 @@ public class BSLinkset { DetailLog("{0},PhysicallyUnlinkAllChildren,taint", rootPrim.LocalID); - m_physicsScene.Constraints.RemoveAndDestroyConstraint(rootPrim.BSBody); + PhysicsScene.Constraints.RemoveAndDestroyConstraint(rootPrim.BSBody); } // Invoke the detailed logger and output something if it's enabled. private void DetailLog(string msg, params Object[] args) { - m_physicsScene.PhysicsLogging.Write(msg, args); + PhysicsScene.PhysicsLogging.Write(msg, args); } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index 3fe71e1..242aa80 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -39,26 +39,150 @@ namespace OpenSim.Region.Physics.BulletSPlugin // unless the difference is significant. public abstract class BSPhysObject : PhysicsActor { - public abstract BSLinkset Linkset { get; set; } + protected void BaseInitialize(BSScene parentScene) + { + PhysicsScene = parentScene; + Linkset = new BSLinkset(PhysicsScene, this); - public abstract bool Collide(uint collidingWith, BSPhysObject collidee, - OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth); - public abstract void SendCollisions(); + CollisionCollection = new CollisionEventUpdate(); + SubscribedEventsMs = 0; + CollidingStep = 0; + CollidingGroundStep = 0; + } - // Return the object mass without calculating it or side effects + public BSScene PhysicsScene { get; protected set; } + + public BSLinkset Linkset { get; set; } + + // Return the object mass without calculating it or having side effects public abstract float MassRaw { get; } // Reference to the physical body (btCollisionObject) of this object - public abstract BulletBody BSBody { get; set; } + public BulletBody BSBody { get; protected set; } // Reference to the physical shape (btCollisionShape) of this object - public abstract BulletShape BSShape { get; set; } + public BulletShape BSShape { get; protected set; } + // Stop all physical motion. public abstract void ZeroMotion(); + // Step the vehicle simulation for this object. A NOOP if the vehicle was not configured. public virtual void StepVehicle(float timeStep) { } + // Update the physical location and motion of the object. Called with data from Bullet. public abstract void UpdateProperties(EntityProperties entprop); + // Tell the object to clean up. public abstract void Destroy(); + + #region Collisions + + // Requested number of milliseconds between collision events. Zero means disabled. + protected int SubscribedEventsMs { get; set; } + // Given subscription, the time that a collision may be passed up + protected int NextCollisionOkTime { get; set; } + // The simulation step that last had a collision + protected long CollidingStep { get; set; } + // The simulation step that last had a collision with the ground + protected long CollidingGroundStep { get; set; } + // The collision flags we think are set in Bullet + protected CollisionFlags CurrentCollisionFlags { get; set; } + + // The collisions that have been collected this tick + protected CollisionEventUpdate CollisionCollection; + + // The simulation step is telling this object about a collision. + // Return 'true' if a collision was processed and should be sent up. + // Called at taint time from within the Step() function + public virtual bool Collide(uint collidingWith, BSPhysObject collidee, + OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth) + { + bool ret = false; + + // The following lines make IsColliding() and IsCollidingGround() work + CollidingStep = PhysicsScene.SimulationStep; + if (collidingWith <= PhysicsScene.TerrainManager.HighestTerrainID) + { + CollidingGroundStep = PhysicsScene.SimulationStep; + } + + // prims in the same linkset cannot collide with each other + if (collidee != null && (this.Linkset.LinksetID == collidee.Linkset.LinksetID)) + { + return ret; + } + + PhysicsScene.PhysicsLogging.Write("{0},BSPhysObject.Collison,call,with={1}", LocalID, collidingWith); + + // if someone has subscribed for collision events.... + if (SubscribedEvents()) { + CollisionCollection.AddCollider(collidingWith, new ContactPoint(contactPoint, contactNormal, pentrationDepth)); + PhysicsScene.PhysicsLogging.Write("{0},BSPhysObject.Collison.AddCollider,call,with={1},point={2},normal={3},depth={4},next={5}", + LocalID, collidingWith, contactPoint, contactNormal, pentrationDepth, NextCollisionOkTime.ToString("yyyyMMddHHmmssfff")); + ret = true; + } + return ret; + } + + // Routine to send the collected collisions into the simulator. + // Also handles removal of this from the collection of objects with collisions if + // there are no collisions from this object. Mechanism is create one last + // collision event to make collision_end work. + public virtual void SendCollisions() + { + // throttle the collisions to the number of milliseconds specified in the subscription + int nowTime = PhysicsScene.SimulationNowTime; + if (nowTime >= NextCollisionOkTime) + { + NextCollisionOkTime = nowTime + 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. + if (CollisionCollection.Count == 0) + PhysicsScene.ObjectsWithNoMoreCollisions.Add(this); + + base.SendCollisionUpdate(CollisionCollection); + + // The collisionCollection structure is passed around in the simulator. + // Make sure we don't have a handle to that one and that a new one is used next time. + CollisionCollection = new CollisionEventUpdate(); + } + } + + // Subscribe for collision events. + // Parameter is the millisecond rate the caller wishes collision events to occur. + public override void SubscribeEvents(int ms) { + SubscribedEventsMs = ms; + if (ms > 0) + { + // make sure first collision happens + NextCollisionOkTime = Util.EnvironmentTickCountSubtract(SubscribedEventsMs); + PhysicsScene.PhysicsLogging.Write("{0},SubscribeEvents,call,ms={1},nextOKTime={2}", + LocalID, SubscribedEventsMs, NextCollisionOkTime.ToString("yyyyMMddHHmmssfff")); + + PhysicsScene.TaintedObject("BSPhysObject.SubscribeEvents", delegate() + { + CurrentCollisionFlags = BulletSimAPI.AddToCollisionFlags2(BSBody.Ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); + }); + } + else + { + // Subscribing for zero or less is the same as unsubscribing + UnSubscribeEvents(); + } + } + public override void UnSubscribeEvents() { + SubscribedEventsMs = 0; + PhysicsScene.PhysicsLogging.Write("{0},UnSubscribeEvents,call", LocalID); + PhysicsScene.TaintedObject("BSPhysObject.UnSubscribeEvents", delegate() + { + CurrentCollisionFlags = BulletSimAPI.RemoveFromCollisionFlags2(BSBody.Ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); + }); + } + // Return 'true' if the simulator wants collision events + public override bool SubscribedEvents() { + return (SubscribedEventsMs > 0); + } + + #endregion // Collisions } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 26a581f..29f27e8 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -49,8 +49,6 @@ public sealed class BSPrim : BSPhysObject private ulong _hullKey; private List _hulls; - private BSScene _scene; - public BSScene Scene { get { return _scene; } } private String _avName; private uint _localID = 0; @@ -87,18 +85,6 @@ public sealed class BSPrim : BSPhysObject private bool _kinematic; private float _buoyancy; - // Membership in a linkset is controlled by this class. - public override BSLinkset Linkset { get; set; } - - private int _subscribedEventsMs = 0; - private int _nextCollisionOkTime = 0; - long _collidingStep; - long _collidingGroundStep; - CollisionFlags m_currentCollisionFlags = 0; - - public override BulletBody BSBody { get; set; } - public override BulletShape BSShape { get; set; } - private BSDynamics _vehicle; private OMV.Vector3 _PIDTarget; @@ -113,10 +99,10 @@ public sealed class BSPrim : BSPhysObject OMV.Quaternion rotation, PrimitiveBaseShape pbs, bool pisPhysical) { // m_log.DebugFormat("{0}: BSPrim creation of {1}, id={2}", LogHeader, primName, localID); + base.BaseInitialize(parent_scene); _localID = localID; _avName = primName; _physicsActorType = (int)ActorTypes.Prim; - _scene = parent_scene; _position = pos; _size = size; _scale = new OMV.Vector3(1f, 1f, 1f); // the scale will be set by CreateGeom depending on object type @@ -129,25 +115,23 @@ public sealed class BSPrim : BSPhysObject _pbs = pbs; _isPhysical = pisPhysical; _isVolumeDetect = false; - _subscribedEventsMs = 0; - _friction = _scene.Params.defaultFriction; // TODO: compute based on object material - _density = _scene.Params.defaultDensity; // TODO: compute based on object material - _restitution = _scene.Params.defaultRestitution; - Linkset = new BSLinkset(Scene, this); // a linkset of one - _vehicle = new BSDynamics(Scene, this); // add vehicleness + _friction = PhysicsScene.Params.defaultFriction; // TODO: compute based on object material + _density = PhysicsScene.Params.defaultDensity; // TODO: compute based on object material + _restitution = PhysicsScene.Params.defaultRestitution; + _vehicle = new BSDynamics(PhysicsScene, this); // add vehicleness _mass = CalculateMass(); DetailLog("{0},BSPrim.constructor,call", LocalID); // do the actual object creation at taint time - _scene.TaintedObject("BSPrim.create", delegate() + PhysicsScene.TaintedObject("BSPrim.create", delegate() { CreateGeomAndObject(true); // Get the pointer to the physical body for this object. // At the moment, we're still letting BulletSim manage the creation and destruction // of the object. Someday we'll move that into the C# code. - BSBody = new BulletBody(LocalID, BulletSimAPI.GetBodyHandle2(_scene.World.Ptr, LocalID)); + BSBody = new BulletBody(LocalID, BulletSimAPI.GetBodyHandle2(PhysicsScene.World.Ptr, LocalID)); BSShape = new BulletShape(BulletSimAPI.GetCollisionShape2(BSBody.Ptr)); - m_currentCollisionFlags = BulletSimAPI.GetCollisionFlags2(BSBody.Ptr); + CurrentCollisionFlags = BulletSimAPI.GetCollisionFlags2(BSBody.Ptr); }); } @@ -168,11 +152,11 @@ public sealed class BSPrim : BSPhysObject // Undo any vehicle properties this.VehicleType = (int)Vehicle.TYPE_NONE; - _scene.TaintedObject("BSPrim.destroy", delegate() + PhysicsScene.TaintedObject("BSPrim.destroy", delegate() { DetailLog("{0},BSPrim.Destroy,taint,", LocalID); // everything in the C# world will get garbage collected. Tell the C++ world to free stuff. - BulletSimAPI.DestroyObject(_scene.WorldID, LocalID); + BulletSimAPI.DestroyObject(PhysicsScene.WorldID, LocalID); }); } @@ -183,7 +167,7 @@ public sealed class BSPrim : BSPhysObject get { return _size; } set { _size = value; - _scene.TaintedObject("BSPrim.setSize", delegate() + PhysicsScene.TaintedObject("BSPrim.setSize", delegate() { _mass = CalculateMass(); // changing size changes the mass // Since _size changed, the mesh needs to be rebuilt. If rebuilt, all the correct @@ -196,7 +180,7 @@ public sealed class BSPrim : BSPhysObject public override PrimitiveBaseShape Shape { set { _pbs = value; - _scene.TaintedObject("BSPrim.setShape", delegate() + PhysicsScene.TaintedObject("BSPrim.setShape", delegate() { _mass = CalculateMass(); // changing the shape changes the mass CreateGeomAndObject(false); @@ -214,7 +198,7 @@ public sealed class BSPrim : BSPhysObject public override bool Selected { set { _isSelected = value; - _scene.TaintedObject("BSPrim.setSelected", delegate() + PhysicsScene.TaintedObject("BSPrim.setSelected", delegate() { SetObjectDynamic(); }); @@ -283,13 +267,13 @@ public sealed class BSPrim : BSPhysObject _position = BulletSimAPI.GetPosition2(BSBody.Ptr); // don't do the GetObjectPosition for root elements because this function is called a zillion times - // _position = BulletSimAPI.GetObjectPosition(_scene.WorldID, _localID); + // _position = BulletSimAPI.GetObjectPosition(Scene.WorldID, _localID); return _position; } set { _position = value; // TODO: what does it mean to set the position of a child prim?? Rebuild the constraint? - _scene.TaintedObject("BSPrim.setPosition", delegate() + PhysicsScene.TaintedObject("BSPrim.setPosition", delegate() { DetailLog("{0},BSPrim.SetPosition,taint,pos={1},orient={2}", LocalID, _position, _orientation); BulletSimAPI.SetTranslation2(BSBody.Ptr, _position, _orientation); @@ -327,7 +311,7 @@ public sealed class BSPrim : BSPhysObject get { return _force; } set { _force = value; - _scene.TaintedObject("BSPrim.setForce", delegate() + PhysicsScene.TaintedObject("BSPrim.setForce", delegate() { DetailLog("{0},BSPrim.setForce,taint,force={1}", LocalID, _force); BulletSimAPI.SetObjectForce2(BSBody.Ptr, _force); @@ -342,40 +326,40 @@ public sealed class BSPrim : BSPhysObject set { Vehicle type = (Vehicle)value; BSPrim vehiclePrim = this; - _scene.TaintedObject("setVehicleType", delegate() + 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. _vehicle.ProcessTypeChange(type); // Tell the scene about the vehicle so it will get processing each frame. - _scene.VehicleInSceneTypeChanged(this, type); + PhysicsScene.VehicleInSceneTypeChanged(this, type); }); } } public override void VehicleFloatParam(int param, float value) { - _scene.TaintedObject("BSPrim.VehicleFloatParam", delegate() + PhysicsScene.TaintedObject("BSPrim.VehicleFloatParam", delegate() { _vehicle.ProcessFloatVehicleParam((Vehicle)param, value); }); } public override void VehicleVectorParam(int param, OMV.Vector3 value) { - _scene.TaintedObject("BSPrim.VehicleVectorParam", delegate() + PhysicsScene.TaintedObject("BSPrim.VehicleVectorParam", delegate() { _vehicle.ProcessVectorVehicleParam((Vehicle)param, value); }); } public override void VehicleRotationParam(int param, OMV.Quaternion rotation) { - _scene.TaintedObject("BSPrim.VehicleRotationParam", delegate() + PhysicsScene.TaintedObject("BSPrim.VehicleRotationParam", delegate() { _vehicle.ProcessRotationVehicleParam((Vehicle)param, rotation); }); } public override void VehicleFlags(int param, bool remove) { - _scene.TaintedObject("BSPrim.VehicleFlags", delegate() + PhysicsScene.TaintedObject("BSPrim.VehicleFlags", delegate() { _vehicle.ProcessVehicleFlags(param, remove); }); @@ -393,8 +377,9 @@ public sealed class BSPrim : BSPhysObject public override void SetVolumeDetect(int param) { bool newValue = (param != 0); _isVolumeDetect = newValue; - _scene.TaintedObject("BSPrim.SetVolumeDetect", delegate() + PhysicsScene.TaintedObject("BSPrim.SetVolumeDetect", delegate() { + DetailLog("{0},setVolumeDetect,taint,volDetect={1}", LocalID, _isVolumeDetect); SetObjectDynamic(); }); return; @@ -404,7 +389,7 @@ public sealed class BSPrim : BSPhysObject get { return _velocity; } set { _velocity = value; - _scene.TaintedObject("BSPrim.setVelocity", delegate() + PhysicsScene.TaintedObject("BSPrim.setVelocity", delegate() { DetailLog("{0},BSPrim.SetVelocity,taint,vel={1}", LocalID, _velocity); BulletSimAPI.SetLinearVelocity2(BSBody.Ptr, _velocity); @@ -438,9 +423,9 @@ public sealed class BSPrim : BSPhysObject set { _orientation = value; // TODO: what does it mean if a child in a linkset changes its orientation? Rebuild the constraint? - _scene.TaintedObject("BSPrim.setOrientation", delegate() + PhysicsScene.TaintedObject("BSPrim.setOrientation", delegate() { - // _position = BulletSimAPI.GetObjectPosition(_scene.WorldID, _localID); + // _position = BulletSimAPI.GetObjectPosition(Scene.WorldID, _localID); DetailLog("{0},BSPrim.setOrientation,taint,pos={1},orient={2}", LocalID, _position, _orientation); BulletSimAPI.SetTranslation2(BSBody.Ptr, _position, _orientation); }); @@ -454,8 +439,9 @@ public sealed class BSPrim : BSPhysObject get { return _isPhysical; } set { _isPhysical = value; - _scene.TaintedObject("BSPrim.setIsPhysical", delegate() + PhysicsScene.TaintedObject("BSPrim.setIsPhysical", delegate() { + DetailLog("{0},setIsPhysical,taint,isPhys={1}", LocalID, _isPhysical); SetObjectDynamic(); }); } @@ -493,9 +479,9 @@ public sealed class BSPrim : BSPhysObject // Bullet wants static objects to have a mass of zero float mass = IsStatic ? 0f : _mass; - BulletSimAPI.SetObjectProperties(_scene.WorldID, LocalID, IsStatic, IsSolid, SubscribedEvents(), mass); + BulletSimAPI.SetObjectProperties(Scene.WorldID, LocalID, IsStatic, IsSolid, SubscribedEvents(), mass); */ - BulletSimAPI.RemoveObjectFromWorld2(Scene.World.Ptr, BSBody.Ptr); + BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.Ptr, BSBody.Ptr); // Set up the object physicalness (does gravity and collisions move this object) MakeDynamic(IsStatic); @@ -506,15 +492,15 @@ public sealed class BSPrim : BSPhysObject // Arrange for collisions events if the simulator wants them EnableCollisions(SubscribedEvents()); - BulletSimAPI.AddObjectToWorld2(Scene.World.Ptr, BSBody.Ptr); + BulletSimAPI.AddObjectToWorld2(PhysicsScene.World.Ptr, BSBody.Ptr); // Recompute any linkset parameters. // When going from non-physical to physical, this re-enables the constraints that // had been automatically disabled when the mass was set to zero. Linkset.Refresh(this); - DetailLog("{0},BSPrim.UpdatePhysicalParameters,taint,static={1},solid={2},mass={3}, cf={4}", - LocalID, IsStatic, IsSolid, _mass, m_currentCollisionFlags); + DetailLog("{0},BSPrim.UpdatePhysicalParameters,taint,static={1},solid={2},mass={3},collide={4},cf={5}", + LocalID, IsStatic, IsSolid, _mass, SubscribedEvents(), CurrentCollisionFlags); } // "Making dynamic" means changing to and from static. @@ -527,7 +513,7 @@ public sealed class BSPrim : BSPhysObject if (makeStatic) { // Become a Bullet 'static' object type - m_currentCollisionFlags = BulletSimAPI.AddToCollisionFlags2(BSBody.Ptr, CollisionFlags.CF_STATIC_OBJECT); + CurrentCollisionFlags = BulletSimAPI.AddToCollisionFlags2(BSBody.Ptr, CollisionFlags.CF_STATIC_OBJECT); // Stop all movement BulletSimAPI.ClearAllForces2(BSBody.Ptr); // Center of mass is at the center of the object @@ -539,16 +525,17 @@ public sealed class BSPrim : BSPhysObject // There can be special things needed for implementing linksets Linkset.MakeStatic(this); // The activation state is 'sleeping' so Bullet will not try to act on it - BulletSimAPI.ForceActivationState2(BSBody.Ptr, ActivationState.ISLAND_SLEEPING); + // BulletSimAPI.ForceActivationState2(BSBody.Ptr, ActivationState.ISLAND_SLEEPING); + BulletSimAPI.ForceActivationState2(BSBody.Ptr, ActivationState.DISABLE_SIMULATION); } else { // Not a Bullet static object - m_currentCollisionFlags = BulletSimAPI.RemoveFromCollisionFlags2(BSBody.Ptr, CollisionFlags.CF_STATIC_OBJECT); + CurrentCollisionFlags = BulletSimAPI.RemoveFromCollisionFlags2(BSBody.Ptr, CollisionFlags.CF_STATIC_OBJECT); - // Set various physical properties so internal things will get computed correctly as they are set - BulletSimAPI.SetFriction2(BSBody.Ptr, Scene.Params.defaultFriction); - BulletSimAPI.SetRestitution2(BSBody.Ptr, Scene.Params.defaultRestitution); + // Set various physical properties so internal dynamic properties will get computed correctly as they are set + BulletSimAPI.SetFriction2(BSBody.Ptr, PhysicsScene.Params.defaultFriction); + BulletSimAPI.SetRestitution2(BSBody.Ptr, PhysicsScene.Params.defaultRestitution); // per http://www.bulletphysics.org/Bullet/phpBB3/viewtopic.php?t=3382 BulletSimAPI.SetInterpolationLinearVelocity2(BSBody.Ptr, OMV.Vector3.Zero); BulletSimAPI.SetInterpolationAngularVelocity2(BSBody.Ptr, OMV.Vector3.Zero); @@ -562,10 +549,10 @@ public sealed class BSPrim : BSPhysObject BulletSimAPI.UpdateInertiaTensor2(BSBody.Ptr); // Various values for simulation limits - BulletSimAPI.SetDamping2(BSBody.Ptr, Scene.Params.linearDamping, Scene.Params.angularDamping); - BulletSimAPI.SetDeactivationTime2(BSBody.Ptr, Scene.Params.deactivationTime); - BulletSimAPI.SetSleepingThresholds2(BSBody.Ptr, Scene.Params.linearSleepingThreshold, Scene.Params.angularSleepingThreshold); - BulletSimAPI.SetContactProcessingThreshold2(BSBody.Ptr, Scene.Params.contactProcessingThreshold); + BulletSimAPI.SetDamping2(BSBody.Ptr, PhysicsScene.Params.linearDamping, PhysicsScene.Params.angularDamping); + BulletSimAPI.SetDeactivationTime2(BSBody.Ptr, PhysicsScene.Params.deactivationTime); + BulletSimAPI.SetSleepingThresholds2(BSBody.Ptr, PhysicsScene.Params.linearSleepingThreshold, PhysicsScene.Params.angularSleepingThreshold); + BulletSimAPI.SetContactProcessingThreshold2(BSBody.Ptr, PhysicsScene.Params.contactProcessingThreshold); // There can be special things needed for implementing linksets Linkset.MakeDynamic(this); @@ -581,11 +568,11 @@ public sealed class BSPrim : BSPhysObject if (makeSolid) { // Easy in Bullet -- just remove the object flag that controls collision response - m_currentCollisionFlags = BulletSimAPI.RemoveFromCollisionFlags2(BSBody.Ptr, CollisionFlags.CF_NO_CONTACT_RESPONSE); + CurrentCollisionFlags = BulletSimAPI.RemoveFromCollisionFlags2(BSBody.Ptr, CollisionFlags.CF_NO_CONTACT_RESPONSE); } else { - m_currentCollisionFlags = BulletSimAPI.AddToCollisionFlags2(BSBody.Ptr, CollisionFlags.CF_NO_CONTACT_RESPONSE); + CurrentCollisionFlags = BulletSimAPI.AddToCollisionFlags2(BSBody.Ptr, CollisionFlags.CF_NO_CONTACT_RESPONSE); } } @@ -594,11 +581,11 @@ public sealed class BSPrim : BSPhysObject { if (wantsCollisionEvents) { - m_currentCollisionFlags = BulletSimAPI.AddToCollisionFlags2(BSBody.Ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); + CurrentCollisionFlags = BulletSimAPI.AddToCollisionFlags2(BSBody.Ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); } else { - m_currentCollisionFlags = BulletSimAPI.RemoveFromCollisionFlags2(BSBody.Ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); + CurrentCollisionFlags = BulletSimAPI.RemoveFromCollisionFlags2(BSBody.Ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); } } @@ -618,11 +605,11 @@ public sealed class BSPrim : BSPhysObject set { _throttleUpdates = value; } } public override bool IsColliding { - get { return (_collidingStep == _scene.SimulationStep); } + get { return (CollidingStep == PhysicsScene.SimulationStep); } set { _isColliding = value; } } public override bool CollidingGround { - get { return (_collidingGroundStep == _scene.SimulationStep); } + get { return (CollidingGroundStep == PhysicsScene.SimulationStep); } set { _collidingGround = value; } } public override bool CollidingObj { @@ -656,7 +643,7 @@ public sealed class BSPrim : BSPhysObject set { _rotationalVelocity = value; // m_log.DebugFormat("{0}: RotationalVelocity={1}", LogHeader, _rotationalVelocity); - _scene.TaintedObject("BSPrim.setRotationalVelocity", delegate() + PhysicsScene.TaintedObject("BSPrim.setRotationalVelocity", delegate() { DetailLog("{0},BSPrim.SetRotationalVel,taint,rotvel={1}", LocalID, _rotationalVelocity); BulletSimAPI.SetAngularVelocity2(BSBody.Ptr, _rotationalVelocity); @@ -673,13 +660,13 @@ public sealed class BSPrim : BSPhysObject get { return _buoyancy; } set { _buoyancy = value; - _scene.TaintedObject("BSPrim.setBuoyancy", delegate() + PhysicsScene.TaintedObject("BSPrim.setBuoyancy", delegate() { DetailLog("{0},BSPrim.SetBuoyancy,taint,buoy={1}", LocalID, _buoyancy); // Buoyancy is faked by changing the gravity applied to the object - float grav = Scene.Params.gravity * (1f - _buoyancy); + float grav = PhysicsScene.Params.gravity * (1f - _buoyancy); BulletSimAPI.SetGravity2(BSBody.Ptr, new OMV.Vector3(0f, 0f, grav)); - // BulletSimAPI.SetObjectBuoyancy(_scene.WorldID, _localID, _buoyancy); + // BulletSimAPI.SetObjectBuoyancy(Scene.WorldID, _localID, _buoyancy); }); } } @@ -730,7 +717,7 @@ public sealed class BSPrim : BSPhysObject m_log.WarnFormat("{0}: Got a NaN force applied to a prim. LocalID={1}", LogHeader, LocalID); return; } - _scene.TaintedObject("BSPrim.AddForce", delegate() + PhysicsScene.TaintedObject("BSPrim.AddForce", delegate() { OMV.Vector3 fSum = OMV.Vector3.Zero; lock (m_accumulatedForces) @@ -754,30 +741,6 @@ public sealed class BSPrim : BSPhysObject public override void SetMomentum(OMV.Vector3 momentum) { DetailLog("{0},BSPrim.SetMomentum,call,mom={1}", LocalID, momentum); } - public override void SubscribeEvents(int ms) { - _subscribedEventsMs = ms; - if (ms > 0) - { - // make sure first collision happens - _nextCollisionOkTime = Util.EnvironmentTickCount() - _subscribedEventsMs; - - Scene.TaintedObject("BSPrim.SubscribeEvents", delegate() - { - m_currentCollisionFlags = BulletSimAPI.AddToCollisionFlags2(BSBody.Ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); - }); - } - } - public override void UnSubscribeEvents() { - _subscribedEventsMs = 0; - Scene.TaintedObject("BSPrim.UnSubscribeEvents", delegate() - { - m_currentCollisionFlags = BulletSimAPI.RemoveFromCollisionFlags2(BSBody.Ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); - }); - } - public override bool SubscribedEvents() { - return (_subscribedEventsMs > 0); - } - #region Mass Calculation private float CalculateMass() @@ -1071,8 +1034,8 @@ public sealed class BSPrim : BSPhysObject if (returnMass <= 0) returnMass = 0.0001f; - if (returnMass > _scene.MaximumObjectMass) - returnMass = _scene.MaximumObjectMass; + if (returnMass > PhysicsScene.MaximumObjectMass) + returnMass = PhysicsScene.MaximumObjectMass; return returnMass; }// end CalculateMass @@ -1090,7 +1053,7 @@ public sealed class BSPrim : BSPhysObject bool haveShape = false; // If the prim attributes are simple, this could be a simple Bullet native shape - if ((_pbs.SculptEntry && !Scene.ShouldMeshSculptedPrim) + if ((_pbs.SculptEntry && !PhysicsScene.ShouldMeshSculptedPrim) || (_pbs.ProfileBegin == 0 && _pbs.ProfileEnd == 0 && _pbs.ProfileHollow == 0 && _pbs.PathTwist == 0 && _pbs.PathTwistBegin == 0 @@ -1156,12 +1119,12 @@ public sealed class BSPrim : BSPhysObject private bool CreateGeomMesh() { // level of detail based on size and type of the object - float lod = _scene.MeshLOD; + float lod = PhysicsScene.MeshLOD; if (_pbs.SculptEntry) - lod = _scene.SculptLOD; + lod = PhysicsScene.SculptLOD; float maxAxis = Math.Max(_size.X, Math.Max(_size.Y, _size.Z)); - if (maxAxis > _scene.MeshMegaPrimThreshold) - lod = _scene.MeshMegaPrimLOD; + if (maxAxis > PhysicsScene.MeshMegaPrimThreshold) + lod = PhysicsScene.MeshMegaPrimLOD; ulong newMeshKey = (ulong)_pbs.GetMeshKey(_size, lod); // m_log.DebugFormat("{0}: CreateGeomMesh: lID={1}, oldKey={2}, newKey={3}", LogHeader, _localID, _meshKey, newMeshKey); @@ -1175,14 +1138,14 @@ public sealed class BSPrim : BSPhysObject { // m_log.DebugFormat("{0}: CreateGeom: deleting old mesh. lID={1}, Key={2}", LogHeader, _localID, _meshKey); DetailLog("{0},BSPrim.CreateGeomMesh,deleteOld,key={1}", LocalID, _meshKey); - BulletSimAPI.DestroyMesh(_scene.WorldID, _meshKey); + BulletSimAPI.DestroyMesh(PhysicsScene.WorldID, _meshKey); _mesh = null; _meshKey = 0; } _meshKey = newMeshKey; // always pass false for physicalness as this creates some sort of bounding box which we don't need - _mesh = _scene.mesher.CreateMesh(_avName, _pbs, _size, lod, false); + _mesh = PhysicsScene.mesher.CreateMesh(_avName, _pbs, _size, lod, false); int[] indices = _mesh.getIndexListAsInt(); List vertices = _mesh.getVertexList(); @@ -1198,7 +1161,7 @@ public sealed class BSPrim : BSPhysObject // m_log.DebugFormat("{0}: CreateGeomMesh: calling CreateMesh. lid={1}, key={2}, indices={3}, vertices={4}", // LogHeader, _localID, _meshKey, indices.Length, vertices.Count); - BulletSimAPI.CreateMesh(_scene.WorldID, _meshKey, indices.GetLength(0), indices, + BulletSimAPI.CreateMesh(PhysicsScene.WorldID, _meshKey, indices.GetLength(0), indices, vertices.Count, verticesAsFloats); _shapeType = ShapeData.PhysicsShapeType.SHAPE_MESH; @@ -1211,7 +1174,7 @@ public sealed class BSPrim : BSPhysObject // Returns 'true' of a mesh was actually rebuild (we could also have one of these specs). private bool CreateGeomHull() { - float lod = _pbs.SculptEntry ? _scene.SculptLOD : _scene.MeshLOD; + float lod = _pbs.SculptEntry ? PhysicsScene.SculptLOD : PhysicsScene.MeshLOD; ulong newHullKey = (ulong)_pbs.GetMeshKey(_size, lod); // m_log.DebugFormat("{0}: CreateGeomHull: lID={1}, oldKey={2}, newKey={3}", LogHeader, _localID, _hullKey, newHullKey); @@ -1225,7 +1188,7 @@ public sealed class BSPrim : BSPhysObject { // m_log.DebugFormat("{0}: CreateGeom: deleting old hull. Key={1}", LogHeader, _hullKey); DetailLog("{0},BSPrim.CreateGeomHull,deleteOldHull,key={1}", LocalID, _hullKey); - BulletSimAPI.DestroyHull(_scene.WorldID, _hullKey); + BulletSimAPI.DestroyHull(PhysicsScene.WorldID, _hullKey); _hullKey = 0; } @@ -1314,7 +1277,7 @@ public sealed class BSPrim : BSPhysObject // create the hull definition in Bullet // m_log.DebugFormat("{0}: CreateGeom: calling CreateHull. lid={1}, key={2}, hulls={3}", LogHeader, _localID, _hullKey, hullCount); - BulletSimAPI.CreateHull(_scene.WorldID, _hullKey, hullCount, convHulls); + BulletSimAPI.CreateHull(PhysicsScene.WorldID, _hullKey, hullCount, convHulls); _shapeType = ShapeData.PhysicsShapeType.SHAPE_HULL; // meshes are already scaled by the meshmerizer _scale = new OMV.Vector3(1f, 1f, 1f); @@ -1354,10 +1317,10 @@ public sealed class BSPrim : BSPhysObject ShapeData shape; FillShapeInfo(out shape); // m_log.DebugFormat("{0}: CreateObject: lID={1}, shape={2}", LogHeader, _localID, shape.Type); - bool ret = BulletSimAPI.CreateObject(_scene.WorldID, shape); + bool ret = BulletSimAPI.CreateObject(PhysicsScene.WorldID, shape); // the CreateObject() may have recreated the rigid body. Make sure we have the latest address. - BSBody = new BulletBody(LocalID, BulletSimAPI.GetBodyHandle2(_scene.World.Ptr, LocalID)); + BSBody = new BulletBody(LocalID, BulletSimAPI.GetBodyHandle2(PhysicsScene.World.Ptr, LocalID)); BSShape = new BulletShape(BulletSimAPI.GetCollisionShape2(BSBody.Ptr)); return ret; @@ -1490,61 +1453,10 @@ public sealed class BSPrim : BSPhysObject } */ } - - // I've collided with something - // Called at taint time from within the Step() function - CollisionEventUpdate collisionCollection; - public override bool Collide(uint collidingWith, BSPhysObject collidee, OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth) - { - bool ret = false; - - // The following lines make IsColliding() and IsCollidingGround() work - _collidingStep = Scene.SimulationStep; - if (collidingWith <= Scene.TerrainManager.HighestTerrainID) - { - _collidingGroundStep = Scene.SimulationStep; - } - - // DetailLog("{0},BSPrim.Collison,call,with={1}", LocalID, collidingWith); - - // prims in the same linkset cannot collide with each other - if (collidee != null && (this.Linkset.LinksetID == collidee.Linkset.LinksetID)) - { - return ret; - } - - // if someone has subscribed for collision events.... - if (SubscribedEvents()) { - // throttle the collisions to the number of milliseconds specified in the subscription - int nowTime = Scene.SimulationNowTime; - if (nowTime >= _nextCollisionOkTime) { - _nextCollisionOkTime = nowTime + _subscribedEventsMs; - - if (collisionCollection == null) - collisionCollection = new CollisionEventUpdate(); - collisionCollection.AddCollider(collidingWith, new ContactPoint(contactPoint, contactNormal, pentrationDepth)); - ret = true; - } - } - return ret; - } - - // The scene is telling us it's time to pass our collected collisions into the simulator - public override void SendCollisions() - { - if (collisionCollection != null && collisionCollection.Count > 0) - { - base.SendCollisionUpdate(collisionCollection); - // The collisionCollection structure is passed around in the simulator. - // Make sure we don't have a handle to that one and that a new one is used next time. - collisionCollection = null; - } - } - // Invoke the detailed logger and output something if it's enabled. private void DetailLog(string msg, params Object[] args) { - Scene.PhysicsLogging.Write(msg, args); + PhysicsScene.PhysicsLogging.Write(msg, args); } } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index 52997dd..dabced5 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -75,10 +75,11 @@ public class BSScene : PhysicsScene, IPhysicsParameters public Dictionary PhysObjects = new Dictionary(); - private HashSet m_objectsWithCollisions = new HashSet(); - // Following is a kludge and can be removed when avatar animation updating is - // moved to a better place. - private HashSet m_avatarsWithCollisions = new HashSet(); + public HashSet ObjectsWithCollisions = new HashSet(); + public HashSet ObjectsWithNoMoreCollisions = 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(); // List of all the objects that have vehicle properties and should be called // to update each physics step. @@ -379,7 +380,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters // TODO: Remove kludge someday. // We must generate a collision for avatars whether they collide or not. // This is required by OpenSim to update avatar animations, etc. - lock (m_avatarsWithCollisions) m_avatarsWithCollisions.Add(actor); + lock (m_avatars) m_avatars.Add(actor); return actor; } @@ -397,7 +398,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters { lock (PhysObjects) PhysObjects.Remove(actor.LocalID); // Remove kludge someday - lock (m_avatarsWithCollisions) m_avatarsWithCollisions.Remove(bsactor); + lock (m_avatars) m_avatars.Remove(bsactor); } catch (Exception e) { @@ -464,6 +465,9 @@ public class BSScene : PhysicsScene, IPhysicsParameters int collidersCount = 0; IntPtr collidersPtr; + int beforeTime = 0; + int simTime = 0; + // prevent simulation until we've been initialized if (!m_initialized) return 5.0f; @@ -481,10 +485,14 @@ public class BSScene : PhysicsScene, IPhysicsParameters int numSubSteps = 0; try { + if (PhysicsLogging.Enabled) beforeTime = Util.EnvironmentTickCount(); + numSubSteps = BulletSimAPI.PhysicsStep(WorldID, timeStep, m_maxSubSteps, m_fixedTimeStep, out updatedEntityCount, out updatedEntitiesPtr, out collidersCount, out collidersPtr); - DetailLog("{0},Simulate,call, nTaints= {1}, substeps={2}, updates={3}, colliders={4}", - DetailLogZero, numTaints, numSubSteps, updatedEntityCount, collidersCount); + + if (PhysicsLogging.Enabled) simTime = Util.EnvironmentTickCountSubtract(beforeTime); + DetailLog("{0},Simulate,call, nTaints={1}, simTime={2}, substeps={3}, updates={4}, colliders={5}", + DetailLogZero, numTaints, simTime, numSubSteps, updatedEntityCount, collidersCount); } catch (Exception e) { @@ -502,12 +510,6 @@ public class BSScene : PhysicsScene, IPhysicsParameters // Get a value for 'now' so all the collision and update routines don't have to get their own SimulationNowTime = Util.EnvironmentTickCount(); - // This is a kludge to get avatar movement updates. - // ODE sends collisions for avatars even if there are have been no collisions. This updates - // avatar animations and stuff. - // If you fix avatar animation updates, remove this overhead and let normal collision processing happen. - m_objectsWithCollisions = new HashSet(m_avatarsWithCollisions); - // If there were collisions, process them by sending the event to the prim. // Collisions must be processed before updates. if (collidersCount > 0) @@ -523,11 +525,31 @@ public class BSScene : PhysicsScene, IPhysicsParameters } } + // This is a kludge to get avatar movement updates. + // ODE sends collisions for avatars even if there are have been no collisions. This 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) + bsp.SendCollisions(); + // The above SendCollision's batch up the collisions on the objects. // Now push the collisions into the simulator. - foreach (BSPhysObject bsp in m_objectsWithCollisions) - bsp.SendCollisions(); - m_objectsWithCollisions.Clear(); + // If the object is done colliding, it will add itself to the ObjectsWithNoMoreCollisions list. + if (ObjectsWithCollisions.Count > 0) + { + foreach (BSPhysObject bsp in ObjectsWithCollisions) + if (!m_avatars.Contains(bsp)) // don't call avatars twice + bsp.SendCollisions(); + } + + // Objects that are done colliding are removed from the ObjectsWithCollisions list. + // This can't be done by SendCollisions because it is inside an iteration of ObjectWithCollisions. + if (ObjectsWithNoMoreCollisions.Count > 0) + { + foreach (BSPhysObject po in ObjectsWithNoMoreCollisions) + ObjectsWithCollisions.Remove(po); + ObjectsWithNoMoreCollisions.Clear(); + } // If any of the objects had updated properties, tell the object it has been changed by the physics engine if (updatedEntityCount > 0) @@ -555,7 +577,7 @@ public 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. // Since Bullet normally does 5 or 6 substeps, this will normally sum to about 60 FPS. - return numSubSteps * m_fixedTimeStep; + return numSubSteps * m_fixedTimeStep * 1000; } // Something has collided @@ -583,7 +605,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters if (collider.Collide(collidingWith, collidee, collidePoint, collideNormal, penetration)) { // If a collision was posted, remember to send it to the simulator - m_objectsWithCollisions.Add(collider); + ObjectsWithCollisions.Add(collider); } return; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs index 9221cdb..4d2d962 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs @@ -249,7 +249,16 @@ public enum CollisionFlags : uint BS_PHYSICAL_OBJECT = 1 << 13, BS_TERRAIN_OBJECT = 1 << 14, BS_NONE = 0, - BS_ALL = 0xFFFFFFFF + BS_ALL = 0xFFFFFFFF, + + // These are the collision flags switched depending on physical state. + // The other flags are used for other things and should not be fooled with. + BS_ACTIVE = CF_STATIC_OBJECT + | CF_KINEMATIC_OBJECT + | CF_NO_CONTACT_RESPONSE + | BS_VOLUME_DETECT_OBJECT + | BS_PHANTOM_OBJECT + | BS_PHYSICAL_OBJECT, }; // Values for collisions groups and masks @@ -270,52 +279,6 @@ public enum CollisionFilterGroups : uint SolidFilter = 1 << 13, }; - // For each type, we first clear and then set the collision flags -public enum ClearCollisionFlag : uint -{ - Terrain = CollisionFlags.BS_ALL, - Phantom = CollisionFlags.BS_ALL, - VolumeDetect = CollisionFlags.BS_ALL, - PhysicalObject = CollisionFlags.BS_ALL, - StaticObject = CollisionFlags.BS_ALL -} - -public enum SetCollisionFlag : uint -{ - Terrain = CollisionFlags.CF_STATIC_OBJECT - | CollisionFlags.BS_TERRAIN_OBJECT, - Phantom = CollisionFlags.CF_STATIC_OBJECT - | CollisionFlags.BS_PHANTOM_OBJECT - | CollisionFlags.CF_NO_CONTACT_RESPONSE, - VolumeDetect = CollisionFlags.CF_STATIC_OBJECT - | CollisionFlags.BS_VOLUME_DETECT_OBJECT - | CollisionFlags.CF_NO_CONTACT_RESPONSE, - PhysicalObject = CollisionFlags.BS_PHYSICAL_OBJECT, - StaticObject = CollisionFlags.CF_STATIC_OBJECT, -} - -// Collision filters used for different types of objects -public enum SetCollisionFilter : uint -{ - Terrain = CollisionFilterGroups.AllFilter, - Phantom = CollisionFilterGroups.GroundPlaneFilter - | CollisionFilterGroups.TerrainFilter, - VolumeDetect = CollisionFilterGroups.AllFilter, - PhysicalObject = CollisionFilterGroups.AllFilter, - StaticObject = CollisionFilterGroups.AllFilter, -} - -// Collision masks used for different types of objects -public enum SetCollisionMask : uint -{ - Terrain = CollisionFilterGroups.AllFilter, - Phantom = CollisionFilterGroups.GroundPlaneFilter - | CollisionFilterGroups.TerrainFilter, - VolumeDetect = CollisionFilterGroups.AllFilter, - PhysicalObject = CollisionFilterGroups.AllFilter, - StaticObject = CollisionFilterGroups.AllFilter -} - // CFM controls the 'hardness' of the constraint. 0=fixed, 0..1=violatable. Default=0 // ERP controls amount of correction per tick. Usable range=0.1..0.8. Default=0.2. public enum ConstraintParams : int -- cgit v1.1 From 91efccabdcb45ed95ae35ab24ed5d3ed5508b463 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 18 Sep 2012 11:26:19 -0700 Subject: BulletSim: Convert BSCharacter to use common BSPhysObject code and variables. Fix avatar height calculation to properly account for the capsule ends. Rearrange some locking in TerrainManager to eliminate possible race conditions. Move DetailLog() definition into common BSPhysObject class. Some variable renaming to make usage clearer (refactor.rename makes this so easy). --- .../Region/Physics/BulletSPlugin/BSCharacter.cs | 66 +++++++++------------ OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 28 +++++---- .../Region/Physics/BulletSPlugin/BSPhysObject.cs | 29 +++++++--- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 40 +++++-------- .../Physics/BulletSPlugin/BSTerrainManager.cs | 67 +++++++++++----------- 5 files changed, 113 insertions(+), 117 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index 57d5726..19eb1e6 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -39,18 +39,16 @@ public class BSCharacter : BSPhysObject private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static readonly string LogHeader = "[BULLETS CHAR]"; - private String _avName; // private bool _stopped; private OMV.Vector3 _size; private OMV.Vector3 _scale; private PrimitiveBaseShape _pbs; - private uint _localID = 0; private bool _grabbed; private bool _selected; private OMV.Vector3 _position; private float _mass; - public float _density; - public float _avatarVolume; + private float _avatarDensity; + private float _avatarVolume; private OMV.Vector3 _force; private OMV.Vector3 _velocity; private OMV.Vector3 _torque; @@ -63,18 +61,12 @@ public class BSCharacter : BSPhysObject private bool _setAlwaysRun; private bool _throttleUpdates; private bool _isColliding; - private long _collidingStep; - private bool _collidingGround; - private long _collidingGroundStep; private bool _collidingObj; private bool _floatOnWater; private OMV.Vector3 _rotationalVelocity; private bool _kinematic; private float _buoyancy; - private int _subscribedEventsMs = 0; - private int _nextCollisionOkTime = 0; - private OMV.Vector3 _PIDTarget; private bool _usePID; private float _PIDTau; @@ -85,9 +77,7 @@ public class BSCharacter : BSPhysObject public BSCharacter(uint localID, String avName, BSScene parent_scene, OMV.Vector3 pos, OMV.Vector3 size, bool isFlying) { - base.BaseInitialize(parent_scene); - _localID = localID; - _avName = avName; + base.BaseInitialize(parent_scene, localID, avName); _physicsActorType = (int)ActorTypes.Agent; _position = pos; _size = size; @@ -95,14 +85,15 @@ public class BSCharacter : BSPhysObject _orientation = OMV.Quaternion.Identity; _velocity = OMV.Vector3.Zero; _buoyancy = ComputeBuoyancyFromFlying(isFlying); + // The dimensions of the avatar capsule are kept in the scale. // Physics creates a unit capsule which is scaled by the physics engine. - _scale = new OMV.Vector3(PhysicsScene.Params.avatarCapsuleRadius, PhysicsScene.Params.avatarCapsuleRadius, size.Z); - _density = PhysicsScene.Params.avatarDensity; + ComputeAvatarScale(_size); + _avatarDensity = PhysicsScene.Params.avatarDensity; ComputeAvatarVolumeAndMass(); // set _avatarVolume and _mass based on capsule size, _density and _scale ShapeData shapeData = new ShapeData(); - shapeData.ID = _localID; + shapeData.ID = LocalID; shapeData.Type = ShapeData.PhysicsShapeType.SHAPE_AVATAR; shapeData.Position = _position; shapeData.Rotation = _orientation; @@ -117,7 +108,7 @@ public class BSCharacter : BSPhysObject // do actual create at taint time PhysicsScene.TaintedObject("BSCharacter.create", delegate() { - DetailLog("{0},BSCharacter.create", _localID); + DetailLog("{0},BSCharacter.create,taint", LocalID); BulletSimAPI.CreateObject(PhysicsScene.WorldID, shapeData); // Set the buoyancy for flying. This will be refactored when all the settings happen in C# @@ -135,7 +126,7 @@ public class BSCharacter : BSPhysObject DetailLog("{0},BSCharacter.Destroy", LocalID); PhysicsScene.TaintedObject("BSCharacter.destroy", delegate() { - BulletSimAPI.DestroyObject(PhysicsScene.WorldID, _localID); + BulletSimAPI.DestroyObject(PhysicsScene.WorldID, LocalID); }); } @@ -158,7 +149,7 @@ public class BSCharacter : BSPhysObject // When an avatar's size is set, only the height is changed // and that really only depends on the radius. _size = value; - _scale.Z = (_size.Z * 1.15f) - (_scale.X + _scale.Y); + ComputeAvatarScale(_size); // TODO: something has to be done with the avatar's vertical position @@ -175,11 +166,6 @@ public class BSCharacter : BSPhysObject set { _pbs = value; } } - public override uint LocalID { - set { _localID = value; - } - get { return _localID; } - } public override bool Grabbed { set { _grabbed = value; } @@ -223,7 +209,7 @@ public class BSCharacter : BSPhysObject PhysicsScene.TaintedObject("BSCharacter.setPosition", delegate() { DetailLog("{0},BSCharacter.SetPosition,taint,pos={1},orient={2}", LocalID, _position, _orientation); - BulletSimAPI.SetObjectTranslation(PhysicsScene.WorldID, _localID, _position, _orientation); + BulletSimAPI.SetObjectTranslation(PhysicsScene.WorldID, LocalID, _position, _orientation); }); } } @@ -261,7 +247,7 @@ public class BSCharacter : BSPhysObject PhysicsScene.TaintedObject("BSCharacter.PositionSanityCheck", delegate() { DetailLog("{0},BSCharacter.PositionSanityCheck,taint,pos={1},orient={2}", LocalID, _position, _orientation); - BulletSimAPI.SetObjectTranslation(PhysicsScene.WorldID, _localID, _position, _orientation); + BulletSimAPI.SetObjectTranslation(PhysicsScene.WorldID, LocalID, _position, _orientation); }); ret = true; } @@ -312,7 +298,7 @@ public class BSCharacter : BSPhysObject PhysicsScene.TaintedObject("BSCharacter.setVelocity", delegate() { DetailLog("{0},BSCharacter.setVelocity,taint,vel={1}", LocalID, _velocity); - BulletSimAPI.SetObjectVelocity(PhysicsScene.WorldID, _localID, _velocity); + BulletSimAPI.SetObjectVelocity(PhysicsScene.WorldID, LocalID, _velocity); }); } } @@ -338,7 +324,7 @@ public class BSCharacter : BSPhysObject PhysicsScene.TaintedObject("BSCharacter.setOrientation", delegate() { // _position = BulletSimAPI.GetObjectPosition(Scene.WorldID, _localID); - BulletSimAPI.SetObjectTranslation(PhysicsScene.WorldID, _localID, _position, _orientation); + BulletSimAPI.SetObjectTranslation(PhysicsScene.WorldID, LocalID, _position, _orientation); }); } } @@ -375,12 +361,12 @@ public class BSCharacter : BSPhysObject set { _throttleUpdates = value; } } public override bool IsColliding { - get { return (_collidingStep == PhysicsScene.SimulationStep); } + get { return (CollidingStep == PhysicsScene.SimulationStep); } set { _isColliding = value; } } public override bool CollidingGround { - get { return (_collidingGroundStep == PhysicsScene.SimulationStep); } - set { _collidingGround = value; } + get { return (CollidingGroundStep == PhysicsScene.SimulationStep); } + set { CollidingGround = value; } } public override bool CollidingObj { get { return _collidingObj; } @@ -466,6 +452,16 @@ public class BSCharacter : BSPhysObject public override void SetMomentum(OMV.Vector3 momentum) { } + private void ComputeAvatarScale(OMV.Vector3 size) + { + _scale.X = PhysicsScene.Params.avatarCapsuleRadius; + _scale.Y = PhysicsScene.Params.avatarCapsuleRadius; + + // The 1.15 came from ODE but it seems to cause the avatar to float off the ground + // _scale.Z = (_size.Z * 1.15f) - (_scale.X + _scale.Y); + _scale.Z = (_size.Z) - (_scale.X + _scale.Y); + } + // set _avatarVolume and _mass based on capsule size, _density and _scale private void ComputeAvatarVolumeAndMass() { @@ -480,7 +476,7 @@ public class BSCharacter : BSPhysObject * Math.Min(_scale.X, _scale.Y) * _scale.Y // plus the volume of the capsule end caps ); - _mass = _density * _avatarVolume; + _mass = _avatarDensity * _avatarVolume; } // The physics engine says that properties have updated. Update same and inform @@ -502,11 +498,5 @@ public class BSCharacter : BSPhysObject DetailLog("{0},BSCharacter.UpdateProperties,call,pos={1},orient={2},vel={3},accel={4},rotVel={5},terrain={6}", LocalID, _position, _orientation, _velocity, _acceleration, _rotationalVelocity, heightHere); } - - // Invoke the detailed logger and output something if it's enabled. - private void DetailLog(string msg, params Object[] args) - { - PhysicsScene.PhysicsLogging.Write(msg, args); - } } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index 005a758..1e8fe52 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -77,7 +77,7 @@ public class BSLinkset // A simple linkset of one (no children) LinksetID = m_nextLinksetID++; // We create LOTS of linksets. - if (m_nextLinksetID < 0) + if (m_nextLinksetID <= 0) m_nextLinksetID = 1; PhysicsScene = scene; LinksetRoot = parent; @@ -157,21 +157,26 @@ public class BSLinkset private float ComputeLinksetMass() { - float mass = LinksetRoot.MassRaw; - foreach (BSPhysObject bp in m_children) + float mass; + lock (m_linksetActivityLock) { - mass += bp.MassRaw; + mass = LinksetRoot.MassRaw; + foreach (BSPhysObject bp in m_children) + { + mass += bp.MassRaw; + } } return mass; } private OMV.Vector3 ComputeLinksetCenterOfMass() { - OMV.Vector3 com = LinksetRoot.Position * LinksetRoot.MassRaw; - float totalMass = LinksetRoot.MassRaw; - + OMV.Vector3 com; lock (m_linksetActivityLock) { + com = LinksetRoot.Position * LinksetRoot.MassRaw; + float totalMass = LinksetRoot.MassRaw; + foreach (BSPhysObject bp in m_children) { com += bp.Position * bp.MassRaw; @@ -186,10 +191,11 @@ public class BSLinkset private OMV.Vector3 ComputeLinksetGeometricCenter() { - OMV.Vector3 com = LinksetRoot.Position; - + OMV.Vector3 com; lock (m_linksetActivityLock) { + com = LinksetRoot.Position; + foreach (BSPhysObject bp in m_children) { com += bp.Position * bp.MassRaw; @@ -208,8 +214,8 @@ public class BSLinkset // Called at taint-time! public bool MakeDynamic(BSPhysObject child) { - bool ret = false; - 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 diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index 242aa80..b575e37 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -39,9 +39,12 @@ namespace OpenSim.Region.Physics.BulletSPlugin // unless the difference is significant. public abstract class BSPhysObject : PhysicsActor { - protected void BaseInitialize(BSScene parentScene) + protected void BaseInitialize(BSScene parentScene, uint localID, string name) { PhysicsScene = parentScene; + LocalID = localID; + PhysObjectName = name; + Linkset = new BSLinkset(PhysicsScene, this); CollisionCollection = new CollisionEventUpdate(); @@ -51,6 +54,8 @@ public abstract class BSPhysObject : PhysicsActor } public BSScene PhysicsScene { get; protected set; } + // public override uint LocalID { get; set; } // Use the LocalID definition in PhysicsActor + public string PhysObjectName { get; protected set; } public BSLinkset Linkset { get; set; } @@ -111,13 +116,13 @@ public abstract class BSPhysObject : PhysicsActor return ret; } - PhysicsScene.PhysicsLogging.Write("{0},BSPhysObject.Collison,call,with={1}", LocalID, collidingWith); + DetailLog("{0},BSPhysObject.Collison,call,with={1}", LocalID, collidingWith); // if someone has subscribed for collision events.... if (SubscribedEvents()) { CollisionCollection.AddCollider(collidingWith, new ContactPoint(contactPoint, contactNormal, pentrationDepth)); - PhysicsScene.PhysicsLogging.Write("{0},BSPhysObject.Collison.AddCollider,call,with={1},point={2},normal={3},depth={4},next={5}", - LocalID, collidingWith, contactPoint, contactNormal, pentrationDepth, NextCollisionOkTime.ToString("yyyyMMddHHmmssfff")); + DetailLog("{0},BSPhysObject.Collison.AddCollider,call,with={1},point={2},normal={3},depth={4}", + LocalID, collidingWith, contactPoint, contactNormal, pentrationDepth); ret = true; } return ret; @@ -127,6 +132,8 @@ public abstract class BSPhysObject : PhysicsActor // Also handles removal of this from the collection of objects with collisions if // there are no collisions from this object. Mechanism is create one last // collision event to make collision_end work. + // Called at taint time from within the Step() function thus no locking problems + // with CollisionCollection and ObjectsWithNoMoreCollisions. public virtual void SendCollisions() { // throttle the collisions to the number of milliseconds specified in the subscription @@ -140,10 +147,11 @@ public abstract class BSPhysObject : PhysicsActor if (CollisionCollection.Count == 0) PhysicsScene.ObjectsWithNoMoreCollisions.Add(this); + DetailLog("{0},SendCollisions.SendCollisionUpdate,call,numCollisions={1}", LocalID, CollisionCollection.Count); base.SendCollisionUpdate(CollisionCollection); // The collisionCollection structure is passed around in the simulator. - // Make sure we don't have a handle to that one and that a new one is used next time. + // Make sure we don't have a handle to that one and that a new one is used for next time. CollisionCollection = new CollisionEventUpdate(); } } @@ -156,8 +164,7 @@ public abstract class BSPhysObject : PhysicsActor { // make sure first collision happens NextCollisionOkTime = Util.EnvironmentTickCountSubtract(SubscribedEventsMs); - PhysicsScene.PhysicsLogging.Write("{0},SubscribeEvents,call,ms={1},nextOKTime={2}", - LocalID, SubscribedEventsMs, NextCollisionOkTime.ToString("yyyyMMddHHmmssfff")); + DetailLog("{0},SubscribeEvents,call,ms={1}", LocalID, SubscribedEventsMs); PhysicsScene.TaintedObject("BSPhysObject.SubscribeEvents", delegate() { @@ -172,7 +179,7 @@ public abstract class BSPhysObject : PhysicsActor } public override void UnSubscribeEvents() { SubscribedEventsMs = 0; - PhysicsScene.PhysicsLogging.Write("{0},UnSubscribeEvents,call", LocalID); + DetailLog("{0},UnSubscribeEvents,call", LocalID); PhysicsScene.TaintedObject("BSPhysObject.UnSubscribeEvents", delegate() { CurrentCollisionFlags = BulletSimAPI.RemoveFromCollisionFlags2(BSBody.Ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); @@ -184,5 +191,11 @@ public abstract class BSPhysObject : PhysicsActor } #endregion // Collisions + + // High performance detailed logging routine used by the physical objects. + protected void DetailLog(string msg, params Object[] args) + { + PhysicsScene.PhysicsLogging.Write(msg, args); + } } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 29f27e8..4f10d46 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -49,9 +49,6 @@ public sealed class BSPrim : BSPhysObject private ulong _hullKey; private List _hulls; - private String _avName; - private uint _localID = 0; - // _size is what the user passed. _scale is what we pass to the physics engine with the mesh. // Often _scale is unity because the meshmerizer will apply _size when creating the mesh. private OMV.Vector3 _size; // the multiplier for each mesh dimension as passed by the user @@ -99,9 +96,7 @@ public sealed class BSPrim : BSPhysObject OMV.Quaternion rotation, PrimitiveBaseShape pbs, bool pisPhysical) { // m_log.DebugFormat("{0}: BSPrim creation of {1}, id={2}", LogHeader, primName, localID); - base.BaseInitialize(parent_scene); - _localID = localID; - _avName = primName; + base.BaseInitialize(parent_scene, localID, primName); _physicsActorType = (int)ActorTypes.Prim; _position = pos; _size = size; @@ -187,10 +182,6 @@ public sealed class BSPrim : BSPhysObject }); } } - public override uint LocalID { - set { _localID = value; } - get { return _localID; } - } public override bool Grabbed { set { _grabbed = value; } @@ -267,7 +258,7 @@ public sealed class BSPrim : BSPhysObject _position = BulletSimAPI.GetPosition2(BSBody.Ptr); // don't do the GetObjectPosition for root elements because this function is called a zillion times - // _position = BulletSimAPI.GetObjectPosition(Scene.WorldID, _localID); + // _position = BulletSimAPI.GetObjectPosition(Scene.WorldID, LocalID); return _position; } set { @@ -425,7 +416,7 @@ public sealed class BSPrim : BSPhysObject // TODO: what does it mean if a child in a linkset changes its orientation? Rebuild the constraint? PhysicsScene.TaintedObject("BSPrim.setOrientation", delegate() { - // _position = BulletSimAPI.GetObjectPosition(Scene.WorldID, _localID); + // _position = BulletSimAPI.GetObjectPosition(Scene.WorldID, LocalID); DetailLog("{0},BSPrim.setOrientation,taint,pos={1},orient={2}", LocalID, _position, _orientation); BulletSimAPI.SetTranslation2(BSBody.Ptr, _position, _orientation); }); @@ -666,7 +657,7 @@ public sealed class BSPrim : BSPhysObject // Buoyancy is faked by changing the gravity applied to the object float grav = PhysicsScene.Params.gravity * (1f - _buoyancy); BulletSimAPI.SetGravity2(BSBody.Ptr, new OMV.Vector3(0f, 0f, grav)); - // BulletSimAPI.SetObjectBuoyancy(Scene.WorldID, _localID, _buoyancy); + // BulletSimAPI.SetObjectBuoyancy(Scene.WorldID, LocalID, _buoyancy); }); } } @@ -1127,7 +1118,7 @@ public sealed class BSPrim : BSPhysObject lod = PhysicsScene.MeshMegaPrimLOD; ulong newMeshKey = (ulong)_pbs.GetMeshKey(_size, lod); - // m_log.DebugFormat("{0}: CreateGeomMesh: lID={1}, oldKey={2}, newKey={3}", LogHeader, _localID, _meshKey, newMeshKey); + // m_log.DebugFormat("{0}: CreateGeomMesh: lID={1}, oldKey={2}, newKey={3}", LogHeader, LocalID, _meshKey, newMeshKey); // if this new shape is the same as last time, don't recreate the mesh if (_meshKey == newMeshKey) return false; @@ -1136,7 +1127,7 @@ public sealed class BSPrim : BSPhysObject // Since we're recreating new, get rid of any previously generated shape if (_meshKey != 0) { - // m_log.DebugFormat("{0}: CreateGeom: deleting old mesh. lID={1}, Key={2}", LogHeader, _localID, _meshKey); + // m_log.DebugFormat("{0}: CreateGeom: deleting old mesh. lID={1}, Key={2}", LogHeader, LocalID, _meshKey); DetailLog("{0},BSPrim.CreateGeomMesh,deleteOld,key={1}", LocalID, _meshKey); BulletSimAPI.DestroyMesh(PhysicsScene.WorldID, _meshKey); _mesh = null; @@ -1145,7 +1136,7 @@ public sealed class BSPrim : BSPhysObject _meshKey = newMeshKey; // always pass false for physicalness as this creates some sort of bounding box which we don't need - _mesh = PhysicsScene.mesher.CreateMesh(_avName, _pbs, _size, lod, false); + _mesh = PhysicsScene.mesher.CreateMesh(PhysObjectName, _pbs, _size, lod, false); int[] indices = _mesh.getIndexListAsInt(); List vertices = _mesh.getVertexList(); @@ -1160,7 +1151,7 @@ public sealed class BSPrim : BSPhysObject } // m_log.DebugFormat("{0}: CreateGeomMesh: calling CreateMesh. lid={1}, key={2}, indices={3}, vertices={4}", - // LogHeader, _localID, _meshKey, indices.Length, vertices.Count); + // LogHeader, LocalID, _meshKey, indices.Length, vertices.Count); BulletSimAPI.CreateMesh(PhysicsScene.WorldID, _meshKey, indices.GetLength(0), indices, vertices.Count, verticesAsFloats); @@ -1176,7 +1167,7 @@ public sealed class BSPrim : BSPhysObject { float lod = _pbs.SculptEntry ? PhysicsScene.SculptLOD : PhysicsScene.MeshLOD; ulong newHullKey = (ulong)_pbs.GetMeshKey(_size, lod); - // m_log.DebugFormat("{0}: CreateGeomHull: lID={1}, oldKey={2}, newKey={3}", LogHeader, _localID, _hullKey, newHullKey); + // m_log.DebugFormat("{0}: CreateGeomHull: lID={1}, oldKey={2}, newKey={3}", LogHeader, LocalID, _hullKey, newHullKey); // if the hull hasn't changed, don't rebuild it if (newHullKey == _hullKey) return false; @@ -1276,7 +1267,7 @@ public sealed class BSPrim : BSPhysObject } // create the hull definition in Bullet - // m_log.DebugFormat("{0}: CreateGeom: calling CreateHull. lid={1}, key={2}, hulls={3}", LogHeader, _localID, _hullKey, hullCount); + // m_log.DebugFormat("{0}: CreateGeom: calling CreateHull. lid={1}, key={2}, hulls={3}", LogHeader, LocalID, _hullKey, hullCount); BulletSimAPI.CreateHull(PhysicsScene.WorldID, _hullKey, hullCount, convHulls); _shapeType = ShapeData.PhysicsShapeType.SHAPE_HULL; // meshes are already scaled by the meshmerizer @@ -1316,7 +1307,7 @@ public sealed class BSPrim : BSPhysObject // the mesh or hull must have already been created in Bullet ShapeData shape; FillShapeInfo(out shape); - // m_log.DebugFormat("{0}: CreateObject: lID={1}, shape={2}", LogHeader, _localID, shape.Type); + // m_log.DebugFormat("{0}: CreateObject: lID={1}, shape={2}", LogHeader, LocalID, shape.Type); bool ret = BulletSimAPI.CreateObject(PhysicsScene.WorldID, shape); // the CreateObject() may have recreated the rigid body. Make sure we have the latest address. @@ -1329,7 +1320,7 @@ public sealed class BSPrim : BSPhysObject // Copy prim's info into the BulletSim shape description structure public void FillShapeInfo(out ShapeData shape) { - shape.ID = _localID; + shape.ID = LocalID; shape.Type = _shapeType; shape.Position = _position; shape.Rotation = _orientation; @@ -1350,7 +1341,7 @@ public sealed class BSPrim : BSPhysObject // No locking here because this is done when the physics engine is not simulating private void CreateGeomAndObject(bool forceRebuild) { - // m_log.DebugFormat("{0}: CreateGeomAndObject. lID={1}, force={2}", LogHeader, _localID, forceRebuild); + // m_log.DebugFormat("{0}: CreateGeomAndObject. lID={1}, force={2}", LogHeader, LocalID, forceRebuild); // Create the geometry that will make up the object if (CreateGeom(forceRebuild)) { @@ -1453,10 +1444,5 @@ public sealed class BSPrim : BSPhysObject } */ } - // Invoke the detailed logger and output something if it's enabled. - private void DetailLog(string msg, params Object[] args) - { - PhysicsScene.PhysicsLogging.Write(msg, args); - } } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs index d48462e..c113db1 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs @@ -57,10 +57,10 @@ public class BSTerrainManager public const float TERRAIN_COLLISION_MARGIN = 0.0f; // Until the whole simulator is changed to pass us the region size, we rely on constants. - public Vector3 DefaultRegionSize = new Vector3(Constants.RegionSize, Constants.RegionSize, 0f); + public Vector3 DefaultRegionSize = new Vector3(Constants.RegionSize, Constants.RegionSize, Constants.RegionHeight); // The scene that I am part of - private BSScene m_physicsScene; + private BSScene PhysicsScene { get; set; } // The ground plane created to keep thing from falling to infinity. private BulletBody m_groundPlane; @@ -84,18 +84,18 @@ public class BSTerrainManager // If the parent region (region 0), this is the extent of the combined regions // relative to the origin of region zero private Vector3 m_worldMax; - private PhysicsScene m_parentScene; + private PhysicsScene MegaRegionParentPhysicsScene { get; set; } public BSTerrainManager(BSScene physicsScene) { - m_physicsScene = physicsScene; + PhysicsScene = physicsScene; m_heightMaps = new Dictionary(); m_terrainModified = false; // Assume one region of default size m_worldOffset = Vector3.Zero; - m_worldMax = new Vector3(DefaultRegionSize.X, DefaultRegionSize.Y, 4096f); - m_parentScene = null; + m_worldMax = new Vector3(DefaultRegionSize); + MegaRegionParentPhysicsScene = null; } // Create the initial instance of terrain and the underlying ground plane. @@ -110,7 +110,7 @@ public class BSTerrainManager BulletShape groundPlaneShape = new BulletShape(BulletSimAPI.CreateGroundPlaneShape2(BSScene.GROUNDPLANE_ID, 1f, TERRAIN_COLLISION_MARGIN)); m_groundPlane = new BulletBody(BSScene.GROUNDPLANE_ID, BulletSimAPI.CreateBodyWithDefaultMotionState2(groundPlaneShape.Ptr, Vector3.Zero, Quaternion.Identity)); - BulletSimAPI.AddObjectToWorld2(m_physicsScene.World.Ptr, m_groundPlane.Ptr); + BulletSimAPI.AddObjectToWorld2(PhysicsScene.World.Ptr, m_groundPlane.Ptr); Vector3 minTerrainCoords = new Vector3(0f, 0f, HEIGHT_INITIALIZATION - HEIGHT_EQUAL_FUDGE); Vector3 maxTerrainCoords = new Vector3(DefaultRegionSize.X, DefaultRegionSize.Y, HEIGHT_INITIALIZATION); @@ -128,9 +128,9 @@ public class BSTerrainManager { if (m_groundPlane.Ptr != IntPtr.Zero) { - if (BulletSimAPI.RemoveObjectFromWorld2(m_physicsScene.World.Ptr, m_groundPlane.Ptr)) + if (BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.Ptr, m_groundPlane.Ptr)) { - BulletSimAPI.DestroyObject2(m_physicsScene.World.Ptr, m_groundPlane.Ptr); + BulletSimAPI.DestroyObject2(PhysicsScene.World.Ptr, m_groundPlane.Ptr); } m_groundPlane.Ptr = IntPtr.Zero; } @@ -143,9 +143,9 @@ public class BSTerrainManager { foreach (KeyValuePair kvp in m_heightMaps) { - if (BulletSimAPI.RemoveObjectFromWorld2(m_physicsScene.World.Ptr, kvp.Value.terrainBody.Ptr)) + if (BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.Ptr, kvp.Value.terrainBody.Ptr)) { - BulletSimAPI.DestroyObject2(m_physicsScene.World.Ptr, kvp.Value.terrainBody.Ptr); + BulletSimAPI.DestroyObject2(PhysicsScene.World.Ptr, kvp.Value.terrainBody.Ptr); BulletSimAPI.ReleaseHeightMapInfo2(kvp.Value.Ptr); } } @@ -155,19 +155,19 @@ public class BSTerrainManager // The simulator wants to set a new heightmap for the terrain. public void SetTerrain(float[] heightMap) { float[] localHeightMap = heightMap; - m_physicsScene.TaintedObject("TerrainManager.SetTerrain", delegate() + PhysicsScene.TaintedObject("TerrainManager.SetTerrain", delegate() { - if (m_worldOffset != Vector3.Zero && m_parentScene != null) + if (m_worldOffset != Vector3.Zero && MegaRegionParentPhysicsScene != null) { // If a child of a mega-region, we shouldn't have any terrain allocated for us ReleaseGroundPlaneAndTerrain(); // If doing the mega-prim stuff and we are the child of the zero region, // the terrain is added to our parent - if (m_parentScene is BSScene) + if (MegaRegionParentPhysicsScene is BSScene) { DetailLog("{0},SetTerrain.ToParent,offset={1},worldMax={2}", BSScene.DetailLogZero, m_worldOffset, m_worldMax); - ((BSScene)m_parentScene).TerrainManager.UpdateOrCreateTerrain(BSScene.CHILDTERRAIN_ID, + ((BSScene)MegaRegionParentPhysicsScene).TerrainManager.UpdateOrCreateTerrain(BSScene.CHILDTERRAIN_ID, localHeightMap, m_worldOffset, m_worldOffset + DefaultRegionSize, true); } } @@ -176,7 +176,8 @@ public class BSTerrainManager // If not doing the mega-prim thing, just change the terrain DetailLog("{0},SetTerrain.Existing", BSScene.DetailLogZero); - UpdateOrCreateTerrain(BSScene.TERRAIN_ID, localHeightMap, m_worldOffset, m_worldOffset + DefaultRegionSize, true); + UpdateOrCreateTerrain(BSScene.TERRAIN_ID, localHeightMap, + m_worldOffset, m_worldOffset + DefaultRegionSize, true); } }); } @@ -232,7 +233,7 @@ public class BSTerrainManager BSScene.TaintCallback rebuildOperation = delegate() { - if (m_parentScene != null) + if (MegaRegionParentPhysicsScene != null) { // It's possible that Combine() was called after this code was queued. // If we are a child of combined regions, we don't create any terrain for us. @@ -252,10 +253,10 @@ public class BSTerrainManager BSScene.DetailLogZero, terrainRegionBase, mapInfo.minCoords, mapInfo.maxCoords, mapInfo.sizeX, mapInfo.sizeY); // Remove from the dynamics world because we're going to mangle this object - BulletSimAPI.RemoveObjectFromWorld2(m_physicsScene.World.Ptr, mapInfo.terrainBody.Ptr); + BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.Ptr, mapInfo.terrainBody.Ptr); // Get rid of the old terrain - BulletSimAPI.DestroyObject2(m_physicsScene.World.Ptr, mapInfo.terrainBody.Ptr); + BulletSimAPI.DestroyObject2(PhysicsScene.World.Ptr, mapInfo.terrainBody.Ptr); BulletSimAPI.ReleaseHeightMapInfo2(mapInfo.Ptr); mapInfo.Ptr = IntPtr.Zero; @@ -286,7 +287,7 @@ public class BSTerrainManager BSScene.DetailLogZero, mapInfo.minCoords.X, mapInfo.minCoords.Y, minZ, maxZ); mapInfo.ID = id; - mapInfo.Ptr = BulletSimAPI.CreateHeightMapInfo2(m_physicsScene.World.Ptr, mapInfo.ID, + mapInfo.Ptr = BulletSimAPI.CreateHeightMapInfo2(PhysicsScene.World.Ptr, mapInfo.ID, mapInfo.minCoords, mapInfo.maxCoords, mapInfo.heightMap, TERRAIN_COLLISION_MARGIN); // The terrain object initial position is at the center of the object @@ -307,19 +308,19 @@ public class BSTerrainManager m_heightMaps[terrainRegionBase] = mapInfo; // Set current terrain attributes - BulletSimAPI.SetFriction2(mapInfo.terrainBody.Ptr, m_physicsScene.Params.terrainFriction); - BulletSimAPI.SetHitFraction2(mapInfo.terrainBody.Ptr, m_physicsScene.Params.terrainHitFraction); - BulletSimAPI.SetRestitution2(mapInfo.terrainBody.Ptr, m_physicsScene.Params.terrainRestitution); + BulletSimAPI.SetFriction2(mapInfo.terrainBody.Ptr, PhysicsScene.Params.terrainFriction); + BulletSimAPI.SetHitFraction2(mapInfo.terrainBody.Ptr, PhysicsScene.Params.terrainHitFraction); + BulletSimAPI.SetRestitution2(mapInfo.terrainBody.Ptr, PhysicsScene.Params.terrainRestitution); BulletSimAPI.SetCollisionFlags2(mapInfo.terrainBody.Ptr, CollisionFlags.CF_STATIC_OBJECT); BulletSimAPI.SetMassProps2(mapInfo.terrainBody.Ptr, 0f, Vector3.Zero); BulletSimAPI.UpdateInertiaTensor2(mapInfo.terrainBody.Ptr); // Return the new terrain to the world of physical objects - BulletSimAPI.AddObjectToWorld2(m_physicsScene.World.Ptr, mapInfo.terrainBody.Ptr); + BulletSimAPI.AddObjectToWorld2(PhysicsScene.World.Ptr, mapInfo.terrainBody.Ptr); // redo its bounding box now that it is in the world - BulletSimAPI.UpdateSingleAabb2(m_physicsScene.World.Ptr, mapInfo.terrainBody.Ptr); + BulletSimAPI.UpdateSingleAabb2(PhysicsScene.World.Ptr, mapInfo.terrainBody.Ptr); // Make sure the new shape is processed. BulletSimAPI.Activate2(mapInfo.terrainBody.Ptr, true); @@ -332,7 +333,7 @@ public class BSTerrainManager if (doNow) rebuildOperation(); else - m_physicsScene.TaintedObject("BSScene.UpdateOrCreateTerrain:UpdateExisting", rebuildOperation); + PhysicsScene.TaintedObject("BSScene.UpdateOrCreateTerrain:UpdateExisting", rebuildOperation); } else { @@ -357,7 +358,7 @@ public class BSTerrainManager DetailLog("{0},UpdateOrCreateTerrain:NewTerrain,taint,baseX={1},baseY={2}", BSScene.DetailLogZero, minCoords.X, minCoords.Y); // Create a new mapInfo that will be filled with the new info mapInfo = new BulletHeightMapInfo(id, heightMapX, - BulletSimAPI.CreateHeightMapInfo2(m_physicsScene.World.Ptr, newTerrainID, + BulletSimAPI.CreateHeightMapInfo2(PhysicsScene.World.Ptr, newTerrainID, minCoordsX, maxCoordsX, heightMapX, TERRAIN_COLLISION_MARGIN)); // Put the unfilled heightmap info into the collection of same m_heightMaps.Add(terrainRegionBase, mapInfo); @@ -371,7 +372,7 @@ public class BSTerrainManager if (doNow) createOperation(); else - m_physicsScene.TaintedObject("BSScene.UpdateOrCreateTerrain:NewTerrain", createOperation); + PhysicsScene.TaintedObject("BSScene.UpdateOrCreateTerrain:NewTerrain", createOperation); } } @@ -419,7 +420,7 @@ public class BSTerrainManager catch { // Sometimes they give us wonky values of X and Y. Give a warning and return something. - m_physicsScene.Logger.WarnFormat("{0} Bad request for terrain height. terrainBase={1}, x={2}, y={3}", + PhysicsScene.Logger.WarnFormat("{0} Bad request for terrain height. terrainBase={1}, x={2}, y={3}", LogHeader, terrainBaseXY, regionX, regionY); ret = HEIGHT_GETHEIGHT_RET; } @@ -428,8 +429,8 @@ public class BSTerrainManager } else { - m_physicsScene.Logger.ErrorFormat("{0} GetTerrainHeightAtXY: terrain not found: region={1}, x={2}, y={3}", - LogHeader, m_physicsScene.RegionName, tX, tY); + PhysicsScene.Logger.ErrorFormat("{0} GetTerrainHeightAtXY: terrain not found: region={1}, x={2}, y={3}", + LogHeader, PhysicsScene.RegionName, tX, tY); } m_terrainModified = false; lastHeight = ret; @@ -453,7 +454,7 @@ public class BSTerrainManager { m_worldOffset = offset; m_worldMax = extents; - m_parentScene = pScene; + MegaRegionParentPhysicsScene = pScene; if (pScene != null) { // We are a child. @@ -474,7 +475,7 @@ public class BSTerrainManager private void DetailLog(string msg, params Object[] args) { - m_physicsScene.PhysicsLogging.Write(msg, args); + PhysicsScene.PhysicsLogging.Write(msg, args); } } } -- cgit v1.1 From a27e4ce6cbfb0a2e852624fd4d81121ca829f85c Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Wed, 19 Sep 2012 08:21:29 -0700 Subject: BulletSim: add class and infrastructure for shape and object tracking in the C# code. Needed for the changing body type (to and from GhostObjects) for volumeDetect. --- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 47 +++++++++-- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 16 ++-- .../Physics/BulletSPlugin/BSShapeCollection.cs | 70 +++++++++++++++++ .../Physics/BulletSPlugin/BSTerrainManager.cs | 7 +- .../Region/Physics/BulletSPlugin/BulletSimAPI.cs | 91 ++++++++++++++++------ 5 files changed, 192 insertions(+), 39 deletions(-) create mode 100755 OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 4f10d46..4d17e6c 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -474,12 +474,13 @@ public sealed class BSPrim : BSPhysObject */ BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.Ptr, BSBody.Ptr); - // Set up the object physicalness (does gravity and collisions move this object) - MakeDynamic(IsStatic); - // Make solid or not (do things bounce off or pass through this object) + // This is done first because it can change the collisionObject type. MakeSolid(IsSolid); + // Set up the object physicalness (does gravity and collisions move this object) + MakeDynamic(IsStatic); + // Arrange for collisions events if the simulator wants them EnableCollisions(SubscribedEvents()); @@ -554,17 +555,51 @@ public sealed class BSPrim : BSPhysObject } // "Making solid" means that other object will not pass through this object. + // To make transparent, we create a Bullet ghost object. + // Note: This expects to be called from the UpdatePhysicalParameters() routine as + // the functions after this one set up the state of a possibly newly created collision body. private void MakeSolid(bool makeSolid) { + CollisionObjectTypes bodyType = (CollisionObjectTypes)BulletSimAPI.GetBodyType2(BSBody.Ptr); + /* if (makeSolid) { - // Easy in Bullet -- just remove the object flag that controls collision response - CurrentCollisionFlags = BulletSimAPI.RemoveFromCollisionFlags2(BSBody.Ptr, CollisionFlags.CF_NO_CONTACT_RESPONSE); + if ((bodyType & CollisionObjectTypes.CO_RIGID_BODY) == 0) + { + // Solid things are made out of rigid bodies. Remove this old body from the world + // and use this shape in a new rigid body. + BulletBody oldBody = BSBody; + BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.Ptr, BSBody.Ptr); + BSShape = new BulletShape(BulletSimAPI.GetCollisionShape2(BSBody.Ptr)); + BSBody = new BulletBody(LocalID, BulletSimAPI.CreateBodyFromShape2(PhysicsScene.World.Ptr, BSShape.Ptr, _position, _orientation)); + BulletSimAPI.DestroyObject2(PhysicsScene.World.Ptr, oldBody.Ptr); + BulletSimAPI.AddObjectToWorld2(PhysicsScene.World.Ptr, BSBody.Ptr); + } } else { - CurrentCollisionFlags = BulletSimAPI.AddToCollisionFlags2(BSBody.Ptr, CollisionFlags.CF_NO_CONTACT_RESPONSE); + if ((bodyType & CollisionObjectTypes.CO_GHOST_OBJECT) == 0) + { + // Non-solid things are made out of ghost objects. Remove this old body from the world + // and use this shape in a new rigid body. + BulletBody oldBody = BSBody; + BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.Ptr, BSBody.Ptr); + BSShape = new BulletShape(BulletSimAPI.GetCollisionShape2(BSBody.Ptr)); + BSBody = new BulletBody(LocalID, + BulletSimAPI.CreateGhostFromShape2(PhysicsScene.World.Ptr, BSShape.Ptr, _position, _orientation)); + if (BSBody.Ptr == IntPtr.Zero) + { + m_log.ErrorFormat("{0} BSPrim.MakeSolid: failed creation of ghost object. LocalID=[1}", LogHeader, LocalID); + BSBody = oldBody; + } + else + { + BulletSimAPI.DestroyObject2(PhysicsScene.World.Ptr, oldBody.Ptr); + BulletSimAPI.AddObjectToWorld2(PhysicsScene.World.Ptr, BSBody.Ptr); + } + } } + */ } // Turn on or off the flag controlling whether collision events are returned to the simulator. diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index dabced5..76da42d 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -73,8 +73,10 @@ public class BSScene : PhysicsScene, IPhysicsParameters public string BulletSimVersion = "?"; - public Dictionary PhysObjects = new Dictionary(); + 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(); // Keep track of all the avatars so we can send them a collision event @@ -203,6 +205,11 @@ public class BSScene : PhysicsScene, IPhysicsParameters public override void Initialise(IMesher meshmerizer, IConfigSource config) { + mesher = meshmerizer; + _taintedObjects = new List(); + PhysObjects = new Dictionary(); + Shapes = new BSShapeCollection(this); + // Allocate pinned memory to pass parameters. m_params = new ConfigurationParameters[1]; m_paramsHandle = GCHandle.Alloc(m_params, GCHandleType.Pinned); @@ -216,12 +223,9 @@ public class BSScene : PhysicsScene, IPhysicsParameters m_updateArray = new EntityProperties[m_maxUpdatesPerFrame]; m_updateArrayPinnedHandle = GCHandle.Alloc(m_updateArray, GCHandleType.Pinned); - mesher = meshmerizer; - _taintedObjects = new List(); - // Enable very detailed logging. // By creating an empty logger when not logging, the log message invocation code - // can be left in and every call doesn't have to check for null. + // 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); @@ -252,7 +256,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters // a child in a mega-region. // Turns out that Bullet really doesn't care about the extents of the simulated // area. It tracks active objects no matter where they are. - Vector3 worldExtent = new Vector3(Constants.RegionSize, Constants.RegionSize, 8192f); + Vector3 worldExtent = new Vector3(Constants.RegionSize, Constants.RegionSize, Constants.RegionHeight); // m_log.DebugFormat("{0}: Initialize: Calling BulletSimAPI.Initialize.", LogHeader); WorldID = BulletSimAPI.Initialize(worldExtent, m_paramsHandle.AddrOfPinnedObject(), diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs new file mode 100755 index 0000000..eb4b2ad --- /dev/null +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -0,0 +1,70 @@ +/* + * 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 OMV = OpenMetaverse; + +namespace OpenSim.Region.Physics.BulletSPlugin +{ +public class BSShapeCollection : IDisposable +{ + protected BSScene PhysicsScene { get; set; } + + public BSShapeCollection(BSScene physScene) + { + PhysicsScene = physScene; + } + + public void Dispose() + { + } + + // Track another user of a body + public void ReferenceBody(BulletBody shape) + { + } + + // Release the usage of a body + public void DereferenceBody(BulletBody shape) + { + } + + // Track another user of the shape + public void ReferenceShape(BulletShape shape) + { + } + + // Release the usage of a shape + public void DereferenceShape(BulletShape shape) + { + } + + + +} +} diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs index c113db1..fb802e4 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs @@ -107,7 +107,9 @@ public class BSTerrainManager public void CreateInitialGroundPlaneAndTerrain() { // The ground plane is here to catch things that are trying to drop to negative infinity - BulletShape groundPlaneShape = new BulletShape(BulletSimAPI.CreateGroundPlaneShape2(BSScene.GROUNDPLANE_ID, 1f, TERRAIN_COLLISION_MARGIN)); + BulletShape groundPlaneShape = new BulletShape( + BulletSimAPI.CreateGroundPlaneShape2(BSScene.GROUNDPLANE_ID, 1f, TERRAIN_COLLISION_MARGIN), + ShapeData.PhysicsShapeType.SHAPE_GROUNDPLANE); m_groundPlane = new BulletBody(BSScene.GROUNDPLANE_ID, BulletSimAPI.CreateBodyWithDefaultMotionState2(groundPlaneShape.Ptr, Vector3.Zero, Quaternion.Identity)); BulletSimAPI.AddObjectToWorld2(PhysicsScene.World.Ptr, m_groundPlane.Ptr); @@ -297,7 +299,8 @@ public class BSTerrainManager centerPos.Z = minZ + ((maxZ - minZ) / 2f); // Create the terrain shape from the mapInfo - mapInfo.terrainShape = new BulletShape(BulletSimAPI.CreateTerrainShape2(mapInfo.Ptr)); + mapInfo.terrainShape = new BulletShape(BulletSimAPI.CreateTerrainShape2(mapInfo.Ptr), + ShapeData.PhysicsShapeType.SHAPE_TERRAIN); mapInfo.terrainBody = new BulletBody(mapInfo.ID, BulletSimAPI.CreateBodyWithDefaultMotionState2(mapInfo.terrainShape.Ptr, diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs index 4d2d962..52c8a24 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs @@ -38,31 +38,54 @@ namespace OpenSim.Region.Physics.BulletSPlugin { // The physics engine controller class created at initialization public struct BulletSim { - public BulletSim(uint worldId, BSScene bss, IntPtr xx) { worldID = worldId; scene = bss; Ptr = xx; } + public BulletSim(uint worldId, BSScene bss, IntPtr xx) + { + worldID = worldId; scene = bss; Ptr = xx; + } public uint worldID; // The scene is only in here so very low level routines have a handle to print debug/error messages public BSScene scene; public IntPtr Ptr; } -public struct BulletShape +// An allocated Bullet btRigidBody +public struct BulletBody { - public BulletShape(IntPtr xx) { Ptr = xx; } + public BulletBody(uint id, IntPtr xx) + { + ID = id; + Ptr = xx; + } public IntPtr Ptr; + public uint ID; } -// An allocated Bullet btRigidBody -public struct BulletBody +public struct BulletShape { - public BulletBody(uint id, IntPtr xx) { ID = id; Ptr = xx; } + public BulletShape(IntPtr xx) + { + Ptr = xx; + type=ShapeData.PhysicsShapeType.SHAPE_UNKNOWN; + hashKey = 0; + } + public BulletShape(IntPtr xx, ShapeData.PhysicsShapeType typ) + { + Ptr = xx; + type = typ; + hashKey = 0; + } public IntPtr Ptr; - public uint ID; + public ShapeData.PhysicsShapeType type; + public ulong hashKey; } // An allocated Bullet btConstraint public struct BulletConstraint { - public BulletConstraint(IntPtr xx) { Ptr = xx; } + public BulletConstraint(IntPtr xx) + { + Ptr = xx; + } public IntPtr Ptr; } @@ -96,14 +119,14 @@ public class BulletHeightMapInfo // =============================================================================== [StructLayout(LayoutKind.Sequential)] -public struct ConvexHull +public struct ConvexHull { Vector3 Offset; int VertexCount; Vector3[] Vertices; } [StructLayout(LayoutKind.Sequential)] -public struct ShapeData +public struct ShapeData { public enum PhysicsShapeType { @@ -114,7 +137,9 @@ public struct ShapeData SHAPE_CYLINDER = 4, SHAPE_SPHERE = 5, SHAPE_MESH = 6, - SHAPE_HULL = 7 + SHAPE_HULL = 7, + SHAPE_GROUNDPLANE = 8, + SHAPE_TERRAIN = 9, }; public uint ID; public PhysicsShapeType Type; @@ -136,7 +161,7 @@ public struct ShapeData public const float numericFalse = 0f; } [StructLayout(LayoutKind.Sequential)] -public struct SweepHit +public struct SweepHit { public uint ID; public float Fraction; @@ -227,7 +252,17 @@ public enum ActivationState : uint ISLAND_SLEEPING, WANTS_DEACTIVATION, DISABLE_DEACTIVATION, - DISABLE_SIMULATION + DISABLE_SIMULATION, +} + +public enum CollisionObjectTypes : int +{ + CO_COLLISION_OBJECT = 1 << 0, + CO_RIGID_BODY = 1 << 1, + CO_GHOST_OBJECT = 1 << 2, + CO_SOFT_BODY = 1 << 3, + CO_HF_FLUID = 1 << 4, + CO_USER_TYPE = 1 << 5, } // Values used by Bullet and BulletSim to control object properties. @@ -313,8 +348,8 @@ public delegate void DebugLogCallback([MarshalAs(UnmanagedType.LPStr)]string msg public static extern string GetVersion(); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern uint Initialize(Vector3 maxPosition, IntPtr parms, - int maxCollisions, IntPtr collisionArray, +public static extern uint Initialize(Vector3 maxPosition, IntPtr parms, + int maxCollisions, IntPtr collisionArray, int maxUpdates, IntPtr updateArray, DebugLogCallback logRoutine); @@ -333,19 +368,19 @@ public static extern bool UpdateParameter(uint worldID, uint localID, // =============================================================================== [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern int PhysicsStep(uint worldID, float timeStep, int maxSubSteps, float fixedTimeStep, - out int updatedEntityCount, +public static extern int PhysicsStep(uint worldID, float timeStep, int maxSubSteps, float fixedTimeStep, + out int updatedEntityCount, out IntPtr updatedEntitiesPtr, out int collidersCount, out IntPtr collidersPtr); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool CreateHull(uint worldID, System.UInt64 meshKey, +public static extern bool CreateHull(uint worldID, System.UInt64 meshKey, int hullCount, [MarshalAs(UnmanagedType.LPArray)] float[] hulls ); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool CreateMesh(uint worldID, System.UInt64 meshKey, +public static extern bool CreateMesh(uint worldID, System.UInt64 meshKey, int indexCount, [MarshalAs(UnmanagedType.LPArray)] int[] indices, int verticesCount, [MarshalAs(UnmanagedType.LPArray)] float[] vertices ); @@ -459,7 +494,7 @@ public static extern void Shutdown2(IntPtr sim); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern int PhysicsStep2(IntPtr world, float timeStep, int maxSubSteps, float fixedTimeStep, - out int updatedEntityCount, + out int updatedEntityCount, out IntPtr updatedEntitiesPtr, out int collidersCount, out IntPtr collidersPtr); @@ -470,8 +505,8 @@ public static extern bool PushUpdate2(IntPtr obj); // ===================================================================================== // Mesh, hull, shape and body creation helper routines [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern IntPtr CreateMeshShape2(IntPtr world, - int indicesCount, [MarshalAs(UnmanagedType.LPArray)] int[] indices, +public static extern IntPtr CreateMeshShape2(IntPtr world, + int indicesCount, [MarshalAs(UnmanagedType.LPArray)] int[] indices, int verticesCount, [MarshalAs(UnmanagedType.LPArray)] float[] vertices ); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] @@ -504,12 +539,18 @@ public static extern IntPtr CreateBodyFromShapeAndInfo2(IntPtr sim, IntPtr shape public static extern bool DeleteCollisionShape2(IntPtr world, IntPtr shape); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern int GetBodyType2(IntPtr obj); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern IntPtr CreateBodyFromShape2(IntPtr sim, IntPtr shape, Vector3 pos, Quaternion rot); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern IntPtr CreateBodyWithDefaultMotionState2(IntPtr shape, Vector3 pos, Quaternion rot); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern IntPtr CreateGhostFromShape2(IntPtr sim, IntPtr shape, Vector3 pos, Quaternion rot); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern IntPtr AllocateBodyInfo2(IntPtr obj); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] @@ -521,11 +562,11 @@ public static extern void DestroyObject2(IntPtr sim, IntPtr obj); // ===================================================================================== // Terrain creation and helper routines [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern IntPtr CreateHeightMapInfo2(IntPtr sim, uint id, Vector3 minCoords, Vector3 maxCoords, +public static extern IntPtr CreateHeightMapInfo2(IntPtr sim, uint id, Vector3 minCoords, Vector3 maxCoords, [MarshalAs(UnmanagedType.LPArray)] float[] heightMap, float collisionMargin); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern IntPtr FillHeightMapInfo2(IntPtr sim, IntPtr mapInfo, uint id, Vector3 minCoords, Vector3 maxCoords, +public static extern IntPtr FillHeightMapInfo2(IntPtr sim, IntPtr mapInfo, uint id, Vector3 minCoords, Vector3 maxCoords, [MarshalAs(UnmanagedType.LPArray)] float[] heightMap, float collisionMargin); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] @@ -563,7 +604,7 @@ public static extern void SetConstraintEnable2(IntPtr constrain, float numericTr public static extern void SetConstraintNumSolverIterations2(IntPtr constrain, float iterations); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool SetFrames2(IntPtr constrain, +public static extern bool SetFrames2(IntPtr constrain, Vector3 frameA, Quaternion frameArot, Vector3 frameB, Quaternion frameBrot); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -- cgit v1.1 From 22290ef35aa13edb1501c69b3cce63a885302563 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Thu, 20 Sep 2012 10:12:51 -0700 Subject: BulletSim: complete code for managed code shape and body tracking. Not debugged. Eliminate some null exceptions created adding the above code. Add and remove some detailed logging statements. --- .../Region/Physics/BulletSPlugin/BSCharacter.cs | 2 +- .../Region/Physics/BulletSPlugin/BSPhysObject.cs | 22 +- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 121 ++-- .../Physics/BulletSPlugin/BSShapeCollection.cs | 617 ++++++++++++++++++--- .../Region/Physics/BulletSPlugin/BulletSimAPI.cs | 43 +- 5 files changed, 675 insertions(+), 130 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index 19eb1e6..014cd99 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -77,7 +77,7 @@ public class BSCharacter : BSPhysObject public BSCharacter(uint localID, String avName, BSScene parent_scene, OMV.Vector3 pos, OMV.Vector3 size, bool isFlying) { - base.BaseInitialize(parent_scene, localID, avName); + base.BaseInitialize(parent_scene, localID, avName, "BSCharacter"); _physicsActorType = (int)ActorTypes.Agent; _position = pos; _size = size; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index b575e37..70a10b1 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -39,11 +39,12 @@ namespace OpenSim.Region.Physics.BulletSPlugin // unless the difference is significant. public abstract class BSPhysObject : PhysicsActor { - protected void BaseInitialize(BSScene parentScene, uint localID, string name) + protected void BaseInitialize(BSScene parentScene, uint localID, string name, string typeName) { PhysicsScene = parentScene; LocalID = localID; PhysObjectName = name; + TypeName = typeName; Linkset = new BSLinkset(PhysicsScene, this); @@ -56,6 +57,7 @@ public abstract class BSPhysObject : PhysicsActor public BSScene PhysicsScene { 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; } public BSLinkset Linkset { get; set; } @@ -63,9 +65,9 @@ public abstract class BSPhysObject : PhysicsActor public abstract float MassRaw { get; } // Reference to the physical body (btCollisionObject) of this object - public BulletBody BSBody { get; protected set; } + public BulletBody BSBody; // Reference to the physical shape (btCollisionShape) of this object - public BulletShape BSShape { get; protected set; } + public BulletShape BSShape; // Stop all physical motion. public abstract void ZeroMotion(); @@ -116,13 +118,11 @@ public abstract class BSPhysObject : PhysicsActor return ret; } - DetailLog("{0},BSPhysObject.Collison,call,with={1}", LocalID, collidingWith); - // if someone has subscribed for collision events.... if (SubscribedEvents()) { CollisionCollection.AddCollider(collidingWith, new ContactPoint(contactPoint, contactNormal, pentrationDepth)); - DetailLog("{0},BSPhysObject.Collison.AddCollider,call,with={1},point={2},normal={3},depth={4}", - LocalID, collidingWith, contactPoint, contactNormal, pentrationDepth); + // DetailLog("{0},{1}.Collison.AddCollider,call,with={2},point={3},normal={4},depth={5}", + // LocalID, TypeName, collidingWith, contactPoint, contactNormal, pentrationDepth); ret = true; } return ret; @@ -147,7 +147,7 @@ public abstract class BSPhysObject : PhysicsActor if (CollisionCollection.Count == 0) PhysicsScene.ObjectsWithNoMoreCollisions.Add(this); - DetailLog("{0},SendCollisions.SendCollisionUpdate,call,numCollisions={1}", LocalID, CollisionCollection.Count); + // DetailLog("{0},{1}.SendCollisionUpdate,call,numCollisions={2}", LocalID, TypeName, CollisionCollection.Count); base.SendCollisionUpdate(CollisionCollection); // The collisionCollection structure is passed around in the simulator. @@ -164,9 +164,8 @@ public abstract class BSPhysObject : PhysicsActor { // make sure first collision happens NextCollisionOkTime = Util.EnvironmentTickCountSubtract(SubscribedEventsMs); - DetailLog("{0},SubscribeEvents,call,ms={1}", LocalID, SubscribedEventsMs); - PhysicsScene.TaintedObject("BSPhysObject.SubscribeEvents", delegate() + PhysicsScene.TaintedObject(TypeName+".SubscribeEvents", delegate() { CurrentCollisionFlags = BulletSimAPI.AddToCollisionFlags2(BSBody.Ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); }); @@ -179,8 +178,7 @@ public abstract class BSPhysObject : PhysicsActor } public override void UnSubscribeEvents() { SubscribedEventsMs = 0; - DetailLog("{0},UnSubscribeEvents,call", LocalID); - PhysicsScene.TaintedObject("BSPhysObject.UnSubscribeEvents", delegate() + PhysicsScene.TaintedObject(TypeName+".UnSubscribeEvents", delegate() { CurrentCollisionFlags = BulletSimAPI.RemoveFromCollisionFlags2(BSBody.Ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); }); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 4d17e6c..4d2c70c 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -96,7 +96,7 @@ public sealed class BSPrim : BSPhysObject OMV.Quaternion rotation, PrimitiveBaseShape pbs, bool pisPhysical) { // m_log.DebugFormat("{0}: BSPrim creation of {1}, id={2}", LogHeader, primName, localID); - base.BaseInitialize(parent_scene, localID, primName); + base.BaseInitialize(parent_scene, localID, primName, "BSPrim"); _physicsActorType = (int)ActorTypes.Prim; _position = pos; _size = size; @@ -115,17 +115,17 @@ public sealed class BSPrim : BSPhysObject _restitution = PhysicsScene.Params.defaultRestitution; _vehicle = new BSDynamics(PhysicsScene, this); // add vehicleness _mass = CalculateMass(); + + // No body or shape yet + BSBody = new BulletBody(LocalID, IntPtr.Zero); + BSShape = new BulletShape(IntPtr.Zero); + DetailLog("{0},BSPrim.constructor,call", LocalID); // do the actual object creation at taint time PhysicsScene.TaintedObject("BSPrim.create", delegate() { CreateGeomAndObject(true); - // Get the pointer to the physical body for this object. - // At the moment, we're still letting BulletSim manage the creation and destruction - // of the object. Someday we'll move that into the C# code. - BSBody = new BulletBody(LocalID, BulletSimAPI.GetBodyHandle2(PhysicsScene.World.Ptr, LocalID)); - BSShape = new BulletShape(BulletSimAPI.GetCollisionShape2(BSBody.Ptr)); CurrentCollisionFlags = BulletSimAPI.GetCollisionFlags2(BSBody.Ptr); }); } @@ -168,17 +168,24 @@ public sealed class BSPrim : BSPhysObject // Since _size changed, the mesh needs to be rebuilt. If rebuilt, all the correct // scale and margins are set. CreateGeomAndObject(true); - DetailLog("{0}: BSPrim.setSize: size={1}, scale={2}, mass={3}, physical={4}", LocalID, _size, _scale, _mass, IsPhysical); + DetailLog("{0},BSPrim.setSize,size={1},scale={2},mass={3},physical={4}", LocalID, _size, _scale, _mass, IsPhysical); }); } } + // Scale is what we set in the physics engine. It is different than 'size' in that + // 'size' can be encorporated into the mesh. In that case, the scale is <1,1,1>. + public OMV.Vector3 Scale + { + get { return _scale; } + set { _scale = value; } + } public override PrimitiveBaseShape Shape { set { _pbs = value; PhysicsScene.TaintedObject("BSPrim.setShape", delegate() { _mass = CalculateMass(); // changing the shape changes the mass - CreateGeomAndObject(false); + CreateGeomAndObject(true); }); } } @@ -191,7 +198,7 @@ public sealed class BSPrim : BSPhysObject _isSelected = value; PhysicsScene.TaintedObject("BSPrim.setSelected", delegate() { - SetObjectDynamic(); + SetObjectDynamic(false); }); } } @@ -371,7 +378,7 @@ public sealed class BSPrim : BSPhysObject PhysicsScene.TaintedObject("BSPrim.SetVolumeDetect", delegate() { DetailLog("{0},setVolumeDetect,taint,volDetect={1}", LocalID, _isVolumeDetect); - SetObjectDynamic(); + SetObjectDynamic(true); }); return; } @@ -433,7 +440,7 @@ public sealed class BSPrim : BSPhysObject PhysicsScene.TaintedObject("BSPrim.setIsPhysical", delegate() { DetailLog("{0},setIsPhysical,taint,isPhys={1}", LocalID, _isPhysical); - SetObjectDynamic(); + SetObjectDynamic(true); }); } } @@ -445,7 +452,7 @@ public sealed class BSPrim : BSPhysObject } // An object is solid if it's not phantom and if it's not doing VolumeDetect - private bool IsSolid + public bool IsSolid { get { return !IsPhantom && !_isVolumeDetect; } } @@ -457,21 +464,23 @@ public sealed 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 - private void SetObjectDynamic() + private void SetObjectDynamic(bool forceRebuild) { +#if CSHARP_BODY_MANAGEMENT + // Recreate the physical object if necessary + CreateGeomAndObject(forceRebuild); +#else // If it's becoming dynamic, it will need hullness VerifyCorrectPhysicalShape(); UpdatePhysicalParameters(); +#endif // CSHARP_BODY_MANAGEMENT } private void UpdatePhysicalParameters() { - /* - // Bullet wants static objects to have a mass of zero - float mass = IsStatic ? 0f : _mass; + DetailLog("{0},BSPrim.UpdatePhysicalParameters,entry,body={1},shape={2}", LocalID, BSBody, BSShape); - BulletSimAPI.SetObjectProperties(Scene.WorldID, LocalID, IsStatic, IsSolid, SubscribedEvents(), mass); - */ + // Mangling all the physical properties requires the object to be out of the physical world BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.Ptr, BSBody.Ptr); // Make solid or not (do things bounce off or pass through this object) @@ -517,8 +526,8 @@ public sealed class BSPrim : BSPhysObject // There can be special things needed for implementing linksets Linkset.MakeStatic(this); // The activation state is 'sleeping' so Bullet will not try to act on it - // BulletSimAPI.ForceActivationState2(BSBody.Ptr, ActivationState.ISLAND_SLEEPING); - BulletSimAPI.ForceActivationState2(BSBody.Ptr, ActivationState.DISABLE_SIMULATION); + BulletSimAPI.ForceActivationState2(BSBody.Ptr, ActivationState.ISLAND_SLEEPING); + // BulletSimAPI.ForceActivationState2(BSBody.Ptr, ActivationState.DISABLE_SIMULATION); } else { @@ -560,8 +569,8 @@ public sealed class BSPrim : BSPhysObject // the functions after this one set up the state of a possibly newly created collision body. private void MakeSolid(bool makeSolid) { +#if !CSHARP_BODY_MANAGEMENT CollisionObjectTypes bodyType = (CollisionObjectTypes)BulletSimAPI.GetBodyType2(BSBody.Ptr); - /* if (makeSolid) { if ((bodyType & CollisionObjectTypes.CO_RIGID_BODY) == 0) @@ -569,11 +578,16 @@ public sealed class BSPrim : BSPhysObject // Solid things are made out of rigid bodies. Remove this old body from the world // and use this shape in a new rigid body. BulletBody oldBody = BSBody; - BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.Ptr, BSBody.Ptr); - BSShape = new BulletShape(BulletSimAPI.GetCollisionShape2(BSBody.Ptr)); + // Zero out the pointer to the shape in the old body so the shape will not get freed + BSShape.Ptr = BulletSimAPI.GetCollisionShape2(oldBody.Ptr); + BulletSimAPI.SetCollisionShape2(PhysicsScene.World.Ptr, oldBody.Ptr, IntPtr.Zero); + // Get rid of the old body and remove it from BulletSim's object list + BulletSimAPI.DestroyObject(PhysicsScene.WorldID, LocalID); + + // Create the new body with the shape BSBody = new BulletBody(LocalID, BulletSimAPI.CreateBodyFromShape2(PhysicsScene.World.Ptr, BSShape.Ptr, _position, _orientation)); - BulletSimAPI.DestroyObject2(PhysicsScene.World.Ptr, oldBody.Ptr); - BulletSimAPI.AddObjectToWorld2(PhysicsScene.World.Ptr, BSBody.Ptr); + BulletSimAPI.RemoveFromCollisionFlags2(BSBody.Ptr, CollisionFlags.CF_NO_CONTACT_RESPONSE); + DetailLog("{0},BSPrim.MakeSolid:rigidBody,body={1},shape={2}", LocalID, BSBody, BSShape); } } else @@ -583,23 +597,20 @@ public sealed class BSPrim : BSPhysObject // Non-solid things are made out of ghost objects. Remove this old body from the world // and use this shape in a new rigid body. BulletBody oldBody = BSBody; - BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.Ptr, BSBody.Ptr); - BSShape = new BulletShape(BulletSimAPI.GetCollisionShape2(BSBody.Ptr)); + + // Zero out the pointer to the shape in the old body so the shape will not get freed + BSShape.Ptr = BulletSimAPI.GetCollisionShape2(oldBody.Ptr); + BulletSimAPI.SetCollisionShape2(PhysicsScene.World.Ptr, oldBody.Ptr, IntPtr.Zero); + // Get rid of the old body and remove it from BulletSim's object list + BulletSimAPI.DestroyObject(PhysicsScene.WorldID, LocalID); + BSBody = new BulletBody(LocalID, BulletSimAPI.CreateGhostFromShape2(PhysicsScene.World.Ptr, BSShape.Ptr, _position, _orientation)); - if (BSBody.Ptr == IntPtr.Zero) - { - m_log.ErrorFormat("{0} BSPrim.MakeSolid: failed creation of ghost object. LocalID=[1}", LogHeader, LocalID); - BSBody = oldBody; - } - else - { - BulletSimAPI.DestroyObject2(PhysicsScene.World.Ptr, oldBody.Ptr); - BulletSimAPI.AddObjectToWorld2(PhysicsScene.World.Ptr, BSBody.Ptr); - } + CurrentCollisionFlags = BulletSimAPI.AddToCollisionFlags2(BSBody.Ptr, CollisionFlags.CF_NO_CONTACT_RESPONSE); + DetailLog("{0},BSPrim.MakeGhostBody,body={1},shape={2}", LocalID, BSBody, BSShape); } } - */ +#endif } // Turn on or off the flag controlling whether collision events are returned to the simulator. @@ -1067,6 +1078,7 @@ public sealed class BSPrim : BSPhysObject }// end CalculateMass #endregion Mass Calculation +#if !CSHARP_BODY_MANAGEMENT // Create the geometry information in Bullet for later use. // The objects needs a hull if it's physical otherwise a mesh is enough. // No locking here because this is done when we know physics is not simulating. @@ -1095,6 +1107,7 @@ public sealed class BSPrim : BSPhysObject { DetailLog("{0},BSPrim.CreateGeom,sphere (force={1}", LocalID, forceRebuild); _shapeType = ShapeData.PhysicsShapeType.SHAPE_SPHERE; + _meshKey = (ulong)ShapeData.FixedShapeKey.KEY_SPHERE; // Bullet native objects are scaled by the Bullet engine so pass the size in _scale = _size; // TODO: do we need to check for and destroy a mesh or hull that might have been left from before? @@ -1109,6 +1122,7 @@ public sealed class BSPrim : BSPhysObject { DetailLog("{0},BSPrim.CreateGeom,box (force={1})", LocalID, forceRebuild); _shapeType = ShapeData.PhysicsShapeType.SHAPE_BOX; + _meshKey = (ulong)ShapeData.FixedShapeKey.KEY_BOX; _scale = _size; // TODO: do we need to check for and destroy a mesh or hull that might have been left from before? ret = true; @@ -1136,6 +1150,7 @@ public sealed class BSPrim : BSPhysObject } } } + return ret; } @@ -1345,12 +1360,9 @@ public sealed class BSPrim : BSPhysObject // m_log.DebugFormat("{0}: CreateObject: lID={1}, shape={2}", LogHeader, LocalID, shape.Type); bool ret = BulletSimAPI.CreateObject(PhysicsScene.WorldID, shape); - // the CreateObject() may have recreated the rigid body. Make sure we have the latest address. - BSBody = new BulletBody(LocalID, BulletSimAPI.GetBodyHandle2(PhysicsScene.World.Ptr, LocalID)); - BSShape = new BulletShape(BulletSimAPI.GetCollisionShape2(BSBody.Ptr)); - return ret; } +#endif // !CSHARP_BODY_MANAGEMENT // Copy prim's info into the BulletSim shape description structure public void FillShapeInfo(out ShapeData shape) @@ -1369,22 +1381,45 @@ public sealed class BSPrim : BSPhysObject shape.Restitution = _restitution; shape.Collidable = (!IsPhantom) ? ShapeData.numericTrue : ShapeData.numericFalse; shape.Static = _isPhysical ? ShapeData.numericFalse : ShapeData.numericTrue; + shape.Solid = IsSolid ? ShapeData.numericFalse : ShapeData.numericTrue; + shape.Size = _size; } - // Rebuild the geometry and object. // This is called when the shape changes so we need to recreate the mesh/hull. // No locking here because this is done when the physics engine is not simulating private void CreateGeomAndObject(bool forceRebuild) { +#if CSHARP_BODY_MANAGEMENT + ShapeData shapeData; + FillShapeInfo(out shapeData); + + // Create the correct physical representation for this type of object. + // Updates BSBody and BSShape with the new information. + if (PhysicsScene.Shapes.GetBodyAndShape(forceRebuild, PhysicsScene.World, this, shapeData, _pbs)) + { + // Make sure the properties are set on the new object + UpdatePhysicalParameters(); + } +#else // m_log.DebugFormat("{0}: CreateGeomAndObject. lID={1}, force={2}", LogHeader, LocalID, forceRebuild); // Create the geometry that will make up the object if (CreateGeom(forceRebuild)) { // Create the object and place it into the world CreateObject(); + + // the CreateObject() may have recreated the rigid body. Make sure we have the latest address. + BSBody = new BulletBody(LocalID, BulletSimAPI.GetBodyHandle2(PhysicsScene.World.Ptr, LocalID)); + BSShape = new BulletShape(BulletSimAPI.GetCollisionShape2(BSBody.Ptr), _shapeType); + BSShape.shapeKey = _meshKey; + DetailLog("{0},BSPrim.CreateGeomAndObject,body={1},shape={2}", LocalID, BSBody, BSShape); + // Make sure the properties are set on the new object UpdatePhysicalParameters(); } + + +#endif // CSHARP_BODY_MANAGEMENT return; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index eb4b2ad..7470d23 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -1,70 +1,547 @@ -/* - * 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 OMV = OpenMetaverse; - -namespace OpenSim.Region.Physics.BulletSPlugin -{ -public class BSShapeCollection : IDisposable -{ - protected BSScene PhysicsScene { get; set; } - - public BSShapeCollection(BSScene physScene) - { - PhysicsScene = physScene; - } - - public void Dispose() - { - } - - // Track another user of a body - public void ReferenceBody(BulletBody shape) - { - } - - // Release the usage of a body - public void DereferenceBody(BulletBody shape) - { - } - - // Track another user of the shape - public void ReferenceShape(BulletShape shape) - { - } - - // Release the usage of a shape - public void DereferenceShape(BulletShape shape) - { - } - - - -} -} +/* + * 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 OMV = OpenMetaverse; +using OpenSim.Framework; +using OpenSim.Region.Physics.Manager; +using OpenSim.Region.Physics.ConvexDecompositionDotNet; + +namespace OpenSim.Region.Physics.BulletSPlugin +{ +public class BSShapeCollection : IDisposable +{ + protected BSScene PhysicsScene { get; set; } + + private Object m_shapeActivityLock = new Object(); + + private struct MeshDesc + { + public IntPtr Ptr; + public int referenceCount; + public DateTime lastReferenced; + public IMesh meshData; + } + + private struct HullDesc + { + public IntPtr Ptr; + public int referenceCount; + public DateTime lastReferenced; + } + + private Dictionary Meshes = new Dictionary(); + private Dictionary Hulls = new Dictionary(); + + public BSShapeCollection(BSScene physScene) + { + PhysicsScene = physScene; + } + + public void Dispose() + { + } + + // 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. + // Return 'true' if either the body or the shape changed. + // Called at taint-time!! + public bool GetBodyAndShape(bool forceRebuild, BulletSim sim, BSPrim prim, ShapeData shapeData, PrimitiveBaseShape pbs) + { + bool ret = false; + + // Do we have the correct geometry for this type of object? + if (CreateGeom(forceRebuild, prim, shapeData, pbs)) + { + // If we had to select a new shape geometry for the object, + // rebuild the body around it. + CreateObject(true, prim, PhysicsScene.World, prim.BSShape, shapeData); + ret = true; + } + + return ret; + } + + // Track another user of a body + public void ReferenceBody(BulletBody shape) + { + } + + // Release the usage of a body + public void DereferenceBody(BulletBody shape) + { + } + + // Track another user of the shape + public void ReferenceShape(BulletShape shape) + { + ReferenceShape(shape, null); + } + + // 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. + private void ReferenceShape(BulletShape shape, IMesh meshData) + { + switch (shape.type) + { + case ShapeData.PhysicsShapeType.SHAPE_MESH: + MeshDesc meshDesc; + if (Meshes.TryGetValue(shape.shapeKey, out meshDesc)) + { + // There is an existing instance of this mesh. + meshDesc.referenceCount++; + } + else + { + // This is a new reference to a mesh + meshDesc.Ptr = shape.Ptr; + meshDesc.meshData = meshData; + meshDesc.referenceCount = 1; + + } + meshDesc.lastReferenced = System.DateTime.Now; + Meshes[shape.shapeKey] = meshDesc; + break; + case ShapeData.PhysicsShapeType.SHAPE_HULL: + HullDesc hullDesc; + if (Hulls.TryGetValue(shape.shapeKey, out hullDesc)) + { + // There is an existing instance of this mesh. + hullDesc.referenceCount++; + } + else + { + // This is a new reference to a mesh + hullDesc.Ptr = shape.Ptr; + hullDesc.referenceCount = 1; + + } + hullDesc.lastReferenced = System.DateTime.Now; + Hulls[shape.shapeKey] = hullDesc; + break; + default: + break; + } + } + + // Release the usage of a shape + public void DereferenceShape(BulletShape shape) + { + switch (shape.type) + { + case ShapeData.PhysicsShapeType.SHAPE_HULL: + DereferenceHull(shape); + // Hulls also include a mesh + DereferenceMesh(shape); + break; + case ShapeData.PhysicsShapeType.SHAPE_MESH: + DereferenceMesh(shape); + break; + default: + break; + } + } + + // Count down the reference count for a mesh shape + private void DereferenceMesh(BulletShape shape) + { + MeshDesc meshDesc; + if (Meshes.TryGetValue(shape.shapeKey, out meshDesc)) + { + meshDesc.referenceCount--; + // TODO: release the Bullet storage + meshDesc.lastReferenced = System.DateTime.Now; + Meshes[shape.shapeKey] = meshDesc; + } + } + + // Count down the reference count for a hull shape + private void DereferenceHull(BulletShape shape) + { + HullDesc hullDesc; + if (Hulls.TryGetValue(shape.shapeKey, out hullDesc)) + { + hullDesc.referenceCount--; + // TODO: release the Bullet storage (aging old entries?) + hullDesc.lastReferenced = System.DateTime.Now; + Hulls[shape.shapeKey] = hullDesc; + } + } + + // Create the geometry information in Bullet for later use. + // The objects needs a hull if it's physical otherwise a mesh is enough. + // No locking here because this is done when we know physics is not simulating. + // if 'forceRebuild' is true, the geometry is rebuilt. Otherwise a previously built version is used. + // Returns 'true' if the geometry was rebuilt. + // Called at taint-time! + private bool CreateGeom(bool forceRebuild, BSPrim prim, ShapeData shapeData, PrimitiveBaseShape pbs) + { + bool ret = false; + bool haveShape = false; + bool nativeShapePossible = true; + + BulletShape newShape = new BulletShape(IntPtr.Zero); + + // If the object is dynamic, it must have a hull shape + if (prim.IsPhysical) + nativeShapePossible = false; + + // If the prim attributes are simple, this could be a simple Bullet native shape + if (nativeShapePossible + && ((pbs.SculptEntry && !PhysicsScene.ShouldMeshSculptedPrim) + || (pbs.ProfileBegin == 0 && pbs.ProfileEnd == 0 + && pbs.ProfileHollow == 0 + && pbs.PathTwist == 0 && pbs.PathTwistBegin == 0 + && pbs.PathBegin == 0 && pbs.PathEnd == 0 + && pbs.PathTaperX == 0 && pbs.PathTaperY == 0 + && pbs.PathScaleX == 100 && pbs.PathScaleY == 100 + && pbs.PathShearX == 0 && pbs.PathShearY == 0) ) ) + { + if (pbs.ProfileShape == ProfileShape.HalfCircle && pbs.PathCurve == (byte)Extrusion.Curve1) + { + haveShape = true; + if (forceRebuild || (prim.BSShape.type != ShapeData.PhysicsShapeType.SHAPE_SPHERE)) + { + DetailLog("{0},BSShapeCollection.CreateGeom,sphere (force={1}", prim.LocalID, forceRebuild); + newShape = AddNativeShapeToPrim(prim, shapeData, ShapeData.PhysicsShapeType.SHAPE_SPHERE); + + ret = true; + } + } + else + { + // m_log.DebugFormat("{0}: CreateGeom: Defaulting to box. lid={1}, type={2}, size={3}", LogHeader, LocalID, _shapeType, _size); + haveShape = true; + if (forceRebuild || (prim.BSShape.type != ShapeData.PhysicsShapeType.SHAPE_BOX)) + { + DetailLog("{0},BSShapeCollection.CreateGeom,box (force={1})", prim.LocalID, forceRebuild); + newShape = AddNativeShapeToPrim(prim, shapeData, ShapeData.PhysicsShapeType.SHAPE_BOX); + + ret = true; + } + } + } + // If a simple shape isn't happening, create a mesh and possibly a hull + if (!haveShape) + { + if (prim.IsPhysical) + { + if (forceRebuild || !Hulls.ContainsKey(prim.BSShape.shapeKey)) + { + // physical objects require a hull for interaction. + // This also creates the mesh if it doesn't already exist + ret = CreateGeomHull(prim, shapeData, pbs); + } + } + else + { + if (forceRebuild || !Meshes.ContainsKey(prim.BSShape.shapeKey)) + { + // Static (non-physical) objects only need a mesh for bumping into + ret = CreateGeomMesh(prim, shapeData, pbs); + } + } + } + return ret; + } + + private BulletShape AddNativeShapeToPrim(BSPrim prim, ShapeData shapeData, ShapeData.PhysicsShapeType shapeType) + { + BulletShape newShape; + + // Bullet native objects are scaled by the Bullet engine so pass the size in + prim.Scale = shapeData.Size; + + // release any previous shape + DereferenceShape(prim.BSShape); + + MeshDesc existingShapeDesc; + if (Meshes.TryGetValue(shapeData.MeshKey, out existingShapeDesc)) + { + // If there is an existing allocated shape, use it + newShape = new BulletShape(existingShapeDesc.Ptr, shapeType); + } + else + { + // Shape of this discriptioin is not allocated. Create new. + newShape = new BulletShape( + BulletSimAPI.BuildNativeShape2(PhysicsScene.World.Ptr, + (float)shapeType, + PhysicsScene.Params.collisionMargin, + prim.Scale), + shapeType); + } + newShape.shapeKey = shapeData.MeshKey; + ReferenceShape(newShape); + prim.BSShape = newShape; + return newShape; + } + + // No locking here because this is done when we know physics is not simulating + // Returns 'true' of a mesh was actually rebuild (we could also have one of these specs). + // Called at taint-time! + private bool CreateGeomMesh(BSPrim prim, ShapeData shapeData, PrimitiveBaseShape pbs) + { + BulletShape newShape = new BulletShape(IntPtr.Zero); + + // level of detail based on size and type of the object + float lod = PhysicsScene.MeshLOD; + if (pbs.SculptEntry) + lod = PhysicsScene.SculptLOD; + + float maxAxis = Math.Max(shapeData.Size.X, Math.Max(shapeData.Size.Y, shapeData.Size.Z)); + if (maxAxis > PhysicsScene.MeshMegaPrimThreshold) + lod = PhysicsScene.MeshMegaPrimLOD; + + ulong newMeshKey = (ulong)pbs.GetMeshKey(shapeData.Size, lod); + // m_log.DebugFormat("{0}: CreateGeomMesh: lID={1}, oldKey={2}, newKey={3}", LogHeader, LocalID, _meshKey, newMeshKey); + + // if this new shape is the same as last time, don't recreate the mesh + if (prim.BSShape.shapeKey == newMeshKey) return false; + + DetailLog("{0},BSShapeCollection.CreateGeomMesh,create,key={1}", prim.LocalID, newMeshKey); + + // Since we're recreating new, get rid of the reference to the previous shape + DereferenceShape(prim.BSShape); + + IMesh meshData = null; + IntPtr meshPtr; + MeshDesc meshDesc; + if (Meshes.TryGetValue(newMeshKey, out meshDesc)) + { + // If the mesh has already been built just use it. + meshPtr = meshDesc.Ptr; + } + else + { + // always pass false for physicalness as this creates some sort of bounding box which we don't need + meshData = PhysicsScene.mesher.CreateMesh(prim.PhysObjectName, pbs, shapeData.Size, lod, false); + + int[] indices = meshData.getIndexListAsInt(); + List vertices = meshData.getVertexList(); + + float[] verticesAsFloats = new float[vertices.Count * 3]; + int vi = 0; + foreach (OMV.Vector3 vv in vertices) + { + verticesAsFloats[vi++] = vv.X; + verticesAsFloats[vi++] = vv.Y; + verticesAsFloats[vi++] = vv.Z; + } + + // m_log.DebugFormat("{0}: CreateGeomMesh: calling CreateMesh. lid={1}, key={2}, indices={3}, vertices={4}", + // LogHeader, prim.LocalID, newMeshKey, indices.Length, vertices.Count); + + meshPtr = BulletSimAPI.CreateMeshShape2(PhysicsScene.World.Ptr, + indices.GetLength(0), indices, vertices.Count, verticesAsFloats); + } + newShape = new BulletShape(meshPtr, ShapeData.PhysicsShapeType.SHAPE_MESH); + newShape.shapeKey = newMeshKey; + + ReferenceShape(newShape, meshData); + + // meshes are already scaled by the meshmerizer + prim.Scale = new OMV.Vector3(1f, 1f, 1f); + prim.BSShape = newShape; + return true; // 'true' means a new shape has been added to this prim + } + + // No locking here because this is done when we know physics is not simulating + // Returns 'true' of a mesh was actually rebuild (we could also have one of these specs). + List m_hulls; + private bool CreateGeomHull(BSPrim prim, ShapeData shapeData, PrimitiveBaseShape pbs) + { + BulletShape newShape; + + float lod = pbs.SculptEntry ? PhysicsScene.SculptLOD : PhysicsScene.MeshLOD; + ulong newHullKey = (ulong)pbs.GetMeshKey(shapeData.Size, lod); + // m_log.DebugFormat("{0}: CreateGeomHull: lID={1}, oldKey={2}, newKey={3}", LogHeader, LocalID, _hullKey, newHullKey); + + // if the hull hasn't changed, don't rebuild it + if (newHullKey == prim.BSShape.shapeKey) return false; + + DetailLog("{0},BSShapeCollection.CreateGeomHull,create,oldKey={1},newKey={2}", prim.LocalID, newHullKey, newHullKey); + + // remove references to any previous shape + DereferenceShape(prim.BSShape); + + // Make sure the underlying mesh exists and is correct + // Since we're in the hull code, we know CreateGeomMesh() will not create a native shape. + CreateGeomMesh(prim, shapeData, pbs); + MeshDesc meshDesc = Meshes[newHullKey]; + + IntPtr hullPtr; + HullDesc hullDesc; + if (Hulls.TryGetValue(newHullKey, out hullDesc)) + { + hullPtr = hullDesc.Ptr; + } + else + { + int[] indices = meshDesc.meshData.getIndexListAsInt(); + List vertices = meshDesc.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)); + } + + // setup and do convex hull conversion + m_hulls = new List(); + DecompDesc dcomp = new DecompDesc(); + dcomp.mIndices = convIndices; + dcomp.mVertices = convVertices; + ConvexBuilder convexBuilder = new ConvexBuilder(HullReturn); + // create the hull into the _hulls variable + convexBuilder.process(dcomp); + + // 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 + // m_log.DebugFormat("{0}: CreateGeom: calling CreateHull. lid={1}, key={2}, hulls={3}", LogHeader, LocalID, _hullKey, hullCount); + hullPtr = BulletSimAPI.CreateHullShape2(PhysicsScene.World.Ptr, hullCount, convHulls); + } + newShape = new BulletShape(hullPtr, ShapeData.PhysicsShapeType.SHAPE_HULL); + newShape.shapeKey = newHullKey; + + ReferenceShape(newShape); + + // meshes are already scaled by the meshmerizer + prim.Scale = new OMV.Vector3(1f, 1f, 1f); + prim.BSShape = newShape; + return true; // 'true' means a new shape has been added to this prim + } + + // Callback from convex hull creater with a newly created hull. + // Just add it to the collection of hulls for this shape. + private void HullReturn(ConvexResult result) + { + m_hulls.Add(result); + return; + } + + // Create an object in Bullet if it has not already been created + // No locking here because this is done when the physics engine is not simulating + // Returns 'true' if an object was actually created. + private bool CreateObject(bool forceRebuild, BSPrim prim, BulletSim sim, BulletShape shape, ShapeData shapeData) + { + // the mesh or hull must have already been created in Bullet + // m_log.DebugFormat("{0}: CreateObject: lID={1}, shape={2}", LogHeader, LocalID, shape.Type); + + DereferenceBody(prim.BSBody); + + BulletBody aBody; + IntPtr bodyPtr = IntPtr.Zero; + if (prim.IsSolid) + { + bodyPtr = BulletSimAPI.CreateBodyFromShape2(sim.Ptr, shape.Ptr, shapeData.Position, shapeData.Rotation); + } + else + { + bodyPtr = BulletSimAPI.CreateGhostFromShape2(sim.Ptr, shape.Ptr, shapeData.Position, shapeData.Rotation); + } + aBody = new BulletBody(shapeData.ID, bodyPtr); + + ReferenceBody(aBody); + + prim.BSBody = aBody; + return true; + } + + private void DetailLog(string msg, params Object[] args) + { + PhysicsScene.PhysicsLogging.Write(msg, args); + } + + + + + +} +} diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs index 52c8a24..47875b0 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs @@ -40,7 +40,9 @@ public struct BulletSim { public BulletSim(uint worldId, BSScene bss, IntPtr xx) { - worldID = worldId; scene = bss; Ptr = xx; + worldID = worldId; + scene = bss; + Ptr = xx; } public uint worldID; // The scene is only in here so very low level routines have a handle to print debug/error messages @@ -58,6 +60,16 @@ public struct BulletBody } public IntPtr Ptr; public uint ID; + public override string ToString() + { + StringBuilder buff = new StringBuilder(); + buff.Append(""); + return buff.ToString(); + } } public struct BulletShape @@ -66,17 +78,29 @@ public struct BulletShape { Ptr = xx; type=ShapeData.PhysicsShapeType.SHAPE_UNKNOWN; - hashKey = 0; + shapeKey = 0; } public BulletShape(IntPtr xx, ShapeData.PhysicsShapeType typ) { Ptr = xx; type = typ; - hashKey = 0; + shapeKey = 0; } public IntPtr Ptr; public ShapeData.PhysicsShapeType type; - public ulong hashKey; + public ulong shapeKey; + public override string ToString() + { + StringBuilder buff = new StringBuilder(); + buff.Append(""); + return buff.ToString(); + } } // An allocated Bullet btConstraint @@ -155,10 +179,21 @@ public struct ShapeData public float Restitution; public float Collidable; // true of things bump into this public float Static; // true if a static object. Otherwise gravity, etc. + public float Solid; // true if object cannot be passed through + public Vector3 Size; // note that bools are passed as floats since bool size changes by language and architecture public const float numericTrue = 1f; public const float numericFalse = 0f; + + // The native shapes have predefined shape hash keys + public enum FixedShapeKey : ulong + { + KEY_BOX = 1, + KEY_SPHERE = 2, + KEY_CONE = 3, + KEY_CYLINDER = 4, + } } [StructLayout(LayoutKind.Sequential)] public struct SweepHit -- cgit v1.1 From 42802669dd8e2d574f9bbd25fbaa86b255fbe25b Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Fri, 21 Sep 2012 10:40:14 -0700 Subject: BulletSim: fix regression that caused cylindar shapes to have a box collision shape --- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 10 +++++++++- 1 file changed, 9 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 4d2c70c..b764379 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -1091,7 +1091,14 @@ public sealed class BSPrim : BSPhysObject bool haveShape = false; // If the prim attributes are simple, this could be a simple Bullet native shape - if ((_pbs.SculptEntry && !PhysicsScene.ShouldMeshSculptedPrim) + if ( + // if the basic shape is a cube or a sphere... + ((_pbs.ProfileShape == ProfileShape.Square && _pbs.PathCurve == (byte)Extrusion.Straight) + || (_pbs.ProfileShape == ProfileShape.HalfCircle && _pbs.PathCurve == (byte)Extrusion.Curve1 + /* && _pbs.Scale.X == _pbs.Scale.Y && _pbs.Scale.Y == _pbs.Scale.Z */ )) + // ... and we are not doing sculpty meshes... + && (_pbs.SculptEntry && !PhysicsScene.ShouldMeshSculptedPrim) + // ... or this is a 'simple' shape... || (_pbs.ProfileBegin == 0 && _pbs.ProfileEnd == 0 && _pbs.ProfileHollow == 0 && _pbs.PathTwist == 0 && _pbs.PathTwistBegin == 0 @@ -1099,6 +1106,7 @@ public sealed class BSPrim : BSPhysObject && _pbs.PathTaperX == 0 && _pbs.PathTaperY == 0 && _pbs.PathScaleX == 100 && _pbs.PathScaleY == 100 && _pbs.PathShearX == 0 && _pbs.PathShearY == 0) ) + // ... then this might be representable as a native Bullet collision shape { if (_pbs.ProfileShape == ProfileShape.HalfCircle && _pbs.PathCurve == (byte)Extrusion.Curve1) { -- cgit v1.1 From d016051fa028a485b09fac47b3fa3d8fd08e207a Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Sun, 23 Sep 2012 18:39:46 -0700 Subject: BulletSim: renamed members of BulletShape, BulletSim and BulletBody so the members case is consistant. Caused modifications everywhere. New logic in BSShapeCollection to track use and sharing of shapes. I just reslized, though, that shapes cannot be shared because the shape's UserPointer is the localID of the prim and is required for tracking collisions. More changes coming. Added DuplicateCollisionShape2() to API and changed BuildNativeShape2 to take a ShapeData structure so don't have to pass so many parameters. This matches the latest version of BulletSim.dll. Additions and removal of DetailLog() statements for debugging. --- .../Physics/BulletSPlugin/BS6DofConstraint.cs | 4 +- .../Region/Physics/BulletSPlugin/BSCharacter.cs | 12 +- .../Region/Physics/BulletSPlugin/BSConstraint.cs | 2 +- .../Physics/BulletSPlugin/BSHingeConstraint.cs | 110 +++---- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 6 +- .../Region/Physics/BulletSPlugin/BSPhysObject.cs | 16 +- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 159 ++++++---- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 4 +- .../Physics/BulletSPlugin/BSShapeCollection.cs | 344 +++++++++++++++------ .../Physics/BulletSPlugin/BSTerrainManager.cs | 46 +-- .../Region/Physics/BulletSPlugin/BulletSimAPI.cs | 49 +-- 11 files changed, 482 insertions(+), 270 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BS6DofConstraint.cs b/OpenSim/Region/Physics/BulletSPlugin/BS6DofConstraint.cs index 683bc51..ff271fe 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BS6DofConstraint.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BS6DofConstraint.cs @@ -44,7 +44,7 @@ public class BS6DofConstraint : BSConstraint m_body1 = obj1; m_body2 = obj2; m_constraint = new BulletConstraint( - BulletSimAPI.Create6DofConstraint2(m_world.Ptr, m_body1.Ptr, m_body2.Ptr, + BulletSimAPI.Create6DofConstraint2(m_world.ptr, m_body1.ptr, m_body2.ptr, frame1, frame1rot, frame2, frame2rot, useLinearReferenceFrameA, disableCollisionsBetweenLinkedBodies)); @@ -59,7 +59,7 @@ public class BS6DofConstraint : BSConstraint m_body1 = obj1; m_body2 = obj2; m_constraint = new BulletConstraint( - BulletSimAPI.Create6DofConstraintToPoint2(m_world.Ptr, m_body1.Ptr, m_body2.Ptr, + BulletSimAPI.Create6DofConstraintToPoint2(m_world.ptr, m_body1.ptr, m_body2.ptr, joinPoint, useLinearReferenceFrameA, disableCollisionsBetweenLinkedBodies)); m_enabled = true; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index 014cd99..e4b1dd4 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -114,7 +114,7 @@ public class BSCharacter : BSPhysObject // Set the buoyancy for flying. This will be refactored when all the settings happen in C# BulletSimAPI.SetObjectBuoyancy(PhysicsScene.WorldID, LocalID, _buoyancy); - BSBody = new BulletBody(LocalID, BulletSimAPI.GetBodyHandle2(PhysicsScene.World.Ptr, LocalID)); + BSBody = new BulletBody(LocalID, BulletSimAPI.GetBodyHandle2(PhysicsScene.World.ptr, LocalID)); }); return; @@ -189,10 +189,10 @@ public class BSCharacter : BSPhysObject _rotationalVelocity = OMV.Vector3.Zero; // Zero some other properties directly into the physics engine - BulletSimAPI.SetLinearVelocity2(BSBody.Ptr, OMV.Vector3.Zero); - BulletSimAPI.SetAngularVelocity2(BSBody.Ptr, OMV.Vector3.Zero); - BulletSimAPI.SetInterpolationVelocity2(BSBody.Ptr, OMV.Vector3.Zero, OMV.Vector3.Zero); - BulletSimAPI.ClearForces2(BSBody.Ptr); + BulletSimAPI.SetLinearVelocity2(BSBody.ptr, OMV.Vector3.Zero); + BulletSimAPI.SetAngularVelocity2(BSBody.ptr, OMV.Vector3.Zero); + BulletSimAPI.SetInterpolationVelocity2(BSBody.ptr, OMV.Vector3.Zero, OMV.Vector3.Zero); + BulletSimAPI.ClearForces2(BSBody.ptr); } public override void LockAngularMotion(OMV.Vector3 axis) { return; } @@ -437,7 +437,7 @@ public class BSCharacter : BSPhysObject PhysicsScene.TaintedObject("BSCharacter.AddForce", delegate() { DetailLog("{0},BSCharacter.setAddForce,taint,addedForce={1}", LocalID, _force); - BulletSimAPI.SetObjectForce2(BSBody.Ptr, _force); + BulletSimAPI.SetObjectForce2(BSBody.ptr, _force); }); } else diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs b/OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs index 1376a29..c21252b 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs @@ -49,7 +49,7 @@ public abstract class BSConstraint : IDisposable if (m_enabled) { m_enabled = false; - bool success = BulletSimAPI.DestroyConstraint2(m_world.Ptr, m_constraint.Ptr); + bool success = BulletSimAPI.DestroyConstraint2(m_world.ptr, m_constraint.Ptr); m_world.scene.DetailLog("{0},BSConstraint.Dispose,taint,body1={1},body2={2},success={3}", BSScene.DetailLogZero, m_body1.ID, m_body2.ID, success); m_constraint.Ptr = System.IntPtr.Zero; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSHingeConstraint.cs b/OpenSim/Region/Physics/BulletSPlugin/BSHingeConstraint.cs index d68048b..a6e4235 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSHingeConstraint.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSHingeConstraint.cs @@ -1,55 +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 -{ - -class BSHingeConstraint : BSConstraint -{ - public BSHingeConstraint(BulletSim world, BulletBody obj1, BulletBody obj2, - Vector3 pivotInA, Vector3 pivotInB, - Vector3 axisInA, Vector3 axisInB, - bool useLinearReferenceFrameA, bool disableCollisionsBetweenLinkedBodies) - { - m_world = world; - m_body1 = obj1; - m_body2 = obj2; - m_constraint = new BulletConstraint( - BulletSimAPI.CreateHingeConstraint2(m_world.Ptr, m_body1.Ptr, m_body2.Ptr, - pivotInA, pivotInB, - axisInA, axisInB, - useLinearReferenceFrameA, disableCollisionsBetweenLinkedBodies)); - m_enabled = true; - } - -} - -} +/* + * 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 +{ + +class BSHingeConstraint : BSConstraint +{ + public BSHingeConstraint(BulletSim world, BulletBody obj1, BulletBody obj2, + Vector3 pivotInA, Vector3 pivotInB, + Vector3 axisInA, Vector3 axisInB, + bool useLinearReferenceFrameA, bool disableCollisionsBetweenLinkedBodies) + { + m_world = world; + m_body1 = obj1; + m_body2 = obj2; + m_constraint = new BulletConstraint( + BulletSimAPI.CreateHingeConstraint2(m_world.ptr, m_body1.ptr, m_body2.ptr, + pivotInA, pivotInB, + axisInA, axisInB, + useLinearReferenceFrameA, disableCollisionsBetweenLinkedBodies)); + m_enabled = true; + } + +} + +} diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index 1e8fe52..84a7fac 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -282,10 +282,10 @@ public class BSLinkset { // If this is a multiple object linkset, set everybody's center of mass to the set's center of mass OMV.Vector3 centerOfMass = ComputeLinksetCenterOfMass(); - BulletSimAPI.SetCenterOfMassByPosRot2(LinksetRoot.BSBody.Ptr, centerOfMass, OMV.Quaternion.Identity); + BulletSimAPI.SetCenterOfMassByPosRot2(LinksetRoot.BSBody.ptr, centerOfMass, OMV.Quaternion.Identity); foreach (BSPhysObject child in m_children) { - BulletSimAPI.SetCenterOfMassByPosRot2(child.BSBody.Ptr, centerOfMass, OMV.Quaternion.Identity); + BulletSimAPI.SetCenterOfMassByPosRot2(child.BSBody.ptr, centerOfMass, OMV.Quaternion.Identity); } /* // The root prim takes on the weight of the whole linkset @@ -442,7 +442,7 @@ public class BSLinkset PhysicsScene.Constraints.RemoveAndDestroyConstraint(rootPrim.BSBody, childPrim.BSBody); // Make the child refresh its location - BulletSimAPI.PushUpdate2(childPrim.BSBody.Ptr); + BulletSimAPI.PushUpdate2(childPrim.BSBody.ptr); } // Remove linkage between myself and any possible children I might have diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index 70a10b1..6a9fe50 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -1,4 +1,4 @@ -/* +/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * @@ -121,8 +121,8 @@ public abstract class BSPhysObject : PhysicsActor // if someone has subscribed for collision events.... if (SubscribedEvents()) { CollisionCollection.AddCollider(collidingWith, new ContactPoint(contactPoint, contactNormal, pentrationDepth)); - // DetailLog("{0},{1}.Collison.AddCollider,call,with={2},point={3},normal={4},depth={5}", - // LocalID, TypeName, collidingWith, contactPoint, contactNormal, pentrationDepth); + DetailLog("{0},{1}.Collison.AddCollider,call,with={2},point={3},normal={4},depth={5}", + LocalID, TypeName, collidingWith, contactPoint, contactNormal, pentrationDepth); ret = true; } return ret; @@ -147,7 +147,7 @@ public abstract class BSPhysObject : PhysicsActor if (CollisionCollection.Count == 0) PhysicsScene.ObjectsWithNoMoreCollisions.Add(this); - // DetailLog("{0},{1}.SendCollisionUpdate,call,numCollisions={2}", LocalID, TypeName, CollisionCollection.Count); + DetailLog("{0},{1}.SendCollisionUpdate,call,numCollisions={2}", LocalID, TypeName, CollisionCollection.Count); base.SendCollisionUpdate(CollisionCollection); // The collisionCollection structure is passed around in the simulator. @@ -158,7 +158,8 @@ public abstract class BSPhysObject : PhysicsActor // Subscribe for collision events. // Parameter is the millisecond rate the caller wishes collision events to occur. - public override void SubscribeEvents(int ms) { + public override void SubscribeEvents(int ms) { + DetailLog("{0},BSScene.SubscribeEvents,subscribing,ms={1}", BSScene.DetailLogZero, ms); SubscribedEventsMs = ms; if (ms > 0) { @@ -167,7 +168,7 @@ public abstract class BSPhysObject : PhysicsActor PhysicsScene.TaintedObject(TypeName+".SubscribeEvents", delegate() { - CurrentCollisionFlags = BulletSimAPI.AddToCollisionFlags2(BSBody.Ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); + CurrentCollisionFlags = BulletSimAPI.AddToCollisionFlags2(BSBody.ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); }); } else @@ -177,10 +178,11 @@ public abstract class BSPhysObject : PhysicsActor } } public override void UnSubscribeEvents() { + DetailLog("{0},BSScene.UnSubscribeEvents,unsubscribing", BSScene.DetailLogZero); SubscribedEventsMs = 0; PhysicsScene.TaintedObject(TypeName+".UnSubscribeEvents", delegate() { - CurrentCollisionFlags = BulletSimAPI.RemoveFromCollisionFlags2(BSBody.Ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); + CurrentCollisionFlags = BulletSimAPI.RemoveFromCollisionFlags2(BSBody.ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); }); } // Return 'true' if the simulator wants collision events diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index b764379..5be2b1b 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -24,6 +24,11 @@ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ + +// Uncomment this it enable code to do all shape an body memory management +// in the C# code. +#define CSHARP_BODY_MANAGEMENT + using System; using System.Reflection; using System.Collections.Generic; @@ -36,6 +41,7 @@ using OpenSim.Region.Physics.ConvexDecompositionDotNet; namespace OpenSim.Region.Physics.BulletSPlugin { + [Serializable] public sealed class BSPrim : BSPhysObject { @@ -126,7 +132,7 @@ public sealed class BSPrim : BSPhysObject { CreateGeomAndObject(true); - CurrentCollisionFlags = BulletSimAPI.GetCollisionFlags2(BSBody.Ptr); + CurrentCollisionFlags = BulletSimAPI.GetCollisionFlags2(BSBody.ptr); }); } @@ -246,10 +252,10 @@ public sealed class BSPrim : BSPhysObject _rotationalVelocity = OMV.Vector3.Zero; // Zero some other properties directly into the physics engine - BulletSimAPI.SetLinearVelocity2(BSBody.Ptr, OMV.Vector3.Zero); - BulletSimAPI.SetAngularVelocity2(BSBody.Ptr, OMV.Vector3.Zero); - BulletSimAPI.SetInterpolationVelocity2(BSBody.Ptr, OMV.Vector3.Zero, OMV.Vector3.Zero); - BulletSimAPI.ClearForces2(BSBody.Ptr); + BulletSimAPI.SetLinearVelocity2(BSBody.ptr, OMV.Vector3.Zero); + BulletSimAPI.SetAngularVelocity2(BSBody.ptr, OMV.Vector3.Zero); + BulletSimAPI.SetInterpolationVelocity2(BSBody.ptr, OMV.Vector3.Zero, OMV.Vector3.Zero); + BulletSimAPI.ClearForces2(BSBody.ptr); } public override void LockAngularMotion(OMV.Vector3 axis) @@ -262,7 +268,7 @@ public sealed class BSPrim : BSPhysObject get { if (!Linkset.IsRoot(this)) // child prims move around based on their parent. Need to get the latest location - _position = BulletSimAPI.GetPosition2(BSBody.Ptr); + _position = BulletSimAPI.GetPosition2(BSBody.ptr); // don't do the GetObjectPosition for root elements because this function is called a zillion times // _position = BulletSimAPI.GetObjectPosition(Scene.WorldID, LocalID); @@ -274,7 +280,7 @@ public sealed class BSPrim : BSPhysObject PhysicsScene.TaintedObject("BSPrim.setPosition", delegate() { DetailLog("{0},BSPrim.SetPosition,taint,pos={1},orient={2}", LocalID, _position, _orientation); - BulletSimAPI.SetTranslation2(BSBody.Ptr, _position, _orientation); + BulletSimAPI.SetTranslation2(BSBody.ptr, _position, _orientation); }); } } @@ -312,7 +318,7 @@ public sealed class BSPrim : BSPhysObject PhysicsScene.TaintedObject("BSPrim.setForce", delegate() { DetailLog("{0},BSPrim.setForce,taint,force={1}", LocalID, _force); - BulletSimAPI.SetObjectForce2(BSBody.Ptr, _force); + BulletSimAPI.SetObjectForce2(BSBody.ptr, _force); }); } } @@ -374,12 +380,15 @@ public sealed class BSPrim : BSPhysObject // Allows the detection of collisions with inherently non-physical prims. see llVolumeDetect for more public override void SetVolumeDetect(int param) { bool newValue = (param != 0); - _isVolumeDetect = newValue; - PhysicsScene.TaintedObject("BSPrim.SetVolumeDetect", delegate() + if (_isVolumeDetect != newValue) { - DetailLog("{0},setVolumeDetect,taint,volDetect={1}", LocalID, _isVolumeDetect); - SetObjectDynamic(true); - }); + _isVolumeDetect = newValue; + PhysicsScene.TaintedObject("BSPrim.SetVolumeDetect", delegate() + { + DetailLog("{0},setVolumeDetect,taint,volDetect={1}", LocalID, _isVolumeDetect); + SetObjectDynamic(true); + }); + } return; } @@ -390,7 +399,7 @@ public sealed class BSPrim : BSPhysObject PhysicsScene.TaintedObject("BSPrim.setVelocity", delegate() { DetailLog("{0},BSPrim.SetVelocity,taint,vel={1}", LocalID, _velocity); - BulletSimAPI.SetLinearVelocity2(BSBody.Ptr, _velocity); + BulletSimAPI.SetLinearVelocity2(BSBody.ptr, _velocity); }); } } @@ -414,7 +423,7 @@ public sealed class BSPrim : BSPhysObject if (!Linkset.IsRoot(this)) { // Children move around because tied to parent. Get a fresh value. - _orientation = BulletSimAPI.GetOrientation2(BSBody.Ptr); + _orientation = BulletSimAPI.GetOrientation2(BSBody.ptr); } return _orientation; } @@ -425,7 +434,7 @@ public sealed class BSPrim : BSPhysObject { // _position = BulletSimAPI.GetObjectPosition(Scene.WorldID, LocalID); DetailLog("{0},BSPrim.setOrientation,taint,pos={1},orient={2}", LocalID, _position, _orientation); - BulletSimAPI.SetTranslation2(BSBody.Ptr, _position, _orientation); + BulletSimAPI.SetTranslation2(BSBody.ptr, _position, _orientation); }); } } @@ -436,12 +445,15 @@ public sealed class BSPrim : BSPhysObject public override bool IsPhysical { get { return _isPhysical; } set { - _isPhysical = value; - PhysicsScene.TaintedObject("BSPrim.setIsPhysical", delegate() + if (_isPhysical != value) { - DetailLog("{0},setIsPhysical,taint,isPhys={1}", LocalID, _isPhysical); - SetObjectDynamic(true); - }); + _isPhysical = value; + PhysicsScene.TaintedObject("BSPrim.setIsPhysical", delegate() + { + DetailLog("{0},setIsPhysical,taint,isPhys={1}", LocalID, _isPhysical); + SetObjectDynamic(true); + }); + } } } @@ -458,7 +470,7 @@ public sealed class BSPrim : BSPhysObject } // Make gravity work if the object is physical and not selected - // No locking here because only called when it is safe + // No locking here because only called when it is safe (called at taint-time). // There are four flags we're interested in: // IsStatic: Object does not move, otherwise the object has mass and moves // isSolid: other objects bounce off of this object @@ -481,11 +493,13 @@ public sealed class BSPrim : BSPhysObject DetailLog("{0},BSPrim.UpdatePhysicalParameters,entry,body={1},shape={2}", LocalID, BSBody, BSShape); // Mangling all the physical properties requires the object to be out of the physical world - BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.Ptr, BSBody.Ptr); + BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.ptr, BSBody.ptr); +#if !CSHARP_BODY_MANAGEMENT // Make solid or not (do things bounce off or pass through this object) // This is done first because it can change the collisionObject type. MakeSolid(IsSolid); +#endif // !CSHARP_BODY_MANAGEMENT // Set up the object physicalness (does gravity and collisions move this object) MakeDynamic(IsStatic); @@ -493,15 +507,23 @@ public sealed class BSPrim : BSPhysObject // Arrange for collisions events if the simulator wants them EnableCollisions(SubscribedEvents()); - BulletSimAPI.AddObjectToWorld2(PhysicsScene.World.Ptr, BSBody.Ptr); +#if CSHARP_BODY_MANAGEMENT + // Make solid or not (do things bounce off or pass through this object). + MakeSolid(IsSolid); +#endif // CSHARP_BODY_MANAGEMENT + + BulletSimAPI.AddObjectToWorld2(PhysicsScene.World.ptr, BSBody.ptr); + + // Rebuild its shape + BulletSimAPI.UpdateSingleAabb2(PhysicsScene.World.ptr, BSBody.ptr); // Recompute any linkset parameters. // When going from non-physical to physical, this re-enables the constraints that // had been automatically disabled when the mass was set to zero. Linkset.Refresh(this); - DetailLog("{0},BSPrim.UpdatePhysicalParameters,taint,static={1},solid={2},mass={3},collide={4},cf={5}", - LocalID, IsStatic, IsSolid, _mass, SubscribedEvents(), CurrentCollisionFlags); + DetailLog("{0},BSPrim.UpdatePhysicalParameters,exit,static={1},solid={2},mass={3},collide={4},cf={5:X},body={6},shape={7}", + LocalID, IsStatic, IsSolid, _mass, SubscribedEvents(), CurrentCollisionFlags, BSBody, BSShape); } // "Making dynamic" means changing to and from static. @@ -514,52 +536,52 @@ public sealed class BSPrim : BSPhysObject if (makeStatic) { // Become a Bullet 'static' object type - CurrentCollisionFlags = BulletSimAPI.AddToCollisionFlags2(BSBody.Ptr, CollisionFlags.CF_STATIC_OBJECT); + CurrentCollisionFlags = BulletSimAPI.AddToCollisionFlags2(BSBody.ptr, CollisionFlags.CF_STATIC_OBJECT); // Stop all movement - BulletSimAPI.ClearAllForces2(BSBody.Ptr); + BulletSimAPI.ClearAllForces2(BSBody.ptr); // Center of mass is at the center of the object - BulletSimAPI.SetCenterOfMassByPosRot2(Linkset.LinksetRoot.BSBody.Ptr, _position, _orientation); + BulletSimAPI.SetCenterOfMassByPosRot2(Linkset.LinksetRoot.BSBody.ptr, _position, _orientation); // Mass is zero which disables a bunch of physics stuff in Bullet - BulletSimAPI.SetMassProps2(BSBody.Ptr, 0f, OMV.Vector3.Zero); + BulletSimAPI.SetMassProps2(BSBody.ptr, 0f, OMV.Vector3.Zero); // There is no inertia in a static object - BulletSimAPI.UpdateInertiaTensor2(BSBody.Ptr); + BulletSimAPI.UpdateInertiaTensor2(BSBody.ptr); // There can be special things needed for implementing linksets Linkset.MakeStatic(this); // The activation state is 'sleeping' so Bullet will not try to act on it - BulletSimAPI.ForceActivationState2(BSBody.Ptr, ActivationState.ISLAND_SLEEPING); + BulletSimAPI.ForceActivationState2(BSBody.ptr, ActivationState.ISLAND_SLEEPING); // BulletSimAPI.ForceActivationState2(BSBody.Ptr, ActivationState.DISABLE_SIMULATION); } else { // Not a Bullet static object - CurrentCollisionFlags = BulletSimAPI.RemoveFromCollisionFlags2(BSBody.Ptr, CollisionFlags.CF_STATIC_OBJECT); + CurrentCollisionFlags = BulletSimAPI.RemoveFromCollisionFlags2(BSBody.ptr, CollisionFlags.CF_STATIC_OBJECT); // Set various physical properties so internal dynamic properties will get computed correctly as they are set - BulletSimAPI.SetFriction2(BSBody.Ptr, PhysicsScene.Params.defaultFriction); - BulletSimAPI.SetRestitution2(BSBody.Ptr, PhysicsScene.Params.defaultRestitution); + BulletSimAPI.SetFriction2(BSBody.ptr, PhysicsScene.Params.defaultFriction); + BulletSimAPI.SetRestitution2(BSBody.ptr, PhysicsScene.Params.defaultRestitution); // per http://www.bulletphysics.org/Bullet/phpBB3/viewtopic.php?t=3382 - BulletSimAPI.SetInterpolationLinearVelocity2(BSBody.Ptr, OMV.Vector3.Zero); - BulletSimAPI.SetInterpolationAngularVelocity2(BSBody.Ptr, OMV.Vector3.Zero); - BulletSimAPI.SetInterpolationVelocity2(BSBody.Ptr, OMV.Vector3.Zero, OMV.Vector3.Zero); + BulletSimAPI.SetInterpolationLinearVelocity2(BSBody.ptr, OMV.Vector3.Zero); + BulletSimAPI.SetInterpolationAngularVelocity2(BSBody.ptr, OMV.Vector3.Zero); + BulletSimAPI.SetInterpolationVelocity2(BSBody.ptr, OMV.Vector3.Zero, OMV.Vector3.Zero); // A dynamic object has mass - IntPtr collisionShapePtr = BulletSimAPI.GetCollisionShape2(BSBody.Ptr); + IntPtr collisionShapePtr = BulletSimAPI.GetCollisionShape2(BSBody.ptr); OMV.Vector3 inertia = BulletSimAPI.CalculateLocalInertia2(collisionShapePtr, Linkset.LinksetMass); - BulletSimAPI.SetMassProps2(BSBody.Ptr, _mass, inertia); + BulletSimAPI.SetMassProps2(BSBody.ptr, _mass, inertia); // Inertia is based on our new mass - BulletSimAPI.UpdateInertiaTensor2(BSBody.Ptr); + BulletSimAPI.UpdateInertiaTensor2(BSBody.ptr); // Various values for simulation limits - BulletSimAPI.SetDamping2(BSBody.Ptr, PhysicsScene.Params.linearDamping, PhysicsScene.Params.angularDamping); - BulletSimAPI.SetDeactivationTime2(BSBody.Ptr, PhysicsScene.Params.deactivationTime); - BulletSimAPI.SetSleepingThresholds2(BSBody.Ptr, PhysicsScene.Params.linearSleepingThreshold, PhysicsScene.Params.angularSleepingThreshold); - BulletSimAPI.SetContactProcessingThreshold2(BSBody.Ptr, PhysicsScene.Params.contactProcessingThreshold); + BulletSimAPI.SetDamping2(BSBody.ptr, PhysicsScene.Params.linearDamping, PhysicsScene.Params.angularDamping); + BulletSimAPI.SetDeactivationTime2(BSBody.ptr, PhysicsScene.Params.deactivationTime); + BulletSimAPI.SetSleepingThresholds2(BSBody.ptr, PhysicsScene.Params.linearSleepingThreshold, PhysicsScene.Params.angularSleepingThreshold); + BulletSimAPI.SetContactProcessingThreshold2(BSBody.ptr, PhysicsScene.Params.contactProcessingThreshold); // There can be special things needed for implementing linksets Linkset.MakeDynamic(this); // Force activation of the object so Bullet will act on it. - BulletSimAPI.Activate2(BSBody.Ptr, true); + BulletSimAPI.Activate2(BSBody.ptr, true); } } @@ -569,8 +591,28 @@ public sealed class BSPrim : BSPhysObject // the functions after this one set up the state of a possibly newly created collision body. private void MakeSolid(bool makeSolid) { -#if !CSHARP_BODY_MANAGEMENT - CollisionObjectTypes bodyType = (CollisionObjectTypes)BulletSimAPI.GetBodyType2(BSBody.Ptr); +#if CSHARP_BODY_MANAGEMENT + CollisionObjectTypes bodyType = (CollisionObjectTypes)BulletSimAPI.GetBodyType2(BSBody.ptr); + if (makeSolid) + { + // Verify the previous code created the correct shape for this type of thing. + if ((bodyType & CollisionObjectTypes.CO_RIGID_BODY) == 0) + { + m_log.ErrorFormat("{0} MakeSolid: physical body of wrong type for solidity. id={1}, type={2}", LogHeader, LocalID, bodyType); + } + CurrentCollisionFlags = BulletSimAPI.RemoveFromCollisionFlags2(BSBody.ptr, CollisionFlags.CF_NO_CONTACT_RESPONSE); + } + else + { + if ((bodyType & CollisionObjectTypes.CO_GHOST_OBJECT) == 0) + { + m_log.ErrorFormat("{0} MakeSolid: physical body of wrong type for non-solidness. id={1}, type={2}", LogHeader, LocalID, bodyType); + } + CurrentCollisionFlags = BulletSimAPI.AddToCollisionFlags2(BSBody.ptr, CollisionFlags.CF_NO_CONTACT_RESPONSE); + } +#else + // If doing the body management in C#, all this logic is in CSShapeCollection.CreateObject(). + CollisionObjectTypes bodyType = (CollisionObjectTypes)BulletSimAPI.GetBodyType2(BSBody.ptr); if (makeSolid) { if ((bodyType & CollisionObjectTypes.CO_RIGID_BODY) == 0) @@ -618,11 +660,11 @@ public sealed class BSPrim : BSPhysObject { if (wantsCollisionEvents) { - CurrentCollisionFlags = BulletSimAPI.AddToCollisionFlags2(BSBody.Ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); + CurrentCollisionFlags = BulletSimAPI.AddToCollisionFlags2(BSBody.ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); } else { - CurrentCollisionFlags = BulletSimAPI.RemoveFromCollisionFlags2(BSBody.Ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); + CurrentCollisionFlags = BulletSimAPI.RemoveFromCollisionFlags2(BSBody.ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); } } @@ -683,7 +725,7 @@ public sealed class BSPrim : BSPhysObject PhysicsScene.TaintedObject("BSPrim.setRotationalVelocity", delegate() { DetailLog("{0},BSPrim.SetRotationalVel,taint,rotvel={1}", LocalID, _rotationalVelocity); - BulletSimAPI.SetAngularVelocity2(BSBody.Ptr, _rotationalVelocity); + BulletSimAPI.SetAngularVelocity2(BSBody.ptr, _rotationalVelocity); }); } } @@ -702,7 +744,7 @@ public sealed class BSPrim : BSPhysObject DetailLog("{0},BSPrim.SetBuoyancy,taint,buoy={1}", LocalID, _buoyancy); // Buoyancy is faked by changing the gravity applied to the object float grav = PhysicsScene.Params.gravity * (1f - _buoyancy); - BulletSimAPI.SetGravity2(BSBody.Ptr, new OMV.Vector3(0f, 0f, grav)); + BulletSimAPI.SetGravity2(BSBody.ptr, new OMV.Vector3(0f, 0f, grav)); // BulletSimAPI.SetObjectBuoyancy(Scene.WorldID, LocalID, _buoyancy); }); } @@ -767,7 +809,7 @@ public sealed class BSPrim : BSPhysObject } DetailLog("{0},BSPrim.AddObjectForce,taint,force={1}", LocalID, fSum); // For unknown reasons, "ApplyCentralForce" adds this force to the total force on the object. - BulletSimAPI.ApplyCentralForce2(BSBody.Ptr, fSum); + BulletSimAPI.ApplyCentralForce2(BSBody.ptr, fSum); }); } @@ -1394,7 +1436,7 @@ public sealed class BSPrim : BSPhysObject } // Rebuild the geometry and object. // This is called when the shape changes so we need to recreate the mesh/hull. - // No locking here because this is done when the physics engine is not simulating + // No locking here because this is done when the physics engine is not simulating (taint-time). private void CreateGeomAndObject(bool forceRebuild) { #if CSHARP_BODY_MANAGEMENT @@ -1403,11 +1445,10 @@ public sealed class BSPrim : BSPhysObject // Create the correct physical representation for this type of object. // Updates BSBody and BSShape with the new information. - if (PhysicsScene.Shapes.GetBodyAndShape(forceRebuild, PhysicsScene.World, this, shapeData, _pbs)) - { - // Make sure the properties are set on the new object - UpdatePhysicalParameters(); - } + PhysicsScene.Shapes.GetBodyAndShape(forceRebuild, PhysicsScene.World, this, shapeData, _pbs); + + // Make sure the properties are set on the new object + UpdatePhysicalParameters(); #else // m_log.DebugFormat("{0}: CreateGeomAndObject. lID={1}, force={2}", LogHeader, LocalID, forceRebuild); // Create the geometry that will make up the object diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index 76da42d..87c7b1b 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -589,6 +589,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters { if (localID <= TerrainManager.HighestTerrainID) { + DetailLog("{0},BSScene.SendCollision,collideWithTerrain,id={1},with={2}", DetailLogZero, localID, collidingWith); return; // don't send collisions to the terrain } @@ -596,6 +597,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters if (!PhysObjects.TryGetValue(localID, out collider)) { // If the object that is colliding cannot be found, just ignore the collision. + DetailLog("{0},BSScene.SendCollision,colliderNotInObjectList,id={1},with={2}", DetailLogZero, localID, collidingWith); return; } @@ -604,7 +606,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters BSPhysObject collidee = null; PhysObjects.TryGetValue(collidingWith, out collidee); - // DetailLog("{0},BSScene.SendCollision,collide,id={1},with={2}", DetailLogZero, localID, collidingWith); + DetailLog("{0},BSScene.SendCollision,collide,id={1},with={2}", DetailLogZero, localID, collidingWith); if (collider.Collide(collidingWith, collidee, collidePoint, collideNormal, penetration)) { diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index 7470d23..6b90661 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -38,8 +38,9 @@ public class BSShapeCollection : IDisposable { protected BSScene PhysicsScene { get; set; } - private Object m_shapeActivityLock = new Object(); + private Object m_collectionActivityLock = new Object(); + // Description of a Mesh private struct MeshDesc { public IntPtr Ptr; @@ -48,6 +49,8 @@ public class BSShapeCollection : IDisposable public IMesh meshData; } + // Description of a hull. + // Meshes and hulls have the same shape hash key but we only need hulls for efficient physical objects private struct HullDesc { public IntPtr Ptr; @@ -55,8 +58,17 @@ public class BSShapeCollection : IDisposable public DateTime lastReferenced; } + private struct BodyDesc + { + public IntPtr Ptr; + // Bodies are only used once so reference count is always either one or zero + public int referenceCount; + public DateTime lastReferenced; + } + private Dictionary Meshes = new Dictionary(); private Dictionary Hulls = new Dictionary(); + private Dictionary Bodies = new Dictionary(); public BSShapeCollection(BSScene physScene) { @@ -65,6 +77,7 @@ public class BSShapeCollection : IDisposable public void Dispose() { + // TODO!!!!!!!!! } // Called to update/change the body and shape for an object. @@ -76,40 +89,104 @@ public class BSShapeCollection : IDisposable { bool ret = false; - // Do we have the correct geometry for this type of object? - if (CreateGeom(forceRebuild, prim, shapeData, pbs)) + // This lock could probably be pushed down lower but building shouldn't take long + lock (m_collectionActivityLock) { + // Do we have the correct geometry for this type of object? + bool newGeom = CreateGeom(forceRebuild, prim, shapeData, pbs); // If we had to select a new shape geometry for the object, // rebuild the body around it. - CreateObject(true, prim, PhysicsScene.World, prim.BSShape, shapeData); - ret = true; + bool newBody = CreateBody((newGeom || forceRebuild), prim, PhysicsScene.World, prim.BSShape, shapeData); + ret = newGeom || newBody; } + DetailLog("{0},BSShapeCollection.GetBodyAndShape,force-{1},ret={2},body={3},shape={4}", + prim.LocalID, forceRebuild, ret, prim.BSBody, prim.BSShape); return ret; } // Track another user of a body - public void ReferenceBody(BulletBody shape) + // We presume the caller has allocated the body. + // Bodies only have one user so the reference count is either 1 or 0. + public void ReferenceBody(BulletBody shape, bool atTaintTime) { - } + lock (m_collectionActivityLock) + { + BodyDesc bodyDesc; + if (Bodies.TryGetValue(shape.ID, out bodyDesc)) + { + bodyDesc.referenceCount++; + DetailLog("{0},BSShapeCollection.ReferenceBody,existingBody,ref={1}", shape.ID, bodyDesc.referenceCount); + } + else + { + bodyDesc.Ptr = shape.ptr; + bodyDesc.referenceCount = 1; + DetailLog("{0},BSShapeCollection.ReferenceBody,newBody,ref={1}", shape.ID, bodyDesc.referenceCount); + } + bodyDesc.lastReferenced = System.DateTime.Now; + Bodies[shape.ID] = bodyDesc; + } +} - // Release the usage of a body - public void DereferenceBody(BulletBody shape) + // Release the usage of a body. + // Not that this will also delete the body in BUllet if the body is now unused (reference count = 0). + public void DereferenceBody(BulletBody shape, bool inTaintTime) { + if (shape.ptr == IntPtr.Zero) + return; + + lock (m_collectionActivityLock) + { + BodyDesc bodyDesc; + if (Bodies.TryGetValue(shape.ID, out bodyDesc)) + { + bodyDesc.referenceCount--; + bodyDesc.lastReferenced = System.DateTime.Now; + Bodies[shape.ID] = bodyDesc; + DetailLog("{0},BSShapeCollection.DereferenceBody,ref={1}", shape.ID, bodyDesc.referenceCount); + + if (bodyDesc.referenceCount == 0) + { + Bodies.Remove(shape.ID); + BSScene.TaintCallback removeOperation = delegate() + { + DetailLog("{0},BSShapeCollection.DereferenceBody,DestroyingBody. Ptr={1:X}", shape.ID, shape.ptr); + // zero any reference to the shape so it is not freed when the body is deleted + BulletSimAPI.SetCollisionShape2(PhysicsScene.World.ptr, shape.ptr, IntPtr.Zero); + // It may have already been removed from the world in which case the next is a NOOP + BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.ptr, shape.ptr); + BulletSimAPI.DestroyObject2(PhysicsScene.World.ptr, shape.ptr); + }; + // If already in taint-time, do the operations now. Otherwise queue for later. + if (inTaintTime) + removeOperation(); + else + PhysicsScene.TaintedObject("BSShapeCollection.DereferenceBody", removeOperation); + } + } + else + { + DetailLog("{0},BSShapeCollection.DereferenceBody,DID NOT FIND BODY", shape.ID, bodyDesc.referenceCount); + } + } } // Track another user of the shape - public void ReferenceShape(BulletShape shape) + private bool ReferenceShape(BulletShape shape) { - ReferenceShape(shape, null); + return ReferenceShape(shape, null); } // 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. - private void ReferenceShape(BulletShape shape, IMesh meshData) + // 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. + private bool ReferenceShape(BulletShape shape, IMesh meshData) { + bool ret = false; switch (shape.type) { case ShapeData.PhysicsShapeType.SHAPE_MESH: @@ -118,14 +195,18 @@ public class BSShapeCollection : IDisposable { // There is an existing instance of this mesh. meshDesc.referenceCount++; + DetailLog("{0},BSShapeColliction.ReferenceShape,existingMesh,key={1},cnt={2}", + BSScene.DetailLogZero, shape.shapeKey, meshDesc.referenceCount); } else { // This is a new reference to a mesh - meshDesc.Ptr = shape.Ptr; + meshDesc.Ptr = shape.ptr; meshDesc.meshData = meshData; meshDesc.referenceCount = 1; - + DetailLog("{0},BSShapeColliction.ReferenceShape,newMesh,key={1},cnt={2}", + BSScene.DetailLogZero, shape.shapeKey, meshDesc.referenceCount); + ret = true; } meshDesc.lastReferenced = System.DateTime.Now; Meshes[shape.shapeKey] = meshDesc; @@ -136,41 +217,68 @@ public class BSShapeCollection : IDisposable { // There is an existing instance of this mesh. hullDesc.referenceCount++; + DetailLog("{0},BSShapeColliction.ReferenceShape,existingHull,key={1},cnt={2}", + BSScene.DetailLogZero, shape.shapeKey, hullDesc.referenceCount); } else { - // This is a new reference to a mesh - hullDesc.Ptr = shape.Ptr; + // This is a new reference to a hull + hullDesc.Ptr = shape.ptr; hullDesc.referenceCount = 1; + DetailLog("{0},BSShapeColliction.ReferenceShape,newHull,key={1},cnt={2}", + BSScene.DetailLogZero, shape.shapeKey, hullDesc.referenceCount); + ret = true; } hullDesc.lastReferenced = System.DateTime.Now; Hulls[shape.shapeKey] = hullDesc; break; + case ShapeData.PhysicsShapeType.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) + private void DereferenceShape(BulletShape shape, bool atTaintTime) { - switch (shape.type) + if (shape.ptr == IntPtr.Zero) + return; + + BSScene.TaintCallback dereferenceOperation = delegate() { - case ShapeData.PhysicsShapeType.SHAPE_HULL: - DereferenceHull(shape); - // Hulls also include a mesh - DereferenceMesh(shape); - break; - case ShapeData.PhysicsShapeType.SHAPE_MESH: - DereferenceMesh(shape); - break; - default: - break; - } + switch (shape.type) + { + case ShapeData.PhysicsShapeType.SHAPE_HULL: + DereferenceHull(shape); + // Hulls also include a mesh + DereferenceMesh(shape); + break; + case ShapeData.PhysicsShapeType.SHAPE_MESH: + DereferenceMesh(shape); + break; + case ShapeData.PhysicsShapeType.SHAPE_UNKNOWN: + break; + default: + // Native shapes are not tracked and are released immediately + if (shape.ptr != IntPtr.Zero & shape.isNativeShape) + { + BulletSimAPI.DeleteCollisionShape2(PhysicsScene.World.ptr, shape.ptr); + } + break; + } + }; + if (atTaintTime) + dereferenceOperation(); + else + PhysicsScene.TaintedObject("BSShapeCollection.DereferenceShape", dereferenceOperation); } // Count down the reference count for a mesh shape + // Called at taint-time. private void DereferenceMesh(BulletShape shape) { MeshDesc meshDesc; @@ -180,10 +288,14 @@ public class BSShapeCollection : IDisposable // TODO: release the Bullet storage meshDesc.lastReferenced = System.DateTime.Now; Meshes[shape.shapeKey] = meshDesc; + DetailLog("{0},BSShapeColliction.DereferenceMesh,key={1},cnt={2}", + BSScene.DetailLogZero, shape.shapeKey, meshDesc.referenceCount); + } } // Count down the reference count for a hull shape + // Called at taint-time. private void DereferenceHull(BulletShape shape) { HullDesc hullDesc; @@ -193,6 +305,8 @@ public class BSShapeCollection : IDisposable // TODO: release the Bullet storage (aging old entries?) hullDesc.lastReferenced = System.DateTime.Now; Hulls[shape.shapeKey] = hullDesc; + DetailLog("{0},BSShapeColliction.DereferenceHull,key={1},cnt={2}", + BSScene.DetailLogZero, shape.shapeKey, hullDesc.referenceCount); } } @@ -210,10 +324,6 @@ public class BSShapeCollection : IDisposable BulletShape newShape = new BulletShape(IntPtr.Zero); - // If the object is dynamic, it must have a hull shape - if (prim.IsPhysical) - nativeShapePossible = false; - // If the prim attributes are simple, this could be a simple Bullet native shape if (nativeShapePossible && ((pbs.SculptEntry && !PhysicsScene.ShouldMeshSculptedPrim) @@ -230,8 +340,10 @@ public class BSShapeCollection : IDisposable haveShape = true; if (forceRebuild || (prim.BSShape.type != ShapeData.PhysicsShapeType.SHAPE_SPHERE)) { - DetailLog("{0},BSShapeCollection.CreateGeom,sphere (force={1}", prim.LocalID, forceRebuild); - newShape = AddNativeShapeToPrim(prim, shapeData, ShapeData.PhysicsShapeType.SHAPE_SPHERE); + newShape = AddNativeShapeToPrim( + prim, shapeData, ShapeData.PhysicsShapeType.SHAPE_SPHERE, ShapeData.FixedShapeKey.KEY_SPHERE); + DetailLog("{0},BSShapeCollection.CreateGeom,sphere,force={1},shape={2}", + prim.LocalID, forceRebuild,prim.BSShape); ret = true; } @@ -242,71 +354,87 @@ public class BSShapeCollection : IDisposable haveShape = true; if (forceRebuild || (prim.BSShape.type != ShapeData.PhysicsShapeType.SHAPE_BOX)) { - DetailLog("{0},BSShapeCollection.CreateGeom,box (force={1})", prim.LocalID, forceRebuild); - newShape = AddNativeShapeToPrim(prim, shapeData, ShapeData.PhysicsShapeType.SHAPE_BOX); + newShape = AddNativeShapeToPrim( + prim, shapeData, ShapeData.PhysicsShapeType.SHAPE_BOX, ShapeData.FixedShapeKey.KEY_BOX); + DetailLog("{0},BSShapeCollection.CreateGeom,box,force={1},shape={2}", + prim.LocalID, forceRebuild,prim.BSShape); ret = true; } } } - // If a simple shape isn't happening, create a mesh and possibly a hull + // If a simple shape is not happening, create a mesh and possibly a hull + // Note that if it's a native shape, the check for physical/non-physical is not + // made. Native shapes are best used in either case. if (!haveShape) { if (prim.IsPhysical) { - if (forceRebuild || !Hulls.ContainsKey(prim.BSShape.shapeKey)) + if (forceRebuild || !Hulls.ContainsKey(shapeData.HullKey)) { // physical objects require a hull for interaction. - // This also creates the mesh if it doesn't already exist + // This also creates the mesh if it doesn't already exist. ret = CreateGeomHull(prim, shapeData, pbs); } + else + { + prim.BSShape = new BulletShape(Hulls[shapeData.HullKey].Ptr, + ShapeData.PhysicsShapeType.SHAPE_HULL); + prim.BSShape.shapeKey = shapeData.HullKey; + // Another user of this shape. + ReferenceShape(prim.BSShape); + ret = true; + } } else { if (forceRebuild || !Meshes.ContainsKey(prim.BSShape.shapeKey)) { // Static (non-physical) objects only need a mesh for bumping into + // Returning 'true' means prim.BShape was changed. ret = CreateGeomMesh(prim, shapeData, pbs); } + else + { + prim.BSShape = new BulletShape(Hulls[shapeData.MeshKey].Ptr, + ShapeData.PhysicsShapeType.SHAPE_MESH); + prim.BSShape.shapeKey = shapeData.MeshKey; + ReferenceShape(prim.BSShape); + ret = true; + } } } return ret; } - private BulletShape AddNativeShapeToPrim(BSPrim prim, ShapeData shapeData, ShapeData.PhysicsShapeType shapeType) + // Creates a native shape and assignes it to prim.BSShape + private BulletShape AddNativeShapeToPrim( + BSPrim prim, ShapeData shapeData, ShapeData.PhysicsShapeType shapeType, + ShapeData.FixedShapeKey shapeKey) { BulletShape newShape; // Bullet native objects are scaled by the Bullet engine so pass the size in prim.Scale = shapeData.Size; + shapeData.Type = shapeType; + shapeData.Scale = prim.Scale; // release any previous shape - DereferenceShape(prim.BSShape); + DereferenceShape(prim.BSShape, true); + + // Shape of this discriptioin is not allocated. Create new. + newShape = new BulletShape( + BulletSimAPI.BuildNativeShape2(PhysicsScene.World.ptr, shapeData), shapeType); + newShape.shapeKey = (ulong)shapeKey; + newShape.isNativeShape = true; + + // Don't to a 'ReferenceShape()' here because native shapes are not tracked. - MeshDesc existingShapeDesc; - if (Meshes.TryGetValue(shapeData.MeshKey, out existingShapeDesc)) - { - // If there is an existing allocated shape, use it - newShape = new BulletShape(existingShapeDesc.Ptr, shapeType); - } - else - { - // Shape of this discriptioin is not allocated. Create new. - newShape = new BulletShape( - BulletSimAPI.BuildNativeShape2(PhysicsScene.World.Ptr, - (float)shapeType, - PhysicsScene.Params.collisionMargin, - prim.Scale), - shapeType); - } - newShape.shapeKey = shapeData.MeshKey; - ReferenceShape(newShape); prim.BSShape = newShape; return newShape; } - // No locking here because this is done when we know physics is not simulating - // Returns 'true' of a mesh was actually rebuild (we could also have one of these specs). + // Returns 'true' of a mesh was actually rebuild. // Called at taint-time! private bool CreateGeomMesh(BSPrim prim, ShapeData shapeData, PrimitiveBaseShape pbs) { @@ -322,7 +450,6 @@ public class BSShapeCollection : IDisposable lod = PhysicsScene.MeshMegaPrimLOD; ulong newMeshKey = (ulong)pbs.GetMeshKey(shapeData.Size, lod); - // m_log.DebugFormat("{0}: CreateGeomMesh: lID={1}, oldKey={2}, newKey={3}", LogHeader, LocalID, _meshKey, newMeshKey); // if this new shape is the same as last time, don't recreate the mesh if (prim.BSShape.shapeKey == newMeshKey) return false; @@ -330,7 +457,7 @@ public class BSShapeCollection : IDisposable DetailLog("{0},BSShapeCollection.CreateGeomMesh,create,key={1}", prim.LocalID, newMeshKey); // Since we're recreating new, get rid of the reference to the previous shape - DereferenceShape(prim.BSShape); + DereferenceShape(prim.BSShape, true); IMesh meshData = null; IntPtr meshPtr; @@ -360,7 +487,7 @@ public class BSShapeCollection : IDisposable // m_log.DebugFormat("{0}: CreateGeomMesh: calling CreateMesh. lid={1}, key={2}, indices={3}, vertices={4}", // LogHeader, prim.LocalID, newMeshKey, indices.Length, vertices.Count); - meshPtr = BulletSimAPI.CreateMeshShape2(PhysicsScene.World.Ptr, + meshPtr = BulletSimAPI.CreateMeshShape2(PhysicsScene.World.ptr, indices.GetLength(0), indices, vertices.Count, verticesAsFloats); } newShape = new BulletShape(meshPtr, ShapeData.PhysicsShapeType.SHAPE_MESH); @@ -374,26 +501,29 @@ public class BSShapeCollection : IDisposable return true; // 'true' means a new shape has been added to this prim } - // No locking here because this is done when we know physics is not simulating // Returns 'true' of a mesh was actually rebuild (we could also have one of these specs). List m_hulls; private bool CreateGeomHull(BSPrim prim, ShapeData shapeData, PrimitiveBaseShape pbs) { BulletShape newShape; + // Level of detail for the mesh can be different for sculpties and regular meshes. float lod = pbs.SculptEntry ? PhysicsScene.SculptLOD : PhysicsScene.MeshLOD; + ulong newHullKey = (ulong)pbs.GetMeshKey(shapeData.Size, lod); - // m_log.DebugFormat("{0}: CreateGeomHull: lID={1}, oldKey={2}, newKey={3}", LogHeader, LocalID, _hullKey, newHullKey); // if the hull hasn't changed, don't rebuild it if (newHullKey == prim.BSShape.shapeKey) return false; DetailLog("{0},BSShapeCollection.CreateGeomHull,create,oldKey={1},newKey={2}", prim.LocalID, newHullKey, newHullKey); - // remove references to any previous shape - DereferenceShape(prim.BSShape); + // Remove references to the previous shape. Also removes reference to underlying mesh. + DereferenceShape(prim.BSShape, true); - // Make sure the underlying mesh exists and is correct + // Do not let the mesh dereference itself again. Was done in the above DerefereceShape(). + prim.BSShape.type = ShapeData.PhysicsShapeType.SHAPE_UNKNOWN; + + // Make sure the underlying mesh exists and is correct. // Since we're in the hull code, we know CreateGeomMesh() will not create a native shape. CreateGeomMesh(prim, shapeData, pbs); MeshDesc meshDesc = Meshes[newHullKey]; @@ -402,10 +532,12 @@ public class BSShapeCollection : IDisposable HullDesc hullDesc; if (Hulls.TryGetValue(newHullKey, out hullDesc)) { + // If the hull shape already is created, just use it. hullPtr = hullDesc.Ptr; } else { + // Build a new hull in the physical world int[] indices = meshDesc.meshData.getIndexListAsInt(); List vertices = meshDesc.meshData.getVertexList(); @@ -485,63 +617,85 @@ public class BSShapeCollection : IDisposable } // create the hull data structure in Bullet // m_log.DebugFormat("{0}: CreateGeom: calling CreateHull. lid={1}, key={2}, hulls={3}", LogHeader, LocalID, _hullKey, hullCount); - hullPtr = BulletSimAPI.CreateHullShape2(PhysicsScene.World.Ptr, hullCount, convHulls); + hullPtr = BulletSimAPI.CreateHullShape2(PhysicsScene.World.ptr, hullCount, convHulls); } + newShape = new BulletShape(hullPtr, ShapeData.PhysicsShapeType.SHAPE_HULL); newShape.shapeKey = newHullKey; + newShape.meshPtr = meshDesc.Ptr; ReferenceShape(newShape); - // meshes are already scaled by the meshmerizer + // meshes and hulls are already scaled by the meshmerizer prim.Scale = new OMV.Vector3(1f, 1f, 1f); prim.BSShape = newShape; return true; // 'true' means a new shape has been added to this prim } // Callback from convex hull creater with a newly created hull. - // Just add it to the collection of hulls for this shape. + // Just add it to our collection of hulls for this shape. private void HullReturn(ConvexResult result) { m_hulls.Add(result); return; } - // Create an object in Bullet if it has not already been created - // No locking here because this is done when the physics engine is not simulating + // Create an object in Bullet if it has not already been created. + // Updates prim.BSBody with the information about the new body if one is created. // Returns 'true' if an object was actually created. - private bool CreateObject(bool forceRebuild, BSPrim prim, BulletSim sim, BulletShape shape, ShapeData shapeData) + // Called at taint-time. + private bool CreateBody(bool forceRebuild, BSPrim prim, BulletSim sim, BulletShape shape, ShapeData shapeData) { - // the mesh or hull must have already been created in Bullet - // m_log.DebugFormat("{0}: CreateObject: lID={1}, shape={2}", LogHeader, LocalID, shape.Type); + bool ret = false; - DereferenceBody(prim.BSBody); + // the mesh, hull or native shape must have already been created in Bullet + bool mustRebuild = (prim.BSBody.ptr == IntPtr.Zero); - BulletBody aBody; - IntPtr bodyPtr = IntPtr.Zero; - if (prim.IsSolid) + // If there is an existing body, verify it's of an acceptable type. + // If not a solid object, body is a GhostObject. Otherwise a RigidBody. + if (!mustRebuild) { - bodyPtr = BulletSimAPI.CreateBodyFromShape2(sim.Ptr, shape.Ptr, shapeData.Position, shapeData.Rotation); + CollisionObjectTypes bodyType = (CollisionObjectTypes)BulletSimAPI.GetBodyType2(prim.BSBody.ptr); + if (prim.IsSolid && bodyType != CollisionObjectTypes.CO_RIGID_BODY + || !prim.IsSolid && bodyType != CollisionObjectTypes.CO_GHOST_OBJECT) + { + // If the collisionObject is not the correct type for solidness, rebuild what's there + mustRebuild = true; + } + } - else + + if (mustRebuild) { - bodyPtr = BulletSimAPI.CreateGhostFromShape2(sim.Ptr, shape.Ptr, shapeData.Position, shapeData.Rotation); - } - aBody = new BulletBody(shapeData.ID, bodyPtr); + DereferenceBody(prim.BSBody, true); + + BulletBody aBody; + IntPtr bodyPtr = IntPtr.Zero; + if (prim.IsSolid) + { + bodyPtr = BulletSimAPI.CreateBodyFromShape2(sim.ptr, shape.ptr, shapeData.Position, shapeData.Rotation); + DetailLog("{0},BSShapeCollection.CreateObject,mesh,ptr={1:X}", prim.LocalID, bodyPtr); + } + else + { + bodyPtr = BulletSimAPI.CreateGhostFromShape2(sim.ptr, shape.ptr, shapeData.Position, shapeData.Rotation); + DetailLog("{0},BSShapeCollection.CreateObject,ghost,ptr={1:X}", prim.LocalID, bodyPtr); + } + aBody = new BulletBody(shapeData.ID, bodyPtr); + + ReferenceBody(aBody, true); + + prim.BSBody = aBody; - ReferenceBody(aBody); + ret = true; + } - prim.BSBody = aBody; - return true; + return ret; } private void DetailLog(string msg, params Object[] args) { PhysicsScene.PhysicsLogging.Write(msg, args); } - - - - - } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs index fb802e4..093d2a4 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs @@ -111,8 +111,8 @@ public class BSTerrainManager BulletSimAPI.CreateGroundPlaneShape2(BSScene.GROUNDPLANE_ID, 1f, TERRAIN_COLLISION_MARGIN), ShapeData.PhysicsShapeType.SHAPE_GROUNDPLANE); m_groundPlane = new BulletBody(BSScene.GROUNDPLANE_ID, - BulletSimAPI.CreateBodyWithDefaultMotionState2(groundPlaneShape.Ptr, Vector3.Zero, Quaternion.Identity)); - BulletSimAPI.AddObjectToWorld2(PhysicsScene.World.Ptr, m_groundPlane.Ptr); + BulletSimAPI.CreateBodyWithDefaultMotionState2(groundPlaneShape.ptr, Vector3.Zero, Quaternion.Identity)); + BulletSimAPI.AddObjectToWorld2(PhysicsScene.World.ptr, m_groundPlane.ptr); Vector3 minTerrainCoords = new Vector3(0f, 0f, HEIGHT_INITIALIZATION - HEIGHT_EQUAL_FUDGE); Vector3 maxTerrainCoords = new Vector3(DefaultRegionSize.X, DefaultRegionSize.Y, HEIGHT_INITIALIZATION); @@ -128,13 +128,13 @@ public class BSTerrainManager // Release all the terrain structures we might have allocated public void ReleaseGroundPlaneAndTerrain() { - if (m_groundPlane.Ptr != IntPtr.Zero) + if (m_groundPlane.ptr != IntPtr.Zero) { - if (BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.Ptr, m_groundPlane.Ptr)) + if (BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.ptr, m_groundPlane.ptr)) { - BulletSimAPI.DestroyObject2(PhysicsScene.World.Ptr, m_groundPlane.Ptr); + BulletSimAPI.DestroyObject2(PhysicsScene.World.ptr, m_groundPlane.ptr); } - m_groundPlane.Ptr = IntPtr.Zero; + m_groundPlane.ptr = IntPtr.Zero; } ReleaseTerrain(); @@ -145,9 +145,9 @@ public class BSTerrainManager { foreach (KeyValuePair kvp in m_heightMaps) { - if (BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.Ptr, kvp.Value.terrainBody.Ptr)) + if (BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.ptr, kvp.Value.terrainBody.ptr)) { - BulletSimAPI.DestroyObject2(PhysicsScene.World.Ptr, kvp.Value.terrainBody.Ptr); + BulletSimAPI.DestroyObject2(PhysicsScene.World.ptr, kvp.Value.terrainBody.ptr); BulletSimAPI.ReleaseHeightMapInfo2(kvp.Value.Ptr); } } @@ -248,17 +248,17 @@ public class BSTerrainManager return; } - if (mapInfo.terrainBody.Ptr != IntPtr.Zero) + if (mapInfo.terrainBody.ptr != IntPtr.Zero) { // Updating an existing terrain. DetailLog("{0},UpdateOrCreateTerrain:UpdateExisting,taint,terrainBase={1},minC={2}, maxC={3}, szX={4}, szY={5}", BSScene.DetailLogZero, terrainRegionBase, mapInfo.minCoords, mapInfo.maxCoords, mapInfo.sizeX, mapInfo.sizeY); // Remove from the dynamics world because we're going to mangle this object - BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.Ptr, mapInfo.terrainBody.Ptr); + BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.ptr, mapInfo.terrainBody.ptr); // Get rid of the old terrain - BulletSimAPI.DestroyObject2(PhysicsScene.World.Ptr, mapInfo.terrainBody.Ptr); + BulletSimAPI.DestroyObject2(PhysicsScene.World.ptr, mapInfo.terrainBody.ptr); BulletSimAPI.ReleaseHeightMapInfo2(mapInfo.Ptr); mapInfo.Ptr = IntPtr.Zero; @@ -289,7 +289,7 @@ public class BSTerrainManager BSScene.DetailLogZero, mapInfo.minCoords.X, mapInfo.minCoords.Y, minZ, maxZ); mapInfo.ID = id; - mapInfo.Ptr = BulletSimAPI.CreateHeightMapInfo2(PhysicsScene.World.Ptr, mapInfo.ID, + mapInfo.Ptr = BulletSimAPI.CreateHeightMapInfo2(PhysicsScene.World.ptr, mapInfo.ID, mapInfo.minCoords, mapInfo.maxCoords, mapInfo.heightMap, TERRAIN_COLLISION_MARGIN); // The terrain object initial position is at the center of the object @@ -303,7 +303,7 @@ public class BSTerrainManager ShapeData.PhysicsShapeType.SHAPE_TERRAIN); mapInfo.terrainBody = new BulletBody(mapInfo.ID, - BulletSimAPI.CreateBodyWithDefaultMotionState2(mapInfo.terrainShape.Ptr, + BulletSimAPI.CreateBodyWithDefaultMotionState2(mapInfo.terrainShape.ptr, centerPos, Quaternion.Identity)); } @@ -311,22 +311,22 @@ public class BSTerrainManager m_heightMaps[terrainRegionBase] = mapInfo; // Set current terrain attributes - BulletSimAPI.SetFriction2(mapInfo.terrainBody.Ptr, PhysicsScene.Params.terrainFriction); - BulletSimAPI.SetHitFraction2(mapInfo.terrainBody.Ptr, PhysicsScene.Params.terrainHitFraction); - BulletSimAPI.SetRestitution2(mapInfo.terrainBody.Ptr, PhysicsScene.Params.terrainRestitution); - BulletSimAPI.SetCollisionFlags2(mapInfo.terrainBody.Ptr, CollisionFlags.CF_STATIC_OBJECT); + BulletSimAPI.SetFriction2(mapInfo.terrainBody.ptr, PhysicsScene.Params.terrainFriction); + BulletSimAPI.SetHitFraction2(mapInfo.terrainBody.ptr, PhysicsScene.Params.terrainHitFraction); + BulletSimAPI.SetRestitution2(mapInfo.terrainBody.ptr, PhysicsScene.Params.terrainRestitution); + BulletSimAPI.SetCollisionFlags2(mapInfo.terrainBody.ptr, CollisionFlags.CF_STATIC_OBJECT); - BulletSimAPI.SetMassProps2(mapInfo.terrainBody.Ptr, 0f, Vector3.Zero); - BulletSimAPI.UpdateInertiaTensor2(mapInfo.terrainBody.Ptr); + BulletSimAPI.SetMassProps2(mapInfo.terrainBody.ptr, 0f, Vector3.Zero); + BulletSimAPI.UpdateInertiaTensor2(mapInfo.terrainBody.ptr); // Return the new terrain to the world of physical objects - BulletSimAPI.AddObjectToWorld2(PhysicsScene.World.Ptr, mapInfo.terrainBody.Ptr); + BulletSimAPI.AddObjectToWorld2(PhysicsScene.World.ptr, mapInfo.terrainBody.ptr); // redo its bounding box now that it is in the world - BulletSimAPI.UpdateSingleAabb2(PhysicsScene.World.Ptr, mapInfo.terrainBody.Ptr); + BulletSimAPI.UpdateSingleAabb2(PhysicsScene.World.ptr, mapInfo.terrainBody.ptr); // Make sure the new shape is processed. - BulletSimAPI.Activate2(mapInfo.terrainBody.Ptr, true); + BulletSimAPI.Activate2(mapInfo.terrainBody.ptr, true); m_terrainModified = true; }; @@ -361,7 +361,7 @@ public class BSTerrainManager DetailLog("{0},UpdateOrCreateTerrain:NewTerrain,taint,baseX={1},baseY={2}", BSScene.DetailLogZero, minCoords.X, minCoords.Y); // Create a new mapInfo that will be filled with the new info mapInfo = new BulletHeightMapInfo(id, heightMapX, - BulletSimAPI.CreateHeightMapInfo2(PhysicsScene.World.Ptr, newTerrainID, + BulletSimAPI.CreateHeightMapInfo2(PhysicsScene.World.ptr, newTerrainID, minCoordsX, maxCoordsX, heightMapX, TERRAIN_COLLISION_MARGIN)); // Put the unfilled heightmap info into the collection of same m_heightMaps.Add(terrainRegionBase, mapInfo); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs index 47875b0..8480dd1 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs @@ -40,14 +40,14 @@ public struct BulletSim { public BulletSim(uint worldId, BSScene bss, IntPtr xx) { + ptr = xx; worldID = worldId; scene = bss; - Ptr = xx; } + public IntPtr ptr; public uint worldID; // The scene is only in here so very low level routines have a handle to print debug/error messages public BSScene scene; - public IntPtr Ptr; } // An allocated Bullet btRigidBody @@ -56,9 +56,9 @@ public struct BulletBody public BulletBody(uint id, IntPtr xx) { ID = id; - Ptr = xx; + ptr = xx; } - public IntPtr Ptr; + public IntPtr ptr; public uint ID; public override string ToString() { @@ -66,7 +66,7 @@ public struct BulletBody buff.Append(""); return buff.ToString(); } @@ -76,28 +76,39 @@ public struct BulletShape { public BulletShape(IntPtr xx) { - Ptr = xx; + ptr = xx; type=ShapeData.PhysicsShapeType.SHAPE_UNKNOWN; shapeKey = 0; + isNativeShape = false; + meshPtr = IntPtr.Zero; } public BulletShape(IntPtr xx, ShapeData.PhysicsShapeType typ) { - Ptr = xx; + ptr = xx; type = typ; shapeKey = 0; + isNativeShape = false; + meshPtr = IntPtr.Zero; } - public IntPtr Ptr; + public IntPtr ptr; public ShapeData.PhysicsShapeType type; public ulong shapeKey; + public bool isNativeShape; + // Hulls have an underlying mesh. A pointer to it is hidden here. + public IntPtr meshPtr; public override string ToString() { StringBuilder buff = new StringBuilder(); buff.Append(""); return buff.ToString(); } @@ -314,10 +325,10 @@ public enum CollisionFlags : uint CF_DISABLE_SPU_COLLISION_PROCESS = 1 << 6, // Following used by BulletSim to control collisions BS_SUBSCRIBE_COLLISION_EVENTS = 1 << 10, - BS_VOLUME_DETECT_OBJECT = 1 << 11, - BS_PHANTOM_OBJECT = 1 << 12, - BS_PHYSICAL_OBJECT = 1 << 13, - BS_TERRAIN_OBJECT = 1 << 14, + // BS_VOLUME_DETECT_OBJECT = 1 << 11, + // BS_PHANTOM_OBJECT = 1 << 12, + // BS_PHYSICAL_OBJECT = 1 << 13, + // BS_TERRAIN_OBJECT = 1 << 14, BS_NONE = 0, BS_ALL = 0xFFFFFFFF, @@ -326,9 +337,9 @@ public enum CollisionFlags : uint BS_ACTIVE = CF_STATIC_OBJECT | CF_KINEMATIC_OBJECT | CF_NO_CONTACT_RESPONSE - | BS_VOLUME_DETECT_OBJECT - | BS_PHANTOM_OBJECT - | BS_PHYSICAL_OBJECT, + // | BS_VOLUME_DETECT_OBJECT + // | BS_PHANTOM_OBJECT + // | BS_PHYSICAL_OBJECT, }; // Values for collisions groups and masks @@ -552,8 +563,7 @@ public static extern IntPtr CreateHullShape2(IntPtr world, public static extern IntPtr BuildHullShape2(IntPtr world, IntPtr meshShape); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern IntPtr BuildNativeShape2(IntPtr world, - float shapeType, float collisionMargin, Vector3 scale); +public static extern IntPtr BuildNativeShape2(IntPtr world, ShapeData shapeData); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern bool IsNativeShape2(IntPtr shape); @@ -568,6 +578,9 @@ public static extern void AddChildToCompoundShape2(IntPtr cShape, IntPtr addShap public static extern void RemoveChildFromCompoundShape2(IntPtr cShape, IntPtr removeShape); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern IntPtr DuplicateCollisionShape2(IntPtr sim, IntPtr srcShape, uint id); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern IntPtr CreateBodyFromShapeAndInfo2(IntPtr sim, IntPtr shape, IntPtr constructionInfo); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -- cgit v1.1 From 735d89e3692bb7c620b9e3c248a1dbd5924b8b3f Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 25 Sep 2012 15:01:18 -0700 Subject: BulletSim: btGhostObjects working to make 'volume detect' work. Rearrangement and cleanup of shape collection code. Much more readable. Enabling and use of collision filters and masks. Addition of ID to body creation BulletSimAPI calls so always set in shape for collision reporting. Change default of ShouldSplitSimulationIslands and ShouldRandomizeSolverOrder from 'false' to 'true'. When 'false', this suppresses NO_CONTACT_RESPONSE which makes volume detect fail. --- .../Region/Physics/BulletSPlugin/BSCharacter.cs | 10 +- .../Region/Physics/BulletSPlugin/BSPhysObject.cs | 8 +- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 28 +- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 24 +- .../Physics/BulletSPlugin/BSShapeCollection.cs | 296 +++++++++++---------- .../Physics/BulletSPlugin/BSTerrainManager.cs | 12 +- .../Region/Physics/BulletSPlugin/BulletSimAPI.cs | 78 ++++-- 7 files changed, 265 insertions(+), 191 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index e4b1dd4..961bcde 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -90,7 +90,8 @@ public class BSCharacter : BSPhysObject // Physics creates a unit capsule which is scaled by the physics engine. ComputeAvatarScale(_size); _avatarDensity = PhysicsScene.Params.avatarDensity; - ComputeAvatarVolumeAndMass(); // set _avatarVolume and _mass based on capsule size, _density and _scale + // set _avatarVolume and _mass based on capsule size, _density and _scale + ComputeAvatarVolumeAndMass(); ShapeData shapeData = new ShapeData(); shapeData.ID = LocalID; @@ -111,10 +112,15 @@ public class BSCharacter : BSPhysObject DetailLog("{0},BSCharacter.create,taint", LocalID); BulletSimAPI.CreateObject(PhysicsScene.WorldID, shapeData); - // Set the buoyancy for flying. This will be refactored when all the settings happen in C# + // Set the buoyancy for flying. This will be refactored when all the settings happen in C#. + // If not set at creation, the avatar will stop flying when created after crossing a region boundry. BulletSimAPI.SetObjectBuoyancy(PhysicsScene.WorldID, LocalID, _buoyancy); BSBody = new BulletBody(LocalID, BulletSimAPI.GetBodyHandle2(PhysicsScene.World.ptr, LocalID)); + + // This works here because CreateObject has already put the character into the physical world. + BulletSimAPI.SetCollisionFilterMask2(BSBody.ptr, + (uint)CollisionFilterGroups.AvatarFilter, (uint)CollisionFilterGroups.AvatarMask); }); return; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index 6a9fe50..3458477 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -123,6 +123,7 @@ public abstract class BSPhysObject : PhysicsActor CollisionCollection.AddCollider(collidingWith, new ContactPoint(contactPoint, contactNormal, pentrationDepth)); DetailLog("{0},{1}.Collison.AddCollider,call,with={2},point={3},normal={4},depth={5}", LocalID, TypeName, collidingWith, contactPoint, contactNormal, pentrationDepth); + ret = true; } return ret; @@ -145,7 +146,10 @@ public abstract class BSPhysObject : PhysicsActor // 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. if (CollisionCollection.Count == 0) + { + // If I have no collisions this time, remove me from the list of objects with collisions. PhysicsScene.ObjectsWithNoMoreCollisions.Add(this); + } DetailLog("{0},{1}.SendCollisionUpdate,call,numCollisions={2}", LocalID, TypeName, CollisionCollection.Count); base.SendCollisionUpdate(CollisionCollection); @@ -159,7 +163,7 @@ public abstract class BSPhysObject : PhysicsActor // Subscribe for collision events. // Parameter is the millisecond rate the caller wishes collision events to occur. public override void SubscribeEvents(int ms) { - DetailLog("{0},BSScene.SubscribeEvents,subscribing,ms={1}", BSScene.DetailLogZero, ms); + DetailLog("{0},{1}.SubscribeEvents,subscribing,ms={2}", LocalID, TypeName, ms); SubscribedEventsMs = ms; if (ms > 0) { @@ -178,7 +182,7 @@ public abstract class BSPhysObject : PhysicsActor } } public override void UnSubscribeEvents() { - DetailLog("{0},BSScene.UnSubscribeEvents,unsubscribing", BSScene.DetailLogZero); + DetailLog("{0},{1}.UnSubscribeEvents,unsubscribing", LocalID, TypeName); SubscribedEventsMs = 0; PhysicsScene.TaintedObject(TypeName+".UnSubscribeEvents", delegate() { diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 5be2b1b..1c6d476 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -271,7 +271,7 @@ public sealed class BSPrim : BSPhysObject _position = BulletSimAPI.GetPosition2(BSBody.ptr); // don't do the GetObjectPosition for root elements because this function is called a zillion times - // _position = BulletSimAPI.GetObjectPosition(Scene.WorldID, LocalID); + // _position = BulletSimAPI.GetObjectPosition2(PhysicsScene.World.ptr, BSBody.ptr); return _position; } set { @@ -432,7 +432,7 @@ public sealed class BSPrim : BSPhysObject // TODO: what does it mean if a child in a linkset changes its orientation? Rebuild the constraint? PhysicsScene.TaintedObject("BSPrim.setOrientation", delegate() { - // _position = BulletSimAPI.GetObjectPosition(Scene.WorldID, LocalID); + // _position = BulletSimAPI.GetObjectPosition2(PhysicsScene.World.ptr, BSBody.ptr); DetailLog("{0},BSPrim.setOrientation,taint,pos={1},orient={2}", LocalID, _position, _orientation); BulletSimAPI.SetTranslation2(BSBody.ptr, _position, _orientation); }); @@ -492,7 +492,8 @@ public sealed class BSPrim : BSPhysObject { DetailLog("{0},BSPrim.UpdatePhysicalParameters,entry,body={1},shape={2}", LocalID, BSBody, BSShape); - // Mangling all the physical properties requires the object to be out of the physical world + // Mangling all the physical properties requires the object to be out of the physical world. + // This is a NOOP if the object is not in the world (BulletSim and Bullet ignore objects not found). BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.ptr, BSBody.ptr); #if !CSHARP_BODY_MANAGEMENT @@ -517,6 +518,14 @@ public sealed class BSPrim : BSPhysObject // Rebuild its shape BulletSimAPI.UpdateSingleAabb2(PhysicsScene.World.ptr, BSBody.ptr); + // Collision filter can be set only when the object is in the world + if (BSBody.collisionFilter != 0 || BSBody.collisionMask != 0) + { + BulletSimAPI.SetCollisionFilterMask2(BSBody.ptr, (uint)BSBody.collisionFilter, (uint)BSBody.collisionMask); + DetailLog("{0},BSPrim.UpdatePhysicalParameters,setCollisionFilterMask,filter={1},mask={2}", + LocalID, BSBody.collisionFilter.ToString("X"), BSBody.collisionMask.ToString("X")); + } + // Recompute any linkset parameters. // When going from non-physical to physical, this re-enables the constraints that // had been automatically disabled when the mass was set to zero. @@ -548,8 +557,11 @@ public sealed class BSPrim : BSPhysObject // There can be special things needed for implementing linksets Linkset.MakeStatic(this); // The activation state is 'sleeping' so Bullet will not try to act on it - BulletSimAPI.ForceActivationState2(BSBody.ptr, ActivationState.ISLAND_SLEEPING); - // BulletSimAPI.ForceActivationState2(BSBody.Ptr, ActivationState.DISABLE_SIMULATION); + // BulletSimAPI.ForceActivationState2(BSBody.ptr, ActivationState.ISLAND_SLEEPING); + BulletSimAPI.ForceActivationState2(BSBody.ptr, ActivationState.DISABLE_SIMULATION); + + BSBody.collisionFilter = CollisionFilterGroups.StaticObjectFilter; + BSBody.collisionMask = CollisionFilterGroups.StaticObjectMask; } else { @@ -582,6 +594,9 @@ public sealed class BSPrim : BSPhysObject // Force activation of the object so Bullet will act on it. BulletSimAPI.Activate2(BSBody.ptr, true); + + BSBody.collisionFilter = CollisionFilterGroups.ObjectFilter; + BSBody.collisionMask = CollisionFilterGroups.ObjectMask; } } @@ -609,6 +624,8 @@ public sealed class BSPrim : BSPhysObject m_log.ErrorFormat("{0} MakeSolid: physical body of wrong type for non-solidness. id={1}, type={2}", LogHeader, LocalID, bodyType); } CurrentCollisionFlags = BulletSimAPI.AddToCollisionFlags2(BSBody.ptr, CollisionFlags.CF_NO_CONTACT_RESPONSE); + BSBody.collisionFilter = CollisionFilterGroups.VolumeDetectFilter; + BSBody.collisionMask = CollisionFilterGroups.VolumeDetectMask; } #else // If doing the body management in C#, all this logic is in CSShapeCollection.CreateObject(). @@ -745,7 +762,6 @@ public sealed class BSPrim : BSPhysObject // Buoyancy is faked by changing the gravity applied to the object float grav = PhysicsScene.Params.gravity * (1f - _buoyancy); BulletSimAPI.SetGravity2(BSBody.ptr, new OMV.Vector3(0f, 0f, grav)); - // BulletSimAPI.SetObjectBuoyancy(Scene.WorldID, LocalID, _buoyancy); }); } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index 87c7b1b..e8c628c 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -39,20 +39,20 @@ using log4net; using OpenMetaverse; // TODOs for BulletSim (for BSScene, BSPrim, BSCharacter and BulletSim) -// Adjust character capsule size when height is adjusted (ScenePresence.SetHeight) -// Test sculpties +// Move all logic out of the C++ code and into the C# code for easier future modifications. +// Test sculpties (verified that they don't work) // Compute physics FPS reasonably // Based on material, set density and friction -// More efficient memory usage when passing hull information from BSPrim to BulletSim -// Move all logic out of the C++ code and into the C# code for easier future modifications. +// Don't use constraints in linksets of non-physical objects. Means having to move children manually. // Four states of prim: Physical, regular, phantom and selected. Are we modeling these correctly? // In SL one can set both physical and phantom (gravity, does not effect others, makes collisions with ground) // At the moment, physical and phantom causes object to drop through the terrain // Physical phantom objects and related typing (collision options ) -// Use collision masks for collision with terrain and phantom objects // Check out llVolumeDetect. Must do something for that. +// Use collision masks for collision with terrain and phantom objects +// More efficient memory usage when passing hull information from BSPrim to BulletSim // Should prim.link() and prim.delink() membership checking happen at taint time? -// Mesh sharing. Use meshHash to tell if we already have a hull of that shape and only create once +// Mesh sharing. Use meshHash to tell if we already have a hull of that shape and only create once. // Do attachments need to be handled separately? Need collision events. Do not collide with VolumeDetect // Implement LockAngularMotion // Decide if clearing forces is the right thing to do when setting position (BulletSim::SetObjectTranslation) @@ -356,6 +356,12 @@ public class BSScene : PhysicsScene, IPhysicsParameters Constraints = null; } + if (Shapes != null) + { + Shapes.Dispose(); + Shapes = null; + } + // Anything left in the unmanaged code should be cleaned out BulletSimAPI.Shutdown(WorldID); @@ -589,7 +595,6 @@ public class BSScene : PhysicsScene, IPhysicsParameters { if (localID <= TerrainManager.HighestTerrainID) { - DetailLog("{0},BSScene.SendCollision,collideWithTerrain,id={1},with={2}", DetailLogZero, localID, collidingWith); return; // don't send collisions to the terrain } @@ -601,8 +606,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters return; } - // The terrain is not in the physical object list so 'collidee' - // can be null when Collide() is called. + // 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); @@ -1026,7 +1030,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters (s) => { return s.m_params[0].shouldRandomizeSolverOrder; }, (s,p,l,v) => { s.m_params[0].shouldRandomizeSolverOrder = v; } ), new ParameterDefn("ShouldSplitSimulationIslands", "Enable splitting active object scanning islands", - ConfigurationParameters.numericFalse, + ConfigurationParameters.numericTrue, (s,cf,p,v) => { s.m_params[0].shouldSplitSimulationIslands = s.NumericBool(cf.GetBoolean(p, s.BoolNumeric(v))); }, (s) => { return s.m_params[0].shouldSplitSimulationIslands; }, (s,p,l,v) => { s.m_params[0].shouldSplitSimulationIslands = v; } ), diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index 6b90661..7fce8c9 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -36,6 +36,8 @@ namespace OpenSim.Region.Physics.BulletSPlugin { public class BSShapeCollection : IDisposable { + private static string LogHeader = "[BULLETSIM SHAPE COLLECTION]"; + protected BSScene PhysicsScene { get; set; } private Object m_collectionActivityLock = new Object(); @@ -43,24 +45,23 @@ public class BSShapeCollection : IDisposable // Description of a Mesh private struct MeshDesc { - public IntPtr Ptr; + public IntPtr ptr; public int referenceCount; public DateTime lastReferenced; - public IMesh meshData; } // Description of a hull. // Meshes and hulls have the same shape hash key but we only need hulls for efficient physical objects private struct HullDesc { - public IntPtr Ptr; + public IntPtr ptr; public int referenceCount; public DateTime lastReferenced; } private struct BodyDesc { - public IntPtr Ptr; + public IntPtr ptr; // Bodies are only used once so reference count is always either one or zero public int referenceCount; public DateTime lastReferenced; @@ -93,14 +94,16 @@ public class BSShapeCollection : IDisposable lock (m_collectionActivityLock) { // Do we have the correct geometry for this type of object? + // Updates prim.BSShape with information/pointers to requested shape bool newGeom = CreateGeom(forceRebuild, prim, shapeData, pbs); // 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 bool newBody = CreateBody((newGeom || forceRebuild), prim, PhysicsScene.World, prim.BSShape, shapeData); ret = newGeom || newBody; } - DetailLog("{0},BSShapeCollection.GetBodyAndShape,force-{1},ret={2},body={3},shape={4}", - prim.LocalID, forceRebuild, ret, prim.BSBody, prim.BSShape); + DetailLog("{0},BSShapeCollection.GetBodyAndShape,force={1},ret={2},body={3},shape={4}", + prim.LocalID, forceRebuild, ret, prim.BSBody, prim.BSShape); return ret; } @@ -120,7 +123,8 @@ public class BSShapeCollection : IDisposable } else { - bodyDesc.Ptr = shape.ptr; + // New entry + bodyDesc.ptr = shape.ptr; bodyDesc.referenceCount = 1; DetailLog("{0},BSShapeCollection.ReferenceBody,newBody,ref={1}", shape.ID, bodyDesc.referenceCount); } @@ -130,7 +134,7 @@ public class BSShapeCollection : IDisposable } // Release the usage of a body. - // Not that this will also delete the body in BUllet if the body is now unused (reference count = 0). + // Called when releasing use of a BSBody. BSShape is handled separately. public void DereferenceBody(BulletBody shape, bool inTaintTime) { if (shape.ptr == IntPtr.Zero) @@ -146,15 +150,17 @@ public class BSShapeCollection : IDisposable Bodies[shape.ID] = bodyDesc; DetailLog("{0},BSShapeCollection.DereferenceBody,ref={1}", shape.ID, bodyDesc.referenceCount); + // If body is no longer being used, free it -- bodies are never shared. if (bodyDesc.referenceCount == 0) { Bodies.Remove(shape.ID); BSScene.TaintCallback removeOperation = delegate() { - DetailLog("{0},BSShapeCollection.DereferenceBody,DestroyingBody. Ptr={1:X}", shape.ID, shape.ptr); - // zero any reference to the shape so it is not freed when the body is deleted + DetailLog("{0},BSShapeCollection.DereferenceBody,DestroyingBody. ptr={1}", + shape.ID, shape.ptr.ToString("X")); + // Zero any reference to the shape so it is not freed when the body is deleted. BulletSimAPI.SetCollisionShape2(PhysicsScene.World.ptr, shape.ptr, IntPtr.Zero); - // It may have already been removed from the world in which case the next is a NOOP + // It may have already been removed from the world in which case the next is a NOOP. BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.ptr, shape.ptr); BulletSimAPI.DestroyObject2(PhysicsScene.World.ptr, shape.ptr); }; @@ -172,19 +178,13 @@ public class BSShapeCollection : IDisposable } } - // Track another user of the shape - private bool ReferenceShape(BulletShape shape) - { - return ReferenceShape(shape, null); - } - // 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. - private bool ReferenceShape(BulletShape shape, IMesh meshData) + private bool ReferenceShape(BulletShape shape) { bool ret = false; switch (shape.type) @@ -196,16 +196,16 @@ public class BSShapeCollection : IDisposable // There is an existing instance of this mesh. meshDesc.referenceCount++; DetailLog("{0},BSShapeColliction.ReferenceShape,existingMesh,key={1},cnt={2}", - BSScene.DetailLogZero, shape.shapeKey, meshDesc.referenceCount); + BSScene.DetailLogZero, shape.shapeKey.ToString("X"), meshDesc.referenceCount); } else { // This is a new reference to a mesh - meshDesc.Ptr = shape.ptr; - meshDesc.meshData = meshData; + meshDesc.ptr = shape.ptr; + // We keep a reference to the underlying IMesh data so a hull can be built meshDesc.referenceCount = 1; DetailLog("{0},BSShapeColliction.ReferenceShape,newMesh,key={1},cnt={2}", - BSScene.DetailLogZero, shape.shapeKey, meshDesc.referenceCount); + BSScene.DetailLogZero, shape.shapeKey.ToString("X"), meshDesc.referenceCount); ret = true; } meshDesc.lastReferenced = System.DateTime.Now; @@ -215,18 +215,18 @@ public class BSShapeCollection : IDisposable HullDesc hullDesc; if (Hulls.TryGetValue(shape.shapeKey, out hullDesc)) { - // There is an existing instance of this mesh. + // There is an existing instance of this hull. hullDesc.referenceCount++; DetailLog("{0},BSShapeColliction.ReferenceShape,existingHull,key={1},cnt={2}", - BSScene.DetailLogZero, shape.shapeKey, hullDesc.referenceCount); + BSScene.DetailLogZero, shape.shapeKey.ToString("X"), hullDesc.referenceCount); } else { // This is a new reference to a hull - hullDesc.Ptr = shape.ptr; + hullDesc.ptr = shape.ptr; hullDesc.referenceCount = 1; DetailLog("{0},BSShapeColliction.ReferenceShape,newHull,key={1},cnt={2}", - BSScene.DetailLogZero, shape.shapeKey, hullDesc.referenceCount); + BSScene.DetailLogZero, shape.shapeKey.ToString("X"), hullDesc.referenceCount); ret = true; } @@ -242,7 +242,8 @@ public class BSShapeCollection : IDisposable return ret; } - // Release the usage of a shape + // Release the usage of a shape. + // The collisionObject is released since it is a copy of the real collision shape. private void DereferenceShape(BulletShape shape, bool atTaintTime) { if (shape.ptr == IntPtr.Zero) @@ -254,8 +255,6 @@ public class BSShapeCollection : IDisposable { case ShapeData.PhysicsShapeType.SHAPE_HULL: DereferenceHull(shape); - // Hulls also include a mesh - DereferenceMesh(shape); break; case ShapeData.PhysicsShapeType.SHAPE_MESH: DereferenceMesh(shape); @@ -266,15 +265,24 @@ public class BSShapeCollection : IDisposable // Native shapes are not tracked and are released immediately if (shape.ptr != IntPtr.Zero & shape.isNativeShape) { + DetailLog("{0},BSShapeCollection.DereferenceShape,deleteNativeShape,ptr={1},taintTime={2}", + BSScene.DetailLogZero, shape.ptr.ToString("X"), atTaintTime); BulletSimAPI.DeleteCollisionShape2(PhysicsScene.World.ptr, shape.ptr); } break; } }; if (atTaintTime) - dereferenceOperation(); + { + lock (m_collectionActivityLock) + { + dereferenceOperation(); + } + } else + { PhysicsScene.TaintedObject("BSShapeCollection.DereferenceShape", dereferenceOperation); + } } // Count down the reference count for a mesh shape @@ -288,8 +296,8 @@ public class BSShapeCollection : IDisposable // TODO: release the Bullet storage meshDesc.lastReferenced = System.DateTime.Now; Meshes[shape.shapeKey] = meshDesc; - DetailLog("{0},BSShapeColliction.DereferenceMesh,key={1},cnt={2}", - BSScene.DetailLogZero, shape.shapeKey, meshDesc.referenceCount); + DetailLog("{0},BSShapeCollection.DereferenceMesh,key={1},refCnt={2}", + BSScene.DetailLogZero, shape.shapeKey.ToString("X"), meshDesc.referenceCount); } } @@ -305,8 +313,8 @@ public class BSShapeCollection : IDisposable // TODO: release the Bullet storage (aging old entries?) hullDesc.lastReferenced = System.DateTime.Now; Hulls[shape.shapeKey] = hullDesc; - DetailLog("{0},BSShapeColliction.DereferenceHull,key={1},cnt={2}", - BSScene.DetailLogZero, shape.shapeKey, hullDesc.referenceCount); + DetailLog("{0},BSShapeCollection.DereferenceHull,key={1},refCnt={2}", + BSScene.DetailLogZero, shape.shapeKey.ToString("X"), hullDesc.referenceCount); } } @@ -322,8 +330,6 @@ public class BSShapeCollection : IDisposable bool haveShape = false; bool nativeShapePossible = true; - BulletShape newShape = new BulletShape(IntPtr.Zero); - // If the prim attributes are simple, this could be a simple Bullet native shape if (nativeShapePossible && ((pbs.SculptEntry && !PhysicsScene.ShouldMeshSculptedPrim) @@ -340,137 +346,117 @@ public class BSShapeCollection : IDisposable haveShape = true; if (forceRebuild || (prim.BSShape.type != ShapeData.PhysicsShapeType.SHAPE_SPHERE)) { - newShape = AddNativeShapeToPrim( - prim, shapeData, ShapeData.PhysicsShapeType.SHAPE_SPHERE, ShapeData.FixedShapeKey.KEY_SPHERE); + ret = GetReferenceToNativeShape(prim, shapeData, + ShapeData.PhysicsShapeType.SHAPE_SPHERE, ShapeData.FixedShapeKey.KEY_SPHERE); DetailLog("{0},BSShapeCollection.CreateGeom,sphere,force={1},shape={2}", - prim.LocalID, forceRebuild,prim.BSShape); - - ret = true; + prim.LocalID, forceRebuild, prim.BSShape); } } else { - // m_log.DebugFormat("{0}: CreateGeom: Defaulting to box. lid={1}, type={2}, size={3}", LogHeader, LocalID, _shapeType, _size); haveShape = true; if (forceRebuild || (prim.BSShape.type != ShapeData.PhysicsShapeType.SHAPE_BOX)) { - newShape = AddNativeShapeToPrim( + ret = GetReferenceToNativeShape( prim, shapeData, ShapeData.PhysicsShapeType.SHAPE_BOX, ShapeData.FixedShapeKey.KEY_BOX); DetailLog("{0},BSShapeCollection.CreateGeom,box,force={1},shape={2}", - prim.LocalID, forceRebuild,prim.BSShape); - - ret = true; + prim.LocalID, forceRebuild, prim.BSShape); } } } - // If a simple shape is not happening, create a mesh and possibly a hull + // If a simple shape is not happening, create a mesh and possibly a hull. // Note that if it's a native shape, the check for physical/non-physical is not // made. Native shapes are best used in either case. if (!haveShape) { if (prim.IsPhysical) { - if (forceRebuild || !Hulls.ContainsKey(shapeData.HullKey)) - { - // physical objects require a hull for interaction. - // This also creates the mesh if it doesn't already exist. - ret = CreateGeomHull(prim, shapeData, pbs); - } - else - { - prim.BSShape = new BulletShape(Hulls[shapeData.HullKey].Ptr, - ShapeData.PhysicsShapeType.SHAPE_HULL); - prim.BSShape.shapeKey = shapeData.HullKey; - // Another user of this shape. - ReferenceShape(prim.BSShape); - ret = true; - } + // Update prim.BSShape to reference a hull of this shape. + ret = GetReferenceToHull(prim, shapeData, pbs); + DetailLog("{0},BSShapeCollection.CreateGeom,hull,shape={1},key={2}", + shapeData.ID, prim.BSShape, prim.BSShape.shapeKey.ToString("X")); } else { - if (forceRebuild || !Meshes.ContainsKey(prim.BSShape.shapeKey)) - { - // Static (non-physical) objects only need a mesh for bumping into - // Returning 'true' means prim.BShape was changed. - ret = CreateGeomMesh(prim, shapeData, pbs); - } - else - { - prim.BSShape = new BulletShape(Hulls[shapeData.MeshKey].Ptr, - ShapeData.PhysicsShapeType.SHAPE_MESH); - prim.BSShape.shapeKey = shapeData.MeshKey; - ReferenceShape(prim.BSShape); - ret = true; - } + ret = GetReferenceToMesh(prim, shapeData, pbs); + DetailLog("{0},BSShapeCollection.CreateGeom,mesh,shape={1},key={2}", + shapeData.ID, prim.BSShape, prim.BSShape.shapeKey.ToString("X")); } } return ret; } // Creates a native shape and assignes it to prim.BSShape - private BulletShape AddNativeShapeToPrim( - BSPrim prim, ShapeData shapeData, ShapeData.PhysicsShapeType shapeType, - ShapeData.FixedShapeKey shapeKey) + private bool GetReferenceToNativeShape( BSPrim prim, ShapeData shapeData, + ShapeData.PhysicsShapeType shapeType, ShapeData.FixedShapeKey shapeKey) { BulletShape newShape; + shapeData.Type = shapeType; // Bullet native objects are scaled by the Bullet engine so pass the size in prim.Scale = shapeData.Size; - shapeData.Type = shapeType; - shapeData.Scale = prim.Scale; + shapeData.Scale = shapeData.Size; // release any previous shape DereferenceShape(prim.BSShape, true); - // Shape of this discriptioin is not allocated. Create new. - newShape = new BulletShape( - BulletSimAPI.BuildNativeShape2(PhysicsScene.World.ptr, shapeData), shapeType); + // Native shapes are always built independently. + newShape = new BulletShape(BulletSimAPI.BuildNativeShape2(PhysicsScene.World.ptr, shapeData), shapeType); newShape.shapeKey = (ulong)shapeKey; newShape.isNativeShape = true; - // Don't to a 'ReferenceShape()' here because native shapes are not tracked. + // Don't need to do a 'ReferenceShape()' here because native shapes are not tracked. + DetailLog("{0},BSShapeCollection.AddNativeShapeToPrim,create,newshape={1}", shapeData.ID, newShape); prim.BSShape = newShape; - return newShape; + return true; } - // Returns 'true' of a mesh was actually rebuild. + // 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 CreateGeomMesh(BSPrim prim, ShapeData shapeData, PrimitiveBaseShape pbs) + private bool GetReferenceToMesh(BSPrim prim, ShapeData shapeData, PrimitiveBaseShape pbs) { BulletShape newShape = new BulletShape(IntPtr.Zero); - // level of detail based on size and type of the object - float lod = PhysicsScene.MeshLOD; - if (pbs.SculptEntry) - lod = PhysicsScene.SculptLOD; - - float maxAxis = Math.Max(shapeData.Size.X, Math.Max(shapeData.Size.Y, shapeData.Size.Z)); - if (maxAxis > PhysicsScene.MeshMegaPrimThreshold) - lod = PhysicsScene.MeshMegaPrimLOD; - - ulong newMeshKey = (ulong)pbs.GetMeshKey(shapeData.Size, lod); + float lod; + ulong newMeshKey = ComputeShapeKey(shapeData, pbs, out lod); // if this new shape is the same as last time, don't recreate the mesh if (prim.BSShape.shapeKey == newMeshKey) return false; - DetailLog("{0},BSShapeCollection.CreateGeomMesh,create,key={1}", prim.LocalID, newMeshKey); + DetailLog("{0},BSShapeCollection.CreateGeomMesh,create,oldKey={1},newKey={2}", + prim.LocalID, prim.BSShape.shapeKey.ToString("X"), newMeshKey.ToString("X")); // Since we're recreating new, get rid of the reference to the previous shape DereferenceShape(prim.BSShape, true); + newShape = CreatePhysicalMesh(prim.PhysObjectName, newMeshKey, pbs, shapeData.Size, lod); + + ReferenceShape(newShape); + + // meshes are already scaled by the meshmerizer + prim.Scale = new OMV.Vector3(1f, 1f, 1f); + prim.BSShape = newShape; + + return true; // 'true' means a new shape has been added to this prim + } + + private BulletShape CreatePhysicalMesh(string objName, ulong newMeshKey, PrimitiveBaseShape pbs, OMV.Vector3 size, float lod) + { IMesh meshData = null; IntPtr meshPtr; MeshDesc meshDesc; if (Meshes.TryGetValue(newMeshKey, out meshDesc)) { // If the mesh has already been built just use it. - meshPtr = meshDesc.Ptr; + meshPtr = meshDesc.ptr; } else { - // always pass false for physicalness as this creates some sort of bounding box which we don't need - meshData = PhysicsScene.mesher.CreateMesh(prim.PhysObjectName, pbs, shapeData.Size, lod, false); + // Pass false for physicalness as this creates some sort of bounding box which we don't need + meshData = PhysicsScene.mesher.CreateMesh(objName, pbs, size, lod, false); int[] indices = meshData.getIndexListAsInt(); List vertices = meshData.getVertexList(); @@ -490,56 +476,62 @@ public class BSShapeCollection : IDisposable meshPtr = BulletSimAPI.CreateMeshShape2(PhysicsScene.World.ptr, indices.GetLength(0), indices, vertices.Count, verticesAsFloats); } - newShape = new BulletShape(meshPtr, ShapeData.PhysicsShapeType.SHAPE_MESH); + BulletShape newShape = new BulletShape(meshPtr, ShapeData.PhysicsShapeType.SHAPE_MESH); newShape.shapeKey = newMeshKey; - ReferenceShape(newShape, meshData); - - // meshes are already scaled by the meshmerizer - prim.Scale = new OMV.Vector3(1f, 1f, 1f); - prim.BSShape = newShape; - return true; // 'true' means a new shape has been added to this prim + return newShape; } - // Returns 'true' of a mesh was actually rebuild (we could also have one of these specs). - List m_hulls; - private bool CreateGeomHull(BSPrim prim, ShapeData shapeData, PrimitiveBaseShape pbs) + // See that hull shape exists in the physical world and update prim.BSShape. + // We could be creating the hull because scale changed or whatever. + private bool GetReferenceToHull(BSPrim prim, ShapeData shapeData, PrimitiveBaseShape pbs) { BulletShape newShape; - // Level of detail for the mesh can be different for sculpties and regular meshes. - float lod = pbs.SculptEntry ? PhysicsScene.SculptLOD : PhysicsScene.MeshLOD; - - ulong newHullKey = (ulong)pbs.GetMeshKey(shapeData.Size, lod); + float lod; + ulong newHullKey = ComputeShapeKey(shapeData, pbs, out lod); // if the hull hasn't changed, don't rebuild it if (newHullKey == prim.BSShape.shapeKey) return false; - DetailLog("{0},BSShapeCollection.CreateGeomHull,create,oldKey={1},newKey={2}", prim.LocalID, newHullKey, newHullKey); + DetailLog("{0},BSShapeCollection.CreateGeomHull,create,oldKey={1},newKey={2}", + prim.LocalID, prim.BSShape.shapeKey.ToString("X"), newHullKey.ToString("X")); - // Remove references to the previous shape. Also removes reference to underlying mesh. + // Remove usage of the previous shape. Also removes reference to underlying mesh if it is a hull. DereferenceShape(prim.BSShape, true); - // Do not let the mesh dereference itself again. Was done in the above DerefereceShape(). - prim.BSShape.type = ShapeData.PhysicsShapeType.SHAPE_UNKNOWN; - - // Make sure the underlying mesh exists and is correct. - // Since we're in the hull code, we know CreateGeomMesh() will not create a native shape. - CreateGeomMesh(prim, shapeData, pbs); - MeshDesc meshDesc = Meshes[newHullKey]; + newShape = CreatePhysicalHull(prim.PhysObjectName, newHullKey, pbs, shapeData.Size, lod); + + if (!ReferenceShape(newShape)) + { + PhysicsScene.Logger.ErrorFormat("{0} Created new hull shape but one already exists: id={1}, key={2}, refCnt={3}", + LogHeader, shapeData.ID, newHullKey.ToString("X"), Hulls[newHullKey].referenceCount); + } + // hulls are already scaled by the meshmerizer + prim.Scale = new OMV.Vector3(1f, 1f, 1f); + prim.BSShape = newShape; + return true; // 'true' means a new shape has been added to this prim + } + + List m_hulls; + private BulletShape CreatePhysicalHull(string objName, ulong newHullKey, PrimitiveBaseShape pbs, OMV.Vector3 size, float lod) + { IntPtr hullPtr; HullDesc hullDesc; if (Hulls.TryGetValue(newHullKey, out hullDesc)) { // If the hull shape already is created, just use it. - hullPtr = hullDesc.Ptr; + hullPtr = hullDesc.ptr; } else { // Build a new hull in the physical world - int[] indices = meshDesc.meshData.getIndexListAsInt(); - List vertices = meshDesc.meshData.getVertexList(); + // Pass false for physicalness as this creates some sort of bounding box which we don't need + IMesh meshData = PhysicsScene.mesher.CreateMesh(objName, pbs, size, lod, false); + + int[] indices = meshData.getIndexListAsInt(); + List vertices = meshData.getVertexList(); //format conversion from IMesh format to DecompDesc format List convIndices = new List(); @@ -616,20 +608,13 @@ public class BSShapeCollection : IDisposable } } // create the hull data structure in Bullet - // m_log.DebugFormat("{0}: CreateGeom: calling CreateHull. lid={1}, key={2}, hulls={3}", LogHeader, LocalID, _hullKey, hullCount); hullPtr = BulletSimAPI.CreateHullShape2(PhysicsScene.World.ptr, hullCount, convHulls); } - newShape = new BulletShape(hullPtr, ShapeData.PhysicsShapeType.SHAPE_HULL); + BulletShape newShape = new BulletShape(hullPtr, ShapeData.PhysicsShapeType.SHAPE_HULL); newShape.shapeKey = newHullKey; - newShape.meshPtr = meshDesc.Ptr; - - ReferenceShape(newShape); - // meshes and hulls are already scaled by the meshmerizer - prim.Scale = new OMV.Vector3(1f, 1f, 1f); - prim.BSShape = newShape; - return true; // 'true' means a new shape has been added to this prim + return newShape; // 'true' means a new shape has been added to this prim } // Callback from convex hull creater with a newly created hull. @@ -640,7 +625,30 @@ public class BSShapeCollection : IDisposable return; } - // Create an object in Bullet if it has not already been created. + // Create a hash of all the shape parameters to be used as a key + // for this particular shape. + private ulong ComputeShapeKey(ShapeData shapeData, PrimitiveBaseShape pbs, out float retLod) + { + // level of detail based on size and type of the object + float lod = PhysicsScene.MeshLOD; + if (pbs.SculptEntry) + lod = PhysicsScene.SculptLOD; + + float maxAxis = Math.Max(shapeData.Size.X, Math.Max(shapeData.Size.Y, shapeData.Size.Z)); + if (maxAxis > PhysicsScene.MeshMegaPrimThreshold) + lod = PhysicsScene.MeshMegaPrimLOD; + + retLod = lod; + return (ulong)pbs.GetMeshKey(shapeData.Size, lod); + } + // For those who don't want the LOD + private ulong ComputeShapeKey(ShapeData shapeData, PrimitiveBaseShape pbs) + { + float lod; + return ComputeShapeKey(shapeData, pbs, out lod); + } + + // 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. @@ -665,7 +673,7 @@ public class BSShapeCollection : IDisposable } - if (mustRebuild) + if (mustRebuild || forceRebuild) { DereferenceBody(prim.BSBody, true); @@ -673,13 +681,15 @@ public class BSShapeCollection : IDisposable IntPtr bodyPtr = IntPtr.Zero; if (prim.IsSolid) { - bodyPtr = BulletSimAPI.CreateBodyFromShape2(sim.ptr, shape.ptr, shapeData.Position, shapeData.Rotation); - DetailLog("{0},BSShapeCollection.CreateObject,mesh,ptr={1:X}", prim.LocalID, bodyPtr); + bodyPtr = BulletSimAPI.CreateBodyFromShape2(sim.ptr, shape.ptr, + shapeData.ID, shapeData.Position, shapeData.Rotation); + DetailLog("{0},BSShapeCollection.CreateBody,mesh,ptr={1}", prim.LocalID, bodyPtr.ToString("X")); } else { - bodyPtr = BulletSimAPI.CreateGhostFromShape2(sim.ptr, shape.ptr, shapeData.Position, shapeData.Rotation); - DetailLog("{0},BSShapeCollection.CreateObject,ghost,ptr={1:X}", prim.LocalID, bodyPtr); + bodyPtr = BulletSimAPI.CreateGhostFromShape2(sim.ptr, shape.ptr, + shapeData.ID, shapeData.Position, shapeData.Rotation); + DetailLog("{0},BSShapeCollection.CreateBody,ghost,ptr={1}", prim.LocalID, bodyPtr.ToString("X")); } aBody = new BulletBody(shapeData.ID, bodyPtr); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs index 093d2a4..5d5d9cb 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs @@ -111,8 +111,12 @@ public class BSTerrainManager BulletSimAPI.CreateGroundPlaneShape2(BSScene.GROUNDPLANE_ID, 1f, TERRAIN_COLLISION_MARGIN), ShapeData.PhysicsShapeType.SHAPE_GROUNDPLANE); m_groundPlane = new BulletBody(BSScene.GROUNDPLANE_ID, - BulletSimAPI.CreateBodyWithDefaultMotionState2(groundPlaneShape.ptr, Vector3.Zero, Quaternion.Identity)); + BulletSimAPI.CreateBodyWithDefaultMotionState2(groundPlaneShape.ptr, BSScene.GROUNDPLANE_ID, + Vector3.Zero, Quaternion.Identity)); BulletSimAPI.AddObjectToWorld2(PhysicsScene.World.ptr, m_groundPlane.ptr); + // Everything collides with the ground plane. + BulletSimAPI.SetCollisionFilterMask2(m_groundPlane.ptr, + (uint)CollisionFilterGroups.GroundPlaneFilter, (uint)CollisionFilterGroups.GroundPlaneMask); Vector3 minTerrainCoords = new Vector3(0f, 0f, HEIGHT_INITIALIZATION - HEIGHT_EQUAL_FUDGE); Vector3 maxTerrainCoords = new Vector3(DefaultRegionSize.X, DefaultRegionSize.Y, HEIGHT_INITIALIZATION); @@ -304,7 +308,11 @@ public class BSTerrainManager mapInfo.terrainBody = new BulletBody(mapInfo.ID, BulletSimAPI.CreateBodyWithDefaultMotionState2(mapInfo.terrainShape.ptr, - centerPos, Quaternion.Identity)); + id, centerPos, Quaternion.Identity)); + + BulletSimAPI.SetCollisionFilterMask2(mapInfo.terrainBody.ptr, + (uint)CollisionFilterGroups.TerrainFilter, + (uint)CollisionFilterGroups.TerrainMask); } // Make sure the entry is in the heightmap table diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs index 8480dd1..6910050 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs @@ -57,9 +57,13 @@ public struct BulletBody { ID = id; ptr = xx; + collisionFilter = 0; + collisionMask = 0; } public IntPtr ptr; public uint ID; + public CollisionFilterGroups collisionFilter; + public CollisionFilterGroups collisionMask; public override string ToString() { StringBuilder buff = new StringBuilder(); @@ -67,6 +71,13 @@ public struct BulletBody buff.Append(ID.ToString()); buff.Append(",p="); buff.Append(ptr.ToString("X")); + if (collisionFilter != 0 && collisionMask != 0) + { + buff.Append(",f="); + buff.Append(collisionFilter.ToString("X")); + buff.Append(",m="); + buff.Append(collisionMask.ToString("X")); + } buff.Append(">"); return buff.ToString(); } @@ -80,7 +91,6 @@ public struct BulletShape type=ShapeData.PhysicsShapeType.SHAPE_UNKNOWN; shapeKey = 0; isNativeShape = false; - meshPtr = IntPtr.Zero; } public BulletShape(IntPtr xx, ShapeData.PhysicsShapeType typ) { @@ -88,14 +98,12 @@ public struct BulletShape type = typ; shapeKey = 0; isNativeShape = false; - meshPtr = IntPtr.Zero; } public IntPtr ptr; public ShapeData.PhysicsShapeType type; public ulong shapeKey; public bool isNativeShape; // Hulls have an underlying mesh. A pointer to it is hidden here. - public IntPtr meshPtr; public override string ToString() { StringBuilder buff = new StringBuilder(); @@ -107,8 +115,6 @@ public struct BulletShape buff.Append(shapeKey.ToString("X")); buff.Append(",n="); buff.Append(isNativeShape.ToString()); - buff.Append(",m="); - buff.Append(meshPtr.ToString("X")); buff.Append(">"); return buff.ToString(); } @@ -124,7 +130,7 @@ public struct BulletConstraint public IntPtr Ptr; } -// An allocated HeightMapThing which hold various heightmap info +// An allocated HeightMapThing which holds various heightmap info. // Made a class rather than a struct so there would be only one // instance of this and C# will pass around pointers rather // than making copies. @@ -345,21 +351,41 @@ public enum CollisionFlags : uint // Values for collisions groups and masks public enum CollisionFilterGroups : uint { - NoneFilter = 0, - DefaultFilter = 1 << 0, - StaticFilter = 1 << 1, - KinematicFilter = 1 << 2, - DebrisFilter = 1 << 3, - SensorTrigger = 1 << 4, - CharacterFilter = 1 << 5, - AllFilter = 0xFFFFFFFF, + // Don't use the bit definitions!! Define the use in a + // filter/mask definition below. This way collision interactions + // are more easily debugged. + BNoneFilter = 0, + BDefaultFilter = 1 << 0, + BStaticFilter = 1 << 1, + BKinematicFilter = 1 << 2, + BDebrisFilter = 1 << 3, + BSensorTrigger = 1 << 4, + BCharacterFilter = 1 << 5, + BAllFilter = 0xFFFFFFFF, // Filter groups defined by BulletSim - GroundPlaneFilter = 1 << 10, - TerrainFilter = 1 << 11, - RaycastFilter = 1 << 12, - SolidFilter = 1 << 13, + BGroundPlaneFilter = 1 << 10, + BTerrainFilter = 1 << 11, + BRaycastFilter = 1 << 12, + BSolidFilter = 1 << 13, + + // The collsion filters and masked are defined in one place -- don't want them scattered + AvatarFilter = BDefaultFilter | BCharacterFilter | BSolidFilter, + AvatarMask = BAllFilter, + ObjectFilter = BDefaultFilter | BSolidFilter, + ObjectMask = BAllFilter, + StaticObjectFilter = BDefaultFilter | BStaticFilter | BSolidFilter, + StaticObjectMask = BAllFilter, + VolumeDetectFilter = BSensorTrigger, + VolumeDetectMask = ~BSensorTrigger, + TerrainFilter = BTerrainFilter, + TerrainMask = BAllFilter, + GroundPlaneFilter = BAllFilter, + GroundPlaneMask = BAllFilter + }; + + // CFM controls the 'hardness' of the constraint. 0=fixed, 0..1=violatable. Default=0 // ERP controls amount of correction per tick. Usable range=0.1..0.8. Default=0.2. public enum ConstraintParams : int @@ -560,7 +586,7 @@ public static extern IntPtr CreateHullShape2(IntPtr world, int hullCount, [MarshalAs(UnmanagedType.LPArray)] float[] hulls); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern IntPtr BuildHullShape2(IntPtr world, IntPtr meshShape); +public static extern IntPtr BuildHullShapeFromMesh2(IntPtr world, IntPtr meshShape); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern IntPtr BuildNativeShape2(IntPtr world, ShapeData shapeData); @@ -581,7 +607,7 @@ public static extern void RemoveChildFromCompoundShape2(IntPtr cShape, IntPtr re public static extern IntPtr DuplicateCollisionShape2(IntPtr sim, IntPtr srcShape, uint id); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern IntPtr CreateBodyFromShapeAndInfo2(IntPtr sim, IntPtr shape, IntPtr constructionInfo); +public static extern IntPtr CreateBodyFromShapeAndInfo2(IntPtr sim, IntPtr shape, uint id, IntPtr constructionInfo); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern bool DeleteCollisionShape2(IntPtr world, IntPtr shape); @@ -590,13 +616,13 @@ public static extern bool DeleteCollisionShape2(IntPtr world, IntPtr shape); public static extern int GetBodyType2(IntPtr obj); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern IntPtr CreateBodyFromShape2(IntPtr sim, IntPtr shape, Vector3 pos, Quaternion rot); +public static extern IntPtr CreateBodyFromShape2(IntPtr sim, IntPtr shape, uint id, Vector3 pos, Quaternion rot); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern IntPtr CreateBodyWithDefaultMotionState2(IntPtr shape, Vector3 pos, Quaternion rot); +public static extern IntPtr CreateBodyWithDefaultMotionState2(IntPtr shape, uint id, Vector3 pos, Quaternion rot); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern IntPtr CreateGhostFromShape2(IntPtr sim, IntPtr shape, Vector3 pos, Quaternion rot); +public static extern IntPtr CreateGhostFromShape2(IntPtr sim, IntPtr shape, uint id, Vector3 pos, Quaternion rot); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern IntPtr AllocateBodyInfo2(IntPtr obj); @@ -1015,6 +1041,9 @@ public static extern Vector3 GetPushVelocity2(IntPtr obj); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern Vector3 GetTurnVelocity2(IntPtr obj); +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void SetCollisionFilterMask2(IntPtr body, uint filter, uint mask); + // ===================================================================================== // btCollisionShape entries @@ -1066,9 +1095,6 @@ public static extern void SetMargin2(IntPtr shape, float val); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern float GetMargin2(IntPtr shape); -[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern void SetCollisionFilterMask(IntPtr shape, uint filter, uint mask); - // ===================================================================================== // Debugging [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -- cgit v1.1 From 4589bc84a32366c6aae68b67f1fc7a2ee08be86d Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Wed, 26 Sep 2012 09:25:56 -0700 Subject: BulletSim: Terrain sets proper collision flags on creation. Static objects are set to ISLAND_SLEEPING rather than DISABLE_SIMULATION. Might reconsider this and, alternatively, have dynamic objects force activation. Clean up use of DetailLog(). --- .../Region/Physics/BulletSPlugin/BSPhysObject.cs | 10 ++-- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 62 +++++++++++----------- .../Physics/BulletSPlugin/BSShapeCollection.cs | 16 ++++-- .../Physics/BulletSPlugin/BSTerrainManager.cs | 20 +++---- 4 files changed, 56 insertions(+), 52 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index 3458477..4f83adc 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -121,8 +121,8 @@ public abstract class BSPhysObject : PhysicsActor // if someone has subscribed for collision events.... if (SubscribedEvents()) { CollisionCollection.AddCollider(collidingWith, new ContactPoint(contactPoint, contactNormal, pentrationDepth)); - DetailLog("{0},{1}.Collison.AddCollider,call,with={2},point={3},normal={4},depth={5}", - LocalID, TypeName, collidingWith, contactPoint, contactNormal, pentrationDepth); + // DetailLog("{0},{1}.Collison.AddCollider,call,with={2},point={3},normal={4},depth={5}", + // LocalID, TypeName, collidingWith, contactPoint, contactNormal, pentrationDepth); ret = true; } @@ -151,7 +151,7 @@ public abstract class BSPhysObject : PhysicsActor PhysicsScene.ObjectsWithNoMoreCollisions.Add(this); } - DetailLog("{0},{1}.SendCollisionUpdate,call,numCollisions={2}", LocalID, TypeName, CollisionCollection.Count); + // DetailLog("{0},{1}.SendCollisionUpdate,call,numCollisions={2}", LocalID, TypeName, CollisionCollection.Count); base.SendCollisionUpdate(CollisionCollection); // The collisionCollection structure is passed around in the simulator. @@ -163,7 +163,7 @@ public abstract class BSPhysObject : PhysicsActor // Subscribe for collision events. // Parameter is the millisecond rate the caller wishes collision events to occur. public override void SubscribeEvents(int ms) { - DetailLog("{0},{1}.SubscribeEvents,subscribing,ms={2}", LocalID, TypeName, ms); + // DetailLog("{0},{1}.SubscribeEvents,subscribing,ms={2}", LocalID, TypeName, ms); SubscribedEventsMs = ms; if (ms > 0) { @@ -182,7 +182,7 @@ public abstract class BSPhysObject : PhysicsActor } } public override void UnSubscribeEvents() { - DetailLog("{0},{1}.UnSubscribeEvents,unsubscribing", LocalID, TypeName); + // DetailLog("{0},{1}.UnSubscribeEvents,unsubscribing", LocalID, TypeName); SubscribedEventsMs = 0; PhysicsScene.TaintedObject(TypeName+".UnSubscribeEvents", delegate() { diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 1c6d476..68a153e 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -174,7 +174,7 @@ public sealed class BSPrim : BSPhysObject // Since _size changed, the mesh needs to be rebuilt. If rebuilt, all the correct // scale and margins are set. CreateGeomAndObject(true); - DetailLog("{0},BSPrim.setSize,size={1},scale={2},mass={3},physical={4}", LocalID, _size, _scale, _mass, IsPhysical); + // DetailLog("{0},BSPrim.setSize,size={1},scale={2},mass={3},physical={4}", LocalID, _size, _scale, _mass, IsPhysical); }); } } @@ -204,6 +204,7 @@ public sealed class BSPrim : BSPhysObject _isSelected = value; PhysicsScene.TaintedObject("BSPrim.setSelected", delegate() { + // DetailLog("{0},BSPrim.selected,taint,selected={1}", LocalID, _isSelected); SetObjectDynamic(false); }); } @@ -279,7 +280,7 @@ public sealed class BSPrim : BSPhysObject // TODO: what does it mean to set the position of a child prim?? Rebuild the constraint? PhysicsScene.TaintedObject("BSPrim.setPosition", delegate() { - DetailLog("{0},BSPrim.SetPosition,taint,pos={1},orient={2}", LocalID, _position, _orientation); + // DetailLog("{0},BSPrim.SetPosition,taint,pos={1},orient={2}", LocalID, _position, _orientation); BulletSimAPI.SetTranslation2(BSBody.ptr, _position, _orientation); }); } @@ -317,7 +318,7 @@ public sealed class BSPrim : BSPhysObject _force = value; PhysicsScene.TaintedObject("BSPrim.setForce", delegate() { - DetailLog("{0},BSPrim.setForce,taint,force={1}", LocalID, _force); + // DetailLog("{0},BSPrim.setForce,taint,force={1}", LocalID, _force); BulletSimAPI.SetObjectForce2(BSBody.ptr, _force); }); } @@ -385,7 +386,7 @@ public sealed class BSPrim : BSPhysObject _isVolumeDetect = newValue; PhysicsScene.TaintedObject("BSPrim.SetVolumeDetect", delegate() { - DetailLog("{0},setVolumeDetect,taint,volDetect={1}", LocalID, _isVolumeDetect); + // DetailLog("{0},setVolumeDetect,taint,volDetect={1}", LocalID, _isVolumeDetect); SetObjectDynamic(true); }); } @@ -398,7 +399,7 @@ public sealed class BSPrim : BSPhysObject _velocity = value; PhysicsScene.TaintedObject("BSPrim.setVelocity", delegate() { - DetailLog("{0},BSPrim.SetVelocity,taint,vel={1}", LocalID, _velocity); + // DetailLog("{0},BSPrim.SetVelocity,taint,vel={1}", LocalID, _velocity); BulletSimAPI.SetLinearVelocity2(BSBody.ptr, _velocity); }); } @@ -406,7 +407,7 @@ public sealed class BSPrim : BSPhysObject public override OMV.Vector3 Torque { get { return _torque; } set { _torque = value; - DetailLog("{0},BSPrim.SetTorque,call,torque={1}", LocalID, _torque); + // DetailLog("{0},BSPrim.SetTorque,call,torque={1}", LocalID, _torque); } } public override float CollisionScore { @@ -433,7 +434,7 @@ public sealed class BSPrim : BSPhysObject PhysicsScene.TaintedObject("BSPrim.setOrientation", delegate() { // _position = BulletSimAPI.GetObjectPosition2(PhysicsScene.World.ptr, BSBody.ptr); - DetailLog("{0},BSPrim.setOrientation,taint,pos={1},orient={2}", LocalID, _position, _orientation); + // DetailLog("{0},BSPrim.setOrientation,taint,pos={1},orient={2}", LocalID, _position, _orientation); BulletSimAPI.SetTranslation2(BSBody.ptr, _position, _orientation); }); } @@ -450,7 +451,7 @@ public sealed class BSPrim : BSPhysObject _isPhysical = value; PhysicsScene.TaintedObject("BSPrim.setIsPhysical", delegate() { - DetailLog("{0},setIsPhysical,taint,isPhys={1}", LocalID, _isPhysical); + // DetailLog("{0},setIsPhysical,taint,isPhys={1}", LocalID, _isPhysical); SetObjectDynamic(true); }); } @@ -470,12 +471,7 @@ public sealed class BSPrim : BSPhysObject } // Make gravity work if the object is physical and not selected - // No locking here because only called when it is safe (called at taint-time). - // There are four flags we're interested in: - // IsStatic: Object does not move, otherwise the object has mass and moves - // isSolid: other objects bounce off of this object - // isVolumeDetect: other objects pass through but can generate collisions - // collisionEvents: whether this object returns collision events + // Called at taint-time!! private void SetObjectDynamic(bool forceRebuild) { #if CSHARP_BODY_MANAGEMENT @@ -488,11 +484,17 @@ public sealed class BSPrim : BSPhysObject #endif // CSHARP_BODY_MANAGEMENT } + // Convert the simulator's physical properties into settings on BulletSim objects. + // There are four flags we're interested in: + // IsStatic: Object does not move, otherwise the object has mass and moves + // isSolid: other objects bounce off of this object + // isVolumeDetect: other objects pass through but can generate collisions + // collisionEvents: whether this object returns collision events private void UpdatePhysicalParameters() { - DetailLog("{0},BSPrim.UpdatePhysicalParameters,entry,body={1},shape={2}", LocalID, BSBody, BSShape); + // DetailLog("{0},BSPrim.UpdatePhysicalParameters,entry,body={1},shape={2}", LocalID, BSBody, BSShape); - // Mangling all the physical properties requires the object to be out of the physical world. + // 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). BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.ptr, BSBody.ptr); @@ -505,7 +507,7 @@ public sealed class BSPrim : BSPhysObject // Set up the object physicalness (does gravity and collisions move this object) MakeDynamic(IsStatic); - // Arrange for collisions events if the simulator wants them + // Arrange for collision events if the simulator wants them EnableCollisions(SubscribedEvents()); #if CSHARP_BODY_MANAGEMENT @@ -522,8 +524,6 @@ public sealed class BSPrim : BSPhysObject if (BSBody.collisionFilter != 0 || BSBody.collisionMask != 0) { BulletSimAPI.SetCollisionFilterMask2(BSBody.ptr, (uint)BSBody.collisionFilter, (uint)BSBody.collisionMask); - DetailLog("{0},BSPrim.UpdatePhysicalParameters,setCollisionFilterMask,filter={1},mask={2}", - LocalID, BSBody.collisionFilter.ToString("X"), BSBody.collisionMask.ToString("X")); } // Recompute any linkset parameters. @@ -557,8 +557,8 @@ public sealed class BSPrim : BSPhysObject // There can be special things needed for implementing linksets Linkset.MakeStatic(this); // The activation state is 'sleeping' so Bullet will not try to act on it - // BulletSimAPI.ForceActivationState2(BSBody.ptr, ActivationState.ISLAND_SLEEPING); - BulletSimAPI.ForceActivationState2(BSBody.ptr, ActivationState.DISABLE_SIMULATION); + BulletSimAPI.ForceActivationState2(BSBody.ptr, ActivationState.ISLAND_SLEEPING); + // BulletSimAPI.ForceActivationState2(BSBody.ptr, ActivationState.DISABLE_SIMULATION); BSBody.collisionFilter = CollisionFilterGroups.StaticObjectFilter; BSBody.collisionMask = CollisionFilterGroups.StaticObjectMask; @@ -571,16 +571,14 @@ public sealed class BSPrim : BSPhysObject // Set various physical properties so internal dynamic properties will get computed correctly as they are set BulletSimAPI.SetFriction2(BSBody.ptr, PhysicsScene.Params.defaultFriction); BulletSimAPI.SetRestitution2(BSBody.ptr, PhysicsScene.Params.defaultRestitution); + // per http://www.bulletphysics.org/Bullet/phpBB3/viewtopic.php?t=3382 - BulletSimAPI.SetInterpolationLinearVelocity2(BSBody.ptr, OMV.Vector3.Zero); - BulletSimAPI.SetInterpolationAngularVelocity2(BSBody.ptr, OMV.Vector3.Zero); - BulletSimAPI.SetInterpolationVelocity2(BSBody.ptr, OMV.Vector3.Zero, OMV.Vector3.Zero); + BulletSimAPI.ClearAllForces2(BSBody.ptr); // A dynamic object has mass IntPtr collisionShapePtr = BulletSimAPI.GetCollisionShape2(BSBody.ptr); OMV.Vector3 inertia = BulletSimAPI.CalculateLocalInertia2(collisionShapePtr, Linkset.LinksetMass); BulletSimAPI.SetMassProps2(BSBody.ptr, _mass, inertia); - // Inertia is based on our new mass BulletSimAPI.UpdateInertiaTensor2(BSBody.ptr); // Various values for simulation limits @@ -645,7 +643,7 @@ public sealed class BSPrim : BSPhysObject // Create the new body with the shape BSBody = new BulletBody(LocalID, BulletSimAPI.CreateBodyFromShape2(PhysicsScene.World.Ptr, BSShape.Ptr, _position, _orientation)); - BulletSimAPI.RemoveFromCollisionFlags2(BSBody.Ptr, CollisionFlags.CF_NO_CONTACT_RESPONSE); + CurrentCollisionFlags = BulletSimAPI.RemoveFromCollisionFlags2(BSBody.Ptr, CollisionFlags.CF_NO_CONTACT_RESPONSE); DetailLog("{0},BSPrim.MakeSolid:rigidBody,body={1},shape={2}", LocalID, BSBody, BSShape); } } @@ -741,7 +739,7 @@ public sealed class BSPrim : BSPhysObject // m_log.DebugFormat("{0}: RotationalVelocity={1}", LogHeader, _rotationalVelocity); PhysicsScene.TaintedObject("BSPrim.setRotationalVelocity", delegate() { - DetailLog("{0},BSPrim.SetRotationalVel,taint,rotvel={1}", LocalID, _rotationalVelocity); + // DetailLog("{0},BSPrim.SetRotationalVel,taint,rotvel={1}", LocalID, _rotationalVelocity); BulletSimAPI.SetAngularVelocity2(BSBody.ptr, _rotationalVelocity); }); } @@ -758,7 +756,7 @@ public sealed class BSPrim : BSPhysObject _buoyancy = value; PhysicsScene.TaintedObject("BSPrim.setBuoyancy", delegate() { - DetailLog("{0},BSPrim.SetBuoyancy,taint,buoy={1}", LocalID, _buoyancy); + // DetailLog("{0},BSPrim.SetBuoyancy,taint,buoy={1}", LocalID, _buoyancy); // Buoyancy is faked by changing the gravity applied to the object float grav = PhysicsScene.Params.gravity * (1f - _buoyancy); BulletSimAPI.SetGravity2(BSBody.ptr, new OMV.Vector3(0f, 0f, grav)); @@ -823,18 +821,18 @@ public sealed class BSPrim : BSPhysObject } m_accumulatedForces.Clear(); } - DetailLog("{0},BSPrim.AddObjectForce,taint,force={1}", LocalID, fSum); + // DetailLog("{0},BSPrim.AddObjectForce,taint,force={1}", LocalID, fSum); // For unknown reasons, "ApplyCentralForce" adds this force to the total force on the object. BulletSimAPI.ApplyCentralForce2(BSBody.ptr, fSum); }); } public override void AddAngularForce(OMV.Vector3 force, bool pushforce) { - DetailLog("{0},BSPrim.AddAngularForce,call,angForce={1},push={2}", LocalID, force, pushforce); + // DetailLog("{0},BSPrim.AddAngularForce,call,angForce={1},push={2}", LocalID, force, pushforce); // m_log.DebugFormat("{0}: AddAngularForce. f={1}, push={2}", LogHeader, force, pushforce); } public override void SetMomentum(OMV.Vector3 momentum) { - DetailLog("{0},BSPrim.SetMomentum,call,mom={1}", LocalID, momentum); + // DetailLog("{0},BSPrim.SetMomentum,call,mom={1}", LocalID, momentum); } #region Mass Calculation @@ -1452,7 +1450,7 @@ public sealed class BSPrim : BSPhysObject } // Rebuild the geometry and object. // This is called when the shape changes so we need to recreate the mesh/hull. - // No locking here because this is done when the physics engine is not simulating (taint-time). + // Called at taint-time!!! private void CreateGeomAndObject(bool forceRebuild) { #if CSHARP_BODY_MANAGEMENT diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index 7fce8c9..aadb8d6 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -344,7 +344,10 @@ public class BSShapeCollection : IDisposable if (pbs.ProfileShape == ProfileShape.HalfCircle && pbs.PathCurve == (byte)Extrusion.Curve1) { haveShape = true; - if (forceRebuild || (prim.BSShape.type != ShapeData.PhysicsShapeType.SHAPE_SPHERE)) + if (forceRebuild + || prim.Scale != shapeData.Size + || prim.BSShape.type != ShapeData.PhysicsShapeType.SHAPE_SPHERE + ) { ret = GetReferenceToNativeShape(prim, shapeData, ShapeData.PhysicsShapeType.SHAPE_SPHERE, ShapeData.FixedShapeKey.KEY_SPHERE); @@ -355,7 +358,10 @@ public class BSShapeCollection : IDisposable else { haveShape = true; - if (forceRebuild || (prim.BSShape.type != ShapeData.PhysicsShapeType.SHAPE_BOX)) + if (forceRebuild + || prim.Scale != shapeData.Size + || prim.BSShape.type != ShapeData.PhysicsShapeType.SHAPE_BOX + ) { ret = GetReferenceToNativeShape( prim, shapeData, ShapeData.PhysicsShapeType.SHAPE_BOX, ShapeData.FixedShapeKey.KEY_BOX); @@ -406,7 +412,7 @@ public class BSShapeCollection : IDisposable newShape.isNativeShape = true; // Don't need to do a 'ReferenceShape()' here because native shapes are not tracked. - DetailLog("{0},BSShapeCollection.AddNativeShapeToPrim,create,newshape={1}", shapeData.ID, newShape); + // DetailLog("{0},BSShapeCollection.AddNativeShapeToPrim,create,newshape={1}", shapeData.ID, newShape); prim.BSShape = newShape; return true; @@ -683,13 +689,13 @@ public class BSShapeCollection : IDisposable { bodyPtr = BulletSimAPI.CreateBodyFromShape2(sim.ptr, shape.ptr, shapeData.ID, shapeData.Position, shapeData.Rotation); - DetailLog("{0},BSShapeCollection.CreateBody,mesh,ptr={1}", prim.LocalID, bodyPtr.ToString("X")); + // DetailLog("{0},BSShapeCollection.CreateBody,mesh,ptr={1}", prim.LocalID, bodyPtr.ToString("X")); } else { bodyPtr = BulletSimAPI.CreateGhostFromShape2(sim.ptr, shape.ptr, shapeData.ID, shapeData.Position, shapeData.Rotation); - DetailLog("{0},BSShapeCollection.CreateBody,ghost,ptr={1}", prim.LocalID, bodyPtr.ToString("X")); + // DetailLog("{0},BSShapeCollection.CreateBody,ghost,ptr={1}", prim.LocalID, bodyPtr.ToString("X")); } aBody = new BulletBody(shapeData.ID, bodyPtr); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs index 5d5d9cb..50638d6 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs @@ -201,10 +201,10 @@ public class BSTerrainManager // The 'doNow' boolean says whether to do all the unmanaged activities right now (like when // calling this routine from initialization or taint-time routines) or whether to delay // all the unmanaged activities to taint-time. - private void UpdateOrCreateTerrain(uint id, float[] heightMap, Vector3 minCoords, Vector3 maxCoords, bool doNow) + private void UpdateOrCreateTerrain(uint id, float[] heightMap, Vector3 minCoords, Vector3 maxCoords, bool atTaintTime) { - DetailLog("{0},BSTerrainManager.UpdateOrCreateTerrain,call,minC={1},maxC={2},doNow={3}", - BSScene.DetailLogZero, minCoords, maxCoords, doNow); + DetailLog("{0},BSTerrainManager.UpdateOrCreateTerrain,call,minC={1},maxC={2},atTaintTime={3}", + BSScene.DetailLogZero, minCoords, maxCoords, atTaintTime); float minZ = float.MaxValue; float maxZ = float.MinValue; @@ -308,11 +308,7 @@ public class BSTerrainManager mapInfo.terrainBody = new BulletBody(mapInfo.ID, BulletSimAPI.CreateBodyWithDefaultMotionState2(mapInfo.terrainShape.ptr, - id, centerPos, Quaternion.Identity)); - - BulletSimAPI.SetCollisionFilterMask2(mapInfo.terrainBody.ptr, - (uint)CollisionFilterGroups.TerrainFilter, - (uint)CollisionFilterGroups.TerrainMask); + id, centerPos, Quaternion.Identity)); } // Make sure the entry is in the heightmap table @@ -333,6 +329,10 @@ public class BSTerrainManager // redo its bounding box now that it is in the world BulletSimAPI.UpdateSingleAabb2(PhysicsScene.World.ptr, mapInfo.terrainBody.ptr); + BulletSimAPI.SetCollisionFilterMask2(mapInfo.terrainBody.ptr, + (uint)CollisionFilterGroups.TerrainFilter, + (uint)CollisionFilterGroups.TerrainMask); + // Make sure the new shape is processed. BulletSimAPI.Activate2(mapInfo.terrainBody.ptr, true); @@ -341,7 +341,7 @@ public class BSTerrainManager // There is the option to do the changes now (we're already in 'taint time'), or // to do the Bullet operations later. - if (doNow) + if (atTaintTime) rebuildOperation(); else PhysicsScene.TaintedObject("BSScene.UpdateOrCreateTerrain:UpdateExisting", rebuildOperation); @@ -380,7 +380,7 @@ public class BSTerrainManager }; // If already in taint-time, just call Bullet. Otherwise queue the operations for the safe time. - if (doNow) + if (atTaintTime) createOperation(); else PhysicsScene.TaintedObject("BSScene.UpdateOrCreateTerrain:NewTerrain", createOperation); -- cgit v1.1 From f82b903deeaaf8eaa7ae5c4d4b7e917dd0a6ce7b Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Thu, 27 Sep 2012 08:23:29 -0700 Subject: BulletSim: Fix linkset crash. Caused by the different body and shape pointers at runtime and at taint-time. Now passes the body into the taint. Vehicles zero inertia when active to eliminate Bullet's contribution to vehicle motion. --- .../Physics/BulletSPlugin/BS6DofConstraint.cs | 20 +++- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 123 ++++++++++++--------- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 75 ++++++++++--- .../Region/Physics/BulletSPlugin/BSPhysObject.cs | 8 +- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 22 +++- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 7 +- .../Physics/BulletSPlugin/BSShapeCollection.cs | 10 +- .../Physics/BulletSPlugin/BSTerrainManager.cs | 3 +- .../Region/Physics/BulletSPlugin/BulletSimAPI.cs | 8 +- 9 files changed, 182 insertions(+), 94 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BS6DofConstraint.cs b/OpenSim/Region/Physics/BulletSPlugin/BS6DofConstraint.cs index ff271fe..39a3421 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BS6DofConstraint.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BS6DofConstraint.cs @@ -58,10 +58,22 @@ public class BS6DofConstraint : BSConstraint m_world = world; m_body1 = obj1; m_body2 = obj2; - m_constraint = new BulletConstraint( - BulletSimAPI.Create6DofConstraintToPoint2(m_world.ptr, m_body1.ptr, m_body2.ptr, - joinPoint, - useLinearReferenceFrameA, disableCollisionsBetweenLinkedBodies)); + if (obj1.ptr == IntPtr.Zero || obj2.ptr == IntPtr.Zero) + { + world.scene.DetailLog("{0},BS6DOFConstraint,badBodyPtr,wID={1}, rID={2}, rBody={3}, cID={4}, cBody={5}", + "[BULLETSIM 6DOF CONSTRAINT]", world.worldID, + obj1.ID, obj1.ptr.ToString("X"), obj2.ID, obj2.ptr.ToString("X")); + world.scene.Logger.ErrorFormat("{0} Attempt to build 6DOF constraint with missing bodies: wID={1}, rID={2}, rBody={3}, cID={4}, cBody={5}", + "[BULLETSIM 6DOF CONSTRAINT]", world.worldID, + obj1.ID, obj1.ptr.ToString("X"), obj2.ID, obj2.ptr.ToString("X")); + } + else + { + m_constraint = new BulletConstraint( + BulletSimAPI.Create6DofConstraintToPoint2(m_world.ptr, m_body1.ptr, m_body2.ptr, + joinPoint, + useLinearReferenceFrameA, disableCollisionsBetweenLinkedBodies)); + } m_enabled = true; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index 2da2331..cf33d0e 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -54,18 +54,13 @@ namespace OpenSim.Region.Physics.BulletSPlugin { public class BSDynamics { - private int frcount = 0; // Used to limit dynamics debug output to - // every 100th frame - - private BSScene m_physicsScene; - private BSPrim m_prim; // the prim this dynamic controller belongs to + private BSScene PhysicsScene { get; set; } + // the prim this dynamic controller belongs to + private BSPrim Prim { get; set; } // Vehicle properties - private Vehicle m_type = Vehicle.TYPE_NONE; // If a 'VEHICLE', and what kind - public Vehicle Type - { - get { return m_type; } - } + public Vehicle Type { get; set; } + // private Quaternion m_referenceFrame = Quaternion.Identity; // Axis modifier private VehicleFlag m_flags = (VehicleFlag) 0; // Boolean settings: // HOVER_TERRAIN_ONLY @@ -126,14 +121,20 @@ namespace OpenSim.Region.Physics.BulletSPlugin public BSDynamics(BSScene myScene, BSPrim myPrim) { - m_physicsScene = myScene; - m_prim = myPrim; - m_type = Vehicle.TYPE_NONE; + PhysicsScene = myScene; + Prim = myPrim; + Type = Vehicle.TYPE_NONE; + } + + // Return 'true' if this vehicle is doing vehicle things + public bool IsActive + { + get { return Type != Vehicle.TYPE_NONE; } } internal void ProcessFloatVehicleParam(Vehicle pParam, float pValue) { - VDetailLog("{0},ProcessFloatVehicleParam,param={1},val={2}", m_prim.LocalID, pParam, pValue); + VDetailLog("{0},ProcessFloatVehicleParam,param={1},val={2}", Prim.LocalID, pParam, pValue); switch (pParam) { case Vehicle.ANGULAR_DEFLECTION_EFFICIENCY: @@ -232,7 +233,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin internal void ProcessVectorVehicleParam(Vehicle pParam, Vector3 pValue) { - VDetailLog("{0},ProcessVectorVehicleParam,param={1},val={2}", m_prim.LocalID, pParam, pValue); + VDetailLog("{0},ProcessVectorVehicleParam,param={1},val={2}", Prim.LocalID, pParam, pValue); switch (pParam) { case Vehicle.ANGULAR_FRICTION_TIMESCALE: @@ -267,7 +268,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin internal void ProcessRotationVehicleParam(Vehicle pParam, Quaternion pValue) { - VDetailLog("{0},ProcessRotationalVehicleParam,param={1},val={2}", m_prim.LocalID, pParam, pValue); + VDetailLog("{0},ProcessRotationalVehicleParam,param={1},val={2}", Prim.LocalID, pParam, pValue); switch (pParam) { case Vehicle.REFERENCE_FRAME: @@ -281,7 +282,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin internal void ProcessVehicleFlags(int pParam, bool remove) { - VDetailLog("{0},ProcessVehicleFlags,param={1},remove={2}", m_prim.LocalID, pParam, remove); + VDetailLog("{0},ProcessVehicleFlags,param={1},remove={2}", Prim.LocalID, pParam, remove); VehicleFlag parm = (VehicleFlag)pParam; if (remove) { @@ -301,9 +302,9 @@ namespace OpenSim.Region.Physics.BulletSPlugin internal void ProcessTypeChange(Vehicle pType) { - VDetailLog("{0},ProcessTypeChange,type={1}", m_prim.LocalID, pType); + VDetailLog("{0},ProcessTypeChange,type={1}", Prim.LocalID, pType); // Set Defaults For Type - m_type = pType; + Type = pType; switch (pType) { case Vehicle.TYPE_NONE: @@ -465,26 +466,37 @@ namespace OpenSim.Region.Physics.BulletSPlugin } }//end SetDefaultsForType + // Some of the properties of this prim may have changed. + // Do any updating needed for a vehicle + public void Refresh() + { + if (Type == Vehicle.TYPE_NONE) return; + + // Set the prim's inertia to zero. The vehicle code handles that and this + // removes the torque action introduced by Bullet. + Vector3 inertia = Vector3.Zero; + BulletSimAPI.SetMassProps2(Prim.BSBody.ptr, Prim.MassRaw, inertia); + BulletSimAPI.UpdateInertiaTensor2(Prim.BSBody.ptr); + } + // One step of the vehicle properties for the next 'pTimestep' seconds. internal void Step(float pTimestep) { - if (m_type == Vehicle.TYPE_NONE) return; - - frcount++; // used to limit debug comment output - if (frcount > 100) - frcount = 0; + if (!IsActive) return; MoveLinear(pTimestep); MoveAngular(pTimestep); LimitRotation(pTimestep); // remember the position so next step we can limit absolute movement effects - m_lastPositionVector = m_prim.Position; + m_lastPositionVector = Prim.Position; VDetailLog("{0},BSDynamics.Step,done,pos={1},force={2},velocity={3},angvel={4}", - m_prim.LocalID, m_prim.Position, m_prim.Force, m_prim.Velocity, m_prim.RotationalVelocity); + Prim.LocalID, Prim.Position, Prim.Force, Prim.Velocity, Prim.RotationalVelocity); }// end Step + // Apply the effect of the linear motor. + // Also does hover and float. private void MoveLinear(float pTimestep) { // m_linearMotorDirection is the direction we are moving relative to the vehicle coordinates @@ -520,18 +532,18 @@ namespace OpenSim.Region.Physics.BulletSPlugin m_linearMotorDirection *= keepfraction; VDetailLog("{0},MoveLinear,nonZero,origdir={1},origvel={2},add={3},notDecay={4},dir={5},vel={6}", - m_prim.LocalID, origDir, origVel, addAmount, keepfraction, m_linearMotorDirection, m_lastLinearVelocityVector); + Prim.LocalID, origDir, origVel, addAmount, keepfraction, m_linearMotorDirection, m_lastLinearVelocityVector); } else { // if what remains of direction is very small, zero it. m_linearMotorDirection = Vector3.Zero; m_lastLinearVelocityVector = Vector3.Zero; - VDetailLog("{0},MoveLinear,zeroed", m_prim.LocalID); + VDetailLog("{0},MoveLinear,zeroed", Prim.LocalID); } // convert requested object velocity to object relative vector - Quaternion rotq = m_prim.Orientation; + Quaternion rotq = Prim.Orientation; m_newVelocity = m_lastLinearVelocityVector * rotq; // Add the various forces into m_dir which will be our new direction vector (velocity) @@ -539,7 +551,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin // add Gravity and Buoyancy // There is some gravity, make a gravity force vector that is applied after object velocity. // m_VehicleBuoyancy: -1=2g; 0=1g; 1=0g; - Vector3 grav = m_prim.PhysicsScene.DefaultGravity * (m_prim.Mass * (1f - m_VehicleBuoyancy)); + Vector3 grav = Prim.PhysicsScene.DefaultGravity * (Prim.Mass * (1f - m_VehicleBuoyancy)); /* * RA: Not sure why one would do this @@ -548,11 +560,11 @@ namespace OpenSim.Region.Physics.BulletSPlugin m_dir.Z = vel_now.Z; // Preserve the accumulated falling velocity */ - Vector3 pos = m_prim.Position; + Vector3 pos = Prim.Position; // Vector3 accel = new Vector3(-(m_dir.X - m_lastLinearVelocityVector.X / 0.1f), -(m_dir.Y - m_lastLinearVelocityVector.Y / 0.1f), m_dir.Z - m_lastLinearVelocityVector.Z / 0.1f); // If below the terrain, move us above the ground a little. - float terrainHeight = m_prim.PhysicsScene.TerrainManager.GetTerrainHeightAtXYZ(pos); + float terrainHeight = Prim.PhysicsScene.TerrainManager.GetTerrainHeightAtXYZ(pos); // Taking the rotated size doesn't work here because m_prim.Size is the size of the root prim and not the linkset. // Need to add a m_prim.LinkSet.Size similar to m_prim.LinkSet.Mass. // Vector3 rotatedSize = m_prim.Size * m_prim.Orientation; @@ -560,8 +572,8 @@ namespace OpenSim.Region.Physics.BulletSPlugin if (pos.Z < terrainHeight) { pos.Z = terrainHeight + 2; - m_prim.Position = pos; - VDetailLog("{0},MoveLinear,terrainHeight,terrainHeight={1},pos={2}", m_prim.LocalID, terrainHeight, pos); + Prim.Position = pos; + VDetailLog("{0},MoveLinear,terrainHeight,terrainHeight={1},pos={2}", Prim.LocalID, terrainHeight, pos); } // Check if hovering @@ -570,7 +582,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin // We should hover, get the target height if ((m_flags & VehicleFlag.HOVER_WATER_ONLY) != 0) { - m_VhoverTargetHeight = m_prim.PhysicsScene.GetWaterLevelAtXYZ(pos) + m_VhoverHeight; + m_VhoverTargetHeight = Prim.PhysicsScene.GetWaterLevelAtXYZ(pos) + m_VhoverHeight; } if ((m_flags & VehicleFlag.HOVER_TERRAIN_ONLY) != 0) { @@ -590,7 +602,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin { if ((pos.Z - m_VhoverTargetHeight) > .2 || (pos.Z - m_VhoverTargetHeight) < -.2) { - m_prim.Position = pos; + Prim.Position = pos; } } else @@ -608,7 +620,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin } } - VDetailLog("{0},MoveLinear,hover,pos={1},dir={2},height={3},target={4}", m_prim.LocalID, pos, m_newVelocity, m_VhoverHeight, m_VhoverTargetHeight); + VDetailLog("{0},MoveLinear,hover,pos={1},dir={2},height={3},target={4}", Prim.LocalID, pos, m_newVelocity, m_VhoverHeight, m_VhoverTargetHeight); } Vector3 posChange = pos - m_lastPositionVector; @@ -642,9 +654,9 @@ namespace OpenSim.Region.Physics.BulletSPlugin } if (changed) { - m_prim.Position = pos; + Prim.Position = pos; VDetailLog("{0},MoveLinear,blockingEndPoint,block={1},origPos={2},pos={3}", - m_prim.LocalID, m_BlockingEndPoint, posChange, pos); + Prim.LocalID, m_BlockingEndPoint, posChange, pos); } } @@ -664,7 +676,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin float postemp = (pos.Z - terrainHeight); if (postemp > 2.5f) grav.Z = (float)(grav.Z * 1.037125); - VDetailLog("{0},MoveLinear,limitMotorUp,grav={1}", m_prim.LocalID, grav); + VDetailLog("{0},MoveLinear,limitMotorUp,grav={1}", Prim.LocalID, grav); } if ((m_flags & (VehicleFlag.NO_X)) != 0) m_newVelocity.X = 0; @@ -674,7 +686,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin m_newVelocity.Z = 0; // Apply velocity - m_prim.Velocity = m_newVelocity; + Prim.Velocity = m_newVelocity; // apply gravity force // Why is this set here? The physics engine already does gravity. // m_prim.AddForce(grav, false); @@ -684,10 +696,11 @@ namespace OpenSim.Region.Physics.BulletSPlugin m_lastLinearVelocityVector *= keepFraction; VDetailLog("{0},MoveLinear,done,lmDir={1},lmVel={2},newVel={3},grav={4},1Mdecay={5}", - m_prim.LocalID, m_linearMotorDirection, m_lastLinearVelocityVector, m_newVelocity, grav, keepFraction); + Prim.LocalID, m_linearMotorDirection, m_lastLinearVelocityVector, m_newVelocity, grav, keepFraction); } // end MoveLinear() + // Apply the effect of the angular motor. private void MoveAngular(float pTimestep) { // m_angularMotorDirection // angular velocity requested by LSL motor @@ -699,7 +712,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin // m_lastAngularVelocity // what was last applied to body // Get what the body is doing, this includes 'external' influences - Vector3 angularVelocity = m_prim.RotationalVelocity; + Vector3 angularVelocity = Prim.RotationalVelocity; if (m_angularMotorApply > 0) { @@ -716,7 +729,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin m_angularMotorVelocity.Z += (m_angularMotorDirection.Z - m_angularMotorVelocity.Z) / (m_angularMotorTimescale / pTimestep); VDetailLog("{0},MoveAngular,angularMotorApply,apply={1},angTScale={2},timeStep={3},origvel={4},dir={5},vel={6}", - m_prim.LocalID, m_angularMotorApply, m_angularMotorTimescale, pTimestep, origAngularVelocity, m_angularMotorDirection, m_angularMotorVelocity); + Prim.LocalID, m_angularMotorApply, m_angularMotorTimescale, pTimestep, origAngularVelocity, m_angularMotorDirection, m_angularMotorVelocity); // This is done so that if script request rate is less than phys frame rate the expected // velocity may still be acheived. @@ -737,7 +750,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin { float VAservo = 0.2f / (m_verticalAttractionTimescale / pTimestep); // get present body rotation - Quaternion rotq = m_prim.Orientation; + Quaternion rotq = Prim.Orientation; // make a vector pointing up Vector3 verterr = Vector3.Zero; verterr.Z = 1.0f; @@ -767,7 +780,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin vertattr.Y += bounce * angularVelocity.Y; VDetailLog("{0},MoveAngular,verticalAttraction,verterr={1},bounce={2},vertattr={3}", - m_prim.LocalID, verterr, bounce, vertattr); + Prim.LocalID, verterr, bounce, vertattr); } // else vertical attractor is off @@ -784,13 +797,13 @@ namespace OpenSim.Region.Physics.BulletSPlugin { m_lastAngularVelocity.X = 0; m_lastAngularVelocity.Y = 0; - VDetailLog("{0},MoveAngular,noDeflectionUp,lastAngular={1}", m_prim.LocalID, m_lastAngularVelocity); + VDetailLog("{0},MoveAngular,noDeflectionUp,lastAngular={1}", Prim.LocalID, m_lastAngularVelocity); } if (m_lastAngularVelocity.ApproxEquals(Vector3.Zero, 0.01f)) { m_lastAngularVelocity = Vector3.Zero; // Reduce small value to zero. - VDetailLog("{0},MoveAngular,zeroSmallValues,lastAngular={1}", m_prim.LocalID, m_lastAngularVelocity); + VDetailLog("{0},MoveAngular,zeroSmallValues,lastAngular={1}", Prim.LocalID, m_lastAngularVelocity); } // apply friction @@ -798,14 +811,14 @@ namespace OpenSim.Region.Physics.BulletSPlugin m_lastAngularVelocity -= m_lastAngularVelocity * decayamount; // Apply to the body - m_prim.RotationalVelocity = m_lastAngularVelocity; + Prim.RotationalVelocity = m_lastAngularVelocity; - VDetailLog("{0},MoveAngular,done,decay={1},lastAngular={2}", m_prim.LocalID, decayamount, m_lastAngularVelocity); + VDetailLog("{0},MoveAngular,done,decay={1},lastAngular={2}", Prim.LocalID, decayamount, m_lastAngularVelocity); } //end MoveAngular internal void LimitRotation(float timestep) { - Quaternion rotq = m_prim.Orientation; + Quaternion rotq = Prim.Orientation; Quaternion m_rot = rotq; bool changed = false; if (m_RollreferenceFrame != Quaternion.Identity) @@ -840,8 +853,8 @@ namespace OpenSim.Region.Physics.BulletSPlugin } if (changed) { - m_prim.Orientation = m_rot; - VDetailLog("{0},LimitRotation,done,orig={1},new={2}", m_prim.LocalID, rotq, m_rot); + Prim.Orientation = m_rot; + VDetailLog("{0},LimitRotation,done,orig={1},new={2}", Prim.LocalID, rotq, m_rot); } } @@ -849,8 +862,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 (m_prim.PhysicsScene.VehicleLoggingEnabled) - m_prim.PhysicsScene.PhysicsLogging.Write(msg, args); + if (Prim.PhysicsScene.VehicleLoggingEnabled) + Prim.PhysicsScene.PhysicsLogging.Write(msg, args); } } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index 84a7fac..6967108 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -92,7 +92,9 @@ public class BSLinkset { lock (m_linksetActivityLock) { - AddChildToLinkset(child); + // Don't add the root to its own linkset + if (!IsRoot(child)) + AddChildToLinkset(child); } return this; } @@ -106,6 +108,17 @@ public class BSLinkset { if (IsRoot(child)) { + // Cannot remove the root from a linkset. + return this; + } + + RemoveChildFromLinkset(child); + + /* Alternate implementation that destroys the linkset of the root is removed. + * This fails because items are added and removed from linksets to build shapes. + * Code left for reference. + if (IsRoot(child)) + { // if root of linkset, take the linkset apart while (m_children.Count > 0) { @@ -120,6 +133,7 @@ public class BSLinkset // Just removing a child from an existing linkset RemoveChildFromLinkset(child); } + */ } // The child is down to a linkset of just itself @@ -308,12 +322,16 @@ public class BSLinkset { m_children.Add(child); - BSPhysObject rootx = LinksetRoot; // capture the root as of now + BSPhysObject rootx = LinksetRoot; // capture the root and body as of now + BulletBody rootBodyx = LinksetRoot.BSBody; BSPhysObject childx = child; + BulletBody childBodyx = child.BSBody; + PhysicsScene.TaintedObject("AddChildToLinkset", delegate() { DetailLog("{0},AddChildToLinkset,taint,child={1}", LinksetRoot.LocalID, child.LocalID); - PhysicallyLinkAChildToRoot(rootx, childx); // build the physical binding between me and the child + // build the physical binding between me and the child + PhysicallyLinkAChildToRoot(rootx, rootBodyx, childx, childBodyx); }); } return; @@ -323,7 +341,7 @@ public class BSLinkset // This is not being called by the child so we have to make sure the child doesn't think // it's still connected to the linkset. // Normal OpenSimulator operation will never do this because other SceneObjectPart information - // has to be updated also (like pointer to prim's parent). + // also has to be updated (like pointer to prim's parent). private void RemoveChildFromOtherLinkset(BSPhysObject pchild) { pchild.Linkset = new BSLinkset(PhysicsScene, pchild); @@ -336,13 +354,15 @@ public class BSLinkset { if (m_children.Remove(child)) { - BSPhysObject rootx = LinksetRoot; // capture the root as of now + BSPhysObject rootx = LinksetRoot; // capture the root and body as of now + BulletBody rootBodyx = LinksetRoot.BSBody; BSPhysObject childx = child; + BulletBody childBodyx = child.BSBody; PhysicsScene.TaintedObject("RemoveChildFromLinkset", delegate() { DetailLog("{0},RemoveChildFromLinkset,taint,child={1}", LinksetRoot.LocalID, child.LocalID); - PhysicallyUnlinkAChildFromRoot(rootx, childx); + PhysicallyUnlinkAChildFromRoot(rootx, rootBodyx, childx, childBodyx); RecomputeLinksetConstraintVariables(); }); @@ -357,7 +377,8 @@ public class BSLinkset // Create a constraint between me (root of linkset) and the passed prim (the child). // Called at taint time! - private void PhysicallyLinkAChildToRoot(BSPhysObject rootPrim, BSPhysObject childPrim) + private void PhysicallyLinkAChildToRoot(BSPhysObject rootPrim, BulletBody rootBody, + BSPhysObject childPrim, BulletBody childBody) { // Zero motion for children so they don't interpolate childPrim.ZeroMotion(); @@ -371,16 +392,32 @@ public class BSLinkset // create a constraint that allows no freedom of movement between the two objects // http://bulletphysics.org/Bullet/phpBB3/viewtopic.php?t=4818 - DetailLog("{0},PhysicallyLinkAChildToRoot,taint,root={1},child={2},rLoc={3},cLoc={4},midLoc={5}", - rootPrim.LocalID, rootPrim.LocalID, childPrim.LocalID, rootPrim.Position, childPrim.Position, midPoint); + DetailLog("{0},PhysicallyLinkAChildToRoot,taint,root={1},rBody={2},child={3},cBody={4},rLoc={5},cLoc={6},midLoc={7}", + rootPrim.LocalID, + rootPrim.LocalID, rootBody.ptr.ToString("X"), + childPrim.LocalID, childBody.ptr.ToString("X"), + rootPrim.Position, childPrim.Position, midPoint); + + // There is great subtlty in these paramters. Notice the check for a ptr of zero. + // We pass the BulletBody structure into the taint in order to capture the pointer + // of the body at the time of constraint creation. This doesn't work for the very first + // construction because there is no body yet. The body + // is constructed later at taint time. Thus we use the body address at time of the + // taint creation but, if it is zero, use what's in the prim at the moment. + // There is a possible race condition since shape can change without a taint call + // (like changing to a mesh that is already constructed). The fix for that would be + // to only change BSShape at taint time thus syncronizing these operations at + // the cost of efficiency and lag. BS6DofConstraint constrain = new BS6DofConstraint( - PhysicsScene.World, rootPrim.BSBody, childPrim.BSBody, + PhysicsScene.World, + rootBody.ptr == IntPtr.Zero ? rootPrim.BSBody : rootBody, + childBody.ptr == IntPtr.Zero ? childPrim.BSBody : childBody, 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 use the transforms + * Using the midpoint is easier since it lets the Bullet code manipulate the transforms * of the objects. * Code left as a warning to future programmers. // ================================================================================== @@ -433,19 +470,26 @@ public class BSLinkset } // Remove linkage between myself and a particular child + // The root and child bodies are passed in because we need to remove the constraint between + // the bodies that were at unlink time. // Called at taint time! - private void PhysicallyUnlinkAChildFromRoot(BSPhysObject rootPrim, BSPhysObject childPrim) + private void PhysicallyUnlinkAChildFromRoot(BSPhysObject rootPrim, BulletBody rootBody, + BSPhysObject childPrim, BulletBody childBody) { - DetailLog("{0},PhysicallyUnlinkAChildFromRoot,taint,root={1},child={2}", rootPrim.LocalID, rootPrim.LocalID, childPrim.LocalID); + DetailLog("{0},PhysicallyUnlinkAChildFromRoot,taint,root={1},rBody={2},child={3},cBody={4}", + rootPrim.LocalID, + rootPrim.LocalID, rootBody.ptr.ToString("X"), + childPrim.LocalID, childBody.ptr.ToString("X")); // Find the constraint for this link and get rid of it from the overall collection and from my list - PhysicsScene.Constraints.RemoveAndDestroyConstraint(rootPrim.BSBody, childPrim.BSBody); + PhysicsScene.Constraints.RemoveAndDestroyConstraint(rootBody, childBody); // Make the child refresh its location BulletSimAPI.PushUpdate2(childPrim.BSBody.ptr); } - // Remove linkage between myself and any possible children I might have + /* + // Remove linkage between myself and any possible children I might have. // Called at taint time! private void PhysicallyUnlinkAllChildrenFromRoot(BSPhysObject rootPrim) { @@ -453,6 +497,7 @@ public class BSLinkset PhysicsScene.Constraints.RemoveAndDestroyConstraint(rootPrim.BSBody); } + */ // Invoke the detailed logger and output something if it's enabled. private void DetailLog(string msg, params Object[] args) diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index 4f83adc..df95625 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -135,8 +135,11 @@ public abstract class BSPhysObject : PhysicsActor // collision event to make collision_end work. // Called at taint time from within the Step() function thus no locking problems // with CollisionCollection and ObjectsWithNoMoreCollisions. - public virtual void SendCollisions() + // Return 'true' if there were some actual collisions passed up + public virtual bool SendCollisions() { + bool ret = true; + // throttle the collisions to the number of milliseconds specified in the subscription int nowTime = PhysicsScene.SimulationNowTime; if (nowTime >= NextCollisionOkTime) @@ -148,7 +151,7 @@ public abstract class BSPhysObject : PhysicsActor if (CollisionCollection.Count == 0) { // If I have no collisions this time, remove me from the list of objects with collisions. - PhysicsScene.ObjectsWithNoMoreCollisions.Add(this); + ret = false; } // DetailLog("{0},{1}.SendCollisionUpdate,call,numCollisions={2}", LocalID, TypeName, CollisionCollection.Count); @@ -158,6 +161,7 @@ public abstract class BSPhysObject : PhysicsActor // Make sure we don't have a handle to that one and that a new one is used for next time. CollisionCollection = new CollisionEventUpdate(); } + return ret; } // Subscribe for collision events. diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 68a153e..17ba85a 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -507,6 +507,9 @@ public sealed class BSPrim : BSPhysObject // Set up the object physicalness (does gravity and collisions move this object) MakeDynamic(IsStatic); + // Do any vehicle stuff + _vehicle.Refresh(); + // Arrange for collision events if the simulator wants them EnableCollisions(SubscribedEvents()); @@ -556,9 +559,8 @@ public sealed class BSPrim : BSPhysObject BulletSimAPI.UpdateInertiaTensor2(BSBody.ptr); // There can be special things needed for implementing linksets Linkset.MakeStatic(this); - // The activation state is 'sleeping' so Bullet will not try to act on it - BulletSimAPI.ForceActivationState2(BSBody.ptr, ActivationState.ISLAND_SLEEPING); - // BulletSimAPI.ForceActivationState2(BSBody.ptr, ActivationState.DISABLE_SIMULATION); + // The activation state is 'disabled' so Bullet will not try to act on it + BulletSimAPI.ForceActivationState2(BSBody.ptr, ActivationState.DISABLE_SIMULATION); BSBody.collisionFilter = CollisionFilterGroups.StaticObjectFilter; BSBody.collisionMask = CollisionFilterGroups.StaticObjectMask; @@ -577,7 +579,8 @@ public sealed class BSPrim : BSPhysObject // A dynamic object has mass IntPtr collisionShapePtr = BulletSimAPI.GetCollisionShape2(BSBody.ptr); - OMV.Vector3 inertia = BulletSimAPI.CalculateLocalInertia2(collisionShapePtr, Linkset.LinksetMass); + OMV.Vector3 inertia = BulletSimAPI.CalculateLocalInertia2(collisionShapePtr, Mass); + // OMV.Vector3 inertia = OMV.Vector3.Zero; BulletSimAPI.SetMassProps2(BSBody.ptr, _mass, inertia); BulletSimAPI.UpdateInertiaTensor2(BSBody.ptr); @@ -587,10 +590,12 @@ public sealed class BSPrim : BSPhysObject BulletSimAPI.SetSleepingThresholds2(BSBody.ptr, PhysicsScene.Params.linearSleepingThreshold, PhysicsScene.Params.angularSleepingThreshold); BulletSimAPI.SetContactProcessingThreshold2(BSBody.ptr, PhysicsScene.Params.contactProcessingThreshold); - // There can be special things needed for implementing linksets + // There can be special things needed for implementing linksets. Linkset.MakeDynamic(this); // Force activation of the object so Bullet will act on it. + // Must do the ForceActivationState2() to overcome the DISABLE_SIMULATION from static objects. + BulletSimAPI.ForceActivationState2(BSBody.ptr, ActivationState.ISLAND_SLEEPING); BulletSimAPI.Activate2(BSBody.ptr, true); BSBody.collisionFilter = CollisionFilterGroups.ObjectFilter; @@ -1457,9 +1462,16 @@ public sealed class BSPrim : BSPhysObject ShapeData shapeData; FillShapeInfo(out shapeData); + // Undo me from any possible linkset so, if body is rebuilt, the link will get restored. + // NOTE that the new linkset is not set. This saves the handle to the linkset + // so we can add ourselves back when shape mangling is complete. + Linkset.RemoveMeFromLinkset(this); + // Create the correct physical representation for this type of object. // Updates BSBody and BSShape with the new information. PhysicsScene.Shapes.GetBodyAndShape(forceRebuild, PhysicsScene.World, this, shapeData, _pbs); + + Linkset = Linkset.AddMeToLinkset(this); // Make sure the properties are set on the new object UpdatePhysicalParameters(); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index e8c628c..44a249c 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -544,12 +544,15 @@ public class BSScene : PhysicsScene, IPhysicsParameters // The above SendCollision's batch up the collisions on the objects. // Now push the collisions into the simulator. - // If the object is done colliding, it will add itself to the ObjectsWithNoMoreCollisions list. if (ObjectsWithCollisions.Count > 0) { foreach (BSPhysObject bsp in ObjectsWithCollisions) if (!m_avatars.Contains(bsp)) // don't call avatars twice - bsp.SendCollisions(); + if (!bsp.SendCollisions()) + { + // If the object is done colliding, see that it's removed from the colliding list + ObjectsWithNoMoreCollisions.Add(bsp); + } } // Objects that are done colliding are removed from the ObjectsWithCollisions list. diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index aadb8d6..72c6df5 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -498,7 +498,8 @@ public class BSShapeCollection : IDisposable ulong newHullKey = ComputeShapeKey(shapeData, pbs, out lod); // if the hull hasn't changed, don't rebuild it - if (newHullKey == prim.BSShape.shapeKey) return false; + if (newHullKey == prim.BSShape.shapeKey && prim.BSShape.type == ShapeData.PhysicsShapeType.SHAPE_HULL) + return false; DetailLog("{0},BSShapeCollection.CreateGeomHull,create,oldKey={1},newKey={2}", prim.LocalID, prim.BSShape.shapeKey.ToString("X"), newHullKey.ToString("X")); @@ -508,11 +509,8 @@ public class BSShapeCollection : IDisposable newShape = CreatePhysicalHull(prim.PhysObjectName, newHullKey, pbs, shapeData.Size, lod); - if (!ReferenceShape(newShape)) - { - PhysicsScene.Logger.ErrorFormat("{0} Created new hull shape but one already exists: id={1}, key={2}, refCnt={3}", - LogHeader, shapeData.ID, newHullKey.ToString("X"), Hulls[newHullKey].referenceCount); - } + ReferenceShape(newShape); + // hulls are already scaled by the meshmerizer prim.Scale = new OMV.Vector3(1f, 1f, 1f); prim.BSShape = newShape; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs index 50638d6..269c3d5 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs @@ -334,7 +334,8 @@ public class BSTerrainManager (uint)CollisionFilterGroups.TerrainMask); // Make sure the new shape is processed. - BulletSimAPI.Activate2(mapInfo.terrainBody.ptr, true); + // BulletSimAPI.Activate2(mapInfo.terrainBody.ptr, true); + BulletSimAPI.ForceActivationState2(mapInfo.terrainBody.ptr, ActivationState.DISABLE_SIMULATION); m_terrainModified = true; }; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs index 6910050..2d65a35 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs @@ -369,16 +369,16 @@ public enum CollisionFilterGroups : uint BSolidFilter = 1 << 13, // The collsion filters and masked are defined in one place -- don't want them scattered - AvatarFilter = BDefaultFilter | BCharacterFilter | BSolidFilter, + AvatarFilter = BCharacterFilter, AvatarMask = BAllFilter, - ObjectFilter = BDefaultFilter | BSolidFilter, + ObjectFilter = BSolidFilter, ObjectMask = BAllFilter, - StaticObjectFilter = BDefaultFilter | BStaticFilter | BSolidFilter, + StaticObjectFilter = BStaticFilter, StaticObjectMask = BAllFilter, VolumeDetectFilter = BSensorTrigger, VolumeDetectMask = ~BSensorTrigger, TerrainFilter = BTerrainFilter, - TerrainMask = BAllFilter, + TerrainMask = BAllFilter & ~BStaticFilter, GroundPlaneFilter = BAllFilter, GroundPlaneMask = BAllFilter -- cgit v1.1 From 5781d4d52d0e4c761737fd9b1382365589a4717e Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Thu, 27 Sep 2012 09:19:42 -0700 Subject: BulletSim: remove the unused body management code from BSPrim. There is no going back now. --- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 374 ------------------------- 1 file changed, 374 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 17ba85a..e65e42b 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -27,8 +27,6 @@ // Uncomment this it enable code to do all shape an body memory management // in the C# code. -#define CSHARP_BODY_MANAGEMENT - using System; using System.Reflection; using System.Collections.Generic; @@ -474,14 +472,8 @@ public sealed class BSPrim : BSPhysObject // Called at taint-time!! private void SetObjectDynamic(bool forceRebuild) { -#if CSHARP_BODY_MANAGEMENT // Recreate the physical object if necessary CreateGeomAndObject(forceRebuild); -#else - // If it's becoming dynamic, it will need hullness - VerifyCorrectPhysicalShape(); - UpdatePhysicalParameters(); -#endif // CSHARP_BODY_MANAGEMENT } // Convert the simulator's physical properties into settings on BulletSim objects. @@ -498,11 +490,6 @@ public sealed class BSPrim : BSPhysObject // This is a NOOP if the object is not in the world (BulletSim and Bullet ignore objects not found). BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.ptr, BSBody.ptr); -#if !CSHARP_BODY_MANAGEMENT - // Make solid or not (do things bounce off or pass through this object) - // This is done first because it can change the collisionObject type. - MakeSolid(IsSolid); -#endif // !CSHARP_BODY_MANAGEMENT // Set up the object physicalness (does gravity and collisions move this object) MakeDynamic(IsStatic); @@ -513,10 +500,8 @@ public sealed class BSPrim : BSPhysObject // Arrange for collision events if the simulator wants them EnableCollisions(SubscribedEvents()); -#if CSHARP_BODY_MANAGEMENT // Make solid or not (do things bounce off or pass through this object). MakeSolid(IsSolid); -#endif // CSHARP_BODY_MANAGEMENT BulletSimAPI.AddObjectToWorld2(PhysicsScene.World.ptr, BSBody.ptr); @@ -609,7 +594,6 @@ public sealed class BSPrim : BSPhysObject // the functions after this one set up the state of a possibly newly created collision body. private void MakeSolid(bool makeSolid) { -#if CSHARP_BODY_MANAGEMENT CollisionObjectTypes bodyType = (CollisionObjectTypes)BulletSimAPI.GetBodyType2(BSBody.ptr); if (makeSolid) { @@ -630,49 +614,6 @@ public sealed class BSPrim : BSPhysObject BSBody.collisionFilter = CollisionFilterGroups.VolumeDetectFilter; BSBody.collisionMask = CollisionFilterGroups.VolumeDetectMask; } -#else - // If doing the body management in C#, all this logic is in CSShapeCollection.CreateObject(). - CollisionObjectTypes bodyType = (CollisionObjectTypes)BulletSimAPI.GetBodyType2(BSBody.ptr); - if (makeSolid) - { - if ((bodyType & CollisionObjectTypes.CO_RIGID_BODY) == 0) - { - // Solid things are made out of rigid bodies. Remove this old body from the world - // and use this shape in a new rigid body. - BulletBody oldBody = BSBody; - // Zero out the pointer to the shape in the old body so the shape will not get freed - BSShape.Ptr = BulletSimAPI.GetCollisionShape2(oldBody.Ptr); - BulletSimAPI.SetCollisionShape2(PhysicsScene.World.Ptr, oldBody.Ptr, IntPtr.Zero); - // Get rid of the old body and remove it from BulletSim's object list - BulletSimAPI.DestroyObject(PhysicsScene.WorldID, LocalID); - - // Create the new body with the shape - BSBody = new BulletBody(LocalID, BulletSimAPI.CreateBodyFromShape2(PhysicsScene.World.Ptr, BSShape.Ptr, _position, _orientation)); - CurrentCollisionFlags = BulletSimAPI.RemoveFromCollisionFlags2(BSBody.Ptr, CollisionFlags.CF_NO_CONTACT_RESPONSE); - DetailLog("{0},BSPrim.MakeSolid:rigidBody,body={1},shape={2}", LocalID, BSBody, BSShape); - } - } - else - { - if ((bodyType & CollisionObjectTypes.CO_GHOST_OBJECT) == 0) - { - // Non-solid things are made out of ghost objects. Remove this old body from the world - // and use this shape in a new rigid body. - BulletBody oldBody = BSBody; - - // Zero out the pointer to the shape in the old body so the shape will not get freed - BSShape.Ptr = BulletSimAPI.GetCollisionShape2(oldBody.Ptr); - BulletSimAPI.SetCollisionShape2(PhysicsScene.World.Ptr, oldBody.Ptr, IntPtr.Zero); - // Get rid of the old body and remove it from BulletSim's object list - BulletSimAPI.DestroyObject(PhysicsScene.WorldID, LocalID); - - BSBody = new BulletBody(LocalID, - BulletSimAPI.CreateGhostFromShape2(PhysicsScene.World.Ptr, BSShape.Ptr, _position, _orientation)); - CurrentCollisionFlags = BulletSimAPI.AddToCollisionFlags2(BSBody.Ptr, CollisionFlags.CF_NO_CONTACT_RESPONSE); - DetailLog("{0},BSPrim.MakeGhostBody,body={1},shape={2}", LocalID, BSBody, BSShape); - } - } -#endif } // Turn on or off the flag controlling whether collision events are returned to the simulator. @@ -1139,300 +1080,6 @@ public sealed class BSPrim : BSPhysObject }// end CalculateMass #endregion Mass Calculation -#if !CSHARP_BODY_MANAGEMENT - // Create the geometry information in Bullet for later use. - // The objects needs a hull if it's physical otherwise a mesh is enough. - // No locking here because this is done when we know physics is not simulating. - // if 'forceRebuild' is true, the geometry is rebuilt. Otherwise a previously built version is used. - // Returns 'true' if the geometry was rebuilt. - // Called at taint-time! - private bool CreateGeom(bool forceRebuild) - { - bool ret = false; - bool haveShape = false; - - // If the prim attributes are simple, this could be a simple Bullet native shape - if ( - // if the basic shape is a cube or a sphere... - ((_pbs.ProfileShape == ProfileShape.Square && _pbs.PathCurve == (byte)Extrusion.Straight) - || (_pbs.ProfileShape == ProfileShape.HalfCircle && _pbs.PathCurve == (byte)Extrusion.Curve1 - /* && _pbs.Scale.X == _pbs.Scale.Y && _pbs.Scale.Y == _pbs.Scale.Z */ )) - // ... and we are not doing sculpty meshes... - && (_pbs.SculptEntry && !PhysicsScene.ShouldMeshSculptedPrim) - // ... or this is a 'simple' shape... - || (_pbs.ProfileBegin == 0 && _pbs.ProfileEnd == 0 - && _pbs.ProfileHollow == 0 - && _pbs.PathTwist == 0 && _pbs.PathTwistBegin == 0 - && _pbs.PathBegin == 0 && _pbs.PathEnd == 0 - && _pbs.PathTaperX == 0 && _pbs.PathTaperY == 0 - && _pbs.PathScaleX == 100 && _pbs.PathScaleY == 100 - && _pbs.PathShearX == 0 && _pbs.PathShearY == 0) ) - // ... then this might be representable as a native Bullet collision shape - { - if (_pbs.ProfileShape == ProfileShape.HalfCircle && _pbs.PathCurve == (byte)Extrusion.Curve1) - { - haveShape = true; - if (forceRebuild || (_shapeType != ShapeData.PhysicsShapeType.SHAPE_SPHERE)) - { - DetailLog("{0},BSPrim.CreateGeom,sphere (force={1}", LocalID, forceRebuild); - _shapeType = ShapeData.PhysicsShapeType.SHAPE_SPHERE; - _meshKey = (ulong)ShapeData.FixedShapeKey.KEY_SPHERE; - // Bullet native objects are scaled by the Bullet engine so pass the size in - _scale = _size; - // TODO: do we need to check for and destroy a mesh or hull that might have been left from before? - ret = true; - } - } - else - { - // m_log.DebugFormat("{0}: CreateGeom: Defaulting to box. lid={1}, type={2}, size={3}", LogHeader, LocalID, _shapeType, _size); - haveShape = true; - if (forceRebuild || (_shapeType != ShapeData.PhysicsShapeType.SHAPE_BOX)) - { - DetailLog("{0},BSPrim.CreateGeom,box (force={1})", LocalID, forceRebuild); - _shapeType = ShapeData.PhysicsShapeType.SHAPE_BOX; - _meshKey = (ulong)ShapeData.FixedShapeKey.KEY_BOX; - _scale = _size; - // TODO: do we need to check for and destroy a mesh or hull that might have been left from before? - ret = true; - } - } - } - // If a simple shape isn't happening, create a mesh and possibly a hull - if (!haveShape) - { - if (IsPhysical) - { - if (forceRebuild || _hullKey == 0) - { - // physical objects require a hull for interaction. - // This also creates the mesh if it doesn't already exist - ret = CreateGeomHull(); - } - } - else - { - if (forceRebuild || _meshKey == 0) - { - // Static (non-physical) objects only need a mesh for bumping into - ret = CreateGeomMesh(); - } - } - } - - return ret; - } - - // No locking here because this is done when we know physics is not simulating - // Returns 'true' of a mesh was actually rebuild (we could also have one of these specs). - // Called at taint-time! - private bool CreateGeomMesh() - { - // level of detail based on size and type of the object - float lod = PhysicsScene.MeshLOD; - if (_pbs.SculptEntry) - lod = PhysicsScene.SculptLOD; - float maxAxis = Math.Max(_size.X, Math.Max(_size.Y, _size.Z)); - if (maxAxis > PhysicsScene.MeshMegaPrimThreshold) - lod = PhysicsScene.MeshMegaPrimLOD; - - ulong newMeshKey = (ulong)_pbs.GetMeshKey(_size, lod); - // m_log.DebugFormat("{0}: CreateGeomMesh: lID={1}, oldKey={2}, newKey={3}", LogHeader, LocalID, _meshKey, newMeshKey); - - // if this new shape is the same as last time, don't recreate the mesh - if (_meshKey == newMeshKey) return false; - - DetailLog("{0},BSPrim.CreateGeomMesh,create,key={1}", LocalID, newMeshKey); - // Since we're recreating new, get rid of any previously generated shape - if (_meshKey != 0) - { - // m_log.DebugFormat("{0}: CreateGeom: deleting old mesh. lID={1}, Key={2}", LogHeader, LocalID, _meshKey); - DetailLog("{0},BSPrim.CreateGeomMesh,deleteOld,key={1}", LocalID, _meshKey); - BulletSimAPI.DestroyMesh(PhysicsScene.WorldID, _meshKey); - _mesh = null; - _meshKey = 0; - } - - _meshKey = newMeshKey; - // always pass false for physicalness as this creates some sort of bounding box which we don't need - _mesh = PhysicsScene.mesher.CreateMesh(PhysObjectName, _pbs, _size, lod, false); - - int[] indices = _mesh.getIndexListAsInt(); - List vertices = _mesh.getVertexList(); - - float[] verticesAsFloats = new float[vertices.Count * 3]; - int vi = 0; - foreach (OMV.Vector3 vv in vertices) - { - verticesAsFloats[vi++] = vv.X; - verticesAsFloats[vi++] = vv.Y; - verticesAsFloats[vi++] = vv.Z; - } - - // m_log.DebugFormat("{0}: CreateGeomMesh: calling CreateMesh. lid={1}, key={2}, indices={3}, vertices={4}", - // LogHeader, LocalID, _meshKey, indices.Length, vertices.Count); - BulletSimAPI.CreateMesh(PhysicsScene.WorldID, _meshKey, indices.GetLength(0), indices, - vertices.Count, verticesAsFloats); - - _shapeType = ShapeData.PhysicsShapeType.SHAPE_MESH; - // meshes are already scaled by the meshmerizer - _scale = new OMV.Vector3(1f, 1f, 1f); - return true; - } - - // No locking here because this is done when we know physics is not simulating - // Returns 'true' of a mesh was actually rebuild (we could also have one of these specs). - private bool CreateGeomHull() - { - float lod = _pbs.SculptEntry ? PhysicsScene.SculptLOD : PhysicsScene.MeshLOD; - ulong newHullKey = (ulong)_pbs.GetMeshKey(_size, lod); - // m_log.DebugFormat("{0}: CreateGeomHull: lID={1}, oldKey={2}, newKey={3}", LogHeader, LocalID, _hullKey, newHullKey); - - // if the hull hasn't changed, don't rebuild it - if (newHullKey == _hullKey) return false; - - DetailLog("{0},BSPrim.CreateGeomHull,create,oldKey={1},newKey={2}", LocalID, _hullKey, newHullKey); - - // Since we're recreating new, get rid of any previously generated shape - if (_hullKey != 0) - { - // m_log.DebugFormat("{0}: CreateGeom: deleting old hull. Key={1}", LogHeader, _hullKey); - DetailLog("{0},BSPrim.CreateGeomHull,deleteOldHull,key={1}", LocalID, _hullKey); - BulletSimAPI.DestroyHull(PhysicsScene.WorldID, _hullKey); - _hullKey = 0; - } - - _hullKey = newHullKey; - - // Make sure the underlying mesh exists and is correct - CreateGeomMesh(); - - int[] indices = _mesh.getIndexListAsInt(); - List vertices = _mesh.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)); - } - - // setup and do convex hull conversion - _hulls = new List(); - DecompDesc dcomp = new DecompDesc(); - dcomp.mIndices = convIndices; - dcomp.mVertices = convVertices; - ConvexBuilder convexBuilder = new ConvexBuilder(HullReturn); - // create the hull into the _hulls variable - convexBuilder.process(dcomp); - - // 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 = _hulls.Count; - int totalVertices = 1; // include one for the count of the hulls - foreach (ConvexResult cr in _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 _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 definition in Bullet - // m_log.DebugFormat("{0}: CreateGeom: calling CreateHull. lid={1}, key={2}, hulls={3}", LogHeader, LocalID, _hullKey, hullCount); - BulletSimAPI.CreateHull(PhysicsScene.WorldID, _hullKey, hullCount, convHulls); - _shapeType = ShapeData.PhysicsShapeType.SHAPE_HULL; - // meshes are already scaled by the meshmerizer - _scale = new OMV.Vector3(1f, 1f, 1f); - DetailLog("{0},BSPrim.CreateGeomHull,done", LocalID); - return true; - } - - // Callback from convex hull creater with a newly created hull. - // Just add it to the collection of hulls for this shape. - private void HullReturn(ConvexResult result) - { - _hulls.Add(result); - return; - } - - private void VerifyCorrectPhysicalShape() - { - if (!IsStatic) - { - // if not static, it will need a hull to efficiently collide with things - if (_hullKey == 0) - { - CreateGeomAndObject(false); - } - - } - } - - // Create an object in Bullet if it has not already been created - // No locking here because this is done when the physics engine is not simulating - // Returns 'true' if an object was actually created. - private bool CreateObject() - { - // this routine is called when objects are rebuilt. - - // the mesh or hull must have already been created in Bullet - ShapeData shape; - FillShapeInfo(out shape); - // m_log.DebugFormat("{0}: CreateObject: lID={1}, shape={2}", LogHeader, LocalID, shape.Type); - bool ret = BulletSimAPI.CreateObject(PhysicsScene.WorldID, shape); - - return ret; - } -#endif // !CSHARP_BODY_MANAGEMENT - // Copy prim's info into the BulletSim shape description structure public void FillShapeInfo(out ShapeData shape) { @@ -1458,7 +1105,6 @@ public sealed class BSPrim : BSPhysObject // Called at taint-time!!! private void CreateGeomAndObject(bool forceRebuild) { -#if CSHARP_BODY_MANAGEMENT ShapeData shapeData; FillShapeInfo(out shapeData); @@ -1475,26 +1121,6 @@ public sealed class BSPrim : BSPhysObject // Make sure the properties are set on the new object UpdatePhysicalParameters(); -#else - // m_log.DebugFormat("{0}: CreateGeomAndObject. lID={1}, force={2}", LogHeader, LocalID, forceRebuild); - // Create the geometry that will make up the object - if (CreateGeom(forceRebuild)) - { - // Create the object and place it into the world - CreateObject(); - - // the CreateObject() may have recreated the rigid body. Make sure we have the latest address. - BSBody = new BulletBody(LocalID, BulletSimAPI.GetBodyHandle2(PhysicsScene.World.Ptr, LocalID)); - BSShape = new BulletShape(BulletSimAPI.GetCollisionShape2(BSBody.Ptr), _shapeType); - BSShape.shapeKey = _meshKey; - DetailLog("{0},BSPrim.CreateGeomAndObject,body={1},shape={2}", LocalID, BSBody, BSShape); - - // Make sure the properties are set on the new object - UpdatePhysicalParameters(); - } - - -#endif // CSHARP_BODY_MANAGEMENT return; } -- cgit v1.1 From 7b65985047bdf0789fe3eccf8f515279f362abf1 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Thu, 27 Sep 2012 09:31:33 -0700 Subject: BulletSim: remove the trailing spaces from lines to make git happier --- .../Region/Physics/BulletSPlugin/BSCharacter.cs | 185 +++++++++--------- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 14 +- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 30 +-- .../Region/Physics/BulletSPlugin/BSPhysObject.cs | 2 +- OpenSim/Region/Physics/BulletSPlugin/BSPlugin.cs | 4 +- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 212 ++++++++++----------- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 26 +-- .../Physics/BulletSPlugin/BSShapeCollection.cs | 42 ++-- .../Physics/BulletSPlugin/BSTerrainManager.cs | 32 ++-- .../Region/Physics/BulletSPlugin/BulletSimAPI.cs | 4 +- 10 files changed, 275 insertions(+), 276 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index 961bcde..b88ec3c 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -122,7 +122,6 @@ public class BSCharacter : BSPhysObject BulletSimAPI.SetCollisionFilterMask2(BSBody.ptr, (uint)CollisionFilterGroups.AvatarFilter, (uint)CollisionFilterGroups.AvatarMask); }); - return; } @@ -141,8 +140,8 @@ public class BSCharacter : BSPhysObject base.RequestPhysicsterseUpdate(); } // No one calls this method so I don't know what it could possibly mean - public override bool Stopped { - get { return false; } + public override bool Stopped { + get { return false; } } public override OMV.Vector3 Size { get @@ -151,7 +150,7 @@ public class BSCharacter : BSPhysObject return new OMV.Vector3(_scale.X * 2, _scale.Y * 2, _scale.Z); } - set { + set { // When an avatar's size is set, only the height is changed // and that really only depends on the radius. _size = value; @@ -166,19 +165,19 @@ public class BSCharacter : BSPhysObject BulletSimAPI.SetObjectScaleMass(PhysicsScene.WorldID, LocalID, _scale, _mass, true); }); - } + } } - public override PrimitiveBaseShape Shape { - set { _pbs = value; - } + public override PrimitiveBaseShape Shape { + set { _pbs = value; + } } - public override bool Grabbed { - set { _grabbed = value; - } + public override bool Grabbed { + set { _grabbed = value; + } } - public override bool Selected { - set { _selected = value; - } + public override bool Selected { + set { _selected = value; + } } public override void CrossingFailure() { return; } public override void link(PhysicsActor obj) { return; } @@ -203,11 +202,11 @@ public class BSCharacter : BSPhysObject public override void LockAngularMotion(OMV.Vector3 axis) { return; } - public override OMV.Vector3 Position { + public override OMV.Vector3 Position { get { // _position = BulletSimAPI.GetObjectPosition(Scene.WorldID, _localID); - return _position; - } + return _position; + } set { _position = value; PositionSanityCheck(); @@ -217,7 +216,7 @@ public class BSCharacter : BSPhysObject DetailLog("{0},BSCharacter.SetPosition,taint,pos={1},orient={2}", LocalID, _position, _orientation); BulletSimAPI.SetObjectTranslation(PhysicsScene.WorldID, LocalID, _position, _orientation); }); - } + } } // Check that the current position is sane and, if not, modify the position to make it so. @@ -226,7 +225,7 @@ public class BSCharacter : BSPhysObject private bool PositionSanityCheck() { bool ret = false; - + // If below the ground, move the avatar up float terrainHeight = PhysicsScene.TerrainManager.GetTerrainHeightAtXYZ(_position); if (Position.Z < terrainHeight) @@ -260,17 +259,17 @@ public class BSCharacter : BSPhysObject return ret; } - public override float Mass { - get { - return _mass; - } + public override float Mass { + get { + return _mass; + } } // used when we only want this prim's mass and not the linkset thing public override float MassRaw { get {return _mass; } } - public override OMV.Vector3 Force { - get { return _force; } + public override OMV.Vector3 Force { + get { return _force; } set { _force = value; // m_log.DebugFormat("{0}: Force = {1}", LogHeader, _force); @@ -279,12 +278,12 @@ public class BSCharacter : BSPhysObject DetailLog("{0},BSCharacter.setForce,taint,force={1}", LocalID, _force); BulletSimAPI.SetObjectForce(PhysicsScene.WorldID, LocalID, _force); }); - } + } } - public override int VehicleType { - get { return 0; } - set { return; } + public override int VehicleType { + get { return 0; } + set { return; } } public override void VehicleFloatParam(int param, float value) { } public override void VehicleVectorParam(int param, OMV.Vector3 value) {} @@ -296,8 +295,8 @@ public class BSCharacter : BSPhysObject public override OMV.Vector3 GeometricCenter { get { return OMV.Vector3.Zero; } } public override OMV.Vector3 CenterOfMass { get { return OMV.Vector3.Zero; } } - public override OMV.Vector3 Velocity { - get { return _velocity; } + public override OMV.Vector3 Velocity { + get { return _velocity; } set { _velocity = value; // m_log.DebugFormat("{0}: set velocity = {1}", LogHeader, _velocity); @@ -306,24 +305,24 @@ public class BSCharacter : BSPhysObject DetailLog("{0},BSCharacter.setVelocity,taint,vel={1}", LocalID, _velocity); BulletSimAPI.SetObjectVelocity(PhysicsScene.WorldID, LocalID, _velocity); }); - } + } } - public override OMV.Vector3 Torque { - get { return _torque; } - set { _torque = value; - } + public override OMV.Vector3 Torque { + get { return _torque; } + set { _torque = value; + } } - public override float CollisionScore { - get { return _collisionScore; } - set { _collisionScore = value; - } + public override float CollisionScore { + get { return _collisionScore; } + set { _collisionScore = value; + } } - public override OMV.Vector3 Acceleration { + public override OMV.Vector3 Acceleration { get { return _acceleration; } set { _acceleration = value; } } - public override OMV.Quaternion Orientation { - get { return _orientation; } + public override OMV.Quaternion Orientation { + get { return _orientation; } set { _orientation = value; // m_log.DebugFormat("{0}: set orientation to {1}", LogHeader, _orientation); @@ -332,98 +331,98 @@ public class BSCharacter : BSPhysObject // _position = BulletSimAPI.GetObjectPosition(Scene.WorldID, _localID); BulletSimAPI.SetObjectTranslation(PhysicsScene.WorldID, LocalID, _position, _orientation); }); - } + } } - public override int PhysicsActorType { - get { return _physicsActorType; } - set { _physicsActorType = value; - } + public override int PhysicsActorType { + get { return _physicsActorType; } + set { _physicsActorType = value; + } } - public override bool IsPhysical { - get { return _isPhysical; } + public override bool IsPhysical { + get { return _isPhysical; } set { _isPhysical = value; - } + } } - public override bool Flying { - get { return _flying; } + public override bool Flying { + get { return _flying; } set { _flying = value; // simulate flying by changing the effect of gravity this.Buoyancy = ComputeBuoyancyFromFlying(_flying); - } + } } // Flying is implimented by changing the avatar's buoyancy. // Would this be done better with a vehicle type? private float ComputeBuoyancyFromFlying(bool ifFlying) { return ifFlying ? 1f : 0f; } - public override bool - SetAlwaysRun { - get { return _setAlwaysRun; } - set { _setAlwaysRun = value; } + public override bool + SetAlwaysRun { + get { return _setAlwaysRun; } + set { _setAlwaysRun = value; } } - public override bool ThrottleUpdates { - get { return _throttleUpdates; } - set { _throttleUpdates = value; } + public override bool ThrottleUpdates { + get { return _throttleUpdates; } + set { _throttleUpdates = value; } } public override bool IsColliding { - get { return (CollidingStep == PhysicsScene.SimulationStep); } - set { _isColliding = value; } + get { return (CollidingStep == PhysicsScene.SimulationStep); } + set { _isColliding = value; } } public override bool CollidingGround { - get { return (CollidingGroundStep == PhysicsScene.SimulationStep); } - set { CollidingGround = value; } + get { return (CollidingGroundStep == PhysicsScene.SimulationStep); } + set { CollidingGround = value; } } - public override bool CollidingObj { - get { return _collidingObj; } - set { _collidingObj = value; } + public override bool CollidingObj { + get { return _collidingObj; } + set { _collidingObj = value; } } - public override bool FloatOnWater { - set { _floatOnWater = value; } + public override bool FloatOnWater { + set { _floatOnWater = value; } } - public override OMV.Vector3 RotationalVelocity { - get { return _rotationalVelocity; } - set { _rotationalVelocity = value; } + public override OMV.Vector3 RotationalVelocity { + get { return _rotationalVelocity; } + set { _rotationalVelocity = value; } } - public override bool Kinematic { - get { return _kinematic; } - set { _kinematic = value; } + public override bool Kinematic { + get { return _kinematic; } + set { _kinematic = value; } } // neg=fall quickly, 0=1g, 1=0g, pos=float up - public override float Buoyancy { - get { return _buoyancy; } - set { _buoyancy = value; + public override float Buoyancy { + get { return _buoyancy; } + set { _buoyancy = value; PhysicsScene.TaintedObject("BSCharacter.setBuoyancy", delegate() { DetailLog("{0},BSCharacter.setBuoyancy,taint,buoy={1}", LocalID, _buoyancy); BulletSimAPI.SetObjectBuoyancy(PhysicsScene.WorldID, LocalID, _buoyancy); }); - } + } } // Used for MoveTo - public override OMV.Vector3 PIDTarget { - set { _PIDTarget = value; } + public override OMV.Vector3 PIDTarget { + set { _PIDTarget = value; } } - public override bool PIDActive { - set { _usePID = value; } + public override bool PIDActive { + set { _usePID = value; } } - public override float PIDTau { - set { _PIDTau = value; } + public override float PIDTau { + set { _PIDTau = value; } } // Used for llSetHoverHeight and maybe vehicle height // Hover Height will override MoveTo target's Z - public override bool PIDHoverActive { + public override bool PIDHoverActive { set { _useHoverPID = value; } } - public override float PIDHoverHeight { + public override float PIDHoverHeight { set { _PIDHoverHeight = value; } } - public override PIDHoverType PIDHoverType { + public override PIDHoverType PIDHoverType { set { _PIDHoverType = value; } } - public override float PIDHoverTau { + public override float PIDHoverTau { set { _PIDHoverTao = value; } } @@ -433,7 +432,7 @@ public class BSCharacter : BSPhysObject public override float APIDStrength { set { return; } } public override float APIDDamping { set { return; } } - public override void AddForce(OMV.Vector3 force, bool pushforce) { + public override void AddForce(OMV.Vector3 force, bool pushforce) { if (force.IsFinite()) { _force.X += force.X; @@ -453,9 +452,9 @@ public class BSCharacter : BSPhysObject //m_lastUpdateSent = false; } - public override void AddAngularForce(OMV.Vector3 force, bool pushforce) { + public override void AddAngularForce(OMV.Vector3 force, bool pushforce) { } - public override void SetMomentum(OMV.Vector3 momentum) { + public override void SetMomentum(OMV.Vector3 momentum) { } private void ComputeAvatarScale(OMV.Vector3 size) diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index cf33d0e..65b38d6 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -491,7 +491,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin // remember the position so next step we can limit absolute movement effects m_lastPositionVector = Prim.Position; - VDetailLog("{0},BSDynamics.Step,done,pos={1},force={2},velocity={3},angvel={4}", + VDetailLog("{0},BSDynamics.Step,done,pos={1},force={2},velocity={3},angvel={4}", Prim.LocalID, Prim.Position, Prim.Force, Prim.Velocity, Prim.RotationalVelocity); }// end Step @@ -511,8 +511,8 @@ namespace OpenSim.Region.Physics.BulletSPlugin Vector3 addAmount = (m_linearMotorDirection - m_lastLinearVelocityVector)/(m_linearMotorTimescale / pTimestep); // lastLinearVelocityVector is the current body velocity vector // RA: Not sure what the *10 is for. A correction for pTimestep? - // m_lastLinearVelocityVector += (addAmount*10); - m_lastLinearVelocityVector += addAmount; + // m_lastLinearVelocityVector += (addAmount*10); + m_lastLinearVelocityVector += addAmount; // Limit the velocity vector to less than the last set linear motor direction if (Math.Abs(m_lastLinearVelocityVector.X) > Math.Abs(m_linearMotorDirectionLASTSET.X)) @@ -695,7 +695,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin Vector3 keepFraction = Vector3.One - (Vector3.One / (m_linearFrictionTimescale / pTimestep)); m_lastLinearVelocityVector *= keepFraction; - VDetailLog("{0},MoveLinear,done,lmDir={1},lmVel={2},newVel={3},grav={4},1Mdecay={5}", + VDetailLog("{0},MoveLinear,done,lmDir={1},lmVel={2},newVel={3},grav={4},1Mdecay={5}", Prim.LocalID, m_linearMotorDirection, m_lastLinearVelocityVector, m_newVelocity, grav, keepFraction); } // end MoveLinear() @@ -728,7 +728,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin m_angularMotorVelocity.Y += (m_angularMotorDirection.Y - m_angularMotorVelocity.Y) / (m_angularMotorTimescale / pTimestep); m_angularMotorVelocity.Z += (m_angularMotorDirection.Z - m_angularMotorVelocity.Z) / (m_angularMotorTimescale / pTimestep); - VDetailLog("{0},MoveAngular,angularMotorApply,apply={1},angTScale={2},timeStep={3},origvel={4},dir={5},vel={6}", + VDetailLog("{0},MoveAngular,angularMotorApply,apply={1},angTScale={2},timeStep={3},origvel={4},dir={5},vel={6}", Prim.LocalID, m_angularMotorApply, m_angularMotorTimescale, pTimestep, origAngularVelocity, m_angularMotorDirection, m_angularMotorVelocity); // This is done so that if script request rate is less than phys frame rate the expected @@ -779,7 +779,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin vertattr.X += bounce * angularVelocity.X; vertattr.Y += bounce * angularVelocity.Y; - VDetailLog("{0},MoveAngular,verticalAttraction,verterr={1},bounce={2},vertattr={3}", + VDetailLog("{0},MoveAngular,verticalAttraction,verterr={1},bounce={2},vertattr={3}", Prim.LocalID, verterr, bounce, vertattr); } // else vertical attractor is off @@ -792,7 +792,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin // Sum velocities m_lastAngularVelocity = m_angularMotorVelocity + vertattr; // + bank + deflection - + if ((m_flags & (VehicleFlag.NO_DEFLECTION_UP)) != 0) { m_lastAngularVelocity.X = 0; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index 6967108..b0cc63c 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -53,9 +53,9 @@ public class BSLinkset // We keep the prim's mass in the linkset structure since it could be dependent on other prims private float m_mass; - public float LinksetMass - { - get + public float LinksetMass + { + get { m_mass = ComputeLinksetMass(); return m_mass; @@ -77,7 +77,7 @@ public class BSLinkset // A simple linkset of one (no children) LinksetID = m_nextLinksetID++; // We create LOTS of linksets. - if (m_nextLinksetID <= 0) + if (m_nextLinksetID <= 0) m_nextLinksetID = 1; PhysicsScene = scene; LinksetRoot = parent; @@ -276,7 +276,7 @@ public class BSLinkset BSConstraint constrain; if (PhysicsScene.Constraints.TryGetConstraint(LinksetRoot.BSBody, child.BSBody, out constrain)) { - // DetailLog("{0},BSLinkset.RecomputeLinksetConstraintVariables,taint,child={1},mass={2},A={3},B={4}", + // DetailLog("{0},BSLinkset.RecomputeLinksetConstraintVariables,taint,child={1},mass={2},A={3},B={4}", // LinksetRoot.LocalID, child.LocalID, linksetMass, constrain.Body1.ID, constrain.Body2.ID); constrain.RecomputeConstraintVariables(linksetMass); } @@ -392,14 +392,14 @@ public class BSLinkset // create a constraint that allows no freedom of movement between the two objects // http://bulletphysics.org/Bullet/phpBB3/viewtopic.php?t=4818 - DetailLog("{0},PhysicallyLinkAChildToRoot,taint,root={1},rBody={2},child={3},cBody={4},rLoc={5},cLoc={6},midLoc={7}", - rootPrim.LocalID, - rootPrim.LocalID, rootBody.ptr.ToString("X"), - childPrim.LocalID, childBody.ptr.ToString("X"), + DetailLog("{0},PhysicallyLinkAChildToRoot,taint,root={1},rBody={2},child={3},cBody={4},rLoc={5},cLoc={6},midLoc={7}", + rootPrim.LocalID, + rootPrim.LocalID, rootBody.ptr.ToString("X"), + childPrim.LocalID, childBody.ptr.ToString("X"), rootPrim.Position, childPrim.Position, midPoint); // There is great subtlty in these paramters. Notice the check for a ptr of zero. - // We pass the BulletBody structure into the taint in order to capture the pointer + // We pass the BulletBody structure into the taint in order to capture the pointer // of the body at the time of constraint creation. This doesn't work for the very first // construction because there is no body yet. The body // is constructed later at taint time. Thus we use the body address at time of the @@ -409,8 +409,8 @@ public class BSLinkset // to only change BSShape at taint time thus syncronizing these operations at // the cost of efficiency and lag. BS6DofConstraint constrain = new BS6DofConstraint( - PhysicsScene.World, - rootBody.ptr == IntPtr.Zero ? rootPrim.BSBody : rootBody, + PhysicsScene.World, + rootBody.ptr == IntPtr.Zero ? rootPrim.BSBody : rootBody, childBody.ptr == IntPtr.Zero ? childPrim.BSBody : childBody, midPoint, true, @@ -473,11 +473,11 @@ public class BSLinkset // The root and child bodies are passed in because we need to remove the constraint between // the bodies that were at unlink time. // Called at taint time! - private void PhysicallyUnlinkAChildFromRoot(BSPhysObject rootPrim, BulletBody rootBody, + private void PhysicallyUnlinkAChildFromRoot(BSPhysObject rootPrim, BulletBody rootBody, BSPhysObject childPrim, BulletBody childBody) { - DetailLog("{0},PhysicallyUnlinkAChildFromRoot,taint,root={1},rBody={2},child={3},cBody={4}", - rootPrim.LocalID, + DetailLog("{0},PhysicallyUnlinkAChildFromRoot,taint,root={1},rBody={2},child={3},cBody={4}", + rootPrim.LocalID, rootPrim.LocalID, rootBody.ptr.ToString("X"), childPrim.LocalID, childBody.ptr.ToString("X")); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index df95625..d9b738b 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -100,7 +100,7 @@ public abstract class BSPhysObject : PhysicsActor // The simulation step is telling this object about a collision. // Return 'true' if a collision was processed and should be sent up. // Called at taint time from within the Step() function - public virtual bool Collide(uint collidingWith, BSPhysObject collidee, + public virtual bool Collide(uint collidingWith, BSPhysObject collidee, OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth) { bool ret = false; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPlugin.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPlugin.cs index 0f027b8..20f5180 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPlugin.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPlugin.cs @@ -33,7 +33,7 @@ using OpenMetaverse; namespace OpenSim.Region.Physics.BulletSPlugin { /// - /// Entry for a port of Bullet (http://bulletphysics.org/) to OpenSim. + /// Entry for a port of Bullet (http://bulletphysics.org/) to OpenSim. /// This module interfaces to an unmanaged C++ library which makes the /// actual calls into the Bullet physics engine. /// The unmanaged library is found in opensim-libs::trunk/unmanaged/BulletSim/. @@ -62,7 +62,7 @@ public class BSPlugin : IPhysicsPlugin if (Util.IsWindows()) Util.LoadArchSpecificWindowsDll("BulletSim.dll"); // If not Windows, loading is performed by the - // Mono loader as specified in + // Mono loader as specified in // "bin/Physics/OpenSim.Region.Physics.BulletSPlugin.dll.config". _mScene = new BSScene(sceneIdentifier); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index e65e42b..8688485 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -158,12 +158,12 @@ public sealed class BSPrim : BSPhysObject BulletSimAPI.DestroyObject(PhysicsScene.WorldID, LocalID); }); } - - public override bool Stopped { - get { return _stopped; } + + public override bool Stopped { + get { return _stopped; } } - public override OMV.Vector3 Size { - get { return _size; } + public override OMV.Vector3 Size { + get { return _size; } set { _size = value; PhysicsScene.TaintedObject("BSPrim.setSize", delegate() @@ -174,7 +174,7 @@ public sealed class BSPrim : BSPhysObject CreateGeomAndObject(true); // DetailLog("{0},BSPrim.setSize,size={1},scale={2},mass={3},physical={4}", LocalID, _size, _scale, _mass, IsPhysical); }); - } + } } // Scale is what we set in the physics engine. It is different than 'size' in that // 'size' can be encorporated into the mesh. In that case, the scale is <1,1,1>. @@ -183,7 +183,7 @@ public sealed class BSPrim : BSPhysObject get { return _scale; } set { _scale = value; } } - public override PrimitiveBaseShape Shape { + public override PrimitiveBaseShape Shape { set { _pbs = value; PhysicsScene.TaintedObject("BSPrim.setShape", delegate() @@ -191,13 +191,13 @@ public sealed class BSPrim : BSPhysObject _mass = CalculateMass(); // changing the shape changes the mass CreateGeomAndObject(true); }); - } + } } - public override bool Grabbed { - set { _grabbed = value; - } + public override bool Grabbed { + set { _grabbed = value; + } } - public override bool Selected { + public override bool Selected { set { _isSelected = value; PhysicsScene.TaintedObject("BSPrim.setSelected", delegate() @@ -205,7 +205,7 @@ public sealed class BSPrim : BSPhysObject // DetailLog("{0},BSPrim.selected,taint,selected={1}", LocalID, _isSelected); SetObjectDynamic(false); }); - } + } } public override void CrossingFailure() { return; } @@ -219,10 +219,10 @@ public sealed class BSPrim : BSPhysObject Linkset = parent.Linkset.AddMeToLinkset(this); - DetailLog("{0},BSPrim.link,call,parentBefore={1}, childrenBefore=={2}, parentAfter={3}, childrenAfter={4}", + DetailLog("{0},BSPrim.link,call,parentBefore={1}, childrenBefore=={2}, parentAfter={3}, childrenAfter={4}", LocalID, parentBefore.LocalID, childrenBefore, Linkset.LinksetRoot.LocalID, Linkset.NumberOfChildren); } - return; + return; } // delink me from my linkset @@ -232,12 +232,12 @@ public sealed class BSPrim : BSPhysObject BSPhysObject parentBefore = Linkset.LinksetRoot; int childrenBefore = Linkset.NumberOfChildren; - + Linkset = Linkset.RemoveMeFromLinkset(this); - DetailLog("{0},BSPrim.delink,parentBefore={1},childrenBefore={2},parentAfter={3},childrenAfter={4}, ", + DetailLog("{0},BSPrim.delink,parentBefore={1},childrenBefore={2},parentAfter={3},childrenAfter={4}, ", LocalID, parentBefore.LocalID, childrenBefore, Linkset.LinksetRoot.LocalID, Linkset.NumberOfChildren); - return; + return; } // Set motion values to zero. @@ -258,21 +258,21 @@ public sealed class BSPrim : BSPhysObject } public override void LockAngularMotion(OMV.Vector3 axis) - { + { DetailLog("{0},BSPrim.LockAngularMotion,call,axis={1}", LocalID, axis); return; } - public override OMV.Vector3 Position { - get { + public override OMV.Vector3 Position { + get { if (!Linkset.IsRoot(this)) // child prims move around based on their parent. Need to get the latest location _position = BulletSimAPI.GetPosition2(BSBody.ptr); // don't do the GetObjectPosition for root elements because this function is called a zillion times // _position = BulletSimAPI.GetObjectPosition2(PhysicsScene.World.ptr, BSBody.ptr); - return _position; - } + return _position; + } set { _position = value; // TODO: what does it mean to set the position of a child prim?? Rebuild the constraint? @@ -281,13 +281,13 @@ public sealed class BSPrim : BSPhysObject // DetailLog("{0},BSPrim.SetPosition,taint,pos={1},orient={2}", LocalID, _position, _orientation); BulletSimAPI.SetTranslation2(BSBody.ptr, _position, _orientation); }); - } + } } // Return the effective mass of the object. // If there are multiple items in the linkset, add them together for the root public override float Mass - { + { get { // return Linkset.LinksetMass; @@ -310,8 +310,8 @@ public sealed class BSPrim : BSPhysObject get { return Linkset.GeometricCenter; } } - public override OMV.Vector3 Force { - get { return _force; } + public override OMV.Vector3 Force { + get { return _force; } set { _force = value; PhysicsScene.TaintedObject("BSPrim.setForce", delegate() @@ -319,13 +319,13 @@ public sealed class BSPrim : BSPhysObject // DetailLog("{0},BSPrim.setForce,taint,force={1}", LocalID, _force); BulletSimAPI.SetObjectForce2(BSBody.ptr, _force); }); - } + } } - public override int VehicleType { + public override int VehicleType { get { return (int)_vehicle.Type; // if we are a vehicle, return that type - } + } set { Vehicle type = (Vehicle)value; BSPrim vehiclePrim = this; @@ -337,30 +337,30 @@ public sealed class BSPrim : BSPhysObject // Tell the scene about the vehicle so it will get processing each frame. PhysicsScene.VehicleInSceneTypeChanged(this, type); }); - } + } } - public override void VehicleFloatParam(int param, float value) + public override void VehicleFloatParam(int param, float value) { PhysicsScene.TaintedObject("BSPrim.VehicleFloatParam", delegate() { _vehicle.ProcessFloatVehicleParam((Vehicle)param, value); }); } - public override void VehicleVectorParam(int param, OMV.Vector3 value) + public override void VehicleVectorParam(int param, OMV.Vector3 value) { PhysicsScene.TaintedObject("BSPrim.VehicleVectorParam", delegate() { _vehicle.ProcessVectorVehicleParam((Vehicle)param, value); }); } - public override void VehicleRotationParam(int param, OMV.Quaternion rotation) + public override void VehicleRotationParam(int param, OMV.Quaternion rotation) { PhysicsScene.TaintedObject("BSPrim.VehicleRotationParam", delegate() { _vehicle.ProcessRotationVehicleParam((Vehicle)param, rotation); }); } - public override void VehicleFlags(int param, bool remove) + public override void VehicleFlags(int param, bool remove) { PhysicsScene.TaintedObject("BSPrim.VehicleFlags", delegate() { @@ -388,11 +388,11 @@ public sealed class BSPrim : BSPhysObject SetObjectDynamic(true); }); } - return; + return; } - public override OMV.Vector3 Velocity { - get { return _velocity; } + public override OMV.Vector3 Velocity { + get { return _velocity; } set { _velocity = value; PhysicsScene.TaintedObject("BSPrim.setVelocity", delegate() @@ -400,24 +400,24 @@ public sealed class BSPrim : BSPhysObject // DetailLog("{0},BSPrim.SetVelocity,taint,vel={1}", LocalID, _velocity); BulletSimAPI.SetLinearVelocity2(BSBody.ptr, _velocity); }); - } + } } - public override OMV.Vector3 Torque { - get { return _torque; } - set { _torque = value; + public override OMV.Vector3 Torque { + get { return _torque; } + set { _torque = value; // DetailLog("{0},BSPrim.SetTorque,call,torque={1}", LocalID, _torque); - } + } } - public override float CollisionScore { - get { return _collisionScore; } - set { _collisionScore = value; - } + public override float CollisionScore { + get { return _collisionScore; } + set { _collisionScore = value; + } } - public override OMV.Vector3 Acceleration { + public override OMV.Vector3 Acceleration { get { return _acceleration; } set { _acceleration = value; } } - public override OMV.Quaternion Orientation { + public override OMV.Quaternion Orientation { get { if (!Linkset.IsRoot(this)) { @@ -425,7 +425,7 @@ public sealed class BSPrim : BSPhysObject _orientation = BulletSimAPI.GetOrientation2(BSBody.ptr); } return _orientation; - } + } set { _orientation = value; // TODO: what does it mean if a child in a linkset changes its orientation? Rebuild the constraint? @@ -435,14 +435,14 @@ public sealed class BSPrim : BSPhysObject // DetailLog("{0},BSPrim.setOrientation,taint,pos={1},orient={2}", LocalID, _position, _orientation); BulletSimAPI.SetTranslation2(BSBody.ptr, _position, _orientation); }); - } + } } - public override int PhysicsActorType { - get { return _physicsActorType; } - set { _physicsActorType = value; } + public override int PhysicsActorType { + get { return _physicsActorType; } + set { _physicsActorType = value; } } - public override bool IsPhysical { - get { return _isPhysical; } + public override bool IsPhysical { + get { return _isPhysical; } set { if (_isPhysical != value) { @@ -453,7 +453,7 @@ public sealed class BSPrim : BSPhysObject SetObjectDynamic(true); }); } - } + } } // An object is static (does not move) if selected or not physical @@ -519,7 +519,7 @@ public sealed class BSPrim : BSPhysObject // had been automatically disabled when the mass was set to zero. Linkset.Refresh(this); - DetailLog("{0},BSPrim.UpdatePhysicalParameters,exit,static={1},solid={2},mass={3},collide={4},cf={5:X},body={6},shape={7}", + DetailLog("{0},BSPrim.UpdatePhysicalParameters,exit,static={1},solid={2},mass={3},collide={4},cf={5:X},body={6},shape={7}", LocalID, IsStatic, IsSolid, _mass, SubscribedEvents(), CurrentCollisionFlags, BSBody, BSShape); } @@ -630,31 +630,31 @@ public sealed class BSPrim : BSPhysObject } // prims don't fly - public override bool Flying { - get { return _flying; } + public override bool Flying { + get { return _flying; } set { _flying = value; - } + } } - public override bool SetAlwaysRun { - get { return _setAlwaysRun; } - set { _setAlwaysRun = value; } + public override bool SetAlwaysRun { + get { return _setAlwaysRun; } + set { _setAlwaysRun = value; } } - public override bool ThrottleUpdates { - get { return _throttleUpdates; } - set { _throttleUpdates = value; } + public override bool ThrottleUpdates { + get { return _throttleUpdates; } + set { _throttleUpdates = value; } } public override bool IsColliding { - get { return (CollidingStep == PhysicsScene.SimulationStep); } - set { _isColliding = value; } + get { return (CollidingStep == PhysicsScene.SimulationStep); } + set { _isColliding = value; } } public override bool CollidingGround { - get { return (CollidingGroundStep == PhysicsScene.SimulationStep); } - set { _collidingGround = value; } + get { return (CollidingGroundStep == PhysicsScene.SimulationStep); } + set { _collidingGround = value; } } - public override bool CollidingObj { - get { return _collidingObj; } - set { _collidingObj = value; } + public override bool CollidingObj { + get { return _collidingObj; } + set { _collidingObj = value; } } public bool IsPhantom { get { @@ -664,10 +664,10 @@ public sealed class BSPrim : BSPhysObject return false; } } - public override bool FloatOnWater { - set { _floatOnWater = value; } + public override bool FloatOnWater { + set { _floatOnWater = value; } } - public override OMV.Vector3 RotationalVelocity { + public override OMV.Vector3 RotationalVelocity { get { /* OMV.Vector3 pv = OMV.Vector3.Zero; @@ -679,7 +679,7 @@ public sealed class BSPrim : BSPhysObject */ return _rotationalVelocity; - } + } set { _rotationalVelocity = value; // m_log.DebugFormat("{0}: RotationalVelocity={1}", LogHeader, _rotationalVelocity); @@ -688,16 +688,16 @@ public sealed class BSPrim : BSPhysObject // DetailLog("{0},BSPrim.SetRotationalVel,taint,rotvel={1}", LocalID, _rotationalVelocity); BulletSimAPI.SetAngularVelocity2(BSBody.ptr, _rotationalVelocity); }); - } + } } - public override bool Kinematic { - get { return _kinematic; } - set { _kinematic = value; + public override bool Kinematic { + get { return _kinematic; } + set { _kinematic = value; // m_log.DebugFormat("{0}: Kinematic={1}", LogHeader, _kinematic); - } + } } - public override float Buoyancy { - get { return _buoyancy; } + public override float Buoyancy { + get { return _buoyancy; } set { _buoyancy = value; PhysicsScene.TaintedObject("BSPrim.setBuoyancy", delegate() @@ -707,32 +707,32 @@ public sealed class BSPrim : BSPhysObject float grav = PhysicsScene.Params.gravity * (1f - _buoyancy); BulletSimAPI.SetGravity2(BSBody.ptr, new OMV.Vector3(0f, 0f, grav)); }); - } + } } // Used for MoveTo - public override OMV.Vector3 PIDTarget { - set { _PIDTarget = value; } + public override OMV.Vector3 PIDTarget { + set { _PIDTarget = value; } } - public override bool PIDActive { - set { _usePID = value; } + public override bool PIDActive { + set { _usePID = value; } } - public override float PIDTau { - set { _PIDTau = value; } + public override float PIDTau { + set { _PIDTau = value; } } // Used for llSetHoverHeight and maybe vehicle height // Hover Height will override MoveTo target's Z - public override bool PIDHoverActive { + public override bool PIDHoverActive { set { _useHoverPID = value; } } - public override float PIDHoverHeight { + public override float PIDHoverHeight { set { _PIDHoverHeight = value; } } - public override PIDHoverType PIDHoverType { + public override PIDHoverType PIDHoverType { set { _PIDHoverType = value; } } - public override float PIDHoverTau { + public override float PIDHoverTau { set { _PIDHoverTao = value; } } @@ -773,11 +773,11 @@ public sealed class BSPrim : BSPhysObject }); } - public override void AddAngularForce(OMV.Vector3 force, bool pushforce) { + public override void AddAngularForce(OMV.Vector3 force, bool pushforce) { // DetailLog("{0},BSPrim.AddAngularForce,call,angForce={1},push={2}", LocalID, force, pushforce); // m_log.DebugFormat("{0}: AddAngularForce. f={1}, push={2}", LogHeader, force, pushforce); } - public override void SetMomentum(OMV.Vector3 momentum) { + public override void SetMomentum(OMV.Vector3 momentum) { // DetailLog("{0},BSPrim.SetMomentum,call,mom={1}", LocalID, momentum); } #region Mass Calculation @@ -789,8 +789,8 @@ public sealed class BSPrim : BSPhysObject float returnMass = 0; float hollowAmount = (float)_pbs.ProfileHollow * 2.0e-5f; - float hollowVolume = hollowAmount * hollowAmount; - + float hollowVolume = hollowAmount * hollowAmount; + switch (_pbs.ProfileShape) { case ProfileShape.Square: @@ -826,16 +826,16 @@ public sealed class BSPrim : BSPhysObject else if (_pbs.PathCurve == (byte)Extrusion.Curve1) { - //a tube + //a tube volume *= 0.78539816339e-2f * (float)(200 - _pbs.PathScaleX); tmp= 1.0f -2.0e-2f * (float)(200 - _pbs.PathScaleY); volume -= volume*tmp*tmp; - + if (hollowAmount > 0.0) { hollowVolume *= hollowAmount; - + switch (_pbs.HollowShape) { case HollowShape.Square: @@ -894,7 +894,7 @@ public sealed class BSPrim : BSPhysObject volume *= 0.61685027506808491367715568749226e-2f * (float)(200 - _pbs.PathScaleX); tmp = 1.0f - .02f * (float)(200 - _pbs.PathScaleY); volume *= (1.0f - tmp * tmp); - + if (hollowAmount > 0.0) { @@ -1118,7 +1118,7 @@ public sealed class BSPrim : BSPhysObject PhysicsScene.Shapes.GetBodyAndShape(forceRebuild, PhysicsScene.World, this, shapeData, _pbs); Linkset = Linkset.AddMeToLinkset(this); - + // Make sure the properties are set on the new object UpdatePhysicalParameters(); return; @@ -1210,7 +1210,7 @@ public sealed class BSPrim : BSPhysObject { // For debugging, we can also 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, + LocalID, entprop.Position, entprop.Rotation, entprop.Velocity, entprop.Acceleration, entprop.RotationalVelocity); } */ diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index 44a249c..0cf8c91 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -49,7 +49,7 @@ using OpenMetaverse; // At the moment, physical and phantom causes object to drop through the terrain // Physical phantom objects and related typing (collision options ) // Check out llVolumeDetect. Must do something for that. -// Use collision masks for collision with terrain and phantom objects +// Use collision masks for collision with terrain and phantom objects // More efficient memory usage when passing hull information from BSPrim to BulletSim // Should prim.link() and prim.delink() membership checking happen at taint time? // Mesh sharing. Use meshHash to tell if we already have a hull of that shape and only create once. @@ -60,7 +60,7 @@ using OpenMetaverse; // Add PID movement operations. What does ScenePresence.MoveToTarget do? // Check terrain size. 128 or 127? // Raycast -// +// namespace OpenSim.Region.Physics.BulletSPlugin { public class BSScene : PhysicsScene, IPhysicsParameters @@ -327,7 +327,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters { m_log.Debug("[BULLETS UNMANAGED]:" + msg); } - + // Called directly from unmanaged code so don't do much private void BulletLoggerPhysLog(string msg) { @@ -460,7 +460,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters } // This is a call from the simulator saying that some physical property has been updated. - // The BulletSim driver senses the changing of relevant properties so this taint + // The BulletSim driver senses the changing of relevant properties so this taint // information call is not needed. public override void AddPhysicsActorTaint(PhysicsActor prim) { } @@ -501,14 +501,14 @@ public class BSScene : PhysicsScene, IPhysicsParameters out updatedEntityCount, out updatedEntitiesPtr, out collidersCount, out collidersPtr); if (PhysicsLogging.Enabled) simTime = Util.EnvironmentTickCountSubtract(beforeTime); - DetailLog("{0},Simulate,call, nTaints={1}, simTime={2}, substeps={3}, updates={4}, colliders={5}", - DetailLogZero, numTaints, simTime, numSubSteps, updatedEntityCount, collidersCount); + DetailLog("{0},Simulate,call, nTaints={1}, simTime={2}, substeps={3}, updates={4}, colliders={5}", + DetailLogZero, numTaints, simTime, numSubSteps, updatedEntityCount, collidersCount); } catch (Exception e) { - m_log.WarnFormat("{0},PhysicsStep Exception: nTaints={1}, substeps={2}, updates={3}, colliders={4}, e={5}", + m_log.WarnFormat("{0},PhysicsStep Exception: nTaints={1}, substeps={2}, updates={3}, colliders={4}, e={5}", LogHeader, numTaints, numSubSteps, updatedEntityCount, collidersCount, e); - DetailLog("{0},PhysicsStepException,call, nTaints={1}, substeps={2}, updates={3}, colliders={4}", + DetailLog("{0},PhysicsStepException,call, nTaints={1}, substeps={2}, updates={3}, colliders={4}", DetailLogZero, numTaints, numSubSteps, updatedEntityCount, collidersCount); updatedEntityCount = 0; collidersCount = 0; @@ -535,7 +535,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters } } - // This is a kludge to get avatar movement updates. + // This is a kludge to get avatar movement updates. // ODE sends collisions for avatars even if there are have been no collisions. This updates // avatar animations and stuff. // If you fix avatar animation updates, remove this overhead and let normal collision processing happen. @@ -634,7 +634,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters TerrainManager.SetTerrain(heightMap); } - public override void SetWaterLevel(float baseheight) + public override void SetWaterLevel(float baseheight) { m_waterLevel = baseheight; } @@ -644,7 +644,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters return m_waterLevel; } - public override void DeleteTerrain() + public override void DeleteTerrain() { // m_log.DebugFormat("{0}: DeleteTerrain()", LogHeader); } @@ -806,7 +806,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters // getters and setters. // It is easiest to find an existing definition and copy it. // Parameter values are floats. Booleans are converted to a floating value. - // + // // A ParameterDefn() takes the following parameters: // -- the text name of the parameter. This is used for console input and ini file. // -- a short text description of the parameter. This shows up in the console listing. @@ -1228,7 +1228,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters } }); break; - default: + default: // setting only one localID TaintedUpdateParameter(parm, localID, val); break; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index 72c6df5..b428ba3 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -102,7 +102,7 @@ public class BSShapeCollection : IDisposable bool newBody = CreateBody((newGeom || forceRebuild), prim, PhysicsScene.World, prim.BSShape, shapeData); ret = newGeom || newBody; } - DetailLog("{0},BSShapeCollection.GetBodyAndShape,force={1},ret={2},body={3},shape={4}", + DetailLog("{0},BSShapeCollection.GetBodyAndShape,force={1},ret={2},body={3},shape={4}", prim.LocalID, forceRebuild, ret, prim.BSBody, prim.BSShape); return ret; @@ -149,14 +149,14 @@ public class BSShapeCollection : IDisposable bodyDesc.lastReferenced = System.DateTime.Now; Bodies[shape.ID] = bodyDesc; DetailLog("{0},BSShapeCollection.DereferenceBody,ref={1}", shape.ID, bodyDesc.referenceCount); - + // If body is no longer being used, free it -- bodies are never shared. if (bodyDesc.referenceCount == 0) { Bodies.Remove(shape.ID); BSScene.TaintCallback removeOperation = delegate() { - DetailLog("{0},BSShapeCollection.DereferenceBody,DestroyingBody. ptr={1}", + DetailLog("{0},BSShapeCollection.DereferenceBody,DestroyingBody. ptr={1}", shape.ID, shape.ptr.ToString("X")); // Zero any reference to the shape so it is not freed when the body is deleted. BulletSimAPI.SetCollisionShape2(PhysicsScene.World.ptr, shape.ptr, IntPtr.Zero); @@ -344,28 +344,28 @@ public class BSShapeCollection : IDisposable if (pbs.ProfileShape == ProfileShape.HalfCircle && pbs.PathCurve == (byte)Extrusion.Curve1) { haveShape = true; - if (forceRebuild + if (forceRebuild || prim.Scale != shapeData.Size || prim.BSShape.type != ShapeData.PhysicsShapeType.SHAPE_SPHERE ) { - ret = GetReferenceToNativeShape(prim, shapeData, + ret = GetReferenceToNativeShape(prim, shapeData, ShapeData.PhysicsShapeType.SHAPE_SPHERE, ShapeData.FixedShapeKey.KEY_SPHERE); - DetailLog("{0},BSShapeCollection.CreateGeom,sphere,force={1},shape={2}", + DetailLog("{0},BSShapeCollection.CreateGeom,sphere,force={1},shape={2}", prim.LocalID, forceRebuild, prim.BSShape); } } else { haveShape = true; - if (forceRebuild + if (forceRebuild || prim.Scale != shapeData.Size || prim.BSShape.type != ShapeData.PhysicsShapeType.SHAPE_BOX ) { ret = GetReferenceToNativeShape( prim, shapeData, ShapeData.PhysicsShapeType.SHAPE_BOX, ShapeData.FixedShapeKey.KEY_BOX); - DetailLog("{0},BSShapeCollection.CreateGeom,box,force={1},shape={2}", + DetailLog("{0},BSShapeCollection.CreateGeom,box,force={1},shape={2}", prim.LocalID, forceRebuild, prim.BSShape); } } @@ -379,13 +379,13 @@ public class BSShapeCollection : IDisposable { // Update prim.BSShape to reference a hull of this shape. ret = GetReferenceToHull(prim, shapeData, pbs); - DetailLog("{0},BSShapeCollection.CreateGeom,hull,shape={1},key={2}", + DetailLog("{0},BSShapeCollection.CreateGeom,hull,shape={1},key={2}", shapeData.ID, prim.BSShape, prim.BSShape.shapeKey.ToString("X")); } else { ret = GetReferenceToMesh(prim, shapeData, pbs); - DetailLog("{0},BSShapeCollection.CreateGeom,mesh,shape={1},key={2}", + DetailLog("{0},BSShapeCollection.CreateGeom,mesh,shape={1},key={2}", shapeData.ID, prim.BSShape, prim.BSShape.shapeKey.ToString("X")); } } @@ -393,7 +393,7 @@ public class BSShapeCollection : IDisposable } // Creates a native shape and assignes it to prim.BSShape - private bool GetReferenceToNativeShape( BSPrim prim, ShapeData shapeData, + private bool GetReferenceToNativeShape( BSPrim prim, ShapeData shapeData, ShapeData.PhysicsShapeType shapeType, ShapeData.FixedShapeKey shapeKey) { BulletShape newShape; @@ -432,7 +432,7 @@ public class BSShapeCollection : IDisposable // if this new shape is the same as last time, don't recreate the mesh if (prim.BSShape.shapeKey == newMeshKey) return false; - DetailLog("{0},BSShapeCollection.CreateGeomMesh,create,oldKey={1},newKey={2}", + DetailLog("{0},BSShapeCollection.CreateGeomMesh,create,oldKey={1},newKey={2}", prim.LocalID, prim.BSShape.shapeKey.ToString("X"), newMeshKey.ToString("X")); // Since we're recreating new, get rid of the reference to the previous shape @@ -476,10 +476,10 @@ public class BSShapeCollection : IDisposable verticesAsFloats[vi++] = vv.Z; } - // m_log.DebugFormat("{0}: CreateGeomMesh: calling CreateMesh. lid={1}, key={2}, indices={3}, vertices={4}", + // m_log.DebugFormat("{0}: CreateGeomMesh: calling CreateMesh. lid={1}, key={2}, indices={3}, vertices={4}", // LogHeader, prim.LocalID, newMeshKey, indices.Length, vertices.Count); - meshPtr = BulletSimAPI.CreateMeshShape2(PhysicsScene.World.ptr, + meshPtr = BulletSimAPI.CreateMeshShape2(PhysicsScene.World.ptr, indices.GetLength(0), indices, vertices.Count, verticesAsFloats); } BulletShape newShape = new BulletShape(meshPtr, ShapeData.PhysicsShapeType.SHAPE_MESH); @@ -501,14 +501,14 @@ public class BSShapeCollection : IDisposable if (newHullKey == prim.BSShape.shapeKey && prim.BSShape.type == ShapeData.PhysicsShapeType.SHAPE_HULL) return false; - DetailLog("{0},BSShapeCollection.CreateGeomHull,create,oldKey={1},newKey={2}", + DetailLog("{0},BSShapeCollection.CreateGeomHull,create,oldKey={1},newKey={2}", prim.LocalID, prim.BSShape.shapeKey.ToString("X"), newHullKey.ToString("X")); // Remove usage of the previous shape. Also removes reference to underlying mesh if it is a hull. DereferenceShape(prim.BSShape, true); newShape = CreatePhysicalHull(prim.PhysObjectName, newHullKey, pbs, shapeData.Size, lod); - + ReferenceShape(newShape); // hulls are already scaled by the meshmerizer @@ -559,7 +559,7 @@ public class BSShapeCollection : IDisposable convexBuilder.process(dcomp); // Convert the vertices and indices for passing to unmanaged. - // The hull information is passed as a large floating point array. + // 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 @@ -635,11 +635,11 @@ public class BSShapeCollection : IDisposable { // level of detail based on size and type of the object float lod = PhysicsScene.MeshLOD; - if (pbs.SculptEntry) + if (pbs.SculptEntry) lod = PhysicsScene.SculptLOD; float maxAxis = Math.Max(shapeData.Size.X, Math.Max(shapeData.Size.Y, shapeData.Size.Z)); - if (maxAxis > PhysicsScene.MeshMegaPrimThreshold) + if (maxAxis > PhysicsScene.MeshMegaPrimThreshold) lod = PhysicsScene.MeshMegaPrimLOD; retLod = lod; @@ -685,13 +685,13 @@ public class BSShapeCollection : IDisposable IntPtr bodyPtr = IntPtr.Zero; if (prim.IsSolid) { - bodyPtr = BulletSimAPI.CreateBodyFromShape2(sim.ptr, shape.ptr, + bodyPtr = BulletSimAPI.CreateBodyFromShape2(sim.ptr, shape.ptr, shapeData.ID, shapeData.Position, shapeData.Rotation); // DetailLog("{0},BSShapeCollection.CreateBody,mesh,ptr={1}", prim.LocalID, bodyPtr.ToString("X")); } else { - bodyPtr = BulletSimAPI.CreateGhostFromShape2(sim.ptr, shape.ptr, + bodyPtr = BulletSimAPI.CreateGhostFromShape2(sim.ptr, shape.ptr, shapeData.ID, shapeData.Position, shapeData.Rotation); // DetailLog("{0},BSShapeCollection.CreateBody,ghost,ptr={1}", prim.LocalID, bodyPtr.ToString("X")); } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs index 269c3d5..70aa429 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs @@ -64,7 +64,7 @@ public class BSTerrainManager // The ground plane created to keep thing from falling to infinity. private BulletBody m_groundPlane; - + // If doing mega-regions, if we're region zero we will be managing multiple // region terrains since region zero does the physics for the whole mega-region. private Dictionary m_heightMaps; @@ -110,8 +110,8 @@ public class BSTerrainManager BulletShape groundPlaneShape = new BulletShape( BulletSimAPI.CreateGroundPlaneShape2(BSScene.GROUNDPLANE_ID, 1f, TERRAIN_COLLISION_MARGIN), ShapeData.PhysicsShapeType.SHAPE_GROUNDPLANE); - m_groundPlane = new BulletBody(BSScene.GROUNDPLANE_ID, - BulletSimAPI.CreateBodyWithDefaultMotionState2(groundPlaneShape.ptr, BSScene.GROUNDPLANE_ID, + m_groundPlane = new BulletBody(BSScene.GROUNDPLANE_ID, + BulletSimAPI.CreateBodyWithDefaultMotionState2(groundPlaneShape.ptr, BSScene.GROUNDPLANE_ID, Vector3.Zero, Quaternion.Identity)); BulletSimAPI.AddObjectToWorld2(PhysicsScene.World.ptr, m_groundPlane.ptr); // Everything collides with the ground plane. @@ -182,7 +182,7 @@ public class BSTerrainManager // If not doing the mega-prim thing, just change the terrain DetailLog("{0},SetTerrain.Existing", BSScene.DetailLogZero); - UpdateOrCreateTerrain(BSScene.TERRAIN_ID, localHeightMap, + UpdateOrCreateTerrain(BSScene.TERRAIN_ID, localHeightMap, m_worldOffset, m_worldOffset + DefaultRegionSize, true); } }); @@ -234,7 +234,7 @@ public class BSTerrainManager mapInfo.maxZ = maxZ; mapInfo.sizeX = maxCoords.X - minCoords.X; mapInfo.sizeY = maxCoords.Y - minCoords.Y; - DetailLog("{0},UpdateOrCreateTerrain:UpdateExisting,call,terrainBase={1},minC={2}, maxC={3}, szX={4}, szY={5}", + DetailLog("{0},UpdateOrCreateTerrain:UpdateExisting,call,terrainBase={1},minC={2}, maxC={3}, szX={4}, szY={5}", BSScene.DetailLogZero, terrainRegionBase, mapInfo.minCoords, mapInfo.maxCoords, mapInfo.sizeX, mapInfo.sizeY); BSScene.TaintCallback rebuildOperation = delegate() @@ -255,7 +255,7 @@ public class BSTerrainManager if (mapInfo.terrainBody.ptr != IntPtr.Zero) { // Updating an existing terrain. - DetailLog("{0},UpdateOrCreateTerrain:UpdateExisting,taint,terrainBase={1},minC={2}, maxC={3}, szX={4}, szY={5}", + DetailLog("{0},UpdateOrCreateTerrain:UpdateExisting,taint,terrainBase={1},minC={2}, maxC={3}, szX={4}, szY={5}", BSScene.DetailLogZero, terrainRegionBase, mapInfo.minCoords, mapInfo.maxCoords, mapInfo.sizeX, mapInfo.sizeY); // Remove from the dynamics world because we're going to mangle this object @@ -289,7 +289,7 @@ public class BSTerrainManager // else { // Creating a new terrain. - DetailLog("{0},UpdateOrCreateTerrain:CreateNewTerrain,taint,baseX={1},baseY={2},minZ={3},maxZ={4}", + DetailLog("{0},UpdateOrCreateTerrain:CreateNewTerrain,taint,baseX={1},baseY={2},minZ={3},maxZ={4}", BSScene.DetailLogZero, mapInfo.minCoords.X, mapInfo.minCoords.Y, minZ, maxZ); mapInfo.ID = id; @@ -306,9 +306,9 @@ public class BSTerrainManager mapInfo.terrainShape = new BulletShape(BulletSimAPI.CreateTerrainShape2(mapInfo.Ptr), ShapeData.PhysicsShapeType.SHAPE_TERRAIN); - mapInfo.terrainBody = new BulletBody(mapInfo.ID, - BulletSimAPI.CreateBodyWithDefaultMotionState2(mapInfo.terrainShape.ptr, - id, centerPos, Quaternion.Identity)); + mapInfo.terrainBody = new BulletBody(mapInfo.ID, + BulletSimAPI.CreateBodyWithDefaultMotionState2(mapInfo.terrainShape.ptr, + id, centerPos, Quaternion.Identity)); } // Make sure the entry is in the heightmap table @@ -329,7 +329,7 @@ public class BSTerrainManager // redo its bounding box now that it is in the world BulletSimAPI.UpdateSingleAabb2(PhysicsScene.World.ptr, mapInfo.terrainBody.ptr); - BulletSimAPI.SetCollisionFilterMask2(mapInfo.terrainBody.ptr, + BulletSimAPI.SetCollisionFilterMask2(mapInfo.terrainBody.ptr, (uint)CollisionFilterGroups.TerrainFilter, (uint)CollisionFilterGroups.TerrainMask); @@ -361,7 +361,7 @@ public class BSTerrainManager Vector3 minCoordsX = minCoords; Vector3 maxCoordsX = maxCoords; - DetailLog("{0},UpdateOrCreateTerrain:NewTerrain,call,id={1}, minC={2}, maxC={3}", + DetailLog("{0},UpdateOrCreateTerrain:NewTerrain,call,id={1}, minC={2}, maxC={3}", BSScene.DetailLogZero, newTerrainID, minCoords, minCoords); // Code that must happen at taint-time @@ -370,7 +370,7 @@ public class BSTerrainManager DetailLog("{0},UpdateOrCreateTerrain:NewTerrain,taint,baseX={1},baseY={2}", BSScene.DetailLogZero, minCoords.X, minCoords.Y); // Create a new mapInfo that will be filled with the new info mapInfo = new BulletHeightMapInfo(id, heightMapX, - BulletSimAPI.CreateHeightMapInfo2(PhysicsScene.World.ptr, newTerrainID, + BulletSimAPI.CreateHeightMapInfo2(PhysicsScene.World.ptr, newTerrainID, minCoordsX, maxCoordsX, heightMapX, TERRAIN_COLLISION_MARGIN)); // Put the unfilled heightmap info into the collection of same m_heightMaps.Add(terrainRegionBase, mapInfo); @@ -454,7 +454,7 @@ public class BSTerrainManager { return true; } - + // This routine is called two ways: // One with 'offset' and 'pScene' zero and null but 'extents' giving the maximum // extent of the combined regions. This is to inform the parent of the size @@ -469,11 +469,11 @@ public class BSTerrainManager MegaRegionParentPhysicsScene = pScene; if (pScene != null) { - // We are a child. + // We are a child. // We want m_worldMax to be the highest coordinate of our piece of terrain. m_worldMax = offset + DefaultRegionSize; } - DetailLog("{0},BSTerrainManager.Combine,offset={1},extents={2},wOffset={3},wMax={4}", + DetailLog("{0},BSTerrainManager.Combine,offset={1},extents={2},wOffset={3},wMax={4}", BSScene.DetailLogZero, offset, extents, m_worldOffset, m_worldMax); } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs index 2d65a35..544c53d 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs @@ -41,8 +41,8 @@ public struct BulletSim public BulletSim(uint worldId, BSScene bss, IntPtr xx) { ptr = xx; - worldID = worldId; - scene = bss; + worldID = worldId; + scene = bss; } public IntPtr ptr; public uint worldID; -- cgit v1.1 From 74dea4cfd52be75b4dd6277260c3ada80b939fbb Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Thu, 27 Sep 2012 19:57:35 -0700 Subject: BulletSim: rename some constraint variables to be consistant with other name use. Added callbacks for shape and body changes in GetBodyAndShape() so the linkset constraints can be picked up and restored. A better design might be to have a "prim shape changed" event. Think about that. Added constraint types to general constraint class. --- .../Physics/BulletSPlugin/BS6DofConstraint.cs | 42 +++-- .../Region/Physics/BulletSPlugin/BSConstraint.cs | 21 ++- .../Physics/BulletSPlugin/BSHingeConstraint.cs | 2 + OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 182 +++++++++++++-------- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 14 +- .../Physics/BulletSPlugin/BSShapeCollection.cs | 65 +++++--- .../Region/Physics/BulletSPlugin/BulletSimAPI.cs | 21 ++- 7 files changed, 231 insertions(+), 116 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BS6DofConstraint.cs b/OpenSim/Region/Physics/BulletSPlugin/BS6DofConstraint.cs index 39a3421..3306a97 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BS6DofConstraint.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BS6DofConstraint.cs @@ -34,6 +34,10 @@ namespace OpenSim.Region.Physics.BulletSPlugin public class BS6DofConstraint : BSConstraint { + private static string LogHeader = "[BULLETSIM 6DOF CONSTRAINT]"; + + public override ConstraintType Type { get { return ConstraintType.D6_CONSTRAINT_TYPE; } } + // Create a btGeneric6DofConstraint public BS6DofConstraint(BulletSim world, BulletBody obj1, BulletBody obj2, Vector3 frame1, Quaternion frame1rot, @@ -49,6 +53,9 @@ public class BS6DofConstraint : 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, + obj1.ID, obj1.ptr.ToString("X"), obj2.ID, obj2.ptr.ToString("X")); } public BS6DofConstraint(BulletSim world, BulletBody obj1, BulletBody obj2, @@ -60,12 +67,13 @@ public class BS6DofConstraint : BSConstraint m_body2 = obj2; if (obj1.ptr == IntPtr.Zero || obj2.ptr == IntPtr.Zero) { - world.scene.DetailLog("{0},BS6DOFConstraint,badBodyPtr,wID={1}, rID={2}, rBody={3}, cID={4}, cBody={5}", - "[BULLETSIM 6DOF CONSTRAINT]", world.worldID, + world.physicsScene.DetailLog("{0},BS6DOFConstraint,badBodyPtr,wID={1}, rID={2}, rBody={3}, cID={4}, cBody={5}", + BSScene.DetailLogZero, world.worldID, obj1.ID, obj1.ptr.ToString("X"), obj2.ID, obj2.ptr.ToString("X")); - world.scene.Logger.ErrorFormat("{0} Attempt to build 6DOF constraint with missing bodies: wID={1}, rID={2}, rBody={3}, cID={4}, cBody={5}", + world.physicsScene.Logger.ErrorFormat("{0} Attempt to build 6DOF constraint with missing bodies: wID={1}, rID={2}, rBody={3}, cID={4}, cBody={5}", "[BULLETSIM 6DOF CONSTRAINT]", world.worldID, obj1.ID, obj1.ptr.ToString("X"), obj2.ID, obj2.ptr.ToString("X")); + m_enabled = false; } else { @@ -73,8 +81,20 @@ public class BS6DofConstraint : BSConstraint BulletSimAPI.Create6DofConstraintToPoint2(m_world.ptr, m_body1.ptr, m_body2.ptr, joinPoint, useLinearReferenceFrameA, disableCollisionsBetweenLinkedBodies)); + world.physicsScene.DetailLog("{0},BS6DofConstraint,createMidPoint,wID={1}, csrt={2}, rID={3}, rBody={4}, cID={5}, cBody={6}", + BSScene.DetailLogZero, world.worldID, m_constraint.ptr.ToString("X"), + obj1.ID, obj1.ptr.ToString("X"), obj2.ID, obj2.ptr.ToString("X")); + if (m_constraint.ptr == IntPtr.Zero) + { + world.physicsScene.Logger.ErrorFormat("{0} Failed creation of 6Dof constraint. rootID={1}, childID={2}", + LogHeader, obj1.ID, obj2.ID); + m_enabled = false; + } + else + { + m_enabled = true; + } } - m_enabled = true; } public bool SetFrames(Vector3 frameA, Quaternion frameArot, Vector3 frameB, Quaternion frameBrot) @@ -82,7 +102,7 @@ public class BS6DofConstraint : BSConstraint bool ret = false; if (m_enabled) { - BulletSimAPI.SetFrames2(m_constraint.Ptr, frameA, frameArot, frameB, frameBrot); + BulletSimAPI.SetFrames2(m_constraint.ptr, frameA, frameArot, frameB, frameBrot); ret = true; } return ret; @@ -93,9 +113,9 @@ public class BS6DofConstraint : BSConstraint bool ret = false; if (m_enabled) { - BulletSimAPI.SetConstraintParam2(m_constraint.Ptr, ConstraintParams.BT_CONSTRAINT_STOP_CFM, cfm, ConstraintParamAxis.AXIS_ALL); - BulletSimAPI.SetConstraintParam2(m_constraint.Ptr, ConstraintParams.BT_CONSTRAINT_STOP_ERP, erp, ConstraintParamAxis.AXIS_ALL); - BulletSimAPI.SetConstraintParam2(m_constraint.Ptr, ConstraintParams.BT_CONSTRAINT_CFM, cfm, ConstraintParamAxis.AXIS_ALL); + BulletSimAPI.SetConstraintParam2(m_constraint.ptr, ConstraintParams.BT_CONSTRAINT_STOP_CFM, cfm, ConstraintParamAxis.AXIS_ALL); + BulletSimAPI.SetConstraintParam2(m_constraint.ptr, ConstraintParams.BT_CONSTRAINT_STOP_ERP, erp, ConstraintParamAxis.AXIS_ALL); + BulletSimAPI.SetConstraintParam2(m_constraint.ptr, ConstraintParams.BT_CONSTRAINT_CFM, cfm, ConstraintParamAxis.AXIS_ALL); ret = true; } return ret; @@ -106,7 +126,7 @@ public class BS6DofConstraint : BSConstraint bool ret = false; float onOff = useOffset ? ConfigurationParameters.numericTrue : ConfigurationParameters.numericFalse; if (m_enabled) - ret = BulletSimAPI.UseFrameOffset2(m_constraint.Ptr, onOff); + ret = BulletSimAPI.UseFrameOffset2(m_constraint.ptr, onOff); return ret; } @@ -115,7 +135,7 @@ public class BS6DofConstraint : BSConstraint bool ret = false; float onOff = enable ? ConfigurationParameters.numericTrue : ConfigurationParameters.numericFalse; if (m_enabled) - ret = BulletSimAPI.TranslationalLimitMotor2(m_constraint.Ptr, onOff, targetVelocity, maxMotorForce); + ret = BulletSimAPI.TranslationalLimitMotor2(m_constraint.ptr, onOff, targetVelocity, maxMotorForce); return ret; } @@ -123,7 +143,7 @@ public class BS6DofConstraint : BSConstraint { bool ret = false; if (m_enabled) - ret = BulletSimAPI.SetBreakingImpulseThreshold2(m_constraint.Ptr, threshold); + ret = BulletSimAPI.SetBreakingImpulseThreshold2(m_constraint.ptr, threshold); return ret; } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs b/OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs index c21252b..63a4127 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs @@ -49,20 +49,23 @@ public abstract class BSConstraint : IDisposable if (m_enabled) { m_enabled = false; - bool success = BulletSimAPI.DestroyConstraint2(m_world.ptr, m_constraint.Ptr); - m_world.scene.DetailLog("{0},BSConstraint.Dispose,taint,body1={1},body2={2},success={3}", BSScene.DetailLogZero, m_body1.ID, m_body2.ID, success); - m_constraint.Ptr = System.IntPtr.Zero; + bool success = BulletSimAPI.DestroyConstraint2(m_world.ptr, m_constraint.ptr); + m_world.physicsScene.DetailLog("{0},BSConstraint.Dispose,taint,body1={1},body2={2},success={3}", BSScene.DetailLogZero, m_body1.ID, m_body2.ID, success); + m_constraint.ptr = System.IntPtr.Zero; } } public BulletBody Body1 { get { return m_body1; } } public BulletBody Body2 { get { return m_body2; } } + public BulletConstraint Constraint { get { return m_constraint; } } + public abstract ConstraintType Type { get; } + public virtual bool SetLinearLimits(Vector3 low, Vector3 high) { bool ret = false; if (m_enabled) - ret = BulletSimAPI.SetLinearLimits2(m_constraint.Ptr, low, high); + ret = BulletSimAPI.SetLinearLimits2(m_constraint.ptr, low, high); return ret; } @@ -70,7 +73,7 @@ public abstract class BSConstraint : IDisposable { bool ret = false; if (m_enabled) - ret = BulletSimAPI.SetAngularLimits2(m_constraint.Ptr, low, high); + ret = BulletSimAPI.SetAngularLimits2(m_constraint.ptr, low, high); return ret; } @@ -79,7 +82,7 @@ public abstract class BSConstraint : IDisposable bool ret = false; if (m_enabled) { - BulletSimAPI.SetConstraintNumSolverIterations2(m_constraint.Ptr, cnt); + BulletSimAPI.SetConstraintNumSolverIterations2(m_constraint.ptr, cnt); ret = true; } return ret; @@ -91,7 +94,7 @@ public abstract class BSConstraint : IDisposable if (m_enabled) { // Recompute the internal transforms - BulletSimAPI.CalculateTransforms2(m_constraint.Ptr); + BulletSimAPI.CalculateTransforms2(m_constraint.ptr); ret = true; } return ret; @@ -110,11 +113,11 @@ public abstract class BSConstraint : IDisposable // Setting an object's mass to zero (making it static like when it's selected) // automatically disables the constraints. // If the link is enabled, be sure to set the constraint itself to enabled. - BulletSimAPI.SetConstraintEnable2(m_constraint.Ptr, m_world.scene.NumericBool(true)); + BulletSimAPI.SetConstraintEnable2(m_constraint.ptr, m_world.physicsScene.NumericBool(true)); } else { - m_world.scene.Logger.ErrorFormat("[BULLETSIM CONSTRAINT] CalculateTransforms failed. A={0}, B={1}", Body1.ID, Body2.ID); + m_world.physicsScene.Logger.ErrorFormat("[BULLETSIM CONSTRAINT] CalculateTransforms failed. A={0}, B={1}", Body1.ID, Body2.ID); } } return ret; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSHingeConstraint.cs b/OpenSim/Region/Physics/BulletSPlugin/BSHingeConstraint.cs index a6e4235..7c8a215 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSHingeConstraint.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSHingeConstraint.cs @@ -34,6 +34,8 @@ namespace OpenSim.Region.Physics.BulletSPlugin class BSHingeConstraint : BSConstraint { + public override ConstraintType Type { get { return ConstraintType.HINGE_CONSTRAINT_TYPE; } } + public BSHingeConstraint(BulletSim world, BulletBody obj1, BulletBody obj2, Vector3 pivotInA, Vector3 pivotInB, Vector3 axisInA, Vector3 axisInB, diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index b0cc63c..dff71af 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -88,6 +88,7 @@ public class BSLinkset // Link to a linkset where the child knows the parent. // Parent changing should not happen so do some sanity checking. // We return the parent's linkset so the child can track its membership. + // Called at runtime. public BSLinkset AddMeToLinkset(BSPhysObject child) { lock (m_linksetActivityLock) @@ -102,6 +103,7 @@ public class BSLinkset // Remove a child from a linkset. // Returns a new linkset for the child which is a linkset of one (just the // orphened child). + // Called at runtime. public BSLinkset RemoveMeFromLinkset(BSPhysObject child) { lock (m_linksetActivityLock) @@ -113,27 +115,6 @@ public class BSLinkset } RemoveChildFromLinkset(child); - - /* Alternate implementation that destroys the linkset of the root is removed. - * This fails because items are added and removed from linksets to build shapes. - * Code left for reference. - if (IsRoot(child)) - { - // if root of linkset, take the linkset apart - while (m_children.Count > 0) - { - // Note that we don't do a foreach because the remove routine - // takes it out of the list. - RemoveChildFromOtherLinkset(m_children[0]); - } - m_children.Clear(); // just to make sure - } - else - { - // Just removing a child from an existing linkset - RemoveChildFromLinkset(child); - } - */ } // The child is down to a linkset of just itself @@ -169,6 +150,106 @@ public class BSLinkset return ret; } + // The object is going dynamic (physical). Do any setup necessary + // for a dynamic linkset. + // Only the state of the passed object can be modified. The rest of the linkset + // has not yet been fully constructed. + // Return 'true' if any properties updated on the passed object. + // Called at taint-time! + public bool MakeDynamic(BSPhysObject child) + { + // 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. + // Return 'true' if any properties updated on the passed object. + // Called at taint-time! + public bool MakeStatic(BSPhysObject child) + { + // What is done for each object in BSPrim is what we want. + return false; + } + + // When physical properties are changed the linkset needs to recalculate + // its internal properties. + // Called at runtime. + public void Refresh(BSPhysObject requestor) + { + // If there are no children, there can't be any constraints to recompute + if (!HasAnyChildren) + return; + + // Only the root does the recomputation + if (IsRoot(requestor)) + { + PhysicsScene.TaintedObject("BSLinkSet.Refresh", delegate() + { + RecomputeLinksetConstraintVariables(); + }); + } + } + + // Routine used when rebuilding the body of the root of the linkset + // Destroy all the constraints have have been made to root. + // This is called when the root body is changing. + // Called at taint-time!! + public void RemoveBodyDependencies(BSPrim child) + { + lock (m_linksetActivityLock) + { + if (IsRoot(child)) + { + // If the one with the dependency is root, must undo all children + DetailLog("{0},BSLinkset.RemoveBodyDependencies,removeChildrenForRoot,rID={1},numChild={2}", + LinksetRoot.LocalID, m_children.Count); + foreach (BSPhysObject bpo in m_children) + { + PhysicallyUnlinkAChildFromRoot(LinksetRoot, LinksetRoot.BSBody, bpo, bpo.BSBody); + } + } + else + { + DetailLog("{0},BSLinkset.RemoveBodyDependencies,removeSingleChild,rID={1},rBody={2},cID={3},cBody={4}", + LinksetRoot.LocalID, LinksetRoot.BSBody.ptr.ToString("X"), + child.LocalID, child.BSBody.ptr.ToString("X")); + // Remove the dependency on the body of this one + PhysicallyUnlinkAChildFromRoot(LinksetRoot, LinksetRoot.BSBody, child, child.BSBody); + } + } + } + + // Routine used when rebuilding the body of the root of the linkset + // This is called after RemoveAllLinksToRoot() to restore all the constraints. + // This is called when the root body has been changed. + // Called at taint-time!! + public void RestoreBodyDependencies(BSPrim child) + { + lock (m_linksetActivityLock) + { + if (IsRoot(child)) + { + DetailLog("{0},BSLinkset.RestoreBodyDependencies,restoreChildrenForRoot,rID={1},numChild={2}", + LinksetRoot.LocalID, m_children.Count); + foreach (BSPhysObject bpo in m_children) + { + PhysicallyLinkAChildToRoot(LinksetRoot, LinksetRoot.BSBody, bpo, bpo.BSBody); + } + } + else + { + DetailLog("{0},BSLinkset.RestoreBodyDependencies,restoreSingleChild,rID={1},rBody={2},cID={3},cBody={4}", + LinksetRoot.LocalID, LinksetRoot.BSBody.ptr.ToString("X"), + child.LocalID, child.BSBody.ptr.ToString("X")); + PhysicallyLinkAChildToRoot(LinksetRoot, LinksetRoot.BSBody, child, child.BSBody); + } + } + } + + // ================================================================ + // Below this point is internal magic + private float ComputeLinksetMass() { float mass; @@ -220,46 +301,6 @@ public class BSLinkset return com; } - // The object is going dynamic (physical). Do any setup necessary - // for a dynamic linkset. - // Only the state of the passed object can be modified. The rest of the linkset - // has not yet been fully constructed. - // Return 'true' if any properties updated on the passed object. - // Called at taint-time! - public bool MakeDynamic(BSPhysObject child) - { - // 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. - // Return 'true' if any properties updated on the passed object. - // Called at taint-time! - public bool MakeStatic(BSPhysObject child) - { - // What is done for each object in BSPrim is what we want. - return false; - } - - // When physical properties are changed the linkset needs to recalculate - // its internal properties. - public void Refresh(BSPhysObject requestor) - { - // If there are no children, there can't be any constraints to recompute - if (!HasAnyChildren) - return; - - // Only the root does the recomputation - if (IsRoot(requestor)) - { - PhysicsScene.TaintedObject("BSLinkSet.Refresh", delegate() - { - RecomputeLinksetConstraintVariables(); - }); - } - } - // Call each of the constraints that make up this linkset and recompute the // various transforms and variables. Used when objects are added or removed // from a linkset to make sure the constraints know about the new mass and @@ -327,6 +368,11 @@ public class BSLinkset BSPhysObject childx = child; BulletBody childBodyx = child.BSBody; + DetailLog("{0},AddChildToLinkset,call,rID={1},rBody={2},cID={3},cBody={4}", + rootx.LocalID, + rootx.LocalID, rootBodyx.ptr.ToString("X"), + childx.LocalID, childBodyx.ptr.ToString("X")); + PhysicsScene.TaintedObject("AddChildToLinkset", delegate() { DetailLog("{0},AddChildToLinkset,taint,child={1}", LinksetRoot.LocalID, child.LocalID); @@ -358,10 +404,14 @@ public class BSLinkset BulletBody rootBodyx = LinksetRoot.BSBody; BSPhysObject childx = child; BulletBody childBodyx = child.BSBody; + + DetailLog("{0},RemoveChildFromLinkset,call,child={1}", + rootx.LocalID, + rootx.LocalID, rootBodyx.ptr.ToString("X"), + childx.LocalID, childBodyx.ptr.ToString("X")); + PhysicsScene.TaintedObject("RemoveChildFromLinkset", delegate() { - DetailLog("{0},RemoveChildFromLinkset,taint,child={1}", LinksetRoot.LocalID, child.LocalID); - PhysicallyUnlinkAChildFromRoot(rootx, rootBodyx, childx, childBodyx); RecomputeLinksetConstraintVariables(); }); @@ -390,14 +440,15 @@ public class BSLinkset // real world coordinate of midpoint between the two objects OMV.Vector3 midPoint = rootPrim.Position + (childRelativePosition / 2); - // create a constraint that allows no freedom of movement between the two objects - // http://bulletphysics.org/Bullet/phpBB3/viewtopic.php?t=4818 DetailLog("{0},PhysicallyLinkAChildToRoot,taint,root={1},rBody={2},child={3},cBody={4},rLoc={5},cLoc={6},midLoc={7}", rootPrim.LocalID, rootPrim.LocalID, rootBody.ptr.ToString("X"), childPrim.LocalID, childBody.ptr.ToString("X"), 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 + // There is great subtlty in these paramters. Notice the check for a ptr of zero. // We pass the BulletBody structure into the taint in order to capture the pointer // of the body at the time of constraint creation. This doesn't work for the very first @@ -416,6 +467,7 @@ public class BSLinkset 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. diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 8688485..c879143 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -1111,13 +1111,21 @@ public sealed class BSPrim : BSPhysObject // Undo me from any possible linkset so, if body is rebuilt, the link will get restored. // NOTE that the new linkset is not set. This saves the handle to the linkset // so we can add ourselves back when shape mangling is complete. - Linkset.RemoveMeFromLinkset(this); + bool needToRestoreLinkset = false; // Create the correct physical representation for this type of object. // Updates BSBody and BSShape with the new information. - PhysicsScene.Shapes.GetBodyAndShape(forceRebuild, PhysicsScene.World, this, shapeData, _pbs); + PhysicsScene.Shapes.GetBodyAndShape(forceRebuild, PhysicsScene.World, this, shapeData, _pbs, + null, delegate(BulletBody dBody) + { + // Called if the current prim body is about to be destroyed. + // The problem is the constraints for Linksets which need to be updated for the new body. + Linkset.RemoveBodyDependencies(this); + needToRestoreLinkset = true; + }); - Linkset = Linkset.AddMeToLinkset(this); + if (needToRestoreLinkset) + Linkset.RestoreBodyDependencies(this); // Make sure the properties are set on the new object UpdatePhysicalParameters(); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index b428ba3..2618971 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -81,12 +81,21 @@ public class BSShapeCollection : IDisposable // TODO!!!!!!!!! } + // Callbacks called just before either the body or shape is destroyed. + // 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); + // 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. // Return 'true' if either the body or the shape changed. // Called at taint-time!! - public bool GetBodyAndShape(bool forceRebuild, BulletSim sim, BSPrim prim, ShapeData shapeData, PrimitiveBaseShape pbs) + public bool GetBodyAndShape(bool forceRebuild, BulletSim sim, BSPrim prim, + ShapeData shapeData, PrimitiveBaseShape pbs, + ShapeDestructionCallback shapeCallback, BodyDestructionCallback bodyCallback) { bool ret = false; @@ -95,11 +104,11 @@ public class BSShapeCollection : IDisposable { // Do we have the correct geometry for this type of object? // Updates prim.BSShape with information/pointers to requested shape - bool newGeom = CreateGeom(forceRebuild, prim, shapeData, pbs); + bool newGeom = CreateGeom(forceRebuild, prim, shapeData, pbs, shapeCallback); // 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 - bool newBody = CreateBody((newGeom || forceRebuild), prim, PhysicsScene.World, prim.BSShape, shapeData); + bool newBody = CreateBody((newGeom || forceRebuild), prim, PhysicsScene.World, prim.BSShape, shapeData, bodyCallback); ret = newGeom || newBody; } DetailLog("{0},BSShapeCollection.GetBodyAndShape,force={1},ret={2},body={3},shape={4}", @@ -135,7 +144,7 @@ public class BSShapeCollection : IDisposable // Release the usage of a body. // Called when releasing use of a BSBody. BSShape is handled separately. - public void DereferenceBody(BulletBody shape, bool inTaintTime) + public void DereferenceBody(BulletBody shape, bool inTaintTime, BodyDestructionCallback bodyCallback ) { if (shape.ptr == IntPtr.Zero) return; @@ -244,7 +253,7 @@ public class BSShapeCollection : IDisposable // Release the usage of a shape. // The collisionObject is released since it is a copy of the real collision shape. - private void DereferenceShape(BulletShape shape, bool atTaintTime) + private void DereferenceShape(BulletShape shape, bool atTaintTime, ShapeDestructionCallback shapeCallback) { if (shape.ptr == IntPtr.Zero) return; @@ -254,10 +263,10 @@ public class BSShapeCollection : IDisposable switch (shape.type) { case ShapeData.PhysicsShapeType.SHAPE_HULL: - DereferenceHull(shape); + DereferenceHull(shape, shapeCallback); break; case ShapeData.PhysicsShapeType.SHAPE_MESH: - DereferenceMesh(shape); + DereferenceMesh(shape, shapeCallback); break; case ShapeData.PhysicsShapeType.SHAPE_UNKNOWN: break; @@ -267,6 +276,7 @@ public class BSShapeCollection : IDisposable { DetailLog("{0},BSShapeCollection.DereferenceShape,deleteNativeShape,ptr={1},taintTime={2}", BSScene.DetailLogZero, shape.ptr.ToString("X"), atTaintTime); + if (shapeCallback != null) shapeCallback(shape); BulletSimAPI.DeleteCollisionShape2(PhysicsScene.World.ptr, shape.ptr); } break; @@ -287,13 +297,14 @@ public class BSShapeCollection : IDisposable // Count down the reference count for a mesh shape // Called at taint-time. - private void DereferenceMesh(BulletShape shape) + 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; DetailLog("{0},BSShapeCollection.DereferenceMesh,key={1},refCnt={2}", @@ -304,13 +315,14 @@ public class BSShapeCollection : IDisposable // Count down the reference count for a hull shape // Called at taint-time. - private void DereferenceHull(BulletShape shape) + private void DereferenceHull(BulletShape shape, ShapeDestructionCallback shapeCallback) { HullDesc hullDesc; if (Hulls.TryGetValue(shape.shapeKey, out hullDesc)) { hullDesc.referenceCount--; // TODO: release the Bullet storage (aging old entries?) + if (shapeCallback != null) shapeCallback(shape); hullDesc.lastReferenced = System.DateTime.Now; Hulls[shape.shapeKey] = hullDesc; DetailLog("{0},BSShapeCollection.DereferenceHull,key={1},refCnt={2}", @@ -324,7 +336,8 @@ public class BSShapeCollection : IDisposable // if 'forceRebuild' is true, the geometry is rebuilt. Otherwise a previously built version is used. // Returns 'true' if the geometry was rebuilt. // Called at taint-time! - private bool CreateGeom(bool forceRebuild, BSPrim prim, ShapeData shapeData, PrimitiveBaseShape pbs) + private bool CreateGeom(bool forceRebuild, BSPrim prim, ShapeData shapeData, + PrimitiveBaseShape pbs, ShapeDestructionCallback shapeCallback) { bool ret = false; bool haveShape = false; @@ -349,8 +362,8 @@ public class BSShapeCollection : IDisposable || prim.BSShape.type != ShapeData.PhysicsShapeType.SHAPE_SPHERE ) { - ret = GetReferenceToNativeShape(prim, shapeData, - ShapeData.PhysicsShapeType.SHAPE_SPHERE, ShapeData.FixedShapeKey.KEY_SPHERE); + ret = GetReferenceToNativeShape(prim, shapeData, ShapeData.PhysicsShapeType.SHAPE_SPHERE, + ShapeData.FixedShapeKey.KEY_SPHERE, shapeCallback); DetailLog("{0},BSShapeCollection.CreateGeom,sphere,force={1},shape={2}", prim.LocalID, forceRebuild, prim.BSShape); } @@ -363,8 +376,8 @@ public class BSShapeCollection : IDisposable || prim.BSShape.type != ShapeData.PhysicsShapeType.SHAPE_BOX ) { - ret = GetReferenceToNativeShape( - prim, shapeData, ShapeData.PhysicsShapeType.SHAPE_BOX, ShapeData.FixedShapeKey.KEY_BOX); + ret = GetReferenceToNativeShape( prim, shapeData, ShapeData.PhysicsShapeType.SHAPE_BOX, + ShapeData.FixedShapeKey.KEY_BOX, shapeCallback); DetailLog("{0},BSShapeCollection.CreateGeom,box,force={1},shape={2}", prim.LocalID, forceRebuild, prim.BSShape); } @@ -378,13 +391,13 @@ public class BSShapeCollection : IDisposable if (prim.IsPhysical) { // Update prim.BSShape to reference a hull of this shape. - ret = GetReferenceToHull(prim, shapeData, pbs); + ret = GetReferenceToHull(prim, shapeData, pbs, shapeCallback); DetailLog("{0},BSShapeCollection.CreateGeom,hull,shape={1},key={2}", shapeData.ID, prim.BSShape, prim.BSShape.shapeKey.ToString("X")); } else { - ret = GetReferenceToMesh(prim, shapeData, pbs); + ret = GetReferenceToMesh(prim, shapeData, pbs, shapeCallback); DetailLog("{0},BSShapeCollection.CreateGeom,mesh,shape={1},key={2}", shapeData.ID, prim.BSShape, prim.BSShape.shapeKey.ToString("X")); } @@ -394,7 +407,8 @@ public class BSShapeCollection : IDisposable // Creates a native shape and assignes it to prim.BSShape private bool GetReferenceToNativeShape( BSPrim prim, ShapeData shapeData, - ShapeData.PhysicsShapeType shapeType, ShapeData.FixedShapeKey shapeKey) + ShapeData.PhysicsShapeType shapeType, ShapeData.FixedShapeKey shapeKey, + ShapeDestructionCallback shapeCallback) { BulletShape newShape; @@ -404,7 +418,7 @@ public class BSShapeCollection : IDisposable shapeData.Scale = shapeData.Size; // release any previous shape - DereferenceShape(prim.BSShape, true); + DereferenceShape(prim.BSShape, true, shapeCallback); // Native shapes are always built independently. newShape = new BulletShape(BulletSimAPI.BuildNativeShape2(PhysicsScene.World.ptr, shapeData), shapeType); @@ -422,7 +436,8 @@ public class BSShapeCollection : IDisposable // 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(BSPrim prim, ShapeData shapeData, PrimitiveBaseShape pbs) + private bool GetReferenceToMesh(BSPrim prim, ShapeData shapeData, PrimitiveBaseShape pbs, + ShapeDestructionCallback shapeCallback) { BulletShape newShape = new BulletShape(IntPtr.Zero); @@ -436,7 +451,7 @@ public class BSShapeCollection : IDisposable prim.LocalID, prim.BSShape.shapeKey.ToString("X"), newMeshKey.ToString("X")); // Since we're recreating new, get rid of the reference to the previous shape - DereferenceShape(prim.BSShape, true); + DereferenceShape(prim.BSShape, true, shapeCallback); newShape = CreatePhysicalMesh(prim.PhysObjectName, newMeshKey, pbs, shapeData.Size, lod); @@ -490,7 +505,8 @@ public class BSShapeCollection : IDisposable // See that hull shape exists in the physical world and update prim.BSShape. // We could be creating the hull because scale changed or whatever. - private bool GetReferenceToHull(BSPrim prim, ShapeData shapeData, PrimitiveBaseShape pbs) + private bool GetReferenceToHull(BSPrim prim, ShapeData shapeData, PrimitiveBaseShape pbs, + ShapeDestructionCallback shapeCallback) { BulletShape newShape; @@ -505,7 +521,7 @@ public class BSShapeCollection : IDisposable prim.LocalID, prim.BSShape.shapeKey.ToString("X"), newHullKey.ToString("X")); // Remove usage of the previous shape. Also removes reference to underlying mesh if it is a hull. - DereferenceShape(prim.BSShape, true); + DereferenceShape(prim.BSShape, true, shapeCallback); newShape = CreatePhysicalHull(prim.PhysObjectName, newHullKey, pbs, shapeData.Size, lod); @@ -656,7 +672,8 @@ public class BSShapeCollection : IDisposable // 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, BSPrim prim, BulletSim sim, BulletShape shape, ShapeData shapeData) + private bool CreateBody(bool forceRebuild, BSPrim prim, BulletSim sim, BulletShape shape, + ShapeData shapeData, BodyDestructionCallback bodyCallback) { bool ret = false; @@ -679,7 +696,7 @@ public class BSShapeCollection : IDisposable if (mustRebuild || forceRebuild) { - DereferenceBody(prim.BSBody, true); + DereferenceBody(prim.BSBody, true, bodyCallback); BulletBody aBody; IntPtr bodyPtr = IntPtr.Zero; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs index 544c53d..1125d7e 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs @@ -42,12 +42,12 @@ public struct BulletSim { ptr = xx; worldID = worldId; - scene = bss; + physicsScene = bss; } public IntPtr ptr; public uint worldID; // The scene is only in here so very low level routines have a handle to print debug/error messages - public BSScene scene; + public BSScene physicsScene; } // An allocated Bullet btRigidBody @@ -120,14 +120,27 @@ public struct BulletShape } } + // Constraint type values as defined by Bullet +public enum ConstraintType : int +{ + POINT2POINT_CONSTRAINT_TYPE = 3, + HINGE_CONSTRAINT_TYPE, + CONETWIST_CONSTRAINT_TYPE, + D6_CONSTRAINT_TYPE, + SLIDER_CONSTRAINT_TYPE, + CONTACT_CONSTRAINT_TYPE, + D6_SPRING_CONSTRAINT_TYPE, + MAX_CONSTRAINT_TYPE +} + // An allocated Bullet btConstraint public struct BulletConstraint { public BulletConstraint(IntPtr xx) { - Ptr = xx; + ptr = xx; } - public IntPtr Ptr; + public IntPtr ptr; } // An allocated HeightMapThing which holds various heightmap info. -- cgit v1.1 From 6f89975526359b81c43c23d9a549660d12212c59 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Thu, 27 Sep 2012 22:00:02 -0700 Subject: BulletSim: add separate runtime and taint-time linkset children lists to keep the creation of constraints separate from runtime. --- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 145 +++++++++++---------- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 3 +- .../Physics/BulletSPlugin/BSShapeCollection.cs | 25 ++-- 3 files changed, 93 insertions(+), 80 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index dff71af..4f225ae 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -43,8 +43,17 @@ public class BSLinkset static int m_nextLinksetID = 1; public int LinksetID { get; private set; } - // The children under the root in this linkset + // The children under the root in this linkset. + // There are two lists of children: the current children at runtime + // and the children at taint-time. For instance, if you delink a + // child from the linkset, the child is removed from m_children + // but the constraint won't be removed until taint time. + // Two lists lets this track the 'current' children and + // the physical 'taint' children separately. + // After taint processing and before the simulation step, these + // two lists must be the same. private List m_children; + private List m_taintChildren; // We lock the diddling of linkset classes to prevent any badness. // This locks the modification of the instances of this class. Changes @@ -82,6 +91,7 @@ public class BSLinkset PhysicsScene = scene; LinksetRoot = parent; m_children = new List(); + m_taintChildren = new List(); m_mass = parent.MassRaw; } @@ -194,30 +204,40 @@ public class BSLinkset // Routine used when rebuilding the body of the root of the linkset // Destroy all the constraints have have been made to root. // This is called when the root body is changing. + // Returns 'true' of something eas actually removed and would need restoring // Called at taint-time!! - public void RemoveBodyDependencies(BSPrim child) + public bool RemoveBodyDependencies(BSPrim child) { + bool ret = false; + lock (m_linksetActivityLock) { if (IsRoot(child)) { // If the one with the dependency is root, must undo all children DetailLog("{0},BSLinkset.RemoveBodyDependencies,removeChildrenForRoot,rID={1},numChild={2}", - LinksetRoot.LocalID, m_children.Count); - foreach (BSPhysObject bpo in m_children) + child.LocalID, LinksetRoot.LocalID, m_taintChildren.Count); + foreach (BSPhysObject bpo in m_taintChildren) { PhysicallyUnlinkAChildFromRoot(LinksetRoot, LinksetRoot.BSBody, bpo, bpo.BSBody); + ret = true; } } else { DetailLog("{0},BSLinkset.RemoveBodyDependencies,removeSingleChild,rID={1},rBody={2},cID={3},cBody={4}", + child.LocalID, LinksetRoot.LocalID, LinksetRoot.BSBody.ptr.ToString("X"), child.LocalID, child.BSBody.ptr.ToString("X")); // Remove the dependency on the body of this one - PhysicallyUnlinkAChildFromRoot(LinksetRoot, LinksetRoot.BSBody, child, child.BSBody); + if (m_taintChildren.Contains(child)) + { + PhysicallyUnlinkAChildFromRoot(LinksetRoot, LinksetRoot.BSBody, child, child.BSBody); + ret = true; + } } } + return ret; } // Routine used when rebuilding the body of the root of the linkset @@ -231,8 +251,8 @@ public class BSLinkset if (IsRoot(child)) { DetailLog("{0},BSLinkset.RestoreBodyDependencies,restoreChildrenForRoot,rID={1},numChild={2}", - LinksetRoot.LocalID, m_children.Count); - foreach (BSPhysObject bpo in m_children) + child.LocalID, LinksetRoot.LocalID, m_taintChildren.Count); + foreach (BSPhysObject bpo in m_taintChildren) { PhysicallyLinkAChildToRoot(LinksetRoot, LinksetRoot.BSBody, bpo, bpo.BSBody); } @@ -240,6 +260,7 @@ public class BSLinkset else { DetailLog("{0},BSLinkset.RestoreBodyDependencies,restoreSingleChild,rID={1},rBody={2},cID={3},cBody={4}", + LinksetRoot.LocalID, LinksetRoot.LocalID, LinksetRoot.BSBody.ptr.ToString("X"), child.LocalID, child.BSBody.ptr.ToString("X")); PhysicallyLinkAChildToRoot(LinksetRoot, LinksetRoot.BSBody, child, child.BSBody); @@ -256,7 +277,7 @@ public class BSLinkset lock (m_linksetActivityLock) { mass = LinksetRoot.MassRaw; - foreach (BSPhysObject bp in m_children) + foreach (BSPhysObject bp in m_taintChildren) { mass += bp.MassRaw; } @@ -272,7 +293,7 @@ public class BSLinkset com = LinksetRoot.Position * LinksetRoot.MassRaw; float totalMass = LinksetRoot.MassRaw; - foreach (BSPhysObject bp in m_children) + foreach (BSPhysObject bp in m_taintChildren) { com += bp.Position * bp.MassRaw; totalMass += bp.MassRaw; @@ -291,70 +312,16 @@ public class BSLinkset { com = LinksetRoot.Position; - foreach (BSPhysObject bp in m_children) + foreach (BSPhysObject bp in m_taintChildren) { com += bp.Position * bp.MassRaw; } - com /= (m_children.Count + 1); + com /= (m_taintChildren.Count + 1); } return com; } - // Call each of the constraints that make up this linkset and recompute the - // various transforms and variables. Used when objects are added or removed - // from a linkset to make sure the constraints know about the new mass and - // geometry. - // Must only be called at taint time!! - private void RecomputeLinksetConstraintVariables() - { - float linksetMass = LinksetMass; - lock (m_linksetActivityLock) - { - bool somethingMissing = false; - foreach (BSPhysObject child in m_children) - { - BSConstraint constrain; - if (PhysicsScene.Constraints.TryGetConstraint(LinksetRoot.BSBody, child.BSBody, out constrain)) - { - // DetailLog("{0},BSLinkset.RecomputeLinksetConstraintVariables,taint,child={1},mass={2},A={3},B={4}", - // LinksetRoot.LocalID, child.LocalID, linksetMass, constrain.Body1.ID, constrain.Body2.ID); - constrain.RecomputeConstraintVariables(linksetMass); - } - else - { - // Non-fatal error that happens when children are being added to the linkset but - // their constraints have not been created yet. - // Caused by the fact that m_children is built at run time but building constraints - // happens at taint time. - somethingMissing = true; - break; - } - } - - // If the whole linkset is not here, doesn't make sense to recompute linkset wide values - if (!somethingMissing) - { - // If this is a multiple object linkset, set everybody's center of mass to the set's center of mass - OMV.Vector3 centerOfMass = ComputeLinksetCenterOfMass(); - BulletSimAPI.SetCenterOfMassByPosRot2(LinksetRoot.BSBody.ptr, centerOfMass, OMV.Quaternion.Identity); - foreach (BSPhysObject child in m_children) - { - BulletSimAPI.SetCenterOfMassByPosRot2(child.BSBody.ptr, centerOfMass, OMV.Quaternion.Identity); - } - /* - // The root prim takes on the weight of the whole linkset - OMV.Vector3 inertia = BulletSimAPI.CalculateLocalInertia2(LinksetRoot.BSShape.Ptr, linksetMass); - BulletSimAPI.SetMassProps2(LinksetRoot.BSBody.Ptr, linksetMass, inertia); - OMV.Vector3 centerOfMass = ComputeLinksetCenterOfMass(); - BulletSimAPI.SetCenterOfMassByPosRot2(LinksetRoot.BSBody.Ptr, centerOfMass, OMV.Quaternion.Identity); - BulletSimAPI.UpdateInertiaTensor2(LinksetRoot.BSBody.Ptr); - */ - } - } - return; - } - // I am the root of a linkset and a new child is being added // Called while LinkActivity is locked. private void AddChildToLinkset(BSPhysObject child) @@ -377,6 +344,7 @@ public class BSLinkset { DetailLog("{0},AddChildToLinkset,taint,child={1}", LinksetRoot.LocalID, child.LocalID); // build the physical binding between me and the child + m_taintChildren.Add(childx); PhysicallyLinkAChildToRoot(rootx, rootBodyx, childx, childBodyx); }); } @@ -405,13 +373,16 @@ public class BSLinkset BSPhysObject childx = child; BulletBody childBodyx = child.BSBody; - DetailLog("{0},RemoveChildFromLinkset,call,child={1}", - rootx.LocalID, + DetailLog("{0},RemoveChildFromLinkset,call,rID={1},rBody={2},cID={3},cBody={4}", + childx.LocalID, rootx.LocalID, rootBodyx.ptr.ToString("X"), childx.LocalID, childBodyx.ptr.ToString("X")); PhysicsScene.TaintedObject("RemoveChildFromLinkset", delegate() { + if (m_taintChildren.Contains(childx)) + m_taintChildren.Remove(childx); + PhysicallyUnlinkAChildFromRoot(rootx, rootBodyx, childx, childBodyx); RecomputeLinksetConstraintVariables(); }); @@ -551,6 +522,46 @@ public class BSLinkset } */ + // Call each of the constraints that make up this linkset and recompute the + // various transforms and variables. Used when objects are added or removed + // from a linkset to make sure the constraints know about the new mass and + // geometry. + // Must only be called at taint time!! + private void RecomputeLinksetConstraintVariables() + { + float linksetMass = LinksetMass; + foreach (BSPhysObject child in m_taintChildren) + { + BSConstraint constrain; + if (PhysicsScene.Constraints.TryGetConstraint(LinksetRoot.BSBody, child.BSBody, out constrain)) + { + // DetailLog("{0},BSLinkset.RecomputeLinksetConstraintVariables,taint,child={1},mass={2},A={3},B={4}", + // LinksetRoot.LocalID, child.LocalID, linksetMass, constrain.Body1.ID, constrain.Body2.ID); + constrain.RecomputeConstraintVariables(linksetMass); + } + else + { + // Non-fatal error that happens when children are being added to the linkset but + // their constraints have not been created yet. + break; + } + } + + // If the whole linkset is not here, doesn't make sense to recompute linkset wide values + if (m_children.Count == m_taintChildren.Count) + { + // If this is a multiple object linkset, set everybody's center of mass to the set's center of mass + OMV.Vector3 centerOfMass = ComputeLinksetCenterOfMass(); + BulletSimAPI.SetCenterOfMassByPosRot2(LinksetRoot.BSBody.ptr, centerOfMass, OMV.Quaternion.Identity); + foreach (BSPhysObject child in m_taintChildren) + { + BulletSimAPI.SetCenterOfMassByPosRot2(child.BSBody.ptr, centerOfMass, OMV.Quaternion.Identity); + } + } + return; + } + + // Invoke the detailed logger and output something if it's enabled. private void DetailLog(string msg, params Object[] args) { diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index c879143..87ffe3e 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -1120,8 +1120,7 @@ public sealed class BSPrim : BSPhysObject { // Called if the current prim body is about to be destroyed. // The problem is the constraints for Linksets which need to be updated for the new body. - Linkset.RemoveBodyDependencies(this); - needToRestoreLinkset = true; + needToRestoreLinkset = Linkset.RemoveBodyDependencies(this); }); if (needToRestoreLinkset) diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index 2618971..648910a 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -144,34 +144,37 @@ public class BSShapeCollection : IDisposable // Release the usage of a body. // Called when releasing use of a BSBody. BSShape is handled separately. - public void DereferenceBody(BulletBody shape, bool inTaintTime, BodyDestructionCallback bodyCallback ) + public void DereferenceBody(BulletBody body, bool inTaintTime, BodyDestructionCallback bodyCallback ) { - if (shape.ptr == IntPtr.Zero) + if (body.ptr == IntPtr.Zero) return; lock (m_collectionActivityLock) { BodyDesc bodyDesc; - if (Bodies.TryGetValue(shape.ID, out bodyDesc)) + if (Bodies.TryGetValue(body.ID, out bodyDesc)) { bodyDesc.referenceCount--; bodyDesc.lastReferenced = System.DateTime.Now; - Bodies[shape.ID] = bodyDesc; - DetailLog("{0},BSShapeCollection.DereferenceBody,ref={1}", shape.ID, bodyDesc.referenceCount); + Bodies[body.ID] = bodyDesc; + DetailLog("{0},BSShapeCollection.DereferenceBody,ref={1}", body.ID, bodyDesc.referenceCount); // If body is no longer being used, free it -- bodies are never shared. if (bodyDesc.referenceCount == 0) { - Bodies.Remove(shape.ID); + Bodies.Remove(body.ID); BSScene.TaintCallback removeOperation = delegate() { DetailLog("{0},BSShapeCollection.DereferenceBody,DestroyingBody. ptr={1}", - shape.ID, shape.ptr.ToString("X")); + body.ID, body.ptr.ToString("X")); + // If the caller needs to know, pass the event up. + if (bodyCallback != null) bodyCallback(body); + // Zero any reference to the shape so it is not freed when the body is deleted. - BulletSimAPI.SetCollisionShape2(PhysicsScene.World.ptr, shape.ptr, IntPtr.Zero); + BulletSimAPI.SetCollisionShape2(PhysicsScene.World.ptr, body.ptr, IntPtr.Zero); // It may have already been removed from the world in which case the next is a NOOP. - BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.ptr, shape.ptr); - BulletSimAPI.DestroyObject2(PhysicsScene.World.ptr, shape.ptr); + BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.ptr, body.ptr); + BulletSimAPI.DestroyObject2(PhysicsScene.World.ptr, body.ptr); }; // If already in taint-time, do the operations now. Otherwise queue for later. if (inTaintTime) @@ -182,7 +185,7 @@ public class BSShapeCollection : IDisposable } else { - DetailLog("{0},BSShapeCollection.DereferenceBody,DID NOT FIND BODY", shape.ID, bodyDesc.referenceCount); + DetailLog("{0},BSShapeCollection.DereferenceBody,DID NOT FIND BODY", body.ID, bodyDesc.referenceCount); } } } -- cgit v1.1 From 76e9cc41bd612035850e105a6fe34f483aab25e7 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Fri, 28 Sep 2012 12:34:50 -0700 Subject: BulletSim: remember to release the physical body and shape when a prim is destroyed. This fixes many problems with physical linksets. --- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 18 +++++++++--------- .../Region/Physics/BulletSPlugin/BSShapeCollection.cs | 14 +++++++------- 2 files changed, 16 insertions(+), 16 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 87ffe3e..a0e627e 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -154,8 +154,9 @@ public sealed class BSPrim : BSPhysObject PhysicsScene.TaintedObject("BSPrim.destroy", delegate() { DetailLog("{0},BSPrim.Destroy,taint,", LocalID); - // everything in the C# world will get garbage collected. Tell the C++ world to free stuff. - BulletSimAPI.DestroyObject(PhysicsScene.WorldID, LocalID); + // If there are physical body and shape, release my use of same. + PhysicsScene.Shapes.DereferenceBody(BSBody, true, null); + PhysicsScene.Shapes.DereferenceShape(BSShape, true, null); }); } @@ -251,9 +252,6 @@ public sealed class BSPrim : BSPhysObject _rotationalVelocity = OMV.Vector3.Zero; // Zero some other properties directly into the physics engine - BulletSimAPI.SetLinearVelocity2(BSBody.ptr, OMV.Vector3.Zero); - BulletSimAPI.SetAngularVelocity2(BSBody.ptr, OMV.Vector3.Zero); - BulletSimAPI.SetInterpolationVelocity2(BSBody.ptr, OMV.Vector3.Zero, OMV.Vector3.Zero); BulletSimAPI.ClearForces2(BSBody.ptr); } @@ -1108,9 +1106,8 @@ public sealed class BSPrim : BSPhysObject ShapeData shapeData; FillShapeInfo(out shapeData); - // Undo me from any possible linkset so, if body is rebuilt, the link will get restored. - // NOTE that the new linkset is not set. This saves the handle to the linkset - // so we can add ourselves back when shape mangling is complete. + // If this prim is part of a linkset, we must remove and restore the physical + // links of the body is rebuilt. bool needToRestoreLinkset = false; // Create the correct physical representation for this type of object. @@ -1119,12 +1116,15 @@ public sealed class BSPrim : BSPhysObject null, delegate(BulletBody dBody) { // Called if the current prim body is about to be destroyed. - // The problem is the constraints for Linksets which need to be updated for the new body. + // Remove all the physical dependencies on the old body. needToRestoreLinkset = Linkset.RemoveBodyDependencies(this); }); if (needToRestoreLinkset) + { + // If physical body dependencies were removed, restore them Linkset.RestoreBodyDependencies(this); + } // Make sure the properties are set on the new object UpdatePhysicalParameters(); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index 648910a..dee6243 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -120,25 +120,25 @@ public class BSShapeCollection : IDisposable // Track another user of a body // We presume the caller has allocated the body. // Bodies only have one user so the reference count is either 1 or 0. - public void ReferenceBody(BulletBody shape, bool atTaintTime) + public void ReferenceBody(BulletBody body, bool atTaintTime) { lock (m_collectionActivityLock) { BodyDesc bodyDesc; - if (Bodies.TryGetValue(shape.ID, out bodyDesc)) + if (Bodies.TryGetValue(body.ID, out bodyDesc)) { bodyDesc.referenceCount++; - DetailLog("{0},BSShapeCollection.ReferenceBody,existingBody,ref={1}", shape.ID, bodyDesc.referenceCount); + DetailLog("{0},BSShapeCollection.ReferenceBody,existingBody,body={1},ref={2}", body.ID, body, bodyDesc.referenceCount); } else { // New entry - bodyDesc.ptr = shape.ptr; + bodyDesc.ptr = body.ptr; bodyDesc.referenceCount = 1; - DetailLog("{0},BSShapeCollection.ReferenceBody,newBody,ref={1}", shape.ID, bodyDesc.referenceCount); + DetailLog("{0},BSShapeCollection.ReferenceBody,newBody,ref={1}", body.ID, body, bodyDesc.referenceCount); } bodyDesc.lastReferenced = System.DateTime.Now; - Bodies[shape.ID] = bodyDesc; + Bodies[body.ID] = bodyDesc; } } @@ -256,7 +256,7 @@ public class BSShapeCollection : IDisposable // Release the usage of a shape. // The collisionObject is released since it is a copy of the real collision shape. - private void DereferenceShape(BulletShape shape, bool atTaintTime, ShapeDestructionCallback shapeCallback) + public void DereferenceShape(BulletShape shape, bool atTaintTime, ShapeDestructionCallback shapeCallback) { if (shape.ptr == IntPtr.Zero) return; -- cgit v1.1 From 5221f2421e2a9b7dcc1a1e0e8cccaf1c9c94d2e2 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Mon, 1 Oct 2012 08:27:26 -0700 Subject: BulletSim: remove warnings for unused variables. --- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 2 +- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 17 +++++------------ .../Region/Physics/BulletSPlugin/BSShapeCollection.cs | 2 +- 3 files changed, 7 insertions(+), 14 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index 4f225ae..a7aaf9b 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -34,7 +34,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin { public class BSLinkset { - private static string LogHeader = "[BULLETSIM LINKSET]"; + // private static string LogHeader = "[BULLETSIM LINKSET]"; public BSPhysObject LinksetRoot { get; protected set; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index a0e627e..e54bf75 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -46,19 +46,13 @@ public sealed class BSPrim : BSPhysObject private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static readonly string LogHeader = "[BULLETS PRIM]"; - private IMesh _mesh; private PrimitiveBaseShape _pbs; - private ShapeData.PhysicsShapeType _shapeType; - private ulong _meshKey; - private ulong _hullKey; - private List _hulls; // _size is what the user passed. _scale is what we pass to the physics engine with the mesh. // Often _scale is unity because the meshmerizer will apply _size when creating the mesh. private OMV.Vector3 _size; // the multiplier for each mesh dimension as passed by the user private OMV.Vector3 _scale; // the multiplier for each mesh dimension for the mesh as created by the meshmerizer - private bool _stopped; private bool _grabbed; private bool _isSelected; private bool _isVolumeDetect; @@ -109,8 +103,6 @@ public sealed class BSPrim : BSPhysObject _buoyancy = 1f; _velocity = OMV.Vector3.Zero; _rotationalVelocity = OMV.Vector3.Zero; - _hullKey = 0; - _meshKey = 0; _pbs = pbs; _isPhysical = pisPhysical; _isVolumeDetect = false; @@ -160,8 +152,9 @@ public sealed class BSPrim : BSPhysObject }); } + // No one uses this property. public override bool Stopped { - get { return _stopped; } + get { return false; } } public override OMV.Vector3 Size { get { return _size; } @@ -1082,15 +1075,15 @@ public sealed class BSPrim : BSPhysObject public void FillShapeInfo(out ShapeData shape) { shape.ID = LocalID; - shape.Type = _shapeType; + shape.Type = ShapeData.PhysicsShapeType.SHAPE_UNKNOWN; shape.Position = _position; shape.Rotation = _orientation; shape.Velocity = _velocity; shape.Scale = _scale; shape.Mass = _isPhysical ? _mass : 0f; shape.Buoyancy = _buoyancy; - shape.HullKey = _hullKey; - shape.MeshKey = _meshKey; + shape.HullKey = 0; + shape.MeshKey = 0; shape.Friction = _friction; shape.Restitution = _restitution; shape.Collidable = (!IsPhantom) ? ShapeData.numericTrue : ShapeData.numericFalse; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index dee6243..a86bf8a 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -36,7 +36,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin { public class BSShapeCollection : IDisposable { - private static string LogHeader = "[BULLETSIM SHAPE COLLECTION]"; + // private static string LogHeader = "[BULLETSIM SHAPE COLLECTION]"; protected BSScene PhysicsScene { get; set; } -- cgit v1.1 From c1740a29036eed153138493f865435d22bd12406 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Mon, 1 Oct 2012 09:58:49 -0700 Subject: Correct my name in CONTRIBUTORS.txt --- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 51 +++++++--------------- 1 file changed, 16 insertions(+), 35 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index 65b38d6..cbfd7e3 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -138,74 +138,55 @@ namespace OpenSim.Region.Physics.BulletSPlugin switch (pParam) { case Vehicle.ANGULAR_DEFLECTION_EFFICIENCY: - if (pValue < 0.01f) pValue = 0.01f; - // m_angularDeflectionEfficiency = pValue; + // m_angularDeflectionEfficiency = Math.Max(pValue, 0.01f); break; case Vehicle.ANGULAR_DEFLECTION_TIMESCALE: - if (pValue < 0.01f) pValue = 0.01f; - // m_angularDeflectionTimescale = pValue; + // m_angularDeflectionTimescale = Math.Max(pValue, 0.01f); break; case Vehicle.ANGULAR_MOTOR_DECAY_TIMESCALE: - if (pValue < 0.01f) pValue = 0.01f; - m_angularMotorDecayTimescale = pValue; + m_angularMotorDecayTimescale = Math.Max(pValue, 0.01f); break; case Vehicle.ANGULAR_MOTOR_TIMESCALE: - if (pValue < 0.01f) pValue = 0.01f; - m_angularMotorTimescale = pValue; + m_angularMotorTimescale = Math.Max(pValue, 0.01f); break; case Vehicle.BANKING_EFFICIENCY: - if (pValue < 0.01f) pValue = 0.01f; - // m_bankingEfficiency = pValue; + // m_bankingEfficiency = Math.Max(pValue, 0.01f); break; case Vehicle.BANKING_MIX: - if (pValue < 0.01f) pValue = 0.01f; - // m_bankingMix = pValue; + // m_bankingMix = Math.Max(pValue, 0.01f); break; case Vehicle.BANKING_TIMESCALE: - if (pValue < 0.01f) pValue = 0.01f; - // m_bankingTimescale = pValue; + // m_bankingTimescale = Math.Max(pValue, 0.01f); break; case Vehicle.BUOYANCY: - if (pValue < -1f) pValue = -1f; - if (pValue > 1f) pValue = 1f; - m_VehicleBuoyancy = pValue; + m_VehicleBuoyancy = Math.Max(-1f, Math.Min(pValue, 1f)); break; // case Vehicle.HOVER_EFFICIENCY: -// if (pValue < 0f) pValue = 0f; -// if (pValue > 1f) pValue = 1f; -// m_VhoverEfficiency = pValue; +// m_VhoverEfficiency = Math.Max(0f, Math.Min(pValue, 1f)); // break; case Vehicle.HOVER_HEIGHT: m_VhoverHeight = pValue; break; case Vehicle.HOVER_TIMESCALE: - if (pValue < 0.01f) pValue = 0.01f; - m_VhoverTimescale = pValue; + m_VhoverTimescale = Math.Max(pValue, 0.01f); break; case Vehicle.LINEAR_DEFLECTION_EFFICIENCY: - if (pValue < 0.01f) pValue = 0.01f; - // m_linearDeflectionEfficiency = pValue; + // m_linearDeflectionEfficiency = Math.Max(pValue, 0.01f); break; case Vehicle.LINEAR_DEFLECTION_TIMESCALE: - if (pValue < 0.01f) pValue = 0.01f; - // m_linearDeflectionTimescale = pValue; + // m_linearDeflectionTimescale = Math.Max(pValue, 0.01f); break; case Vehicle.LINEAR_MOTOR_DECAY_TIMESCALE: - if (pValue < 0.01f) pValue = 0.01f; - m_linearMotorDecayTimescale = pValue; + m_linearMotorDecayTimescale = Math.Max(pValue, 0.01f); break; case Vehicle.LINEAR_MOTOR_TIMESCALE: - if (pValue < 0.01f) pValue = 0.01f; - m_linearMotorTimescale = pValue; + m_linearMotorTimescale = Math.Max(pValue, 0.01f); break; case Vehicle.VERTICAL_ATTRACTION_EFFICIENCY: - if (pValue < 0.1f) pValue = 0.1f; // Less goes unstable - if (pValue > 1.0f) pValue = 1.0f; - m_verticalAttractionEfficiency = pValue; + m_verticalAttractionEfficiency = Math.Max(0.1f, Math.Min(pValue, 1f)); break; case Vehicle.VERTICAL_ATTRACTION_TIMESCALE: - if (pValue < 0.01f) pValue = 0.01f; - m_verticalAttractionTimescale = pValue; + m_verticalAttractionTimescale = Math.Max(pValue, 0.01f); break; // These are vector properties but the engine lets you use a single float value to -- cgit v1.1 From 33617e09a185be68ceeaaba0fe9b7b2e6068124d Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Mon, 1 Oct 2012 11:54:35 -0700 Subject: BulletSim: impliment FloatOnWater OS function. --- .../Region/Physics/BulletSPlugin/BSCharacter.cs | 41 +++++++++--- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 77 ++++++++++++++++++++-- .../Region/Physics/BulletSPlugin/BulletSimAPI.cs | 8 +-- 3 files changed, 104 insertions(+), 22 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index b88ec3c..5cf8953 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -234,6 +234,15 @@ public class BSCharacter : BSPhysObject _position.Z = terrainHeight + 2.0f; ret = true; } + if ((CurrentCollisionFlags & CollisionFlags.BS_FLOATS_ON_WATER) == 0) + { + float waterHeight = PhysicsScene.GetWaterLevelAtXYZ(_position); + if (Position.Z < waterHeight) + { + _position.Z = waterHeight; + ret = true; + } + } // TODO: check for out of bounds return ret; @@ -242,18 +251,22 @@ public class BSCharacter : BSPhysObject // A version of the sanity check that also makes sure a new position value is // pushed back to the physics engine. This routine would be used by anyone // who is not already pushing the value. - private bool PositionSanityCheck2() + private bool PositionSanityCheck2(bool atTaintTime) { bool ret = false; if (PositionSanityCheck()) { // 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("BSCharacter.PositionSanityCheck", delegate() + BSScene.TaintCallback sanityOperation = delegate() { DetailLog("{0},BSCharacter.PositionSanityCheck,taint,pos={1},orient={2}", LocalID, _position, _orientation); BulletSimAPI.SetObjectTranslation(PhysicsScene.WorldID, LocalID, _position, _orientation); - }); + }; + if (atTaintTime) + sanityOperation(); + else + PhysicsScene.TaintedObject("BSCharacter.PositionSanityCheck", sanityOperation); ret = true; } return ret; @@ -378,7 +391,16 @@ public class BSCharacter : BSPhysObject set { _collidingObj = value; } } public override bool FloatOnWater { - set { _floatOnWater = value; } + set { + _floatOnWater = value; + PhysicsScene.TaintedObject("BSCharacter.setFloatOnWater", delegate() + { + if (_floatOnWater) + CurrentCollisionFlags = BulletSimAPI.AddToCollisionFlags2(BSBody.ptr, CollisionFlags.BS_FLOATS_ON_WATER); + else + CurrentCollisionFlags = BulletSimAPI.RemoveFromCollisionFlags2(BSBody.ptr, CollisionFlags.BS_FLOATS_ON_WATER); + }); + } } public override OMV.Vector3 RotationalVelocity { get { return _rotationalVelocity; } @@ -493,15 +515,14 @@ public class BSCharacter : BSPhysObject _velocity = entprop.Velocity; _acceleration = entprop.Acceleration; _rotationalVelocity = entprop.RotationalVelocity; + // Do some sanity checking for the avatar. Make sure it's above ground and inbounds. + PositionSanityCheck2(true); + // Avatars don't report their changes the usual way. Changes are checked for in the heartbeat loop. // base.RequestPhysicsterseUpdate(); - // Do some sanity checking for the avatar. Make sure it's above ground and inbounds. - PositionSanityCheck2(); - - float heightHere = PhysicsScene.TerrainManager.GetTerrainHeightAtXYZ(_position); // only for debug - DetailLog("{0},BSCharacter.UpdateProperties,call,pos={1},orient={2},vel={3},accel={4},rotVel={5},terrain={6}", - LocalID, _position, _orientation, _velocity, _acceleration, _rotationalVelocity, heightHere); + DetailLog("{0},BSCharacter.UpdateProperties,call,pos={1},orient={2},vel={3},accel={4},rotVel={5}", + LocalID, _position, _orientation, _velocity, _acceleration, _rotationalVelocity); } } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index e54bf75..e37a4a0 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -267,6 +267,7 @@ public sealed class BSPrim : BSPhysObject set { _position = value; // TODO: what does it mean to set the position of a child prim?? Rebuild the constraint? + PositionSanityCheck(); PhysicsScene.TaintedObject("BSPrim.setPosition", delegate() { // DetailLog("{0},BSPrim.SetPosition,taint,pos={1},orient={2}", LocalID, _position, _orientation); @@ -275,6 +276,63 @@ public sealed class BSPrim : BSPhysObject } } + // Check that the current position is sane and, if not, modify the position to make it so. + // Check for being below terrain and being out of bounds. + // Returns 'true' of the position was made sane by some action. + private bool PositionSanityCheck() + { + bool ret = false; + + // If totally below the ground, move the prim up + // TODO: figure out the right solution for this... only for dynamic objects? + /* + float terrainHeight = PhysicsScene.TerrainManager.GetTerrainHeightAtXYZ(_position); + if (Position.Z < terrainHeight) + { + DetailLog("{0},BSPrim.PositionAdjustUnderGround,call,pos={1},terrain={2}", LocalID, _position, terrainHeight); + _position.Z = terrainHeight + 2.0f; + ret = true; + } + */ + if ((CurrentCollisionFlags & CollisionFlags.BS_FLOATS_ON_WATER) != 0) + { + float waterHeight = PhysicsScene.GetWaterLevelAtXYZ(_position); + if (Position.Z < waterHeight) + { + _position.Z = waterHeight; + ret = true; + } + } + + // TODO: check for out of bounds + return ret; + } + + // A version of the sanity check that also makes sure a new position value is + // pushed back to the physics engine. This routine would be used by anyone + // who is not already pushing the value. + private bool PositionSanityCheck2(bool atTaintTime) + { + bool ret = false; + if (PositionSanityCheck()) + { + // The new position value must be pushed into the physics engine but we can't + // just assign to "Position" because of potential call loops. + BSScene.TaintCallback sanityOperation = delegate() + { + DetailLog("{0},BSPrim.PositionSanityCheck,taint,pos={1},orient={2}", LocalID, _position, _orientation); + BulletSimAPI.SetObjectTranslation(PhysicsScene.WorldID, LocalID, _position, _orientation); + }; + if (atTaintTime) + sanityOperation(); + else + PhysicsScene.TaintedObject("BSPrim.PositionSanityCheck", sanityOperation); + + ret = true; + } + return ret; + } + // Return the effective mass of the object. // If there are multiple items in the linkset, add them together for the root public override float Mass @@ -481,11 +539,10 @@ public sealed class BSPrim : BSPhysObject // This is a NOOP if the object is not in the world (BulletSim and Bullet ignore objects not found). BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.ptr, BSBody.ptr); - // Set up the object physicalness (does gravity and collisions move this object) MakeDynamic(IsStatic); - // Do any vehicle stuff + // Update vehicle specific parameters _vehicle.Refresh(); // Arrange for collision events if the simulator wants them @@ -556,7 +613,6 @@ public sealed class BSPrim : BSPhysObject // A dynamic object has mass IntPtr collisionShapePtr = BulletSimAPI.GetCollisionShape2(BSBody.ptr); OMV.Vector3 inertia = BulletSimAPI.CalculateLocalInertia2(collisionShapePtr, Mass); - // OMV.Vector3 inertia = OMV.Vector3.Zero; BulletSimAPI.SetMassProps2(BSBody.ptr, _mass, inertia); BulletSimAPI.UpdateInertiaTensor2(BSBody.ptr); @@ -566,7 +622,7 @@ public sealed class BSPrim : BSPhysObject BulletSimAPI.SetSleepingThresholds2(BSBody.ptr, PhysicsScene.Params.linearSleepingThreshold, PhysicsScene.Params.angularSleepingThreshold); BulletSimAPI.SetContactProcessingThreshold2(BSBody.ptr, PhysicsScene.Params.contactProcessingThreshold); - // There can be special things needed for implementing linksets. + // There might be special things needed for implementing linksets. Linkset.MakeDynamic(this); // Force activation of the object so Bullet will act on it. @@ -656,7 +712,16 @@ public sealed class BSPrim : BSPhysObject } } public override bool FloatOnWater { - set { _floatOnWater = value; } + set { + _floatOnWater = value; + PhysicsScene.TaintedObject("BSPrim.setFloatOnWater", delegate() + { + if (_floatOnWater) + CurrentCollisionFlags = BulletSimAPI.AddToCollisionFlags2(BSBody.ptr, CollisionFlags.BS_FLOATS_ON_WATER); + else + CurrentCollisionFlags = BulletSimAPI.RemoveFromCollisionFlags2(BSBody.ptr, CollisionFlags.BS_FLOATS_ON_WATER); + }); + } } public override OMV.Vector3 RotationalVelocity { get { @@ -1198,6 +1263,8 @@ public sealed class BSPrim : BSPhysObject _acceleration = entprop.Acceleration; _rotationalVelocity = entprop.RotationalVelocity; + PositionSanityCheck2(true); + DetailLog("{0},BSPrim.UpdateProperties,call,pos={1},orient={2},vel={3},accel={4},rotVel={5}", LocalID, _position, _orientation, _velocity, _acceleration, _rotationalVelocity); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs index 1125d7e..d49e5f3 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs @@ -344,10 +344,7 @@ public enum CollisionFlags : uint CF_DISABLE_SPU_COLLISION_PROCESS = 1 << 6, // Following used by BulletSim to control collisions BS_SUBSCRIBE_COLLISION_EVENTS = 1 << 10, - // BS_VOLUME_DETECT_OBJECT = 1 << 11, - // BS_PHANTOM_OBJECT = 1 << 12, - // BS_PHYSICAL_OBJECT = 1 << 13, - // BS_TERRAIN_OBJECT = 1 << 14, + BS_FLOATS_ON_WATER = 1 << 11, BS_NONE = 0, BS_ALL = 0xFFFFFFFF, @@ -356,9 +353,6 @@ public enum CollisionFlags : uint BS_ACTIVE = CF_STATIC_OBJECT | CF_KINEMATIC_OBJECT | CF_NO_CONTACT_RESPONSE - // | BS_VOLUME_DETECT_OBJECT - // | BS_PHANTOM_OBJECT - // | BS_PHYSICAL_OBJECT, }; // Values for collisions groups and masks -- cgit v1.1 From f2c78281ce46ff1be96f0bf86f2b7ddefd94a900 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Mon, 1 Oct 2012 12:10:06 -0700 Subject: BulletSim: fix the FloatOnWater code so avatars can normally go underwater. --- OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index 5cf8953..2fe4d68 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -234,7 +234,7 @@ public class BSCharacter : BSPhysObject _position.Z = terrainHeight + 2.0f; ret = true; } - if ((CurrentCollisionFlags & CollisionFlags.BS_FLOATS_ON_WATER) == 0) + if ((CurrentCollisionFlags & CollisionFlags.BS_FLOATS_ON_WATER) != 0) { float waterHeight = PhysicsScene.GetWaterLevelAtXYZ(_position); if (Position.Z < waterHeight) -- cgit v1.1 From b6b505163c98683adaf7f298026c5bd2f954c05c Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 2 Oct 2012 10:50:29 -0700 Subject: BulletSim: call ForcePosition and ForceOrientation in BSDynamics so there is no lag between what the vehicle code sees and what the physics engine is using. --- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 96 +++++++++++++--------- 1 file changed, 57 insertions(+), 39 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index cbfd7e3..4ba2f62 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -92,7 +92,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin private float m_angularMotorDecayTimescale = 0; // motor angular velocity decay rate private Vector3 m_angularFrictionTimescale = Vector3.Zero; // body angular velocity decay rate private Vector3 m_lastAngularVelocity = Vector3.Zero; // what was last applied to body - // private Vector3 m_lastVertAttractor = Vector3.Zero; // what VA was last applied to body + private Vector3 m_lastVertAttractor = Vector3.Zero; // what VA was last applied to body //Deflection properties // private float m_angularDeflectionEfficiency = 0; @@ -352,8 +352,9 @@ namespace OpenSim.Region.Physics.BulletSPlugin // m_bankingMix = 1; // m_bankingTimescale = 1; // m_referenceFrame = Quaternion.Identity; - m_flags |= (VehicleFlag.NO_DEFLECTION_UP | VehicleFlag.LIMIT_ROLL_ONLY | - VehicleFlag.LIMIT_MOTOR_UP); + m_flags |= (VehicleFlag.NO_DEFLECTION_UP + | VehicleFlag.LIMIT_ROLL_ONLY + | VehicleFlag.LIMIT_MOTOR_UP); m_flags &= ~(VehicleFlag.HOVER_WATER_ONLY | VehicleFlag.HOVER_TERRAIN_ONLY | VehicleFlag.HOVER_GLOBAL_HEIGHT); m_flags |= (VehicleFlag.HOVER_UP_ONLY); break; @@ -380,12 +381,13 @@ namespace OpenSim.Region.Physics.BulletSPlugin // m_bankingMix = 0.8f; // m_bankingTimescale = 1; // m_referenceFrame = Quaternion.Identity; - m_flags &= ~(VehicleFlag.HOVER_TERRAIN_ONLY | - VehicleFlag.HOVER_GLOBAL_HEIGHT | VehicleFlag.HOVER_UP_ONLY); - m_flags &= ~(VehicleFlag.LIMIT_ROLL_ONLY); - m_flags |= (VehicleFlag.NO_DEFLECTION_UP | - VehicleFlag.LIMIT_MOTOR_UP); - m_flags |= (VehicleFlag.HOVER_WATER_ONLY); + m_flags &= ~(VehicleFlag.HOVER_TERRAIN_ONLY + | VehicleFlag.HOVER_GLOBAL_HEIGHT + | VehicleFlag.LIMIT_ROLL_ONLY + | VehicleFlag.HOVER_UP_ONLY); + m_flags |= (VehicleFlag.NO_DEFLECTION_UP + | VehicleFlag.LIMIT_MOTOR_UP + | VehicleFlag.HOVER_WATER_ONLY); break; case Vehicle.TYPE_AIRPLANE: m_linearFrictionTimescale = new Vector3(200, 10, 5); @@ -410,9 +412,12 @@ namespace OpenSim.Region.Physics.BulletSPlugin // m_bankingMix = 0.7f; // m_bankingTimescale = 2; // m_referenceFrame = Quaternion.Identity; - m_flags &= ~(VehicleFlag.HOVER_WATER_ONLY | VehicleFlag.HOVER_TERRAIN_ONLY | - VehicleFlag.HOVER_GLOBAL_HEIGHT | VehicleFlag.HOVER_UP_ONLY); - m_flags &= ~(VehicleFlag.NO_DEFLECTION_UP | VehicleFlag.LIMIT_MOTOR_UP); + m_flags &= ~(VehicleFlag.HOVER_WATER_ONLY + | VehicleFlag.HOVER_TERRAIN_ONLY + | VehicleFlag.HOVER_GLOBAL_HEIGHT + | VehicleFlag.HOVER_UP_ONLY + | VehicleFlag.NO_DEFLECTION_UP + | VehicleFlag.LIMIT_MOTOR_UP); m_flags |= (VehicleFlag.LIMIT_ROLL_ONLY); break; case Vehicle.TYPE_BALLOON: @@ -438,11 +443,13 @@ namespace OpenSim.Region.Physics.BulletSPlugin // m_bankingMix = 0.7f; // m_bankingTimescale = 5; // m_referenceFrame = Quaternion.Identity; - m_flags &= ~(VehicleFlag.HOVER_WATER_ONLY | VehicleFlag.HOVER_TERRAIN_ONLY | - VehicleFlag.HOVER_UP_ONLY); - m_flags &= ~(VehicleFlag.NO_DEFLECTION_UP | VehicleFlag.LIMIT_MOTOR_UP); - m_flags |= (VehicleFlag.LIMIT_ROLL_ONLY); - m_flags |= (VehicleFlag.HOVER_GLOBAL_HEIGHT); + m_flags &= ~(VehicleFlag.HOVER_WATER_ONLY + | VehicleFlag.HOVER_TERRAIN_ONLY + | VehicleFlag.HOVER_UP_ONLY + | VehicleFlag.NO_DEFLECTION_UP + | VehicleFlag.LIMIT_MOTOR_UP); + m_flags |= (VehicleFlag.LIMIT_ROLL_ONLY + | VehicleFlag.HOVER_GLOBAL_HEIGHT); break; } }//end SetDefaultsForType @@ -451,7 +458,8 @@ namespace OpenSim.Region.Physics.BulletSPlugin // Do any updating needed for a vehicle public void Refresh() { - if (Type == Vehicle.TYPE_NONE) return; + if (!IsActive) + return; // Set the prim's inertia to zero. The vehicle code handles that and this // removes the torque action introduced by Bullet. @@ -470,7 +478,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin LimitRotation(pTimestep); // remember the position so next step we can limit absolute movement effects - m_lastPositionVector = Prim.Position; + m_lastPositionVector = Prim.ForcePosition; VDetailLog("{0},BSDynamics.Step,done,pos={1},force={2},velocity={3},angvel={4}", Prim.LocalID, Prim.Position, Prim.Force, Prim.Velocity, Prim.RotationalVelocity); @@ -524,7 +532,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin } // convert requested object velocity to object relative vector - Quaternion rotq = Prim.Orientation; + Quaternion rotq = Prim.ForceOrientation; m_newVelocity = m_lastLinearVelocityVector * rotq; // Add the various forces into m_dir which will be our new direction vector (velocity) @@ -541,19 +549,19 @@ namespace OpenSim.Region.Physics.BulletSPlugin m_dir.Z = vel_now.Z; // Preserve the accumulated falling velocity */ - Vector3 pos = Prim.Position; + Vector3 pos = Prim.ForcePosition; // Vector3 accel = new Vector3(-(m_dir.X - m_lastLinearVelocityVector.X / 0.1f), -(m_dir.Y - m_lastLinearVelocityVector.Y / 0.1f), m_dir.Z - m_lastLinearVelocityVector.Z / 0.1f); // If below the terrain, move us above the ground a little. float terrainHeight = Prim.PhysicsScene.TerrainManager.GetTerrainHeightAtXYZ(pos); // Taking the rotated size doesn't work here because m_prim.Size is the size of the root prim and not the linkset. // Need to add a m_prim.LinkSet.Size similar to m_prim.LinkSet.Mass. - // Vector3 rotatedSize = m_prim.Size * m_prim.Orientation; + // Vector3 rotatedSize = m_prim.Size * m_prim.ForceOrientation; // if (rotatedSize.Z < terrainHeight) if (pos.Z < terrainHeight) { pos.Z = terrainHeight + 2; - Prim.Position = pos; + Prim.ForcePosition = pos; VDetailLog("{0},MoveLinear,terrainHeight,terrainHeight={1},pos={2}", Prim.LocalID, terrainHeight, pos); } @@ -583,7 +591,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin { if ((pos.Z - m_VhoverTargetHeight) > .2 || (pos.Z - m_VhoverTargetHeight) < -.2) { - Prim.Position = pos; + Prim.ForcePosition = pos; } } else @@ -635,12 +643,13 @@ namespace OpenSim.Region.Physics.BulletSPlugin } if (changed) { - Prim.Position = pos; + Prim.ForcePosition = pos; VDetailLog("{0},MoveLinear,blockingEndPoint,block={1},origPos={2},pos={3}", Prim.LocalID, m_BlockingEndPoint, posChange, pos); } } + // Limit absolute vertical change float Zchange = Math.Abs(posChange.Z); if ((m_flags & (VehicleFlag.LIMIT_MOTOR_UP)) != 0) { @@ -659,6 +668,8 @@ namespace OpenSim.Region.Physics.BulletSPlugin grav.Z = (float)(grav.Z * 1.037125); VDetailLog("{0},MoveLinear,limitMotorUp,grav={1}", Prim.LocalID, grav); } + + // If not changing some axis, reduce out velocity if ((m_flags & (VehicleFlag.NO_X)) != 0) m_newVelocity.X = 0; if ((m_flags & (VehicleFlag.NO_Y)) != 0) @@ -701,19 +712,19 @@ namespace OpenSim.Region.Physics.BulletSPlugin // a newly set velocity, this routine steps the value from the previous // value (m_angularMotorVelocity) to the requested value (m_angularMotorDirection). // There are m_angularMotorApply steps. - Vector3 origAngularVelocity = m_angularMotorVelocity; + Vector3 origVel = m_angularMotorVelocity; + Vector3 origDir = m_angularMotorDirection; + // ramp up to new value - // current velocity += error / ( time to get there / step interval) + // new velocity += error / ( time to get there / step interval) // requested speed - last motor speed m_angularMotorVelocity.X += (m_angularMotorDirection.X - m_angularMotorVelocity.X) / (m_angularMotorTimescale / pTimestep); m_angularMotorVelocity.Y += (m_angularMotorDirection.Y - m_angularMotorVelocity.Y) / (m_angularMotorTimescale / pTimestep); m_angularMotorVelocity.Z += (m_angularMotorDirection.Z - m_angularMotorVelocity.Z) / (m_angularMotorTimescale / pTimestep); - VDetailLog("{0},MoveAngular,angularMotorApply,apply={1},angTScale={2},timeStep={3},origvel={4},dir={5},vel={6}", - Prim.LocalID, m_angularMotorApply, m_angularMotorTimescale, pTimestep, origAngularVelocity, m_angularMotorDirection, m_angularMotorVelocity); + VDetailLog("{0},MoveAngular,angularMotorApply,apply={1},angTScale={2},timeStep={3},origvel={4},origDir={5},vel={6}", + Prim.LocalID, m_angularMotorApply, m_angularMotorTimescale, pTimestep, origVel, origDir, m_angularMotorVelocity); - // This is done so that if script request rate is less than phys frame rate the expected - // velocity may still be acheived. m_angularMotorApply--; } else @@ -727,25 +738,32 @@ namespace OpenSim.Region.Physics.BulletSPlugin // Vertical attractor section Vector3 vertattr = Vector3.Zero; - if (m_verticalAttractionTimescale < 300) + Vector3 deflection = Vector3.Zero; + Vector3 banking = Vector3.Zero; + + if (m_verticalAttractionTimescale < 300 && m_lastAngularVelocity != Vector3.Zero) { float VAservo = 0.2f / (m_verticalAttractionTimescale / pTimestep); + VAservo *= (m_verticalAttractionEfficiency * m_verticalAttractionEfficiency); + // get present body rotation - Quaternion rotq = Prim.Orientation; - // make a vector pointing up + Quaternion rotq = Prim.ForceOrientation; + // vector pointing up Vector3 verterr = Vector3.Zero; verterr.Z = 1.0f; + // rotate it to Body Angle verterr = verterr * rotq; - // verterr.X and .Y are the World error ammounts. They are 0 when there is no error (Vehicle Body is 'vertical'), and .Z will be 1. + // verterr.X and .Y are the World error amounts. They are 0 when there is no error (Vehicle Body is 'vertical'), and .Z will be 1. // As the body leans to its side |.X| will increase to 1 and .Z fall to 0. As body inverts |.X| will fall and .Z will go // negative. Similar for tilt and |.Y|. .X and .Y must be modulated to prevent a stable inverted body. + + // Error is 0 (no error) to +/- 2 (max error) if (verterr.Z < 0.0f) { verterr.X = 2.0f - verterr.X; verterr.Y = 2.0f - verterr.Y; } - // Error is 0 (no error) to +/- 2 (max error) // scale it by VAservo verterr = verterr * VAservo; @@ -765,7 +783,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin } // else vertical attractor is off - // m_lastVertAttractor = vertattr; + m_lastVertAttractor = vertattr; // Bank section tba @@ -799,7 +817,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin internal void LimitRotation(float timestep) { - Quaternion rotq = Prim.Orientation; + Quaternion rotq = Prim.ForceOrientation; Quaternion m_rot = rotq; bool changed = false; if (m_RollreferenceFrame != Quaternion.Identity) @@ -834,7 +852,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin } if (changed) { - Prim.Orientation = m_rot; + Prim.ForceOrientation = m_rot; VDetailLog("{0},LimitRotation,done,orig={1},new={2}", Prim.LocalID, rotq, m_rot); } -- cgit v1.1 From ce97ebdc88ea525fe6e0c823b6f0072b6acddbc9 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 2 Oct 2012 10:52:51 -0700 Subject: BulletSim: Fix linkset problem where delayed manipulations of child objects was using the child shape address at call time rather than the one created at taint time. --- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index a7aaf9b..3e82642 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -331,21 +331,21 @@ public class BSLinkset m_children.Add(child); BSPhysObject rootx = LinksetRoot; // capture the root and body as of now - BulletBody rootBodyx = LinksetRoot.BSBody; BSPhysObject childx = child; - BulletBody childBodyx = child.BSBody; DetailLog("{0},AddChildToLinkset,call,rID={1},rBody={2},cID={3},cBody={4}", rootx.LocalID, - rootx.LocalID, rootBodyx.ptr.ToString("X"), - childx.LocalID, childBodyx.ptr.ToString("X")); + rootx.LocalID, rootx.BSBody.ptr.ToString("X"), + childx.LocalID, childx.BSBody.ptr.ToString("X")); PhysicsScene.TaintedObject("AddChildToLinkset", delegate() { DetailLog("{0},AddChildToLinkset,taint,child={1}", LinksetRoot.LocalID, child.LocalID); // build the physical binding between me and the child m_taintChildren.Add(childx); - PhysicallyLinkAChildToRoot(rootx, rootBodyx, childx, childBodyx); + + // Since this is taint-time, the body and shape could have changed for the child + PhysicallyLinkAChildToRoot(rootx, rootx.BSBody, childx, childx.BSBody); }); } return; @@ -369,21 +369,19 @@ public class BSLinkset if (m_children.Remove(child)) { BSPhysObject rootx = LinksetRoot; // capture the root and body as of now - BulletBody rootBodyx = LinksetRoot.BSBody; BSPhysObject childx = child; - BulletBody childBodyx = child.BSBody; DetailLog("{0},RemoveChildFromLinkset,call,rID={1},rBody={2},cID={3},cBody={4}", childx.LocalID, - rootx.LocalID, rootBodyx.ptr.ToString("X"), - childx.LocalID, childBodyx.ptr.ToString("X")); + rootx.LocalID, rootx.BSBody.ptr.ToString("X"), + childx.LocalID, childx.BSBody.ptr.ToString("X")); PhysicsScene.TaintedObject("RemoveChildFromLinkset", delegate() { if (m_taintChildren.Contains(childx)) m_taintChildren.Remove(childx); - PhysicallyUnlinkAChildFromRoot(rootx, rootBodyx, childx, childBodyx); + PhysicallyUnlinkAChildFromRoot(rootx, rootx.BSBody, childx, childx.BSBody); RecomputeLinksetConstraintVariables(); }); -- cgit v1.1 From d8a786870b5ff03241e9f6b0393a2e1f91de2b01 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 2 Oct 2012 10:56:39 -0700 Subject: BulletSim: Fix problem where box shapes were not being rebuilt if the shape type changed. --- OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index a86bf8a..399a133 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -108,7 +108,8 @@ public class BSShapeCollection : IDisposable // 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 - bool newBody = CreateBody((newGeom || forceRebuild), prim, PhysicsScene.World, prim.BSShape, shapeData, bodyCallback); + bool newBody = CreateBody((newGeom || forceRebuild), prim, PhysicsScene.World, + prim.BSShape, shapeData, bodyCallback); ret = newGeom || newBody; } DetailLog("{0},BSShapeCollection.GetBodyAndShape,force={1},ret={2},body={3},shape={4}", @@ -140,7 +141,7 @@ public class BSShapeCollection : IDisposable bodyDesc.lastReferenced = System.DateTime.Now; Bodies[body.ID] = bodyDesc; } -} + } // Release the usage of a body. // Called when releasing use of a BSBody. BSShape is handled separately. @@ -167,7 +168,7 @@ public class BSShapeCollection : IDisposable { DetailLog("{0},BSShapeCollection.DereferenceBody,DestroyingBody. ptr={1}", body.ID, body.ptr.ToString("X")); - // If the caller needs to know, pass the event up. + // If the caller needs to know the old body is going away, pass the event up. if (bodyCallback != null) bodyCallback(body); // Zero any reference to the shape so it is not freed when the body is deleted. @@ -448,7 +449,8 @@ public class BSShapeCollection : IDisposable ulong newMeshKey = ComputeShapeKey(shapeData, pbs, out lod); // if this new shape is the same as last time, don't recreate the mesh - if (prim.BSShape.shapeKey == newMeshKey) return false; + if (newMeshKey == prim.BSShape.shapeKey && prim.BSShape.type == ShapeData.PhysicsShapeType.SHAPE_MESH) + return false; DetailLog("{0},BSShapeCollection.CreateGeomMesh,create,oldKey={1},newKey={2}", prim.LocalID, prim.BSShape.shapeKey.ToString("X"), newMeshKey.ToString("X")); -- cgit v1.1 From ce47d0c4541159a730b2d83a7b2ccffc908d06f1 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 2 Oct 2012 11:06:07 -0700 Subject: BulletSim: Add ForcePosition and ForceOrientation to BSPhysObject and to its children of BSPrim and BSCharacter. --- .../Region/Physics/BulletSPlugin/BSCharacter.cs | 26 +++++++++++++++ .../Region/Physics/BulletSPlugin/BSPhysObject.cs | 4 +++ OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 39 +++++++++++++++++++--- 3 files changed, 64 insertions(+), 5 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index 2fe4d68..2a52e01 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -218,6 +218,18 @@ public class BSCharacter : BSPhysObject }); } } + public override OMV.Vector3 ForcePosition { + get { + _position = BulletSimAPI.GetPosition2(BSBody.ptr); + return _position; + } + set { + _position = value; + PositionSanityCheck(); + BulletSimAPI.SetTranslation2(BSBody.ptr, _position, _orientation); + } + } + // Check that the current position is sane and, if not, modify the position to make it so. // Check for being below terrain and being out of bounds. @@ -346,6 +358,20 @@ public class BSCharacter : BSPhysObject }); } } + // Go directly to Bullet to get/set the value. + public override OMV.Quaternion ForceOrientation + { + get + { + _orientation = BulletSimAPI.GetOrientation2(BSBody.ptr); + return _orientation; + } + set + { + _orientation = value; + BulletSimAPI.SetTranslation2(BSBody.ptr, _position, _orientation); + } + } public override int PhysicsActorType { get { return _physicsActorType; } set { _physicsActorType = value; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index d9b738b..1ac8c59 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -81,6 +81,10 @@ public abstract class BSPhysObject : PhysicsActor // Tell the object to clean up. public abstract void Destroy(); + public abstract OMV.Vector3 ForcePosition { get; set; } + + public abstract OMV.Quaternion ForceOrientation { get; set; } + #region Collisions // Requested number of milliseconds between collision events. Zero means disabled. diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index e37a4a0..f7b68ba 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -275,6 +275,17 @@ public sealed class BSPrim : BSPhysObject }); } } + public override OMV.Vector3 ForcePosition { + get { + _position = BulletSimAPI.GetPosition2(BSBody.ptr); + return _position; + } + set { + _position = value; + PositionSanityCheck(); + BulletSimAPI.SetTranslation2(BSBody.ptr, _position, _orientation); + } + } // Check that the current position is sane and, if not, modify the position to make it so. // Check for being below terrain and being out of bounds. @@ -377,14 +388,15 @@ public sealed class BSPrim : BSPhysObject } set { Vehicle type = (Vehicle)value; - BSPrim vehiclePrim = this; + + // Tell the scene about the vehicle so it will get processing each frame. + PhysicsScene.VehicleInSceneTypeChanged(this, type); + 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. - _vehicle.ProcessTypeChange(type); - // Tell the scene about the vehicle so it will get processing each frame. - PhysicsScene.VehicleInSceneTypeChanged(this, type); + this._vehicle.ProcessTypeChange(type); }); } } @@ -422,7 +434,9 @@ public sealed class BSPrim : BSPhysObject public override void StepVehicle(float timeStep) { if (IsPhysical) + { _vehicle.Step(timeStep); + } } // Allows the detection of collisions with inherently non-physical prims. see llVolumeDetect for more @@ -486,6 +500,20 @@ public sealed class BSPrim : BSPhysObject }); } } + // Go directly to Bullet to get/set the value. + public override OMV.Quaternion ForceOrientation + { + get + { + _orientation = BulletSimAPI.GetOrientation2(BSBody.ptr); + return _orientation; + } + set + { + _orientation = value; + BulletSimAPI.SetTranslation2(BSBody.ptr, _position, _orientation); + } + } public override int PhysicsActorType { get { return _physicsActorType; } set { _physicsActorType = value; } @@ -1170,7 +1198,8 @@ public sealed class BSPrim : BSPhysObject // Create the correct physical representation for this type of object. // Updates BSBody and BSShape with the new information. - PhysicsScene.Shapes.GetBodyAndShape(forceRebuild, PhysicsScene.World, this, shapeData, _pbs, + // Ignore 'forceRebuild'. This routine makes the right choices and changes of necessary. + PhysicsScene.Shapes.GetBodyAndShape(false, PhysicsScene.World, this, shapeData, _pbs, null, delegate(BulletBody dBody) { // Called if the current prim body is about to be destroyed. -- cgit v1.1 From 210f227fe69138f736e3d37e5bfbacd10e967922 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 2 Oct 2012 11:11:22 -0700 Subject: BulletSim: Make parameter value defaults match what should be the default and what is in OpenSimDefaults.ini. Comment and debug printout changes. --- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 26 +++++++++++----------- .../Region/Physics/BulletSPlugin/BulletSimAPI.cs | 2 +- 2 files changed, 14 insertions(+), 14 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index 0cf8c91..aaed7de 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -493,6 +493,10 @@ public class BSScene : PhysicsScene, IPhysicsParameters // step the physical world one interval m_simulationStep++; int numSubSteps = 0; + + // Sometimes needed for debugging to find out what happened before the step + // PhysicsLogging.Flush(); + try { if (PhysicsLogging.Enabled) beforeTime = Util.EnvironmentTickCount(); @@ -536,7 +540,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters } // This is a kludge to get avatar movement updates. - // ODE sends collisions for avatars even if there are have been no collisions. This updates + // the simulator expects collisions for avatars even if there are have been no collisions. This 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) @@ -556,7 +560,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters } // Objects that are done colliding are removed from the ObjectsWithCollisions list. - // This can't be done by SendCollisions because it is inside an iteration of ObjectWithCollisions. + // Not done above because it is inside an iteration of ObjectWithCollisions. if (ObjectsWithNoMoreCollisions.Count > 0) { foreach (BSPhysObject po in ObjectsWithNoMoreCollisions) @@ -726,13 +730,10 @@ public class BSScene : PhysicsScene, IPhysicsParameters public void VehicleInSceneTypeChanged(BSPrim vehic, Vehicle newType) { - if (newType == Vehicle.TYPE_NONE) - { - RemoveVehiclePrim(vehic); - } - else + RemoveVehiclePrim(vehic); + if (newType != Vehicle.TYPE_NONE) { - // make it so the scene will call us each tick to do vehicle things + // make it so the scene will call us each tick to do vehicle things AddVehiclePrim(vehic); } } @@ -764,7 +765,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters } // Some prims have extra vehicle actions - // no locking because only called when physics engine is not busy + // Called at taint time! private void ProcessVehicles(float timeStep) { foreach (BSPhysObject pobj in m_vehicles) @@ -1008,12 +1009,12 @@ public class BSScene : PhysicsScene, IPhysicsParameters new ParameterDefn("MaxPersistantManifoldPoolSize", "Number of manifolds pooled (0 means default of 4096)", - 0f, // zero to disable + 0f, (s,cf,p,v) => { s.m_params[0].maxPersistantManifoldPoolSize = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].maxPersistantManifoldPoolSize; }, (s,p,l,v) => { s.m_params[0].maxPersistantManifoldPoolSize = v; } ), new ParameterDefn("MaxCollisionAlgorithmPoolSize", "Number of collisions pooled (0 means default of 4096)", - 0f, // zero to disable + 0f, (s,cf,p,v) => { s.m_params[0].maxCollisionAlgorithmPoolSize = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].maxCollisionAlgorithmPoolSize; }, (s,p,l,v) => { s.m_params[0].maxCollisionAlgorithmPoolSize = v; } ), @@ -1028,7 +1029,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters (s) => { return s.m_params[0].shouldForceUpdateAllAabbs; }, (s,p,l,v) => { s.m_params[0].shouldForceUpdateAllAabbs = v; } ), new ParameterDefn("ShouldRandomizeSolverOrder", "Enable for slightly better stacking interaction", - ConfigurationParameters.numericFalse, + ConfigurationParameters.numericTrue, (s,cf,p,v) => { s.m_params[0].shouldRandomizeSolverOrder = s.NumericBool(cf.GetBoolean(p, s.BoolNumeric(v))); }, (s) => { return s.m_params[0].shouldRandomizeSolverOrder; }, (s,p,l,v) => { s.m_params[0].shouldRandomizeSolverOrder = v; } ), @@ -1152,7 +1153,6 @@ public class BSScene : PhysicsScene, IPhysicsParameters { if (SettableParameters.Length < ParameterDefinitions.Length) { - List entries = new List(); for (int ii = 0; ii < ParameterDefinitions.Length; ii++) { diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs index d49e5f3..a43880d 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs @@ -71,7 +71,7 @@ public struct BulletBody buff.Append(ID.ToString()); buff.Append(",p="); buff.Append(ptr.ToString("X")); - if (collisionFilter != 0 && collisionMask != 0) + if (collisionFilter != 0 || collisionMask != 0) { buff.Append(",f="); buff.Append(collisionFilter.ToString("X")); -- cgit v1.1 From df3d1d13014cf937240ddc2131231624b47eaccd Mon Sep 17 00:00:00 2001 From: teravus Date: Tue, 2 Oct 2012 23:14:35 -0400 Subject: Minor Modification, switch /2 to 0.5f in ODEPrim.Velocity --- OpenSim/Region/Physics/OdePlugin/ODEPrim.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs b/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs index 0716214..3056f67 100644 --- a/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs +++ b/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs @@ -2395,15 +2395,15 @@ Console.WriteLine(" JointCreateFixed"); { get { - // Averate previous velocity with the new one so + // Average previous velocity with the new one so // client object interpolation works a 'little' better if (_zeroFlag) return Vector3.Zero; Vector3 returnVelocity = Vector3.Zero; - returnVelocity.X = (m_lastVelocity.X + _velocity.X)/2; - returnVelocity.Y = (m_lastVelocity.Y + _velocity.Y)/2; - returnVelocity.Z = (m_lastVelocity.Z + _velocity.Z)/2; + returnVelocity.X = (m_lastVelocity.X + _velocity.X) * 0.5f; // 0.5f is mathematically equiv to '/ 2' + returnVelocity.Y = (m_lastVelocity.Y + _velocity.Y) * 0.5f; + returnVelocity.Z = (m_lastVelocity.Z + _velocity.Z) * 0.5f; return returnVelocity; } set -- cgit v1.1 From e56ef2720ecd603c9b3c81cbb7c3a0d49d24bf85 Mon Sep 17 00:00:00 2001 From: teravus Date: Wed, 3 Oct 2012 02:30:23 -0400 Subject: I propose that 0.5m/step change for linear velocity is too big of a change to control the reporting of a new angular velocity. I think that this could be here for one of two reasons, 1. vehicles and llMoveToTarget with axis lock, or 2. To attempt to make things look more stable in the physics scene then they really are, however, this also really affects the angular velocity reporting negatively causing things to spin wildly and jump back into place repeatedly. To compromise, if the prim is a vehicle or is being used as a motor target, the original functionality is still applied. If that's not the case, angular velocity is reported with a linear velocity of 0.02m/step. To be clear on the effect of the physical world... When you push things, there's still a lag time where you walk into the object but once the object is in motion, it begins to move as you would expect so results in slightly more realistic motion. --- OpenSim/Region/Physics/OdePlugin/ODEPrim.cs | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs b/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs index 3056f67..1b47754 100644 --- a/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs +++ b/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs @@ -2600,6 +2600,7 @@ Console.WriteLine(" JointCreateFixed"); { Vector3 pv = Vector3.Zero; bool lastZeroFlag = _zeroFlag; + float m_minvelocity = 0; if (Body != (IntPtr)0) // FIXME -> or if it is a joint { d.Vector3 vec = d.BodyGetPosition(Body); @@ -2752,8 +2753,21 @@ Console.WriteLine(" JointCreateFixed"); _acceleration = ((_velocity - m_lastVelocity) / 0.1f); _acceleration = new Vector3(_velocity.X - m_lastVelocity.X / 0.1f, _velocity.Y - m_lastVelocity.Y / 0.1f, _velocity.Z - m_lastVelocity.Z / 0.1f); //m_log.Info("[PHYSICS]: V1: " + _velocity + " V2: " + m_lastVelocity + " Acceleration: " + _acceleration.ToString()); + + // Note here that linearvelocity is affecting angular velocity... so I'm guessing this is a vehicle specific thing... + // it does make sense to do this for tiny little instabilities with physical prim, however 0.5m/frame is fairly large. + // reducing this to 0.02m/frame seems to help the angular rubberbanding quite a bit, however, to make sure it doesn't affect elevators and vehicles + // adding these logical exclusion situations to maintain this where I think it was intended to be. + if (m_throttleUpdates || m_usePID || (m_vehicle != null && m_vehicle.Type != Vehicle.TYPE_NONE) || (Amotor != IntPtr.Zero)) + { + m_minvelocity = 0.5f; + } + else + { + m_minvelocity = 0.02f; + } - if (_velocity.ApproxEquals(pv, 0.5f)) + if (_velocity.ApproxEquals(pv, m_minvelocity)) { m_rotationalVelocity = pv; } -- cgit v1.1 From a2ab3b88de764112996b1e37d74c1e7b7355b1d8 Mon Sep 17 00:00:00 2001 From: teravus Date: Wed, 3 Oct 2012 18:30:44 -0400 Subject: Soliciting for comments on smoothness of physics objects for this build. This introduces expected contact point hints to the ODE Collider to better determine when to throttle updates as excessive. This /should/ smooth physics objects out again, however, I cannot know every configuration of OpenSimulator, so I'm requesting that testers please examine this change on their build. Thanks! --- OpenSim/Region/Physics/OdePlugin/ODEPrim.cs | 13 +++++++-- OpenSim/Region/Physics/OdePlugin/OdeScene.cs | 41 ++++++++++++++++++++++++---- 2 files changed, 46 insertions(+), 8 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs b/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs index 1b47754..e7b3b2b 100644 --- a/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs +++ b/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs @@ -63,6 +63,9 @@ namespace OpenSim.Region.Physics.OdePlugin private bool m_isphysical; + public int ExpectedCollisionContacts { get { return m_expectedCollisionContacts; } } + private int m_expectedCollisionContacts = 0; + /// /// Is this prim subject to physics? Even if not, it's still solid for collision purposes. /// @@ -150,7 +153,7 @@ namespace OpenSim.Region.Physics.OdePlugin private PrimitiveBaseShape _pbs; private OdeScene _parent_scene; - + /// /// The physics space which contains prim geometries /// @@ -840,7 +843,7 @@ namespace OpenSim.Region.Physics.OdePlugin int vertexStride, triStride; mesh.getVertexListAsPtrToFloatArray(out vertices, out vertexStride, out vertexCount); // Note, that vertices are fixed in unmanaged heap mesh.getIndexListAsPtrToIntArray(out indices, out triStride, out indexCount); // Also fixed, needs release after usage - + m_expectedCollisionContacts = indexCount; mesh.releaseSourceMeshData(); // free up the original mesh data to save memory // We must lock here since m_MeshToTriMeshMap is static and multiple scene threads may call this method at @@ -1377,6 +1380,7 @@ Console.WriteLine("CreateGeom:"); { //Console.WriteLine(" CreateGeom 1"); SetGeom(d.CreateSphere(m_targetSpace, _size.X / 2)); + m_expectedCollisionContacts = 3; } catch (AccessViolationException) { @@ -1391,6 +1395,7 @@ Console.WriteLine("CreateGeom:"); { //Console.WriteLine(" CreateGeom 2"); SetGeom(d.CreateBox(m_targetSpace, _size.X, _size.Y, _size.Z)); + m_expectedCollisionContacts = 4; } catch (AccessViolationException) { @@ -1406,6 +1411,7 @@ Console.WriteLine("CreateGeom:"); { //Console.WriteLine(" CreateGeom 3"); SetGeom(d.CreateBox(m_targetSpace, _size.X, _size.Y, _size.Z)); + m_expectedCollisionContacts = 4; } catch (AccessViolationException) { @@ -1421,6 +1427,7 @@ Console.WriteLine("CreateGeom:"); { //Console.WriteLine(" CreateGeom 4"); SetGeom(d.CreateBox(m_targetSpace, _size.X, _size.Y, _size.Z)); + m_expectedCollisionContacts = 4; } catch (AccessViolationException) { @@ -1446,11 +1453,13 @@ Console.WriteLine("CreateGeom:"); _parent_scene.geom_name_map.Remove(prim_geom); _parent_scene.actor_name_map.Remove(prim_geom); d.GeomDestroy(prim_geom); + m_expectedCollisionContacts = 0; prim_geom = IntPtr.Zero; } catch (System.AccessViolationException) { prim_geom = IntPtr.Zero; + m_expectedCollisionContacts = 0; m_log.ErrorFormat("[PHYSICS]: PrimGeom dead for {0}", Name); return false; diff --git a/OpenSim/Region/Physics/OdePlugin/OdeScene.cs b/OpenSim/Region/Physics/OdePlugin/OdeScene.cs index 929b019..7a50c4c 100644 --- a/OpenSim/Region/Physics/OdePlugin/OdeScene.cs +++ b/OpenSim/Region/Physics/OdePlugin/OdeScene.cs @@ -336,6 +336,7 @@ namespace OpenSim.Region.Physics.OdePlugin public int geomContactPointsStartthrottle = 3; public int geomUpdatesPerThrottledUpdate = 15; + private const int avatarExpectedContacts = 3; public float bodyPIDD = 35f; public float bodyPIDG = 25; @@ -474,6 +475,8 @@ namespace OpenSim.Region.Physics.OdePlugin private OdePrim cp1; private OdeCharacter cc2; private OdePrim cp2; + private int p1ExpectedPoints = 0; + private int p2ExpectedPoints = 0; //private int cStartStop = 0; //private string cDictKey = ""; @@ -498,6 +501,7 @@ namespace OpenSim.Region.Physics.OdePlugin public int physics_logging_interval = 0; public bool physics_logging_append_existing_logfile = false; + public d.Vector3 xyz = new d.Vector3(128.1640f, 128.3079f, 25.7600f); public d.Vector3 hpr = new d.Vector3(125.5000f, -17.0000f, 0.0000f); @@ -644,7 +648,7 @@ namespace OpenSim.Region.Physics.OdePlugin contactsPerCollision = physicsconfig.GetInt("contacts_per_collision", 80); - geomContactPointsStartthrottle = physicsconfig.GetInt("geom_contactpoints_start_throttling", 3); + geomContactPointsStartthrottle = physicsconfig.GetInt("geom_contactpoints_start_throttling", 5); geomUpdatesPerThrottledUpdate = physicsconfig.GetInt("geom_updates_before_throttled_update", 15); geomCrossingFailuresBeforeOutofbounds = physicsconfig.GetInt("geom_crossing_failures_before_outofbounds", 5); @@ -1064,7 +1068,10 @@ namespace OpenSim.Region.Physics.OdePlugin PhysicsActor p1; PhysicsActor p2; - + + p1ExpectedPoints = 0; + p2ExpectedPoints = 0; + if (!actor_name_map.TryGetValue(g1, out p1)) { p1 = PANull; @@ -1121,9 +1128,13 @@ namespace OpenSim.Region.Physics.OdePlugin switch (p1.PhysicsActorType) { case (int)ActorTypes.Agent: + p1ExpectedPoints = avatarExpectedContacts; p2.CollidingObj = true; break; case (int)ActorTypes.Prim: + if (p1 != null && p1 is OdePrim) + p1ExpectedPoints = ((OdePrim) p1).ExpectedCollisionContacts; + if (p2.Velocity.LengthSquared() > 0.0f) p2.CollidingObj = true; break; @@ -1319,6 +1330,7 @@ namespace OpenSim.Region.Physics.OdePlugin if ((p2.PhysicsActorType == (int) ActorTypes.Agent) && (Math.Abs(p2.Velocity.X) > 0.01f || Math.Abs(p2.Velocity.Y) > 0.01f)) { + p2ExpectedPoints = avatarExpectedContacts; // Avatar is moving on terrain, use the movement terrain contact AvatarMovementTerrainContact.geom = curContact; @@ -1332,6 +1344,7 @@ namespace OpenSim.Region.Physics.OdePlugin { if (p2.PhysicsActorType == (int)ActorTypes.Agent) { + p2ExpectedPoints = avatarExpectedContacts; // Avatar is standing on terrain, use the non moving terrain contact TerrainContact.geom = curContact; @@ -1356,9 +1369,18 @@ namespace OpenSim.Region.Physics.OdePlugin } if (p2 is OdePrim) - material = ((OdePrim)p2).m_material; - + { + material = ((OdePrim) p2).m_material; + p2ExpectedPoints = ((OdePrim)p2).ExpectedCollisionContacts; + } + + // Unnessesary because p1 is defined above + //if (p1 is OdePrim) + // { + // p1ExpectedPoints = ((OdePrim)p1).ExpectedCollisionContacts; + // } //m_log.DebugFormat("Material: {0}", material); + m_materialContacts[material, movintYN].geom = curContact; if (m_global_contactcount < maxContactsbeforedeath) @@ -1379,7 +1401,10 @@ namespace OpenSim.Region.Physics.OdePlugin int material = (int)Material.Wood; if (p2 is OdePrim) + { material = ((OdePrim)p2).m_material; + p2ExpectedPoints = ((OdePrim)p2).ExpectedCollisionContacts; + } //m_log.DebugFormat("Material: {0}", material); m_materialContacts[material, movintYN].geom = curContact; @@ -1429,6 +1454,7 @@ namespace OpenSim.Region.Physics.OdePlugin { if ((p2.PhysicsActorType == (int)ActorTypes.Agent)) { + p2ExpectedPoints = avatarExpectedContacts; if ((Math.Abs(p2.Velocity.X) > 0.01f || Math.Abs(p2.Velocity.Y) > 0.01f)) { // Avatar is moving on a prim, use the Movement prim contact @@ -1458,7 +1484,10 @@ namespace OpenSim.Region.Physics.OdePlugin int material = (int)Material.Wood; if (p2 is OdePrim) + { material = ((OdePrim)p2).m_material; + p2ExpectedPoints = ((OdePrim)p2).ExpectedCollisionContacts; + } //m_log.DebugFormat("Material: {0}", material); m_materialContacts[material, 0].geom = curContact; @@ -1479,8 +1508,8 @@ namespace OpenSim.Region.Physics.OdePlugin } collision_accounting_events(p1, p2, maxDepthContact); - - if (count > geomContactPointsStartthrottle) + + if (count > ((p1ExpectedPoints + p2ExpectedPoints) * 0.25) + (geomContactPointsStartthrottle)) { // If there are more then 3 contact points, it's likely // that we've got a pile of objects, so ... -- cgit v1.1 From 764270a0d81ef3aeba9ceb2eb50eab74a4707a95 Mon Sep 17 00:00:00 2001 From: teravus Date: Tue, 9 Oct 2012 09:26:11 -0400 Subject: Add config option to plant avatar where they are reducing avatar avatar 'pushability' av_planted see OpenSimDefaults.ini. Use when you have unruly visitors that rudely push each other around. Still allows a small amount of movement based on the avatar movement PID controller settings. You can increase the spring tension in the PID controller and really prevent any movement if you would like. --- OpenSim/Region/Physics/OdePlugin/ODECharacter.cs | 4 ++-- OpenSim/Region/Physics/OdePlugin/OdeScene.cs | 8 +++++++- 2 files changed, 9 insertions(+), 3 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/OdePlugin/ODECharacter.cs b/OpenSim/Region/Physics/OdePlugin/ODECharacter.cs index f3b0630..c736557 100644 --- a/OpenSim/Region/Physics/OdePlugin/ODECharacter.cs +++ b/OpenSim/Region/Physics/OdePlugin/ODECharacter.cs @@ -100,7 +100,7 @@ namespace OpenSim.Region.Physics.OdePlugin private bool m_hackSentFly = false; private int m_requestedUpdateFrequency = 0; private Vector3 m_taintPosition; - + internal bool m_avatarplanted = false; /// /// Hold set forces so we can process them outside physics calculations. This prevents race conditions if we set force /// while calculatios are going on @@ -413,7 +413,7 @@ namespace OpenSim.Region.Physics.OdePlugin set { m_iscollidingObj = value; - if (value) + if (value && !m_avatarplanted) m_pidControllerActive = false; else m_pidControllerActive = true; diff --git a/OpenSim/Region/Physics/OdePlugin/OdeScene.cs b/OpenSim/Region/Physics/OdePlugin/OdeScene.cs index 7a50c4c..8421cdf 100644 --- a/OpenSim/Region/Physics/OdePlugin/OdeScene.cs +++ b/OpenSim/Region/Physics/OdePlugin/OdeScene.cs @@ -501,6 +501,8 @@ namespace OpenSim.Region.Physics.OdePlugin public int physics_logging_interval = 0; public bool physics_logging_append_existing_logfile = false; + private bool avplanted = false; + public d.Vector3 xyz = new d.Vector3(128.1640f, 128.3079f, 25.7600f); public d.Vector3 hpr = new d.Vector3(125.5000f, -17.0000f, 0.0000f); @@ -644,6 +646,8 @@ namespace OpenSim.Region.Physics.OdePlugin avMovementDivisorWalk = physicsconfig.GetFloat("av_movement_divisor_walk", 1.3f); avMovementDivisorRun = physicsconfig.GetFloat("av_movement_divisor_run", 0.8f); avCapRadius = physicsconfig.GetFloat("av_capsule_radius", 0.37f); + avplanted = physicsconfig.GetBoolean("av_planted", false); + IsAvCapsuleTilted = physicsconfig.GetBoolean("av_capsule_tilted", false); contactsPerCollision = physicsconfig.GetInt("contacts_per_collision", 80); @@ -1972,7 +1976,8 @@ namespace OpenSim.Region.Physics.OdePlugin newAv.Flying = isFlying; newAv.MinimumGroundFlightOffset = minimumGroundFlightOffset; - + newAv.m_avatarplanted = avplanted; + return newAv; } @@ -1987,6 +1992,7 @@ namespace OpenSim.Region.Physics.OdePlugin internal void AddCharacter(OdeCharacter chr) { + chr.m_avatarplanted = avplanted; if (!_characters.Contains(chr)) { _characters.Add(chr); -- cgit v1.1 From 7e90ea355120c717d1639d817b2b38326a4d5528 Mon Sep 17 00:00:00 2001 From: teravus Date: Tue, 9 Oct 2012 10:41:16 -0400 Subject: av_av_collisions_off = false OdePhysics Settings in OpenSimDefaults.ini - No Avatar Avatar Collisions. This causes avatar to be able to walk through each other as if they're ghosts but still interact with the environment. --- OpenSim/Region/Physics/OdePlugin/OdeScene.cs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/OdePlugin/OdeScene.cs b/OpenSim/Region/Physics/OdePlugin/OdeScene.cs index 8421cdf..cbe21e2 100644 --- a/OpenSim/Region/Physics/OdePlugin/OdeScene.cs +++ b/OpenSim/Region/Physics/OdePlugin/OdeScene.cs @@ -502,7 +502,7 @@ namespace OpenSim.Region.Physics.OdePlugin public bool physics_logging_append_existing_logfile = false; private bool avplanted = false; - + private bool av_av_collisions_off = false; public d.Vector3 xyz = new d.Vector3(128.1640f, 128.3079f, 25.7600f); public d.Vector3 hpr = new d.Vector3(125.5000f, -17.0000f, 0.0000f); @@ -647,7 +647,8 @@ namespace OpenSim.Region.Physics.OdePlugin avMovementDivisorRun = physicsconfig.GetFloat("av_movement_divisor_run", 0.8f); avCapRadius = physicsconfig.GetFloat("av_capsule_radius", 0.37f); avplanted = physicsconfig.GetBoolean("av_planted", false); - + av_av_collisions_off = physicsconfig.GetBoolean("av_av_collisions_off", false); + IsAvCapsuleTilted = physicsconfig.GetBoolean("av_capsule_tilted", false); contactsPerCollision = physicsconfig.GetInt("contacts_per_collision", 80); @@ -667,6 +668,8 @@ namespace OpenSim.Region.Physics.OdePlugin meshSculptLOD = physicsconfig.GetFloat("mesh_lod", 32f); MeshSculptphysicalLOD = physicsconfig.GetFloat("mesh_physical_lod", 16f); m_filterCollisions = physicsconfig.GetBoolean("filter_collisions", false); + + if (Environment.OSVersion.Platform == PlatformID.Unix) { @@ -1313,6 +1316,10 @@ namespace OpenSim.Region.Physics.OdePlugin if ((p1 is OdePrim) && (((OdePrim)p1).m_isVolumeDetect)) skipThisContact = true; // No collision on volume detect prims + if (av_av_collisions_off) + if ((p1 is OdeCharacter) && (p2 is OdeCharacter)) + skipThisContact = true; + if (!skipThisContact && (p2 is OdePrim) && (((OdePrim)p2).m_isVolumeDetect)) skipThisContact = true; // No collision on volume detect prims -- cgit v1.1 From 87825b0abee76c28dcffdaa2c532779b813b6d14 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Fri, 5 Oct 2012 15:33:17 -0700 Subject: BulletSim: Fix crash when linking large physical linksets. Properly remove and restore linkage constraints when upgrading a prim's mesh to a hull. Lots more debug logging. Definitions and use of Bullet structure dumping. Centralize detail logging so a Flush() can be added for debugging. --- .../Region/Physics/BulletSPlugin/BSConstraint.cs | 13 +- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 2 +- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 137 ++++++++++----------- .../Region/Physics/BulletSPlugin/BSPhysObject.cs | 3 +- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 9 +- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 11 +- .../Physics/BulletSPlugin/BSShapeCollection.cs | 45 ++++--- .../Region/Physics/BulletSPlugin/BulletSimAPI.cs | 14 ++- 8 files changed, 132 insertions(+), 102 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs b/OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs index 63a4127..a20be3a 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs @@ -49,9 +49,16 @@ public abstract class BSConstraint : IDisposable if (m_enabled) { m_enabled = false; - bool success = BulletSimAPI.DestroyConstraint2(m_world.ptr, m_constraint.ptr); - m_world.physicsScene.DetailLog("{0},BSConstraint.Dispose,taint,body1={1},body2={2},success={3}", BSScene.DetailLogZero, m_body1.ID, m_body2.ID, success); - m_constraint.ptr = System.IntPtr.Zero; + if (m_constraint.ptr != IntPtr.Zero) + { + bool success = BulletSimAPI.DestroyConstraint2(m_world.ptr, m_constraint.ptr); + 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.ptr.ToString("X"), + m_body2.ID, m_body2.ptr.ToString("X"), + success); + m_constraint.ptr = System.IntPtr.Zero; + } } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index 4ba2f62..3fb2253 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -862,7 +862,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin private void VDetailLog(string msg, params Object[] args) { if (Prim.PhysicsScene.VehicleLoggingEnabled) - Prim.PhysicsScene.PhysicsLogging.Write(msg, args); + Prim.PhysicsScene.DetailLog(msg, args); } } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index 3e82642..20db4de 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -52,8 +52,8 @@ public class BSLinkset // the physical 'taint' children separately. // After taint processing and before the simulation step, these // two lists must be the same. - private List m_children; - private List m_taintChildren; + private HashSet m_children; + private HashSet m_taintChildren; // We lock the diddling of linkset classes to prevent any badness. // This locks the modification of the instances of this class. Changes @@ -90,8 +90,8 @@ public class BSLinkset m_nextLinksetID = 1; PhysicsScene = scene; LinksetRoot = parent; - m_children = new List(); - m_taintChildren = new List(); + m_children = new HashSet(); + m_taintChildren = new HashSet(); m_mass = parent.MassRaw; } @@ -197,6 +197,8 @@ public class BSLinkset PhysicsScene.TaintedObject("BSLinkSet.Refresh", delegate() { RecomputeLinksetConstraintVariables(); + DetailLog("{0},BSLinkset.Refresh,complete,rBody={1}", + LinksetRoot.LocalID, LinksetRoot.BSBody.ptr.ToString("X")); }); } } @@ -215,13 +217,10 @@ public class BSLinkset if (IsRoot(child)) { // If the one with the dependency is root, must undo all children - DetailLog("{0},BSLinkset.RemoveBodyDependencies,removeChildrenForRoot,rID={1},numChild={2}", - child.LocalID, LinksetRoot.LocalID, m_taintChildren.Count); - foreach (BSPhysObject bpo in m_taintChildren) - { - PhysicallyUnlinkAChildFromRoot(LinksetRoot, LinksetRoot.BSBody, bpo, bpo.BSBody); - ret = true; - } + DetailLog("{0},BSLinkset.RemoveBodyDependencies,removeChildrenForRoot,rID={1},rBody={2}", + child.LocalID, LinksetRoot.LocalID, LinksetRoot.BSBody.ptr.ToString("X")); + + ret = PhysicallyUnlinkAllChildrenFromRoot(LinksetRoot); } else { @@ -229,12 +228,9 @@ public class BSLinkset child.LocalID, LinksetRoot.LocalID, LinksetRoot.BSBody.ptr.ToString("X"), child.LocalID, child.BSBody.ptr.ToString("X")); - // Remove the dependency on the body of this one - if (m_taintChildren.Contains(child)) - { - PhysicallyUnlinkAChildFromRoot(LinksetRoot, LinksetRoot.BSBody, child, child.BSBody); - ret = true; - } + // ret = PhysicallyUnlinkAChildFromRoot(LinksetRoot, child); + // Despite the function name, this removes any link to the specified object. + ret = PhysicallyUnlinkAllChildrenFromRoot(child); } } return ret; @@ -254,7 +250,7 @@ public class BSLinkset child.LocalID, LinksetRoot.LocalID, m_taintChildren.Count); foreach (BSPhysObject bpo in m_taintChildren) { - PhysicallyLinkAChildToRoot(LinksetRoot, LinksetRoot.BSBody, bpo, bpo.BSBody); + PhysicallyLinkAChildToRoot(LinksetRoot, bpo); } } else @@ -263,7 +259,7 @@ public class BSLinkset LinksetRoot.LocalID, LinksetRoot.LocalID, LinksetRoot.BSBody.ptr.ToString("X"), child.LocalID, child.BSBody.ptr.ToString("X")); - PhysicallyLinkAChildToRoot(LinksetRoot, LinksetRoot.BSBody, child, child.BSBody); + PhysicallyLinkAChildToRoot(LinksetRoot, child); } } } @@ -330,22 +326,22 @@ public class BSLinkset { m_children.Add(child); - BSPhysObject rootx = LinksetRoot; // capture the root and body as of now + BSPhysObject rootx = LinksetRoot; // capture the root as of now BSPhysObject childx = child; - DetailLog("{0},AddChildToLinkset,call,rID={1},rBody={2},cID={3},cBody={4}", - rootx.LocalID, - rootx.LocalID, rootx.BSBody.ptr.ToString("X"), - childx.LocalID, childx.BSBody.ptr.ToString("X")); + DetailLog("{0},AddChildToLinkset,call,child={1}", LinksetRoot.LocalID, child.LocalID); PhysicsScene.TaintedObject("AddChildToLinkset", delegate() { - DetailLog("{0},AddChildToLinkset,taint,child={1}", LinksetRoot.LocalID, child.LocalID); - // build the physical binding between me and the child - m_taintChildren.Add(childx); - + DetailLog("{0},AddChildToLinkset,taint,rID={1},rBody={2},cID={3},cBody={4}", + rootx.LocalID, + rootx.LocalID, rootx.BSBody.ptr.ToString("X"), + childx.LocalID, childx.BSBody.ptr.ToString("X")); // Since this is taint-time, the body and shape could have changed for the child - PhysicallyLinkAChildToRoot(rootx, rootx.BSBody, childx, childx.BSBody); + rootx.ForcePosition = rootx.Position; // DEBUG + childx.ForcePosition = childx.Position; // DEBUG + PhysicallyLinkAChildToRoot(rootx, childx); + m_taintChildren.Add(child); }); } return; @@ -378,10 +374,8 @@ public class BSLinkset PhysicsScene.TaintedObject("RemoveChildFromLinkset", delegate() { - if (m_taintChildren.Contains(childx)) - m_taintChildren.Remove(childx); - - PhysicallyUnlinkAChildFromRoot(rootx, rootx.BSBody, childx, childx.BSBody); + m_taintChildren.Remove(child); + PhysicallyUnlinkAChildFromRoot(rootx, childx); RecomputeLinksetConstraintVariables(); }); @@ -396,8 +390,7 @@ public class BSLinkset // Create a constraint between me (root of linkset) and the passed prim (the child). // Called at taint time! - private void PhysicallyLinkAChildToRoot(BSPhysObject rootPrim, BulletBody rootBody, - BSPhysObject childPrim, BulletBody childBody) + private void PhysicallyLinkAChildToRoot(BSPhysObject rootPrim, BSPhysObject childPrim) { // Zero motion for children so they don't interpolate childPrim.ZeroMotion(); @@ -409,33 +402,17 @@ public class BSLinkset // real world coordinate of midpoint between the two objects OMV.Vector3 midPoint = rootPrim.Position + (childRelativePosition / 2); - DetailLog("{0},PhysicallyLinkAChildToRoot,taint,root={1},rBody={2},child={3},cBody={4},rLoc={5},cLoc={6},midLoc={7}", + DetailLog("{0},BSLinkset.PhysicallyLinkAChildToRoot,taint,root={1},rBody={2},child={3},cBody={4},rLoc={5},cLoc={6},midLoc={7}", rootPrim.LocalID, - rootPrim.LocalID, rootBody.ptr.ToString("X"), - childPrim.LocalID, childBody.ptr.ToString("X"), + rootPrim.LocalID, rootPrim.BSBody.ptr.ToString("X"), + childPrim.LocalID, childPrim.BSBody.ptr.ToString("X"), 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 - // There is great subtlty in these paramters. Notice the check for a ptr of zero. - // We pass the BulletBody structure into the taint in order to capture the pointer - // of the body at the time of constraint creation. This doesn't work for the very first - // construction because there is no body yet. The body - // is constructed later at taint time. Thus we use the body address at time of the - // taint creation but, if it is zero, use what's in the prim at the moment. - // There is a possible race condition since shape can change without a taint call - // (like changing to a mesh that is already constructed). The fix for that would be - // to only change BSShape at taint time thus syncronizing these operations at - // the cost of efficiency and lag. BS6DofConstraint constrain = new BS6DofConstraint( - PhysicsScene.World, - rootBody.ptr == IntPtr.Zero ? rootPrim.BSBody : rootBody, - childBody.ptr == IntPtr.Zero ? childPrim.BSBody : childBody, - midPoint, - true, - true - ); + PhysicsScene.World, rootPrim.BSBody, childPrim.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 @@ -452,7 +429,7 @@ public class BSLinkset // create a constraint that allows no freedom of movement between the two objects // http://bulletphysics.org/Bullet/phpBB3/viewtopic.php?t=4818 - DetailLog("{0},PhysicallyLinkAChildToRoot,taint,root={1},child={2}", rootPrim.LocalID, rootPrim.LocalID, childPrim.LocalID); + DetailLog("{0},BSLinkset.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, @@ -486,39 +463,44 @@ public class BSLinkset { constrain.SetSolverIterations(PhysicsScene.Params.linkConstraintSolverIterations); } - - RecomputeLinksetConstraintVariables(); } // Remove linkage between myself and a particular child // The root and child bodies are passed in because we need to remove the constraint between // the bodies that were at unlink time. // Called at taint time! - private void PhysicallyUnlinkAChildFromRoot(BSPhysObject rootPrim, BulletBody rootBody, - BSPhysObject childPrim, BulletBody childBody) + private bool PhysicallyUnlinkAChildFromRoot(BSPhysObject rootPrim, BSPhysObject childPrim) { - DetailLog("{0},PhysicallyUnlinkAChildFromRoot,taint,root={1},rBody={2},child={3},cBody={4}", + bool ret = false; + DetailLog("{0},BSLinkset.PhysicallyUnlinkAChildFromRoot,taint,root={1},rBody={2},child={3},cBody={4}", rootPrim.LocalID, - rootPrim.LocalID, rootBody.ptr.ToString("X"), - childPrim.LocalID, childBody.ptr.ToString("X")); + rootPrim.LocalID, rootPrim.BSBody.ptr.ToString("X"), + childPrim.LocalID, childPrim.BSBody.ptr.ToString("X")); // Find the constraint for this link and get rid of it from the overall collection and from my list - PhysicsScene.Constraints.RemoveAndDestroyConstraint(rootBody, childBody); + if (PhysicsScene.Constraints.RemoveAndDestroyConstraint(rootPrim.BSBody, childPrim.BSBody)) + { + // Make the child refresh its location + BulletSimAPI.PushUpdate2(childPrim.BSBody.ptr); + ret = true; + } - // Make the child refresh its location - BulletSimAPI.PushUpdate2(childPrim.BSBody.ptr); + return ret; } - /* // Remove linkage between myself and any possible children I might have. // Called at taint time! - private void PhysicallyUnlinkAllChildrenFromRoot(BSPhysObject rootPrim) + private bool PhysicallyUnlinkAllChildrenFromRoot(BSPhysObject rootPrim) { - DetailLog("{0},PhysicallyUnlinkAllChildren,taint", rootPrim.LocalID); + DetailLog("{0},BSLinkset.PhysicallyUnlinkAllChildren,taint", rootPrim.LocalID); + bool ret = false; - PhysicsScene.Constraints.RemoveAndDestroyConstraint(rootPrim.BSBody); + if (PhysicsScene.Constraints.RemoveAndDestroyConstraint(rootPrim.BSBody)) + { + ret = true; + } + return ret; } - */ // Call each of the constraints that make up this linkset and recompute the // various transforms and variables. Used when objects are added or removed @@ -550,11 +532,17 @@ public class BSLinkset { // If this is a multiple object linkset, set everybody's center of mass to the set's center of mass OMV.Vector3 centerOfMass = ComputeLinksetCenterOfMass(); - BulletSimAPI.SetCenterOfMassByPosRot2(LinksetRoot.BSBody.ptr, centerOfMass, OMV.Quaternion.Identity); + BulletSimAPI.SetCenterOfMassByPosRot2(LinksetRoot.BSBody.ptr, + centerOfMass, OMV.Quaternion.Identity); + DetailLog("{0},BSLinkset.RecomputeLinksetConstraintVariables,setCenterOfMass,COM={1},rBody={2}", + LinksetRoot.LocalID, centerOfMass, LinksetRoot.BSBody.ptr.ToString("X")); foreach (BSPhysObject child in m_taintChildren) { - BulletSimAPI.SetCenterOfMassByPosRot2(child.BSBody.ptr, centerOfMass, OMV.Quaternion.Identity); + BulletSimAPI.SetCenterOfMassByPosRot2(child.BSBody.ptr, + centerOfMass, OMV.Quaternion.Identity); } + + // BulletSimAPI.DumpAllInfo2(PhysicsScene.World.ptr); // DEBUG DEBUG DEBUG } return; } @@ -563,7 +551,8 @@ public class BSLinkset // Invoke the detailed logger and output something if it's enabled. private void DetailLog(string msg, params Object[] args) { - PhysicsScene.PhysicsLogging.Write(msg, args); + if (PhysicsScene.PhysicsLogging.Enabled) + PhysicsScene.DetailLog(msg, args); } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index 1ac8c59..0665292 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -207,7 +207,8 @@ public abstract class BSPhysObject : PhysicsActor // High performance detailed logging routine used by the physical objects. protected void DetailLog(string msg, params Object[] args) { - PhysicsScene.PhysicsLogging.Write(msg, args); + if (PhysicsScene.PhysicsLogging.Enabled) + PhysicsScene.DetailLog(msg, args); } } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index f7b68ba..98a18a1 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -196,7 +196,7 @@ public sealed class BSPrim : BSPhysObject _isSelected = value; PhysicsScene.TaintedObject("BSPrim.setSelected", delegate() { - // DetailLog("{0},BSPrim.selected,taint,selected={1}", LocalID, _isSelected); + DetailLog("{0},BSPrim.selected,taint,selected={1}", LocalID, _isSelected); SetObjectDynamic(false); }); } @@ -620,8 +620,10 @@ public sealed class BSPrim : BSPhysObject BulletSimAPI.UpdateInertiaTensor2(BSBody.ptr); // There can be special things needed for implementing linksets Linkset.MakeStatic(this); - // The activation state is 'disabled' so Bullet will not try to act on it - BulletSimAPI.ForceActivationState2(BSBody.ptr, ActivationState.DISABLE_SIMULATION); + // The activation state is 'disabled' so Bullet will not try to act on it. + // BulletSimAPI.ForceActivationState2(BSBody.ptr, ActivationState.DISABLE_SIMULATION); + // Start it out sleeping and physical actions could wake it up. + BulletSimAPI.ForceActivationState2(BSBody.ptr, ActivationState.ISLAND_SLEEPING); BSBody.collisionFilter = CollisionFilterGroups.StaticObjectFilter; BSBody.collisionMask = CollisionFilterGroups.StaticObjectMask; @@ -1204,6 +1206,7 @@ public sealed class BSPrim : BSPhysObject { // 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 handled by BSLinkset.) needToRestoreLinkset = Linkset.RemoveBodyDependencies(this); }); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index aaed7de..eed915d 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -254,7 +254,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters // The bounding box for the simulated world. The origin is 0,0,0 unless we're // a child in a mega-region. - // Turns out that Bullet really doesn't care about the extents of the simulated + // Bullet actually doesn't care about the extents of the simulated // area. It tracks active objects no matter where they are. Vector3 worldExtent = new Vector3(Constants.RegionSize, Constants.RegionSize, Constants.RegionHeight); @@ -331,7 +331,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters // Called directly from unmanaged code so don't do much private void BulletLoggerPhysLog(string msg) { - PhysicsLogging.Write("[BULLETS UNMANAGED]:" + msg); + DetailLog("[BULLETS UNMANAGED]:" + msg); } public override void Dispose() @@ -494,8 +494,8 @@ public class BSScene : PhysicsScene, IPhysicsParameters m_simulationStep++; int numSubSteps = 0; - // Sometimes needed for debugging to find out what happened before the step - // PhysicsLogging.Flush(); + // DEBUG + DetailLog("{0},BSScene.Simulate,beforeStep,ntaimts={1},step={2}", DetailLogZero, numTaints, m_simulationStep); try { @@ -715,6 +715,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters { try { + DetailLog("{0},BSScene.ProcessTaints,doTaint,id={1}", DetailLogZero, tcbe.ident); // DEBUG DEBUG DEBUG tcbe.callback(); } catch (Exception e) @@ -1270,6 +1271,8 @@ public class BSScene : PhysicsScene, IPhysicsParameters public void DetailLog(string msg, params Object[] args) { PhysicsLogging.Write(msg, args); + // Add the Flush() if debugging crashes to get all the messages written out. + PhysicsLogging.Flush(); // DEBUG DEBUG DEBUG } // used to fill in the LocalID when there isn't one public const string DetailLogZero = "0000000000"; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index 399a133..283b601 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -136,7 +136,21 @@ public class BSShapeCollection : IDisposable // New entry bodyDesc.ptr = body.ptr; bodyDesc.referenceCount = 1; - DetailLog("{0},BSShapeCollection.ReferenceBody,newBody,ref={1}", body.ID, body, bodyDesc.referenceCount); + DetailLog("{0},BSShapeCollection.ReferenceBody,newBody,ref={2}", + body.ID, body, bodyDesc.referenceCount); + BSScene.TaintCallback createOperation = delegate() + { + if (!BulletSimAPI.IsInWorld2(body.ptr)) + { + BulletSimAPI.AddObjectToWorld2(PhysicsScene.World.ptr, body.ptr); + DetailLog("{0},BSShapeCollection.ReferenceBody,addedToWorld,ref={1}", + body.ID, body); + } + }; + if (atTaintTime) + createOperation(); + else + PhysicsScene.TaintedObject("BSShapeCollection.ReferenceBody", createOperation); } bodyDesc.lastReferenced = System.DateTime.Now; Bodies[body.ID] = bodyDesc; @@ -160,21 +174,22 @@ public class BSShapeCollection : IDisposable Bodies[body.ID] = bodyDesc; DetailLog("{0},BSShapeCollection.DereferenceBody,ref={1}", body.ID, bodyDesc.referenceCount); - // If body is no longer being used, free it -- bodies are never shared. + // If body is no longer being used, free it -- bodies can never be shared. if (bodyDesc.referenceCount == 0) { Bodies.Remove(body.ID); BSScene.TaintCallback removeOperation = delegate() { - DetailLog("{0},BSShapeCollection.DereferenceBody,DestroyingBody. ptr={1}", - body.ID, body.ptr.ToString("X")); + DetailLog("{0},BSShapeCollection.DereferenceBody,DestroyingBody. ptr={1}, inTaintTime={2}", + body.ID, body.ptr.ToString("X"), inTaintTime); // If the caller needs to know the old body is going away, pass the event up. if (bodyCallback != null) bodyCallback(body); - // Zero any reference to the shape so it is not freed when the body is deleted. - BulletSimAPI.SetCollisionShape2(PhysicsScene.World.ptr, body.ptr, IntPtr.Zero); // It may have already been removed from the world in which case the next is a NOOP. BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.ptr, body.ptr); + + // Zero any reference to the shape so it is not freed when the body is deleted. + BulletSimAPI.SetCollisionShape2(PhysicsScene.World.ptr, body.ptr, IntPtr.Zero); BulletSimAPI.DestroyObject2(PhysicsScene.World.ptr, body.ptr); }; // If already in taint-time, do the operations now. Otherwise queue for later. @@ -208,7 +223,7 @@ public class BSShapeCollection : IDisposable { // There is an existing instance of this mesh. meshDesc.referenceCount++; - DetailLog("{0},BSShapeColliction.ReferenceShape,existingMesh,key={1},cnt={2}", + DetailLog("{0},BSShapeCollection.ReferenceShape,existingMesh,key={1},cnt={2}", BSScene.DetailLogZero, shape.shapeKey.ToString("X"), meshDesc.referenceCount); } else @@ -217,7 +232,7 @@ public class BSShapeCollection : IDisposable meshDesc.ptr = shape.ptr; // We keep a reference to the underlying IMesh data so a hull can be built meshDesc.referenceCount = 1; - DetailLog("{0},BSShapeColliction.ReferenceShape,newMesh,key={1},cnt={2}", + DetailLog("{0},BSShapeCollection.ReferenceShape,newMesh,key={1},cnt={2}", BSScene.DetailLogZero, shape.shapeKey.ToString("X"), meshDesc.referenceCount); ret = true; } @@ -230,7 +245,7 @@ public class BSShapeCollection : IDisposable { // There is an existing instance of this hull. hullDesc.referenceCount++; - DetailLog("{0},BSShapeColliction.ReferenceShape,existingHull,key={1},cnt={2}", + DetailLog("{0},BSShapeCollection.ReferenceShape,existingHull,key={1},cnt={2}", BSScene.DetailLogZero, shape.shapeKey.ToString("X"), hullDesc.referenceCount); } else @@ -238,7 +253,7 @@ public class BSShapeCollection : IDisposable // This is a new reference to a hull hullDesc.ptr = shape.ptr; hullDesc.referenceCount = 1; - DetailLog("{0},BSShapeColliction.ReferenceShape,newHull,key={1},cnt={2}", + DetailLog("{0},BSShapeCollection.ReferenceShape,newHull,key={1},cnt={2}", BSScene.DetailLogZero, shape.shapeKey.ToString("X"), hullDesc.referenceCount); ret = true; @@ -525,7 +540,7 @@ public class BSShapeCollection : IDisposable DetailLog("{0},BSShapeCollection.CreateGeomHull,create,oldKey={1},newKey={2}", prim.LocalID, prim.BSShape.shapeKey.ToString("X"), newHullKey.ToString("X")); - // Remove usage of the previous shape. Also removes reference to underlying mesh if it is a hull. + // Remove usage of the previous shape. DereferenceShape(prim.BSShape, true, shapeCallback); newShape = CreatePhysicalHull(prim.PhysObjectName, newHullKey, pbs, shapeData.Size, lod); @@ -659,6 +674,7 @@ public class BSShapeCollection : IDisposable if (pbs.SculptEntry) lod = PhysicsScene.SculptLOD; + // Mega prims usually get more detail because one can interact with shape approximations at this size. float maxAxis = Math.Max(shapeData.Size.X, Math.Max(shapeData.Size.Y, shapeData.Size.Z)); if (maxAxis > PhysicsScene.MeshMegaPrimThreshold) lod = PhysicsScene.MeshMegaPrimLOD; @@ -709,13 +725,13 @@ public class BSShapeCollection : IDisposable { bodyPtr = BulletSimAPI.CreateBodyFromShape2(sim.ptr, shape.ptr, shapeData.ID, shapeData.Position, shapeData.Rotation); - // DetailLog("{0},BSShapeCollection.CreateBody,mesh,ptr={1}", prim.LocalID, bodyPtr.ToString("X")); + DetailLog("{0},BSShapeCollection.CreateBody,mesh,ptr={1}", prim.LocalID, bodyPtr.ToString("X")); } else { bodyPtr = BulletSimAPI.CreateGhostFromShape2(sim.ptr, shape.ptr, shapeData.ID, shapeData.Position, shapeData.Rotation); - // DetailLog("{0},BSShapeCollection.CreateBody,ghost,ptr={1}", prim.LocalID, bodyPtr.ToString("X")); + DetailLog("{0},BSShapeCollection.CreateBody,ghost,ptr={1}", prim.LocalID, bodyPtr.ToString("X")); } aBody = new BulletBody(shapeData.ID, bodyPtr); @@ -731,7 +747,8 @@ public class BSShapeCollection : IDisposable private void DetailLog(string msg, params Object[] args) { - PhysicsScene.PhysicsLogging.Write(msg, args); + if (PhysicsScene.PhysicsLogging.Enabled) + PhysicsScene.DetailLog(msg, args); } } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs index a43880d..bb4d399 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs @@ -192,8 +192,9 @@ public struct ShapeData SHAPE_SPHERE = 5, SHAPE_MESH = 6, SHAPE_HULL = 7, - SHAPE_GROUNDPLANE = 8, - SHAPE_TERRAIN = 9, + // following defined by BulletSim + SHAPE_GROUNDPLANE = 20, + SHAPE_TERRAIN = 21, }; public uint ID; public PhysicsShapeType Type; @@ -1108,6 +1109,15 @@ public static extern float GetMargin2(IntPtr shape); public static extern void DumpRigidBody2(IntPtr sim, IntPtr collisionObject); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void DumpCollisionShape2(IntPtr sim, IntPtr collisionShape); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void DumpConstraint2(IntPtr sim, IntPtr constrain); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void DumpAllInfo2(IntPtr sim); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern void DumpMapInfo2(IntPtr sim, IntPtr manInfo); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -- cgit v1.1 From 68698975f1537725a1f53bc4b2db2cfc798ac7f3 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 9 Oct 2012 12:58:06 -0700 Subject: BulletSim: Add Force* operations to objects to allow direct push to engine. Update BSDynamics to use same (don't want to delay updates til next taint-time. Suppress queuing a taint update for position and orientation calls if value does not change. Move Bullet timing statistics call from C# back to C++ code. Throttle taints per simulation step and add parameter to set. By default, don't create hulls for physical objects. Add a parameter to turn on and off. --- .../Region/Physics/BulletSPlugin/BSCharacter.cs | 11 ++++ OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 12 ++-- .../Region/Physics/BulletSPlugin/BSPhysObject.cs | 4 ++ OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 33 +++++++++-- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 65 ++++++++++++++++------ .../Physics/BulletSPlugin/BSShapeCollection.cs | 2 +- .../Region/Physics/BulletSPlugin/BulletSimAPI.cs | 2 + 7 files changed, 100 insertions(+), 29 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index 2a52e01..c23ccd5 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -332,6 +332,13 @@ public class BSCharacter : BSPhysObject }); } } + public override OMV.Vector3 ForceVelocity { + get { return _velocity; } + set { + _velocity = value; + BulletSimAPI.SetObjectVelocity(PhysicsScene.WorldID, LocalID, _velocity); + } + } public override OMV.Vector3 Torque { get { return _torque; } set { _torque = value; @@ -432,6 +439,10 @@ public class BSCharacter : BSPhysObject get { return _rotationalVelocity; } set { _rotationalVelocity = value; } } + public override OMV.Vector3 ForceRotationalVelocity { + get { return _rotationalVelocity; } + set { _rotationalVelocity = value; } + } public override bool Kinematic { get { return _kinematic; } set { _kinematic = value; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index 3fb2253..76230a1 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -481,7 +481,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin m_lastPositionVector = Prim.ForcePosition; VDetailLog("{0},BSDynamics.Step,done,pos={1},force={2},velocity={3},angvel={4}", - Prim.LocalID, Prim.Position, Prim.Force, Prim.Velocity, Prim.RotationalVelocity); + Prim.LocalID, Prim.ForcePosition, Prim.Force, Prim.ForceVelocity, Prim.RotationalVelocity); }// end Step // Apply the effect of the linear motor. @@ -540,7 +540,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin // add Gravity and Buoyancy // There is some gravity, make a gravity force vector that is applied after object velocity. // m_VehicleBuoyancy: -1=2g; 0=1g; 1=0g; - Vector3 grav = Prim.PhysicsScene.DefaultGravity * (Prim.Mass * (1f - m_VehicleBuoyancy)); + Vector3 grav = Prim.PhysicsScene.DefaultGravity * (Prim.MassRaw * (1f - m_VehicleBuoyancy)); /* * RA: Not sure why one would do this @@ -678,10 +678,10 @@ namespace OpenSim.Region.Physics.BulletSPlugin m_newVelocity.Z = 0; // Apply velocity - Prim.Velocity = m_newVelocity; + Prim.ForceVelocity = m_newVelocity; // apply gravity force // Why is this set here? The physics engine already does gravity. - // m_prim.AddForce(grav, false); + Prim.AddForce(grav, false); // Apply friction Vector3 keepFraction = Vector3.One - (Vector3.One / (m_linearFrictionTimescale / pTimestep)); @@ -704,7 +704,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin // m_lastAngularVelocity // what was last applied to body // Get what the body is doing, this includes 'external' influences - Vector3 angularVelocity = Prim.RotationalVelocity; + Vector3 angularVelocity = Prim.ForceRotationalVelocity; if (m_angularMotorApply > 0) { @@ -810,7 +810,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin m_lastAngularVelocity -= m_lastAngularVelocity * decayamount; // Apply to the body - Prim.RotationalVelocity = m_lastAngularVelocity; + Prim.ForceRotationalVelocity = m_lastAngularVelocity; VDetailLog("{0},MoveAngular,done,decay={1},lastAngular={2}", Prim.LocalID, decayamount, m_lastAngularVelocity); } //end MoveAngular diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index 0665292..cae599c 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -85,6 +85,10 @@ public abstract class BSPhysObject : PhysicsActor public abstract OMV.Quaternion ForceOrientation { get; set; } + public abstract OMV.Vector3 ForceVelocity { get; set; } + + public abstract OMV.Vector3 ForceRotationalVelocity { get; set; } + #region Collisions // Requested number of milliseconds between collision events. Zero means disabled. diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 98a18a1..d408be0 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -265,6 +265,11 @@ public sealed class BSPrim : BSPhysObject return _position; } set { + // If you must push the position into the physics engine, use ForcePosition. + if (_position == value) + { + return; + } _position = value; // TODO: what does it mean to set the position of a child prim?? Rebuild the constraint? PositionSanityCheck(); @@ -453,7 +458,6 @@ public sealed class BSPrim : BSPhysObject } return; } - public override OMV.Vector3 Velocity { get { return _velocity; } set { @@ -465,6 +469,13 @@ public sealed class BSPrim : BSPhysObject }); } } + public override OMV.Vector3 ForceVelocity { + get { return _velocity; } + set { + _velocity = value; + BulletSimAPI.SetLinearVelocity2(BSBody.ptr, _velocity); + } + } public override OMV.Vector3 Torque { get { return _torque; } set { _torque = value; @@ -490,6 +501,8 @@ public sealed class BSPrim : BSPhysObject return _orientation; } set { + if (_orientation == value) + return; _orientation = value; // TODO: what does it mean if a child in a linkset changes its orientation? Rebuild the constraint? PhysicsScene.TaintedObject("BSPrim.setOrientation", delegate() @@ -621,9 +634,9 @@ public sealed class BSPrim : BSPhysObject // There can be special things needed for implementing linksets Linkset.MakeStatic(this); // The activation state is 'disabled' so Bullet will not try to act on it. - // BulletSimAPI.ForceActivationState2(BSBody.ptr, ActivationState.DISABLE_SIMULATION); + BulletSimAPI.ForceActivationState2(BSBody.ptr, ActivationState.DISABLE_SIMULATION); // Start it out sleeping and physical actions could wake it up. - BulletSimAPI.ForceActivationState2(BSBody.ptr, ActivationState.ISLAND_SLEEPING); + // BulletSimAPI.ForceActivationState2(BSBody.ptr, ActivationState.ISLAND_SLEEPING); BSBody.collisionFilter = CollisionFilterGroups.StaticObjectFilter; BSBody.collisionMask = CollisionFilterGroups.StaticObjectMask; @@ -640,6 +653,9 @@ public sealed class BSPrim : BSPhysObject // per http://www.bulletphysics.org/Bullet/phpBB3/viewtopic.php?t=3382 BulletSimAPI.ClearAllForces2(BSBody.ptr); + // For good measure, make sure the transform is set through to the motion state + BulletSimAPI.SetTranslation2(BSBody.ptr, _position, _orientation); + // A dynamic object has mass IntPtr collisionShapePtr = BulletSimAPI.GetCollisionShape2(BSBody.ptr); OMV.Vector3 inertia = BulletSimAPI.CalculateLocalInertia2(collisionShapePtr, Mass); @@ -776,6 +792,15 @@ public sealed class BSPrim : BSPhysObject }); } } + public override OMV.Vector3 ForceRotationalVelocity { + get { + return _rotationalVelocity; + } + set { + _rotationalVelocity = value; + BulletSimAPI.SetAngularVelocity2(BSBody.ptr, _rotationalVelocity); + } + } public override bool Kinematic { get { return _kinematic; } set { _kinematic = value; @@ -1307,7 +1332,7 @@ public sealed class BSPrim : BSPhysObject /* else { - // For debugging, we can also report the movement of children + // 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/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index eed915d..33ac116 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -90,10 +90,6 @@ public class BSScene : PhysicsScene, IPhysicsParameters // let my minuions use my logger public ILog Logger { get { return m_log; } } - // If non-zero, the number of simulation steps between calls to the physics - // engine to output detailed physics stats. Debug logging level must be on also. - private int m_detailedStatsStep = 0; - public IMesher mesher; // Level of Detail values kept as float because that's what the Meshmerizer wants public float MeshLOD { get; private set; } @@ -112,6 +108,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters private float m_fixedTimeStep; private long m_simulationStep = 0; public long SimulationStep { get { return m_simulationStep; } } + private int m_taintsToProcessPerStep; // 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 @@ -131,6 +128,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters public bool ShouldMeshSculptedPrim { get; private set; } // cause scuplted prims to get meshed public bool ShouldForceSimplePrimMeshing { get; private set; } // if a cube or sphere, let Bullet do internal shapes + public bool ShouldUseHullsForPhysicalObjects { get; private set; } // 'true' if should create hulls for physical objects public float PID_D { get; private set; } // derivative public float PID_P { get; private set; } // proportional @@ -582,15 +580,6 @@ public class BSScene : PhysicsScene, IPhysicsParameters } } - // If enabled, call into the physics engine to dump statistics - if (m_detailedStatsStep > 0) - { - if ((m_simulationStep % m_detailedStatsStep) == 0) - { - BulletSimAPI.DumpBulletStatistics(); - } - } - // 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. // Since Bullet normally does 5 or 6 substeps, this will normally sum to about 60 FPS. @@ -617,7 +606,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters BSPhysObject collidee = null; PhysObjects.TryGetValue(collidingWith, out collidee); - DetailLog("{0},BSScene.SendCollision,collide,id={1},with={2}", DetailLogZero, localID, collidingWith); + // DetailLog("{0},BSScene.SendCollision,collide,id={1},with={2}", DetailLogZero, localID, collidingWith); if (collider.Collide(collidingWith, collidee, collidePoint, collideNormal, penetration)) { @@ -704,6 +693,35 @@ public class BSScene : PhysicsScene, IPhysicsParameters if (_taintedObjects.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 + int taintCount = m_taintsToProcessPerStep; + TaintCallbackEntry oneCallback = new TaintCallbackEntry(); + while (_taintedObjects.Count > 0 && taintCount-- > 0) + { + bool gotOne = false; + lock (_taintLock) + { + if (_taintedObjects.Count > 0) + { + oneCallback = _taintedObjects[0]; + _taintedObjects.RemoveAt(0); + gotOne = true; + } + } + if (gotOne) + { + try + { + DetailLog("{0},BSScene.ProcessTaints,doTaint,id={1}", DetailLogZero, oneCallback.ident); // DEBUG DEBUG DEBUG + oneCallback.callback(); + } + catch (Exception e) + { + m_log.ErrorFormat("{0}: ProcessTaints: {1}: Exception: {2}", LogHeader, oneCallback.ident, e); + } + } + } + /* + // swizzle a new list into the list location so we can process what's there List oldList; lock (_taintLock) { @@ -724,6 +742,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters } } oldList.Clear(); + */ } } @@ -835,6 +854,11 @@ public class BSScene : PhysicsScene, IPhysicsParameters (s,cf,p,v) => { s.ShouldForceSimplePrimMeshing = cf.GetBoolean(p, s.BoolNumeric(v)); }, (s) => { return s.NumericBool(s.ShouldForceSimplePrimMeshing); }, (s,p,l,v) => { s.ShouldForceSimplePrimMeshing = s.BoolNumeric(v); } ), + new ParameterDefn("UseHullsForPhysicalObjects", "If true, create hulls for physical objects", + ConfigurationParameters.numericFalse, + (s,cf,p,v) => { s.ShouldUseHullsForPhysicalObjects = cf.GetBoolean(p, s.BoolNumeric(v)); }, + (s) => { return s.NumericBool(s.ShouldUseHullsForPhysicalObjects); }, + (s,p,l,v) => { s.ShouldUseHullsForPhysicalObjects = s.BoolNumeric(v); } ), new ParameterDefn("MeshLevelOfDetail", "Level of detail to render meshes (32, 16, 8 or 4. 32=most detailed)", 8f, @@ -877,6 +901,11 @@ public class BSScene : PhysicsScene, IPhysicsParameters (s,cf,p,v) => { s.m_maxUpdatesPerFrame = cf.GetInt(p, (int)v); }, (s) => { return (float)s.m_maxUpdatesPerFrame; }, (s,p,l,v) => { s.m_maxUpdatesPerFrame = (int)v; } ), + new ParameterDefn("MaxTaintsToProcessPerStep", "Number of update taints to process before each simulation step", + 100f, + (s,cf,p,v) => { s.m_taintsToProcessPerStep = cf.GetInt(p, (int)v); }, + (s) => { return (float)s.m_taintsToProcessPerStep; }, + (s,p,l,v) => { s.m_taintsToProcessPerStep = (int)v; } ), new ParameterDefn("MaxObjectMass", "Maximum object mass (10000.01)", 10000.01f, (s,cf,p,v) => { s.MaximumObjectMass = cf.GetFloat(p, v); }, @@ -1086,11 +1115,11 @@ public class BSScene : PhysicsScene, IPhysicsParameters (s) => { return s.m_params[0].linkConstraintSolverIterations; }, (s,p,l,v) => { s.m_params[0].linkConstraintSolverIterations = v; } ), - new ParameterDefn("DetailedStats", "Frames between outputting detailed phys stats. (0 is off)", + new ParameterDefn("LogPhysicsStatisticsFrames", "Frames between outputting detailed phys stats. (0 is off)", 0f, - (s,cf,p,v) => { s.m_detailedStatsStep = cf.GetInt(p, (int)v); }, - (s) => { return (float)s.m_detailedStatsStep; }, - (s,p,l,v) => { s.m_detailedStatsStep = (int)v; } ), + (s,cf,p,v) => { s.m_params[0].physicsLoggingFrames = cf.GetInt(p, (int)v); }, + (s) => { return (float)s.m_params[0].physicsLoggingFrames; }, + (s,p,l,v) => { s.m_params[0].physicsLoggingFrames = (int)v; } ), }; // Convert a boolean to our numeric true and false values diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index 283b601..e619b48 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -407,7 +407,7 @@ public class BSShapeCollection : IDisposable // made. Native shapes are best used in either case. if (!haveShape) { - if (prim.IsPhysical) + if (prim.IsPhysical && PhysicsScene.ShouldUseHullsForPhysicalObjects) { // Update prim.BSShape to reference a hull of this shape. ret = GetReferenceToHull(prim, shapeData, pbs, shapeCallback); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs index bb4d399..7a60afb 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs @@ -306,6 +306,8 @@ public struct ConfigurationParameters public float linkConstraintCFM; public float linkConstraintSolverIterations; + public float physicsLoggingFrames; + public const float numericTrue = 1f; public const float numericFalse = 0f; } -- cgit v1.1 From a791620622dc0a67a6af2c4a9c011d9057360411 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Wed, 10 Oct 2012 08:02:37 -0700 Subject: BulletSim: cosmetic changes (comments and renaming). Give mass to terrain to improve interactions. --- .../Region/Physics/BulletSPlugin/BSCharacter.cs | 4 +- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 55 +++++++++++++++------- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 10 ++-- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 9 ++-- .../Physics/BulletSPlugin/BSShapeCollection.cs | 31 ++++++------ .../Physics/BulletSPlugin/BSTerrainManager.cs | 14 +++--- .../Region/Physics/BulletSPlugin/BulletSimAPI.cs | 3 +- 7 files changed, 74 insertions(+), 52 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index c23ccd5..2e6b2da 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -263,7 +263,7 @@ public class BSCharacter : BSPhysObject // A version of the sanity check that also makes sure a new position value is // pushed back to the physics engine. This routine would be used by anyone // who is not already pushing the value. - private bool PositionSanityCheck2(bool atTaintTime) + private bool PositionSanityCheck2(bool inTaintTime) { bool ret = false; if (PositionSanityCheck()) @@ -275,7 +275,7 @@ public class BSCharacter : BSPhysObject DetailLog("{0},BSCharacter.PositionSanityCheck,taint,pos={1},orient={2}", LocalID, _position, _orientation); BulletSimAPI.SetObjectTranslation(PhysicsScene.WorldID, LocalID, _position, _orientation); }; - if (atTaintTime) + if (inTaintTime) sanityOperation(); else PhysicsScene.TaintedObject("BSCharacter.PositionSanityCheck", sanityOperation); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index 20db4de..b84ccdc 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -160,6 +160,31 @@ public class BSLinkset return ret; } + // When physical properties are changed the linkset needs to recalculate + // its internal properties. + // May be called at runtime or taint-time (just pass the appropriate flag). + public void Refresh(BSPhysObject requestor, bool inTaintTime) + { + // If there are no children, there can't be any constraints to recompute + if (!HasAnyChildren) + return; + + // Only the root does the recomputation + if (IsRoot(requestor)) + { + BSScene.TaintCallback refreshOperation = delegate() + { + RecomputeLinksetConstraintVariables(); + DetailLog("{0},BSLinkset.Refresh,complete,rBody={1}", + LinksetRoot.LocalID, LinksetRoot.BSBody.ptr.ToString("X")); + }; + if (inTaintTime) + refreshOperation(); + else + PhysicsScene.TaintedObject("BSLinkSet.Refresh", refreshOperation); + } + } + // The object is going dynamic (physical). Do any setup necessary // for a dynamic linkset. // Only the state of the passed object can be modified. The rest of the linkset @@ -182,24 +207,19 @@ public class BSLinkset return false; } - // When physical properties are changed the linkset needs to recalculate - // its internal properties. - // Called at runtime. - public void Refresh(BSPhysObject requestor) + // If the software is handling the movement of all the objects in a linkset + // (like if one doesn't use constraints for static linksets), this is called + // when an update for the root of the linkset is received. + // Called at taint-time!! + public void UpdateProperties(BSPhysObject physObject) { - // If there are no children, there can't be any constraints to recompute - if (!HasAnyChildren) - return; - - // Only the root does the recomputation - if (IsRoot(requestor)) + // The root local properties have been updated. Apply to the children if appropriate. + if (IsRoot(physObject) && HasAnyChildren) { - PhysicsScene.TaintedObject("BSLinkSet.Refresh", delegate() + if (!physObject.IsPhysical) { - RecomputeLinksetConstraintVariables(); - DetailLog("{0},BSLinkset.Refresh,complete,rBody={1}", - LinksetRoot.LocalID, LinksetRoot.BSBody.ptr.ToString("X")); - }); + // TODO: implement software linkset update for static object linksets + } } } @@ -236,9 +256,8 @@ public class BSLinkset return ret; } - // Routine used when rebuilding the body of the root of the linkset - // This is called after RemoveAllLinksToRoot() to restore all the constraints. - // This is called when the root body has been changed. + // Companion to RemoveBodyDependencies(). If RemoveBodyDependencies() returns 'true', + // this routine will restore the removed constraints. // Called at taint-time!! public void RestoreBodyDependencies(BSPrim child) { diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index d408be0..b26f049 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -327,7 +327,7 @@ public sealed class BSPrim : BSPhysObject // A version of the sanity check that also makes sure a new position value is // pushed back to the physics engine. This routine would be used by anyone // who is not already pushing the value. - private bool PositionSanityCheck2(bool atTaintTime) + private bool PositionSanityCheck2(bool inTaintTime) { bool ret = false; if (PositionSanityCheck()) @@ -339,7 +339,7 @@ public sealed class BSPrim : BSPhysObject DetailLog("{0},BSPrim.PositionSanityCheck,taint,pos={1},orient={2}", LocalID, _position, _orientation); BulletSimAPI.SetObjectTranslation(PhysicsScene.WorldID, LocalID, _position, _orientation); }; - if (atTaintTime) + if (inTaintTime) sanityOperation(); else PhysicsScene.TaintedObject("BSPrim.PositionSanityCheck", sanityOperation); @@ -583,7 +583,7 @@ public sealed class BSPrim : BSPhysObject // Set up the object physicalness (does gravity and collisions move this object) MakeDynamic(IsStatic); - // Update vehicle specific parameters + // Update vehicle specific parameters (after MakeDynamic() so can change physical parameters) _vehicle.Refresh(); // Arrange for collision events if the simulator wants them @@ -606,7 +606,7 @@ public sealed class BSPrim : BSPhysObject // Recompute any linkset parameters. // When going from non-physical to physical, this re-enables the constraints that // had been automatically disabled when the mass was set to zero. - Linkset.Refresh(this); + Linkset.Refresh(this, true); DetailLog("{0},BSPrim.UpdatePhysicalParameters,exit,static={1},solid={2},mass={3},collide={4},cf={5:X},body={6},shape={7}", LocalID, IsStatic, IsSolid, _mass, SubscribedEvents(), CurrentCollisionFlags, BSBody, BSShape); @@ -1322,6 +1322,8 @@ public sealed class BSPrim : BSPhysObject PositionSanityCheck2(true); + Linkset.UpdateProperties(this); + DetailLog("{0},BSPrim.UpdateProperties,call,pos={1},orient={2},vel={3},accel={4},rotVel={5}", LocalID, _position, _orientation, _velocity, _acceleration, _rotationalVelocity); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index 33ac116..50091cc 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -39,7 +39,6 @@ using log4net; using OpenMetaverse; // TODOs for BulletSim (for BSScene, BSPrim, BSCharacter and BulletSim) -// Move all logic out of the C++ code and into the C# code for easier future modifications. // Test sculpties (verified that they don't work) // Compute physics FPS reasonably // Based on material, set density and friction @@ -493,7 +492,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters int numSubSteps = 0; // DEBUG - DetailLog("{0},BSScene.Simulate,beforeStep,ntaimts={1},step={2}", DetailLogZero, numTaints, m_simulationStep); + // DetailLog("{0},BSScene.Simulate,beforeStep,ntaimts={1},step={2}", DetailLogZero, numTaints, m_simulationStep); try { @@ -503,8 +502,8 @@ public class BSScene : PhysicsScene, IPhysicsParameters out updatedEntityCount, out updatedEntitiesPtr, out collidersCount, out collidersPtr); if (PhysicsLogging.Enabled) simTime = Util.EnvironmentTickCountSubtract(beforeTime); - DetailLog("{0},Simulate,call, nTaints={1}, simTime={2}, substeps={3}, updates={4}, colliders={5}", - DetailLogZero, numTaints, simTime, numSubSteps, updatedEntityCount, collidersCount); + DetailLog("{0},Simulate,call, frame={1}, nTaints={2}, simTime={3}, substeps={4}, updates={5}, colliders={6}", + DetailLogZero, m_simulationStep, numTaints, simTime, numSubSteps, updatedEntityCount, collidersCount); } catch (Exception e) { @@ -855,7 +854,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters (s) => { return s.NumericBool(s.ShouldForceSimplePrimMeshing); }, (s,p,l,v) => { s.ShouldForceSimplePrimMeshing = s.BoolNumeric(v); } ), new ParameterDefn("UseHullsForPhysicalObjects", "If true, create hulls for physical objects", - ConfigurationParameters.numericFalse, + ConfigurationParameters.numericTrue, (s,cf,p,v) => { s.ShouldUseHullsForPhysicalObjects = cf.GetBoolean(p, s.BoolNumeric(v)); }, (s) => { return s.NumericBool(s.ShouldUseHullsForPhysicalObjects); }, (s,p,l,v) => { s.ShouldUseHullsForPhysicalObjects = s.BoolNumeric(v); } ), diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index e619b48..d5e2172 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -67,8 +67,8 @@ public class BSShapeCollection : IDisposable public DateTime lastReferenced; } - private Dictionary Meshes = new Dictionary(); - private Dictionary Hulls = new Dictionary(); + private Dictionary Meshes = new Dictionary(); + private Dictionary Hulls = new Dictionary(); private Dictionary Bodies = new Dictionary(); public BSShapeCollection(BSScene physScene) @@ -121,7 +121,7 @@ public class BSShapeCollection : IDisposable // Track another user of a body // We presume the caller has allocated the body. // Bodies only have one user so the reference count is either 1 or 0. - public void ReferenceBody(BulletBody body, bool atTaintTime) + public void ReferenceBody(BulletBody body, bool inTaintTime) { lock (m_collectionActivityLock) { @@ -147,7 +147,7 @@ public class BSShapeCollection : IDisposable body.ID, body); } }; - if (atTaintTime) + if (inTaintTime) createOperation(); else PhysicsScene.TaintedObject("BSShapeCollection.ReferenceBody", createOperation); @@ -272,7 +272,7 @@ public class BSShapeCollection : IDisposable // Release the usage of a shape. // The collisionObject is released since it is a copy of the real collision shape. - public void DereferenceShape(BulletShape shape, bool atTaintTime, ShapeDestructionCallback shapeCallback) + public void DereferenceShape(BulletShape shape, bool inTaintTime, ShapeDestructionCallback shapeCallback) { if (shape.ptr == IntPtr.Zero) return; @@ -294,14 +294,14 @@ public class BSShapeCollection : IDisposable if (shape.ptr != IntPtr.Zero & shape.isNativeShape) { DetailLog("{0},BSShapeCollection.DereferenceShape,deleteNativeShape,ptr={1},taintTime={2}", - BSScene.DetailLogZero, shape.ptr.ToString("X"), atTaintTime); + BSScene.DetailLogZero, shape.ptr.ToString("X"), inTaintTime); if (shapeCallback != null) shapeCallback(shape); BulletSimAPI.DeleteCollisionShape2(PhysicsScene.World.ptr, shape.ptr); } break; } }; - if (atTaintTime) + if (inTaintTime) { lock (m_collectionActivityLock) { @@ -441,7 +441,7 @@ public class BSShapeCollection : IDisposable // Native shapes are always built independently. newShape = new BulletShape(BulletSimAPI.BuildNativeShape2(PhysicsScene.World.ptr, shapeData), shapeType); - newShape.shapeKey = (ulong)shapeKey; + newShape.shapeKey = (System.UInt64)shapeKey; newShape.isNativeShape = true; // Don't need to do a 'ReferenceShape()' here because native shapes are not tracked. @@ -461,7 +461,7 @@ public class BSShapeCollection : IDisposable BulletShape newShape = new BulletShape(IntPtr.Zero); float lod; - ulong newMeshKey = ComputeShapeKey(shapeData, pbs, out lod); + System.UInt64 newMeshKey = ComputeShapeKey(shapeData, pbs, out lod); // if this new shape is the same as last time, don't recreate the mesh if (newMeshKey == prim.BSShape.shapeKey && prim.BSShape.type == ShapeData.PhysicsShapeType.SHAPE_MESH) @@ -484,7 +484,7 @@ public class BSShapeCollection : IDisposable return true; // 'true' means a new shape has been added to this prim } - private BulletShape CreatePhysicalMesh(string objName, ulong newMeshKey, PrimitiveBaseShape pbs, OMV.Vector3 size, float lod) + private BulletShape CreatePhysicalMesh(string objName, System.UInt64 newMeshKey, PrimitiveBaseShape pbs, OMV.Vector3 size, float lod) { IMesh meshData = null; IntPtr meshPtr; @@ -531,7 +531,7 @@ public class BSShapeCollection : IDisposable BulletShape newShape; float lod; - ulong newHullKey = ComputeShapeKey(shapeData, pbs, out lod); + System.UInt64 newHullKey = ComputeShapeKey(shapeData, pbs, out lod); // if the hull hasn't changed, don't rebuild it if (newHullKey == prim.BSShape.shapeKey && prim.BSShape.type == ShapeData.PhysicsShapeType.SHAPE_HULL) @@ -554,7 +554,7 @@ public class BSShapeCollection : IDisposable } List m_hulls; - private BulletShape CreatePhysicalHull(string objName, ulong newHullKey, PrimitiveBaseShape pbs, OMV.Vector3 size, float lod) + private BulletShape CreatePhysicalHull(string objName, System.UInt64 newHullKey, PrimitiveBaseShape pbs, OMV.Vector3 size, float lod) { IntPtr hullPtr; @@ -667,7 +667,7 @@ public class BSShapeCollection : IDisposable // Create a hash of all the shape parameters to be used as a key // for this particular shape. - private ulong ComputeShapeKey(ShapeData shapeData, PrimitiveBaseShape pbs, out float retLod) + private System.UInt64 ComputeShapeKey(ShapeData shapeData, PrimitiveBaseShape pbs, out float retLod) { // level of detail based on size and type of the object float lod = PhysicsScene.MeshLOD; @@ -680,10 +680,10 @@ public class BSShapeCollection : IDisposable lod = PhysicsScene.MeshMegaPrimLOD; retLod = lod; - return (ulong)pbs.GetMeshKey(shapeData.Size, lod); + return pbs.GetMeshKey(shapeData.Size, lod); } // For those who don't want the LOD - private ulong ComputeShapeKey(ShapeData shapeData, PrimitiveBaseShape pbs) + private System.UInt64 ComputeShapeKey(ShapeData shapeData, PrimitiveBaseShape pbs) { float lod; return ComputeShapeKey(shapeData, pbs, out lod); @@ -717,6 +717,7 @@ public class BSShapeCollection : IDisposable if (mustRebuild || forceRebuild) { + // Free any old body DereferenceBody(prim.BSBody, true, bodyCallback); BulletBody aBody; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs index 70aa429..2808603 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs @@ -201,10 +201,10 @@ public class BSTerrainManager // The 'doNow' boolean says whether to do all the unmanaged activities right now (like when // calling this routine from initialization or taint-time routines) or whether to delay // all the unmanaged activities to taint-time. - private void UpdateOrCreateTerrain(uint id, float[] heightMap, Vector3 minCoords, Vector3 maxCoords, bool atTaintTime) + private void UpdateOrCreateTerrain(uint id, float[] heightMap, Vector3 minCoords, Vector3 maxCoords, bool inTaintTime) { - DetailLog("{0},BSTerrainManager.UpdateOrCreateTerrain,call,minC={1},maxC={2},atTaintTime={3}", - BSScene.DetailLogZero, minCoords, maxCoords, atTaintTime); + DetailLog("{0},BSTerrainManager.UpdateOrCreateTerrain,call,minC={1},maxC={2},inTaintTime={3}", + BSScene.DetailLogZero, minCoords, maxCoords, inTaintTime); float minZ = float.MaxValue; float maxZ = float.MinValue; @@ -320,7 +320,9 @@ public class BSTerrainManager BulletSimAPI.SetRestitution2(mapInfo.terrainBody.ptr, PhysicsScene.Params.terrainRestitution); BulletSimAPI.SetCollisionFlags2(mapInfo.terrainBody.ptr, CollisionFlags.CF_STATIC_OBJECT); - BulletSimAPI.SetMassProps2(mapInfo.terrainBody.ptr, 0f, Vector3.Zero); + float terrainMass = 1000; + Vector3 localInertia = BulletSimAPI.CalculateLocalInertia2(mapInfo.terrainBody.ptr, terrainMass); + BulletSimAPI.SetMassProps2(mapInfo.terrainBody.ptr, terrainMass, localInertia); BulletSimAPI.UpdateInertiaTensor2(mapInfo.terrainBody.ptr); // Return the new terrain to the world of physical objects @@ -342,7 +344,7 @@ public class BSTerrainManager // There is the option to do the changes now (we're already in 'taint time'), or // to do the Bullet operations later. - if (atTaintTime) + if (inTaintTime) rebuildOperation(); else PhysicsScene.TaintedObject("BSScene.UpdateOrCreateTerrain:UpdateExisting", rebuildOperation); @@ -381,7 +383,7 @@ public class BSTerrainManager }; // If already in taint-time, just call Bullet. Otherwise queue the operations for the safe time. - if (atTaintTime) + if (inTaintTime) createOperation(); else PhysicsScene.TaintedObject("BSScene.UpdateOrCreateTerrain:NewTerrain", createOperation); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs index 7a60afb..e23fe5a 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs @@ -101,9 +101,8 @@ public struct BulletShape } public IntPtr ptr; public ShapeData.PhysicsShapeType type; - public ulong shapeKey; + public System.UInt64 shapeKey; public bool isNativeShape; - // Hulls have an underlying mesh. A pointer to it is hidden here. public override string ToString() { StringBuilder buff = new StringBuilder(); -- cgit v1.1 From 919569f6ecd5fe84d0f5b0981a48b4808a44f7ad Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Wed, 10 Oct 2012 09:43:46 -0700 Subject: BulletSim: Change defaults for constraint CFM and ERP to make large linksets more rigid. Remove mass calculation for terrain (it should stay a static object). --- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 4 ++-- OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs | 15 ++++++--------- 2 files changed, 8 insertions(+), 11 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index 50091cc..617bdb4 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -1099,12 +1099,12 @@ public class BSScene : PhysicsScene, IPhysicsParameters (s) => { return s.m_params[0].linkConstraintTransMotorMaxForce; }, (s,p,l,v) => { s.m_params[0].linkConstraintTransMotorMaxForce = v; } ), new ParameterDefn("LinkConstraintCFM", "Amount constraint can be violated. 0=no violation, 1=infinite. Default=0.1", - 0.1f, + 0.001f, (s,cf,p,v) => { s.m_params[0].linkConstraintCFM = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].linkConstraintCFM; }, (s,p,l,v) => { s.m_params[0].linkConstraintCFM = v; } ), new ParameterDefn("LinkConstraintERP", "Amount constraint is corrected each tick. 0=none, 1=all. Default = 0.2", - 0.2f, + 0.8f, (s,cf,p,v) => { s.m_params[0].linkConstraintERP = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].linkConstraintERP; }, (s,p,l,v) => { s.m_params[0].linkConstraintERP = v; } ), diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs index 2808603..caf411e 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs @@ -114,6 +114,8 @@ public class BSTerrainManager BulletSimAPI.CreateBodyWithDefaultMotionState2(groundPlaneShape.ptr, BSScene.GROUNDPLANE_ID, Vector3.Zero, Quaternion.Identity)); BulletSimAPI.AddObjectToWorld2(PhysicsScene.World.ptr, m_groundPlane.ptr); + // Ground plane does not move + BulletSimAPI.ForceActivationState2(m_groundPlane.ptr, ActivationState.DISABLE_SIMULATION); // Everything collides with the ground plane. BulletSimAPI.SetCollisionFilterMask2(m_groundPlane.ptr, (uint)CollisionFilterGroups.GroundPlaneFilter, (uint)CollisionFilterGroups.GroundPlaneMask); @@ -296,16 +298,16 @@ public class BSTerrainManager mapInfo.Ptr = BulletSimAPI.CreateHeightMapInfo2(PhysicsScene.World.ptr, mapInfo.ID, mapInfo.minCoords, mapInfo.maxCoords, mapInfo.heightMap, TERRAIN_COLLISION_MARGIN); + // Create the terrain shape from the mapInfo + mapInfo.terrainShape = new BulletShape(BulletSimAPI.CreateTerrainShape2(mapInfo.Ptr), + ShapeData.PhysicsShapeType.SHAPE_TERRAIN); + // The terrain object initial position is at the center of the object Vector3 centerPos; centerPos.X = minCoords.X + (mapInfo.sizeX / 2f); centerPos.Y = minCoords.Y + (mapInfo.sizeY / 2f); centerPos.Z = minZ + ((maxZ - minZ) / 2f); - // Create the terrain shape from the mapInfo - mapInfo.terrainShape = new BulletShape(BulletSimAPI.CreateTerrainShape2(mapInfo.Ptr), - ShapeData.PhysicsShapeType.SHAPE_TERRAIN); - mapInfo.terrainBody = new BulletBody(mapInfo.ID, BulletSimAPI.CreateBodyWithDefaultMotionState2(mapInfo.terrainShape.ptr, id, centerPos, Quaternion.Identity)); @@ -320,11 +322,6 @@ public class BSTerrainManager BulletSimAPI.SetRestitution2(mapInfo.terrainBody.ptr, PhysicsScene.Params.terrainRestitution); BulletSimAPI.SetCollisionFlags2(mapInfo.terrainBody.ptr, CollisionFlags.CF_STATIC_OBJECT); - float terrainMass = 1000; - Vector3 localInertia = BulletSimAPI.CalculateLocalInertia2(mapInfo.terrainBody.ptr, terrainMass); - BulletSimAPI.SetMassProps2(mapInfo.terrainBody.ptr, terrainMass, localInertia); - BulletSimAPI.UpdateInertiaTensor2(mapInfo.terrainBody.ptr); - // Return the new terrain to the world of physical objects BulletSimAPI.AddObjectToWorld2(PhysicsScene.World.ptr, mapInfo.terrainBody.ptr); -- cgit v1.1 From 3a458e2a36253f6514720213deaa19372b06cc52 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Wed, 10 Oct 2012 13:56:16 -0700 Subject: BulletSim: Use full linkset mass when computing vehicle gravity force. Add taint-time specification to new AddForce(). --- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 6 +++--- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 9 +++------ OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 12 ++++++++++-- 3 files changed, 16 insertions(+), 11 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index 76230a1..56342b8 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -462,7 +462,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin return; // Set the prim's inertia to zero. The vehicle code handles that and this - // removes the torque action introduced by Bullet. + // removes the motion and torque actions introduced by Bullet. Vector3 inertia = Vector3.Zero; BulletSimAPI.SetMassProps2(Prim.BSBody.ptr, Prim.MassRaw, inertia); BulletSimAPI.UpdateInertiaTensor2(Prim.BSBody.ptr); @@ -540,7 +540,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin // add Gravity and Buoyancy // There is some gravity, make a gravity force vector that is applied after object velocity. // m_VehicleBuoyancy: -1=2g; 0=1g; 1=0g; - Vector3 grav = Prim.PhysicsScene.DefaultGravity * (Prim.MassRaw * (1f - m_VehicleBuoyancy)); + Vector3 grav = Prim.PhysicsScene.DefaultGravity * (Prim.Linkset.LinksetMass * (1f - m_VehicleBuoyancy)); /* * RA: Not sure why one would do this @@ -681,7 +681,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin Prim.ForceVelocity = m_newVelocity; // apply gravity force // Why is this set here? The physics engine already does gravity. - Prim.AddForce(grav, false); + Prim.AddForce(grav, false, true); // Apply friction Vector3 keepFraction = Vector3.One - (Vector3.One / (m_linearFrictionTimescale / pTimestep)); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index b84ccdc..43b1262 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -165,13 +165,11 @@ public class BSLinkset // May be called at runtime or taint-time (just pass the appropriate flag). public void Refresh(BSPhysObject requestor, bool inTaintTime) { - // If there are no children, there can't be any constraints to recompute - if (!HasAnyChildren) + // If there are no children, not physical or not root, I am not the one that recomputes the constraints + // (For the moment, static linksets do create constraints so remove the test for physical.) + if (!HasAnyChildren || /*!requestor.IsPhysical ||*/ !IsRoot(requestor)) return; - // Only the root does the recomputation - if (IsRoot(requestor)) - { BSScene.TaintCallback refreshOperation = delegate() { RecomputeLinksetConstraintVariables(); @@ -182,7 +180,6 @@ public class BSLinkset refreshOperation(); else PhysicsScene.TaintedObject("BSLinkSet.Refresh", refreshOperation); - } } // The object is going dynamic (physical). Do any setup necessary diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index b26f049..692713d 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -855,6 +855,9 @@ public sealed class BSPrim : BSPhysObject private List m_accumulatedForces = new List(); public override void AddForce(OMV.Vector3 force, bool pushforce) { + AddForce(force, pushforce, false); + } + public void AddForce(OMV.Vector3 force, bool pushforce, bool inTaintTime) { // for an object, doesn't matter if force is a pushforce or not if (force.IsFinite()) { @@ -867,11 +870,12 @@ public sealed class BSPrim : BSPhysObject m_log.WarnFormat("{0}: Got a NaN force applied to a prim. LocalID={1}", LogHeader, LocalID); return; } - PhysicsScene.TaintedObject("BSPrim.AddForce", delegate() + BSScene.TaintCallback addForceOperation = delegate() { OMV.Vector3 fSum = OMV.Vector3.Zero; lock (m_accumulatedForces) { + // Sum the accumulated additional forces for one big force to apply once. foreach (OMV.Vector3 v in m_accumulatedForces) { fSum += v; @@ -881,7 +885,11 @@ public sealed class BSPrim : BSPhysObject // DetailLog("{0},BSPrim.AddObjectForce,taint,force={1}", LocalID, fSum); // For unknown reasons, "ApplyCentralForce" adds this force to the total force on the object. BulletSimAPI.ApplyCentralForce2(BSBody.ptr, fSum); - }); + }; + if (inTaintTime) + addForceOperation(); + else + PhysicsScene.TaintedObject("BSPrim.AddForce", addForceOperation); } public override void AddAngularForce(OMV.Vector3 force, bool pushforce) { -- cgit v1.1 From a86fedd25ffb02c328b0591d16eda1dab797d8f9 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Wed, 10 Oct 2012 16:51:50 -0700 Subject: BulletSim: normalize physics FPS to 45. --- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index 617bdb4..25f8f5f 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -581,8 +581,9 @@ public 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. - // Since Bullet normally does 5 or 6 substeps, this will normally sum to about 60 FPS. - return numSubSteps * m_fixedTimeStep * 1000; + // We multiply by 45 to give a recognizable running rate (45 or less). + return numSubSteps * m_fixedTimeStep * 1000 * 45; + // return timeStep * 1000 * 45; } // Something has collided @@ -1300,7 +1301,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters { PhysicsLogging.Write(msg, args); // Add the Flush() if debugging crashes to get all the messages written out. - PhysicsLogging.Flush(); // DEBUG DEBUG DEBUG + // PhysicsLogging.Flush(); } // used to fill in the LocalID when there isn't one public const string DetailLogZero = "0000000000"; -- cgit v1.1 From 5b82f18d6422d89da53d382eb1ae89e47b4465b7 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Wed, 10 Oct 2012 16:53:58 -0700 Subject: BulletSim: normalize physics FPS to 45 (for real this time). --- 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 25f8f5f..2c3c481 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -582,8 +582,8 @@ public 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. // We multiply by 45 to give a recognizable running rate (45 or less). - return numSubSteps * m_fixedTimeStep * 1000 * 45; - // return timeStep * 1000 * 45; + return numSubSteps * m_fixedTimeStep * 1000 * 45; + // return timeStep * 1000 * 45; } // Something has collided -- cgit v1.1 From b24190ec98f31f1e4672d1174163426b9b44e25d Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Thu, 11 Oct 2012 12:54:27 -0700 Subject: BulletSim: remove some unused API2 calls because they were removed from Bullet 2.81 --- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 4 ++-- OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs | 12 ------------ 2 files changed, 2 insertions(+), 14 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 692713d..6a4365c 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -673,8 +673,8 @@ public sealed class BSPrim : BSPhysObject // Force activation of the object so Bullet will act on it. // Must do the ForceActivationState2() to overcome the DISABLE_SIMULATION from static objects. - BulletSimAPI.ForceActivationState2(BSBody.ptr, ActivationState.ISLAND_SLEEPING); - BulletSimAPI.Activate2(BSBody.ptr, true); + BulletSimAPI.ForceActivationState2(BSBody.ptr, ActivationState.ACTIVE_TAG); + // BulletSimAPI.Activate2(BSBody.ptr, true); BSBody.collisionFilter = CollisionFilterGroups.ObjectFilter; BSBody.collisionMask = CollisionFilterGroups.ObjectMask; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs index e23fe5a..276111c 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs @@ -1039,18 +1039,6 @@ public static extern IntPtr GetConstraintRef2(IntPtr obj, int index); public static extern int GetNumConstraintRefs2(IntPtr obj); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern Vector3 GetDeltaLinearVelocity2(IntPtr obj); - -[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern Vector3 GetDeltaAngularVelocity2(IntPtr obj); - -[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern Vector3 GetPushVelocity2(IntPtr obj); - -[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern Vector3 GetTurnVelocity2(IntPtr obj); - -[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern void SetCollisionFilterMask2(IntPtr body, uint filter, uint mask); // ===================================================================================== -- cgit v1.1 From 87a87ebb9a68f9bb4cd44f3b00954ed7fca7da3a Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Thu, 11 Oct 2012 17:06:58 -0700 Subject: BulletSim: fix problem with some shapes (like cylinders) being implemented as cubes. --- OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index d5e2172..a0d111a 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -387,7 +387,7 @@ public class BSShapeCollection : IDisposable prim.LocalID, forceRebuild, prim.BSShape); } } - else + if (pbs.ProfileShape == ProfileShape.Square && pbs.PathCurve == (byte)Extrusion.Straight) { haveShape = true; if (forceRebuild -- cgit v1.1 From 8c40215834bc1286a6bd2902e1c8b0f2ef793fd7 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Fri, 12 Oct 2012 07:37:52 -0700 Subject: BulletSim: only use native sphere shape if it is a sphere. --- OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index a0d111a..d189f1d 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -373,7 +373,8 @@ public class BSShapeCollection : IDisposable && pbs.PathScaleX == 100 && pbs.PathScaleY == 100 && pbs.PathShearX == 0 && pbs.PathShearY == 0) ) ) { - if (pbs.ProfileShape == ProfileShape.HalfCircle && pbs.PathCurve == (byte)Extrusion.Curve1) + if ((pbs.ProfileShape == ProfileShape.HalfCircle && pbs.PathCurve == (byte)Extrusion.Curve1) + && pbs.Scale.X == pbs.Scale.Y && pbs.Scale.Y == pbs.Scale.Z) { haveShape = true; if (forceRebuild -- cgit v1.1 From 1e7fb2dc364bd8fcbe92fc3cca45c3eea85e5558 Mon Sep 17 00:00:00 2001 From: UbitUmarov Date: Sun, 7 Oct 2012 05:53:52 +0100 Subject: i update core ode plugin and make it load is meshs (i hope) Signed-off-by: Melanie --- OpenSim/Region/Physics/OdePlugin/ODEPrim.cs | 51 +++++++++++++++++++++++++++- OpenSim/Region/Physics/OdePlugin/OdeScene.cs | 2 +- 2 files changed, 51 insertions(+), 2 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs b/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs index e7b3b2b..c86084c 100644 --- a/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs +++ b/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs @@ -100,6 +100,9 @@ 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; private float m_PIDTau; private float PID_D = 35f; @@ -282,6 +285,7 @@ namespace OpenSim.Region.Physics.OdePlugin } m_taintadd = true; + m_assetFailed = false; _parent_scene.AddPhysicsActorTaint(this); } @@ -1498,6 +1502,8 @@ Console.WriteLine("CreateGeom:"); mesh = _parent_scene.mesher.CreateMesh(Name, _pbs, _size, _parent_scene.meshSculptLOD, IsPhysical); // createmesh returns null when it's a shape that isn't a cube. // m_log.Debug(m_localID); + if (mesh == null) + CheckMeshAsset(); } #if SPAM @@ -1997,7 +2003,12 @@ Console.WriteLine(" JointCreateFixed"); // Don't need to re-enable body.. it's done in SetMesh if (_parent_scene.needsMeshing(_pbs)) + { mesh = _parent_scene.mesher.CreateMesh(Name, _pbs, _size, meshlod, IsPhysical); + if (mesh == null) + CheckMeshAsset(); + } + } CreateGeom(m_targetSpace, mesh); @@ -2057,6 +2068,8 @@ Console.WriteLine(" JointCreateFixed"); /// private void changeshape() { + m_taintshape = false; + // Cleanup of old prim geometry and Bodies if (IsPhysical && Body != IntPtr.Zero) { @@ -2084,6 +2097,7 @@ Console.WriteLine(" JointCreateFixed"); IMesh mesh = null; + if (_parent_scene.needsMeshing(_pbs)) { // Don't need to re-enable body.. it's done in CreateMesh @@ -2094,6 +2108,8 @@ Console.WriteLine(" JointCreateFixed"); // createmesh returns null when it doesn't mesh. mesh = _parent_scene.mesher.CreateMesh(Name, _pbs, _size, meshlod, IsPhysical); + if (mesh == null) + CheckMeshAsset(); } CreateGeom(m_targetSpace, mesh); @@ -2130,7 +2146,7 @@ Console.WriteLine(" JointCreateFixed"); } resetCollisionAccounting(); - m_taintshape = false; +// m_taintshape = false; } /// @@ -2396,6 +2412,7 @@ Console.WriteLine(" JointCreateFixed"); set { _pbs = value; + m_assetFailed = false; m_taintshape = true; } } @@ -3234,5 +3251,37 @@ Console.WriteLine(" JointCreateFixed"); { m_material = pMaterial; } + + + private void CheckMeshAsset() + { + if (_pbs.SculptEntry && !m_assetFailed && _pbs.SculptTexture != UUID.Zero) + { + m_assetFailed = true; + Util.FireAndForget(delegate + { + RequestAssetDelegate assetProvider = _parent_scene.RequestAssetMethod; + if (assetProvider != null) + assetProvider(_pbs.SculptTexture, MeshAssetReveived); + }); + } + } + + void MeshAssetReveived(AssetBase asset) + { + if (asset.Data != null && asset.Data.Length > 0) + { + if (!_pbs.SculptEntry) + return; + if (_pbs.SculptTexture.ToString() != asset.ID) + return; + + _pbs.SculptData = new byte[asset.Data.Length]; + asset.Data.CopyTo(_pbs.SculptData, 0); + m_assetFailed = false; + m_taintshape = true; + _parent_scene.AddPhysicsActorTaint(this); + } + } } } \ No newline at end of file diff --git a/OpenSim/Region/Physics/OdePlugin/OdeScene.cs b/OpenSim/Region/Physics/OdePlugin/OdeScene.cs index cbe21e2..d53bd90 100644 --- a/OpenSim/Region/Physics/OdePlugin/OdeScene.cs +++ b/OpenSim/Region/Physics/OdePlugin/OdeScene.cs @@ -4320,4 +4320,4 @@ namespace OpenSim.Region.Physics.OdePlugin m_stats[ODEPrimUpdateFrameMsStatName] = 0; } } -} \ No newline at end of file +} -- cgit v1.1 From de44e93aa27f55d939fd27493d195ee498270381 Mon Sep 17 00:00:00 2001 From: UbitUmarov Date: Wed, 3 Oct 2012 23:18:35 +0100 Subject: missing changed file Signed-off-by: Melanie --- OpenSim/Region/Physics/Manager/PhysicsScene.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/Manager/PhysicsScene.cs b/OpenSim/Region/Physics/Manager/PhysicsScene.cs index 6a0558a..488900e 100644 --- a/OpenSim/Region/Physics/Manager/PhysicsScene.cs +++ b/OpenSim/Region/Physics/Manager/PhysicsScene.cs @@ -76,7 +76,7 @@ namespace OpenSim.Region.Physics.Manager get { return new NullPhysicsScene(); } } - public RequestAssetDelegate RequestAssetMethod { private get; set; } + public RequestAssetDelegate RequestAssetMethod { get; set; } public virtual void TriggerPhysicsBasedRestart() { -- cgit v1.1 From b058ba5859b1012a23e58c9b9e0d91f77ac19ba3 Mon Sep 17 00:00:00 2001 From: UbitUmarov Date: Fri, 19 Oct 2012 00:36:32 +0100 Subject: [UNTESTED] core Ode: stop trying to load a broken asset. Make broken assets behave like phantom by Nebadon request --- OpenSim/Region/Physics/OdePlugin/ODEPrim.cs | 118 +++++++++++++++++++++++----- 1 file changed, 97 insertions(+), 21 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs b/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs index c86084c..a6c657f 100644 --- a/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs +++ b/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs @@ -341,8 +341,17 @@ namespace OpenSim.Region.Physics.OdePlugin prim_geom = geom; //Console.WriteLine("SetGeom to " + prim_geom + " for " + Name); - d.GeomSetCategoryBits(prim_geom, (int)m_collisionCategories); - d.GeomSetCollideBits(prim_geom, (int)m_collisionFlags); + if (m_assetFailed) + { + d.GeomSetCategoryBits(prim_geom, 0); + d.GeomSetCollideBits(prim_geom, 0); + } + else + { + + d.GeomSetCategoryBits(prim_geom, (int)m_collisionCategories); + d.GeomSetCollideBits(prim_geom, (int)m_collisionFlags); + } _parent_scene.geom_name_map[prim_geom] = Name; _parent_scene.actor_name_map[prim_geom] = this; @@ -405,8 +414,17 @@ namespace OpenSim.Region.Physics.OdePlugin myrot.W = _orientation.W; d.BodySetQuaternion(Body, ref myrot); d.GeomSetBody(prim_geom, Body); - m_collisionCategories |= CollisionCategories.Body; - m_collisionFlags |= (CollisionCategories.Land | CollisionCategories.Wind); + + if (m_assetFailed) + { + d.GeomSetCategoryBits(prim_geom, 0); + d.GeomSetCollideBits(prim_geom, 0); + } + else + { + m_collisionCategories |= CollisionCategories.Body; + m_collisionFlags |= (CollisionCategories.Land | CollisionCategories.Wind); + } d.GeomSetCategoryBits(prim_geom, (int)m_collisionCategories); d.GeomSetCollideBits(prim_geom, (int)m_collisionFlags); @@ -778,8 +796,16 @@ namespace OpenSim.Region.Physics.OdePlugin m_collisionCategories &= ~CollisionCategories.Body; m_collisionFlags &= ~(CollisionCategories.Wind | CollisionCategories.Land); - d.GeomSetCategoryBits(prim_geom, (int)m_collisionCategories); - d.GeomSetCollideBits(prim_geom, (int)m_collisionFlags); + if (m_assetFailed) + { + d.GeomSetCategoryBits(prim_geom, 0); + d.GeomSetCollideBits(prim_geom, 0); + } + else + { + d.GeomSetCategoryBits(prim_geom, (int)m_collisionCategories); + d.GeomSetCollideBits(prim_geom, (int)m_collisionFlags); + } d.BodyDestroy(Body); lock (childrenPrim) @@ -803,8 +829,17 @@ namespace OpenSim.Region.Physics.OdePlugin m_collisionCategories &= ~CollisionCategories.Body; m_collisionFlags &= ~(CollisionCategories.Wind | CollisionCategories.Land); - d.GeomSetCategoryBits(prim_geom, (int)m_collisionCategories); - d.GeomSetCollideBits(prim_geom, (int)m_collisionFlags); + if (m_assetFailed) + { + d.GeomSetCategoryBits(prim_geom, 0); + d.GeomSetCollideBits(prim_geom, 0); + } + else + { + + d.GeomSetCategoryBits(prim_geom, (int)m_collisionCategories); + d.GeomSetCollideBits(prim_geom, (int)m_collisionFlags); + } Body = IntPtr.Zero; } @@ -1094,8 +1129,16 @@ Console.WriteLine("ZProcessTaints for " + Name); prm.m_collisionFlags |= (CollisionCategories.Land | CollisionCategories.Wind); //Console.WriteLine(" GeomSetCategoryBits 1: " + prm.prim_geom + " - " + (int)prm.m_collisionCategories + " for " + Name); - d.GeomSetCategoryBits(prm.prim_geom, (int)prm.m_collisionCategories); - d.GeomSetCollideBits(prm.prim_geom, (int)prm.m_collisionFlags); + if (prm.m_assetFailed) + { + d.GeomSetCategoryBits(prm.prim_geom, 0); + d.GeomSetCollideBits(prm.prim_geom, 0); + } + else + { + d.GeomSetCategoryBits(prm.prim_geom, (int)prm.m_collisionCategories); + d.GeomSetCollideBits(prm.prim_geom, (int)prm.m_collisionFlags); + } d.Quaternion quat = new d.Quaternion(); quat.W = prm._orientation.W; @@ -1140,10 +1183,18 @@ Console.WriteLine("ZProcessTaints for " + Name); m_collisionCategories |= CollisionCategories.Body; m_collisionFlags |= (CollisionCategories.Land | CollisionCategories.Wind); -//Console.WriteLine("GeomSetCategoryBits 2: " + prim_geom + " - " + (int)m_collisionCategories + " for " + Name); - d.GeomSetCategoryBits(prim_geom, (int)m_collisionCategories); -//Console.WriteLine(" Post GeomSetCategoryBits 2"); - d.GeomSetCollideBits(prim_geom, (int)m_collisionFlags); + if (m_assetFailed) + { + d.GeomSetCategoryBits(prim_geom, 0); + d.GeomSetCollideBits(prim_geom, 0); + } + else + { + //Console.WriteLine("GeomSetCategoryBits 2: " + prim_geom + " - " + (int)m_collisionCategories + " for " + Name); + d.GeomSetCategoryBits(prim_geom, (int)m_collisionCategories); + //Console.WriteLine(" Post GeomSetCategoryBits 2"); + d.GeomSetCollideBits(prim_geom, (int)m_collisionFlags); + } d.Quaternion quat2 = new d.Quaternion(); quat2.W = _orientation.W; @@ -1304,8 +1355,16 @@ Console.WriteLine("ZProcessTaints for " + Name); disableBodySoft(); } - d.GeomSetCategoryBits(prim_geom, (int)m_collisionCategories); - d.GeomSetCollideBits(prim_geom, (int)m_collisionFlags); + if (m_assetFailed) + { + d.GeomSetCategoryBits(prim_geom, 0); + d.GeomSetCollideBits(prim_geom, 0); + } + else + { + d.GeomSetCategoryBits(prim_geom, (int)m_collisionCategories); + d.GeomSetCollideBits(prim_geom, (int)m_collisionFlags); + } if (IsPhysical) { @@ -1326,8 +1385,16 @@ Console.WriteLine("ZProcessTaints for " + Name); if (m_collidesWater) m_collisionFlags |= CollisionCategories.Water; - d.GeomSetCategoryBits(prim_geom, (int)m_collisionCategories); - d.GeomSetCollideBits(prim_geom, (int)m_collisionFlags); + if (m_assetFailed) + { + d.GeomSetCategoryBits(prim_geom, 0); + d.GeomSetCollideBits(prim_geom, 0); + } + else + { + d.GeomSetCategoryBits(prim_geom, (int)m_collisionCategories); + d.GeomSetCollideBits(prim_geom, (int)m_collisionFlags); + } if (IsPhysical) { @@ -1504,6 +1571,8 @@ Console.WriteLine("CreateGeom:"); // m_log.Debug(m_localID); if (mesh == null) CheckMeshAsset(); + else + m_assetFailed = false; } #if SPAM @@ -2007,6 +2076,8 @@ Console.WriteLine(" JointCreateFixed"); mesh = _parent_scene.mesher.CreateMesh(Name, _pbs, _size, meshlod, IsPhysical); if (mesh == null) CheckMeshAsset(); + else + m_assetFailed = false; } } @@ -2060,9 +2131,12 @@ Console.WriteLine(" JointCreateFixed"); m_collisionFlags &= ~CollisionCategories.Water; } - d.GeomSetCollideBits(prim_geom, (int)m_collisionFlags); - } + if (m_assetFailed) + d.GeomSetCollideBits(prim_geom, 0); + else + d.GeomSetCollideBits(prim_geom, (int)m_collisionFlags); + } /// /// Change prim in response to a shape taint. /// @@ -2110,6 +2184,8 @@ Console.WriteLine(" JointCreateFixed"); mesh = _parent_scene.mesher.CreateMesh(Name, _pbs, _size, meshlod, IsPhysical); if (mesh == null) CheckMeshAsset(); + else + m_assetFailed = false; } CreateGeom(m_targetSpace, mesh); @@ -3278,7 +3354,7 @@ Console.WriteLine(" JointCreateFixed"); _pbs.SculptData = new byte[asset.Data.Length]; asset.Data.CopyTo(_pbs.SculptData, 0); - m_assetFailed = false; +// m_assetFailed = false; m_taintshape = true; _parent_scene.AddPhysicsActorTaint(this); } -- cgit v1.1 From 28483150e2dcc123b632c89d0a08595b567af669 Mon Sep 17 00:00:00 2001 From: UbitUmarov Date: Fri, 19 Oct 2012 01:25:30 +0100 Subject: [UNTESTED] core Ode: let broken mesh physical prims collide with land as the defaul basic box so they don't go off world. --- OpenSim/Region/Physics/OdePlugin/ODEPrim.cs | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs b/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs index a6c657f..5a1fdf9 100644 --- a/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs +++ b/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs @@ -344,7 +344,7 @@ namespace OpenSim.Region.Physics.OdePlugin if (m_assetFailed) { d.GeomSetCategoryBits(prim_geom, 0); - d.GeomSetCollideBits(prim_geom, 0); + d.GeomSetCollideBits(prim_geom, BadAssetColideBits()); } else { @@ -418,7 +418,7 @@ namespace OpenSim.Region.Physics.OdePlugin if (m_assetFailed) { d.GeomSetCategoryBits(prim_geom, 0); - d.GeomSetCollideBits(prim_geom, 0); + d.GeomSetCollideBits(prim_geom, BadAssetColideBits()); } else { @@ -851,6 +851,11 @@ namespace OpenSim.Region.Physics.OdePlugin private static Dictionary m_MeshToTriMeshMap = new Dictionary(); + public int BadAssetColideBits() + { + return (m_isphysical ? (int)CollisionCategories.Land : 0); + } + private void setMesh(OdeScene parent_scene, IMesh mesh) { // m_log.DebugFormat("[ODE PRIM]: Setting mesh on {0} to {1}", Name, mesh); @@ -1132,7 +1137,7 @@ Console.WriteLine("ZProcessTaints for " + Name); if (prm.m_assetFailed) { d.GeomSetCategoryBits(prm.prim_geom, 0); - d.GeomSetCollideBits(prm.prim_geom, 0); + d.GeomSetCollideBits(prm.prim_geom, prm.BadAssetColideBits()); } else { @@ -1186,7 +1191,7 @@ Console.WriteLine("ZProcessTaints for " + Name); if (m_assetFailed) { d.GeomSetCategoryBits(prim_geom, 0); - d.GeomSetCollideBits(prim_geom, 0); + d.GeomSetCollideBits(prim_geom, BadAssetColideBits()); } else { @@ -1388,7 +1393,7 @@ Console.WriteLine("ZProcessTaints for " + Name); if (m_assetFailed) { d.GeomSetCategoryBits(prim_geom, 0); - d.GeomSetCollideBits(prim_geom, 0); + d.GeomSetCollideBits(prim_geom, BadAssetColideBits()); } else { @@ -2132,7 +2137,7 @@ Console.WriteLine(" JointCreateFixed"); } if (m_assetFailed) - d.GeomSetCollideBits(prim_geom, 0); + d.GeomSetCollideBits(prim_geom, BadAssetColideBits()); else d.GeomSetCollideBits(prim_geom, (int)m_collisionFlags); -- cgit v1.1 From fd7a097849b8a405bdd62cfe6d4ee2bbf0a3961c Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Fri, 12 Oct 2012 16:03:03 -0700 Subject: BulletSim: Update BSCharacter to use API2 interface. Add capsule shape to BSShapeCollection(). Remember last updated values so inter frame diffs can be computed. Parameterize avatarStandingFriction and reduce to 10 from 999. The latter high value made avatars very hard to push. Set CCD parameters for prims and characters of specified. --- .../Region/Physics/BulletSPlugin/BSCharacter.cs | 182 +++++++++++++++------ .../Region/Physics/BulletSPlugin/BSPhysObject.cs | 12 ++ OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 66 +++++--- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 21 ++- .../Physics/BulletSPlugin/BSShapeCollection.cs | 51 ++++-- .../Region/Physics/BulletSPlugin/BulletSimAPI.cs | 11 +- 6 files changed, 250 insertions(+), 93 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index 2e6b2da..7c2f856 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -41,8 +41,6 @@ public class BSCharacter : BSPhysObject // private bool _stopped; private OMV.Vector3 _size; - private OMV.Vector3 _scale; - private PrimitiveBaseShape _pbs; private bool _grabbed; private bool _selected; private OMV.Vector3 _position; @@ -67,6 +65,10 @@ public class BSCharacter : BSPhysObject private bool _kinematic; private float _buoyancy; + // The friction and velocity of the avatar is modified depending on whether walking or not. + private OMV.Vector3 _appliedVelocity; // the last velocity applied to the avatar + private float _currentFriction; // the friction currently being used (changed by setVelocity). + private OMV.Vector3 _PIDTarget; private bool _usePID; private float _PIDTau; @@ -84,13 +86,15 @@ public class BSCharacter : BSPhysObject _flying = isFlying; _orientation = OMV.Quaternion.Identity; _velocity = OMV.Vector3.Zero; + _appliedVelocity = OMV.Vector3.Zero; _buoyancy = ComputeBuoyancyFromFlying(isFlying); + _currentFriction = PhysicsScene.Params.avatarStandingFriction; // The dimensions of the avatar capsule are kept in the scale. // Physics creates a unit capsule which is scaled by the physics engine. ComputeAvatarScale(_size); _avatarDensity = PhysicsScene.Params.avatarDensity; - // set _avatarVolume and _mass based on capsule size, _density and _scale + // set _avatarVolume and _mass based on capsule size, _density and Scale ComputeAvatarVolumeAndMass(); ShapeData shapeData = new ShapeData(); @@ -99,24 +103,24 @@ public class BSCharacter : BSPhysObject shapeData.Position = _position; shapeData.Rotation = _orientation; shapeData.Velocity = _velocity; - shapeData.Scale = _scale; + shapeData.Scale = Scale; shapeData.Mass = _mass; shapeData.Buoyancy = _buoyancy; shapeData.Static = ShapeData.numericFalse; - shapeData.Friction = PhysicsScene.Params.avatarFriction; + shapeData.Friction = PhysicsScene.Params.avatarStandingFriction; shapeData.Restitution = PhysicsScene.Params.avatarRestitution; // do actual create at taint time PhysicsScene.TaintedObject("BSCharacter.create", delegate() { DetailLog("{0},BSCharacter.create,taint", LocalID); - BulletSimAPI.CreateObject(PhysicsScene.WorldID, shapeData); + PhysicsScene.Shapes.GetBodyAndShape(true, PhysicsScene.World, this, shapeData, null, null, null); + + SetPhysicalProperties(); // Set the buoyancy for flying. This will be refactored when all the settings happen in C#. // If not set at creation, the avatar will stop flying when created after crossing a region boundry. - BulletSimAPI.SetObjectBuoyancy(PhysicsScene.WorldID, LocalID, _buoyancy); - - BSBody = new BulletBody(LocalID, BulletSimAPI.GetBodyHandle2(PhysicsScene.World.ptr, LocalID)); + ForceBuoyancy = _buoyancy; // This works here because CreateObject has already put the character into the physical world. BulletSimAPI.SetCollisionFilterMask2(BSBody.ptr, @@ -131,10 +135,40 @@ public class BSCharacter : BSPhysObject DetailLog("{0},BSCharacter.Destroy", LocalID); PhysicsScene.TaintedObject("BSCharacter.destroy", delegate() { - BulletSimAPI.DestroyObject(PhysicsScene.WorldID, LocalID); + PhysicsScene.Shapes.DereferenceBody(BSBody, true, null); + PhysicsScene.Shapes.DereferenceShape(BSShape, true, null); }); } + private void SetPhysicalProperties() + { + BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.ptr, BSBody.ptr); + + ZeroMotion(); + + OMV.Vector3 localInertia = BulletSimAPI.CalculateLocalInertia2(BSBody.ptr, MassRaw); + BulletSimAPI.SetMassProps2(BSBody.ptr, MassRaw, localInertia); + + // Set the velocity and compute the proper friction + ForceVelocity = _velocity; + + BulletSimAPI.SetFriction2(BSBody.ptr, _currentFriction); + BulletSimAPI.SetRestitution2(BSBody.ptr, PhysicsScene.Params.avatarRestitution); + + BulletSimAPI.SetLocalScaling2(BSShape.ptr, Scale); + BulletSimAPI.SetContactProcessingThreshold2(BSBody.ptr, PhysicsScene.Params.contactProcessingThreshold); + + if (PhysicsScene.Params.ccdMotionThreshold > 0f) + { + BulletSimAPI.SetCcdMotionThreshold2(BSBody.ptr, PhysicsScene.Params.ccdMotionThreshold); + BulletSimAPI.SetCcdSweepSphereRadius2(BSBody.ptr, PhysicsScene.Params.ccdSweptSphereRadius); + } + + BulletSimAPI.SetActivationState2(BSBody.ptr, (int)ActivationState.DISABLE_DEACTIVATION); + + BulletSimAPI.AddObjectToWorld2(PhysicsScene.World.ptr, BSBody.ptr); + } + public override void RequestPhysicsterseUpdate() { base.RequestPhysicsterseUpdate(); @@ -147,7 +181,7 @@ public class BSCharacter : BSPhysObject get { // Avatar capsule size is kept in the scale parameter. - return new OMV.Vector3(_scale.X * 2, _scale.Y * 2, _scale.Z); + return new OMV.Vector3(Scale.X * 2, Scale.Y * 2, Scale.Z); } set { @@ -162,22 +196,25 @@ public class BSCharacter : BSPhysObject PhysicsScene.TaintedObject("BSCharacter.setSize", delegate() { - BulletSimAPI.SetObjectScaleMass(PhysicsScene.WorldID, LocalID, _scale, _mass, true); + BulletSimAPI.SetLocalScaling2(BSBody.ptr, Scale); + OMV.Vector3 localInertia = BulletSimAPI.CalculateLocalInertia2(BSBody.ptr, MassRaw); + BulletSimAPI.SetMassProps2(BSBody.ptr, MassRaw, localInertia); }); } } - public override PrimitiveBaseShape Shape { - set { _pbs = value; - } + public override OMV.Vector3 Scale { get; set; } + private PrimitiveBaseShape _pbs; + public override PrimitiveBaseShape Shape + { + set { _pbs = value;} } + public override bool Grabbed { - set { _grabbed = value; - } + set { _grabbed = value; } } public override bool Selected { - set { _selected = value; - } + set { _selected = value; } } public override void CrossingFailure() { return; } public override void link(PhysicsActor obj) { return; } @@ -204,7 +241,7 @@ public class BSCharacter : BSPhysObject public override OMV.Vector3 Position { get { - // _position = BulletSimAPI.GetObjectPosition(Scene.WorldID, _localID); + // _position = BulletSimAPI.GetObjectPosition2(Scene.World.ptr, LocalID); return _position; } set { @@ -214,7 +251,7 @@ public class BSCharacter : BSPhysObject PhysicsScene.TaintedObject("BSCharacter.setPosition", delegate() { DetailLog("{0},BSCharacter.SetPosition,taint,pos={1},orient={2}", LocalID, _position, _orientation); - BulletSimAPI.SetObjectTranslation(PhysicsScene.WorldID, LocalID, _position, _orientation); + BulletSimAPI.SetTranslation2(BSBody.ptr, _position, _orientation); }); } } @@ -273,7 +310,7 @@ public class BSCharacter : BSPhysObject BSScene.TaintCallback sanityOperation = delegate() { DetailLog("{0},BSCharacter.PositionSanityCheck,taint,pos={1},orient={2}", LocalID, _position, _orientation); - BulletSimAPI.SetObjectTranslation(PhysicsScene.WorldID, LocalID, _position, _orientation); + BulletSimAPI.SetTranslation2(BSBody.ptr, _position, _orientation); }; if (inTaintTime) sanityOperation(); @@ -284,11 +321,7 @@ public class BSCharacter : BSPhysObject return ret; } - public override float Mass { - get { - return _mass; - } - } + public override float Mass { get { return _mass; } } // used when we only want this prim's mass and not the linkset thing public override float MassRaw { get {return _mass; } } @@ -301,15 +334,13 @@ public class BSCharacter : BSPhysObject PhysicsScene.TaintedObject("BSCharacter.SetForce", delegate() { DetailLog("{0},BSCharacter.setForce,taint,force={1}", LocalID, _force); - BulletSimAPI.SetObjectForce(PhysicsScene.WorldID, LocalID, _force); + BulletSimAPI.SetObjectForce2(BSBody.ptr, _force); }); } } - public override int VehicleType { - get { return 0; } - set { return; } - } + // Avatars don't do vehicles + public override int VehicleType { get { return 0; } set { return; } } public override void VehicleFloatParam(int param, float value) { } public override void VehicleVectorParam(int param, OMV.Vector3 value) {} public override void VehicleRotationParam(int param, OMV.Quaternion rotation) { } @@ -328,15 +359,35 @@ public class BSCharacter : BSPhysObject PhysicsScene.TaintedObject("BSCharacter.setVelocity", delegate() { DetailLog("{0},BSCharacter.setVelocity,taint,vel={1}", LocalID, _velocity); - BulletSimAPI.SetObjectVelocity(PhysicsScene.WorldID, LocalID, _velocity); + ForceVelocity = _velocity; }); } } public override OMV.Vector3 ForceVelocity { get { return _velocity; } set { + // Depending on whether the avatar is moving or not, change the friction + // to keep the avatar from slipping around + if (_velocity.Length() == 0) + { + if (_currentFriction != PhysicsScene.Params.avatarStandingFriction) + { + _currentFriction = PhysicsScene.Params.avatarStandingFriction; + BulletSimAPI.SetFriction2(BSBody.ptr, _currentFriction); + } + } + else + { + if (_currentFriction == 999f) + { + _currentFriction = PhysicsScene.Params.avatarFriction; + BulletSimAPI.SetFriction2(BSBody.ptr, _currentFriction); + } + } _velocity = value; - BulletSimAPI.SetObjectVelocity(PhysicsScene.WorldID, LocalID, _velocity); + _appliedVelocity = value; + BulletSimAPI.SetLinearVelocity2(BSBody.ptr, _velocity); + BulletSimAPI.Activate2(BSBody.ptr, true); } } public override OMV.Vector3 Torque { @@ -360,8 +411,8 @@ public class BSCharacter : BSPhysObject // m_log.DebugFormat("{0}: set orientation to {1}", LogHeader, _orientation); PhysicsScene.TaintedObject("BSCharacter.setOrientation", delegate() { - // _position = BulletSimAPI.GetObjectPosition(Scene.WorldID, _localID); - BulletSimAPI.SetObjectTranslation(PhysicsScene.WorldID, LocalID, _position, _orientation); + // _position = BulletSimAPI.GetPosition2(BSBody.ptr); + BulletSimAPI.SetTranslation2(BSBody.ptr, _position, _orientation); }); } } @@ -389,12 +440,18 @@ public class BSCharacter : BSPhysObject set { _isPhysical = value; } } + public override bool IsSolid { + get { return true; } + } + public override bool IsStatic { + get { return false; } + } public override bool Flying { get { return _flying; } set { _flying = value; // simulate flying by changing the effect of gravity - this.Buoyancy = ComputeBuoyancyFromFlying(_flying); + Buoyancy = ComputeBuoyancyFromFlying(_flying); } } // Flying is implimented by changing the avatar's buoyancy. @@ -454,10 +511,19 @@ public class BSCharacter : BSPhysObject PhysicsScene.TaintedObject("BSCharacter.setBuoyancy", delegate() { DetailLog("{0},BSCharacter.setBuoyancy,taint,buoy={1}", LocalID, _buoyancy); - BulletSimAPI.SetObjectBuoyancy(PhysicsScene.WorldID, LocalID, _buoyancy); + ForceBuoyancy = _buoyancy; }); } } + public override float ForceBuoyancy { + get { return _buoyancy; } + set { _buoyancy = value; + DetailLog("{0},BSCharacter.setForceBuoyancy,taint,buoy={1}", LocalID, _buoyancy); + // Buoyancy is faked by changing the gravity applied to the object + float grav = PhysicsScene.Params.gravity * (1f - _buoyancy); + BulletSimAPI.SetGravity2(BSBody.ptr, new OMV.Vector3(0f, 0f, grav)); + } + } // Used for MoveTo public override OMV.Vector3 PIDTarget { @@ -518,27 +584,29 @@ public class BSCharacter : BSPhysObject private void ComputeAvatarScale(OMV.Vector3 size) { - _scale.X = PhysicsScene.Params.avatarCapsuleRadius; - _scale.Y = PhysicsScene.Params.avatarCapsuleRadius; + OMV.Vector3 newScale = OMV.Vector3.Zero; + newScale.X = PhysicsScene.Params.avatarCapsuleRadius; + newScale.Y = PhysicsScene.Params.avatarCapsuleRadius; // The 1.15 came from ODE but it seems to cause the avatar to float off the ground - // _scale.Z = (_size.Z * 1.15f) - (_scale.X + _scale.Y); - _scale.Z = (_size.Z) - (_scale.X + _scale.Y); + // Scale.Z = (_size.Z * 1.15f) - (Scale.X + Scale.Y); + newScale.Z = (_size.Z) - (Scale.X + Scale.Y); + Scale = newScale; } - // set _avatarVolume and _mass based on capsule size, _density and _scale + // set _avatarVolume and _mass based on capsule size, _density and Scale private void ComputeAvatarVolumeAndMass() { _avatarVolume = (float)( Math.PI - * _scale.X - * _scale.Y // the area of capsule cylinder - * _scale.Z // times height of capsule cylinder + * Scale.X + * Scale.Y // the area of capsule cylinder + * Scale.Z // times height of capsule cylinder + 1.33333333f * Math.PI - * _scale.X - * Math.Min(_scale.X, _scale.Y) - * _scale.Y // plus the volume of the capsule end caps + * Scale.X + * Math.Min(Scale.X, Scale.Y) + * Scale.Y // plus the volume of the capsule end caps ); _mass = _avatarDensity * _avatarVolume; } @@ -555,6 +623,22 @@ public class BSCharacter : BSPhysObject // Do some sanity checking for the avatar. Make sure it's above ground and inbounds. PositionSanityCheck2(true); + // remember the current and last set values + LastEntityProperties = CurrentEntityProperties; + CurrentEntityProperties = entprop; + + if (entprop.Velocity != LastEntityProperties.Velocity) + { + // Changes in the velocity are suppressed in avatars. + // That's just the way they are defined. + OMV.Vector3 avVel = new OMV.Vector3(_appliedVelocity.X, _appliedVelocity.Y, entprop.Velocity.Z); + _velocity = avVel; + BulletSimAPI.SetLinearVelocity2(BSBody.ptr, avVel); + } + + // Tell the linkset about this + Linkset.UpdateProperties(this); + // Avatars don't report their changes the usual way. Changes are checked for in the heartbeat loop. // base.RequestPhysicsterseUpdate(); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index cae599c..34dec26 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -69,6 +69,16 @@ public abstract class BSPhysObject : PhysicsActor // Reference to the physical shape (btCollisionShape) of this object public BulletShape BSShape; + // 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. + public EntityProperties CurrentEntityProperties { get; set; } + public EntityProperties LastEntityProperties { get; set; } + + public abstract OMV.Vector3 Scale { get; set; } + public abstract bool IsSolid { get; } + public abstract bool IsStatic { get; } + // Stop all physical motion. public abstract void ZeroMotion(); @@ -89,6 +99,8 @@ public abstract class BSPhysObject : PhysicsActor public abstract OMV.Vector3 ForceRotationalVelocity { get; set; } + public abstract float ForceBuoyancy { get; set; } + #region Collisions // Requested number of milliseconds between collision events. Zero means disabled. diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 6a4365c..3421e30 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -172,11 +172,8 @@ public sealed class BSPrim : BSPhysObject } // Scale is what we set in the physics engine. It is different than 'size' in that // 'size' can be encorporated into the mesh. In that case, the scale is <1,1,1>. - public OMV.Vector3 Scale - { - get { return _scale; } - set { _scale = value; } - } + public override OMV.Vector3 Scale { get; set; } + public override PrimitiveBaseShape Shape { set { _pbs = value; @@ -325,9 +322,9 @@ public sealed class BSPrim : BSPhysObject } // A version of the sanity check that also makes sure a new position value is - // pushed back to the physics engine. This routine would be used by anyone + // pushed to the physics engine. This routine would be used by anyone // who is not already pushing the value. - private bool PositionSanityCheck2(bool inTaintTime) + private bool PositionSanityCheck(bool inTaintTime) { bool ret = false; if (PositionSanityCheck()) @@ -336,8 +333,8 @@ public sealed class BSPrim : BSPhysObject // just assign to "Position" because of potential call loops. BSScene.TaintCallback sanityOperation = delegate() { - DetailLog("{0},BSPrim.PositionSanityCheck,taint,pos={1},orient={2}", LocalID, _position, _orientation); - BulletSimAPI.SetObjectTranslation(PhysicsScene.WorldID, LocalID, _position, _orientation); + DetailLog("{0},BSPrim.PositionSanityCheck,taint,pos={1},orient={2}", LocalID, _position, _orientation); + ForcePosition = _position; }; if (inTaintTime) sanityOperation(); @@ -547,13 +544,13 @@ public sealed class BSPrim : BSPhysObject } // An object is static (does not move) if selected or not physical - private bool IsStatic + public override bool IsStatic { get { return _isSelected || !IsPhysical; } } // An object is solid if it's not phantom and if it's not doing VolumeDetect - public bool IsSolid + public override bool IsSolid { get { return !IsPhantom && !_isVolumeDetect; } } @@ -631,6 +628,12 @@ public sealed class BSPrim : BSPhysObject BulletSimAPI.SetMassProps2(BSBody.ptr, 0f, OMV.Vector3.Zero); // There is no inertia in a static object BulletSimAPI.UpdateInertiaTensor2(BSBody.ptr); + // Set collision detection parameters + if (PhysicsScene.Params.ccdMotionThreshold > 0f) + { + BulletSimAPI.SetCcdMotionThreshold2(BSBody.ptr, PhysicsScene.Params.ccdMotionThreshold); + BulletSimAPI.SetCcdSweepSphereRadius2(BSBody.ptr, PhysicsScene.Params.ccdSweptSphereRadius); + } // There can be special things needed for implementing linksets Linkset.MakeStatic(this); // The activation state is 'disabled' so Bullet will not try to act on it. @@ -662,6 +665,13 @@ public sealed class BSPrim : BSPhysObject BulletSimAPI.SetMassProps2(BSBody.ptr, _mass, inertia); BulletSimAPI.UpdateInertiaTensor2(BSBody.ptr); + // Set collision detection parameters + if (PhysicsScene.Params.ccdMotionThreshold > 0f) + { + BulletSimAPI.SetCcdMotionThreshold2(BSBody.ptr, PhysicsScene.Params.ccdMotionThreshold); + BulletSimAPI.SetCcdSweepSphereRadius2(BSBody.ptr, PhysicsScene.Params.ccdSweptSphereRadius); + } + // Various values for simulation limits BulletSimAPI.SetDamping2(BSBody.ptr, PhysicsScene.Params.linearDamping, PhysicsScene.Params.angularDamping); BulletSimAPI.SetDeactivationTime2(BSBody.ptr, PhysicsScene.Params.deactivationTime); @@ -812,14 +822,21 @@ public sealed class BSPrim : BSPhysObject set { _buoyancy = value; PhysicsScene.TaintedObject("BSPrim.setBuoyancy", delegate() - { - // DetailLog("{0},BSPrim.SetBuoyancy,taint,buoy={1}", LocalID, _buoyancy); - // Buoyancy is faked by changing the gravity applied to the object - float grav = PhysicsScene.Params.gravity * (1f - _buoyancy); - BulletSimAPI.SetGravity2(BSBody.ptr, new OMV.Vector3(0f, 0f, grav)); + { + ForceBuoyancy = _buoyancy; }); } } + public override float ForceBuoyancy { + get { return _buoyancy; } + set { + _buoyancy = value; + // DetailLog("{0},BSPrim.setForceBuoyancy,taint,buoy={1}", LocalID, _buoyancy); + // Buoyancy is faked by changing the gravity applied to the object + float grav = PhysicsScene.Params.gravity * (1f - _buoyancy); + BulletSimAPI.SetGravity2(BSBody.ptr, new OMV.Vector3(0f, 0f, grav)); + } + } // Used for MoveTo public override OMV.Vector3 PIDTarget { @@ -1269,8 +1286,8 @@ public sealed class BSPrim : BSPhysObject const float VELOCITY_TOLERANCE = 0.001f; const float POSITION_TOLERANCE = 0.05f; const float ACCELERATION_TOLERANCE = 0.01f; - const float ROTATIONAL_VELOCITY_TOLERANCE = 0.01f; - + const float ROTATIONAL_VELOCITY_TOLERANCE = 0.01f; + public override void UpdateProperties(EntityProperties entprop) { /* @@ -1326,11 +1343,13 @@ public sealed class BSPrim : BSPhysObject _orientation = entprop.Rotation; _velocity = entprop.Velocity; _acceleration = entprop.Acceleration; - _rotationalVelocity = entprop.RotationalVelocity; + _rotationalVelocity = entprop.RotationalVelocity; + + // remember the current and last set values + LastEntityProperties = CurrentEntityProperties; + CurrentEntityProperties = entprop; - PositionSanityCheck2(true); - - Linkset.UpdateProperties(this); + PositionSanityCheck(true); DetailLog("{0},BSPrim.UpdateProperties,call,pos={1},orient={2},vel={3},accel={4},rotVel={5}", LocalID, _position, _orientation, _velocity, _acceleration, _rotationalVelocity); @@ -1348,6 +1367,9 @@ public sealed class BSPrim : BSPhysObject entprop.Acceleration, entprop.RotationalVelocity); } */ + // The linkset implimentation might want to know about this. + + Linkset.UpdateProperties(this); } } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index 2c3c481..5158011 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -256,10 +256,10 @@ public class BSScene : PhysicsScene, IPhysicsParameters Vector3 worldExtent = new Vector3(Constants.RegionSize, Constants.RegionSize, Constants.RegionHeight); // m_log.DebugFormat("{0}: Initialize: Calling BulletSimAPI.Initialize.", LogHeader); - WorldID = BulletSimAPI.Initialize(worldExtent, m_paramsHandle.AddrOfPinnedObject(), + World = new BulletSim(0, this, BulletSimAPI.Initialize2(worldExtent, m_paramsHandle.AddrOfPinnedObject(), m_maxCollisionsPerFrame, m_collisionArrayPinnedHandle.AddrOfPinnedObject(), m_maxUpdatesPerFrame, m_updateArrayPinnedHandle.AddrOfPinnedObject(), - m_DebugLogCallbackHandle); + m_DebugLogCallbackHandle)); // Initialization to support the transition to a new API which puts most of the logic // into the C# code so it is easier to modify and add to. @@ -360,7 +360,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters } // Anything left in the unmanaged code should be cleaned out - BulletSimAPI.Shutdown(WorldID); + BulletSimAPI.Shutdown2(World.ptr); // Not logging any more PhysicsLogging.Close(); @@ -498,7 +498,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters { if (PhysicsLogging.Enabled) beforeTime = Util.EnvironmentTickCount(); - numSubSteps = BulletSimAPI.PhysicsStep(WorldID, timeStep, m_maxSubSteps, m_fixedTimeStep, + numSubSteps = BulletSimAPI.PhysicsStep2(World.ptr, timeStep, m_maxSubSteps, m_fixedTimeStep, out updatedEntityCount, out updatedEntitiesPtr, out collidersCount, out collidersPtr); if (PhysicsLogging.Enabled) simTime = Util.EnvironmentTickCountSubtract(beforeTime); @@ -1011,6 +1011,11 @@ public class BSScene : PhysicsScene, IPhysicsParameters (s,cf,p,v) => { s.m_params[0].avatarFriction = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].avatarFriction; }, (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].avatarFriction, p, l, v); } ), + new ParameterDefn("AvatarStandingFriction", "Avatar friction when standing. Changed on avatar recreation.", + 10f, + (s,cf,p,v) => { s.m_params[0].avatarStandingFriction = cf.GetFloat(p, v); }, + (s) => { return s.m_params[0].avatarStandingFriction; }, + (s,p,l,v) => { s.m_params[0].avatarStandingFriction = v; } ), new ParameterDefn("AvatarDensity", "Density of an avatar. Changed on avatar recreation.", 60f, (s,cf,p,v) => { s.m_params[0].avatarDensity = cf.GetFloat(p, v); }, @@ -1246,7 +1251,9 @@ public class BSScene : PhysicsScene, IPhysicsParameters case PhysParameterEntry.APPLY_TO_NONE: defaultLoc = val; // setting only the default value break; - case PhysParameterEntry.APPLY_TO_ALL: + case PhysParameterEntry.APPLY_TO_ALL: + m_log.ErrorFormat("{0} Cannot change parameters of multiple objects. Someday it will be added.", LogHeader); + /* defaultLoc = val; // setting ALL also sets the default value List objectIDs = lIDs; string xparm = parm.ToLower(); @@ -1257,6 +1264,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters BulletSimAPI.UpdateParameter(WorldID, lID, xparm, xval); } }); + */ break; default: // setting only one localID @@ -1268,12 +1276,15 @@ public class BSScene : PhysicsScene, IPhysicsParameters // schedule the actual updating of the paramter to when the phys engine is not busy protected void TaintedUpdateParameter(string parm, uint localID, float val) { + m_log.ErrorFormat("{0} Cannot change parameters of base objects. Someday it will be added.", LogHeader); + /* uint xlocalID = localID; string xparm = parm.ToLower(); float xval = val; TaintedObject("BSScene.TaintedUpdateParameter", delegate() { BulletSimAPI.UpdateParameter(WorldID, xlocalID, xparm, xval); }); + */ } // Get parameter. diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index d189f1d..7d0f84a 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -93,7 +93,7 @@ public class BSShapeCollection : IDisposable // sure the body is of the right type. // Return 'true' if either the body or the shape changed. // Called at taint-time!! - public bool GetBodyAndShape(bool forceRebuild, BulletSim sim, BSPrim prim, + public bool GetBodyAndShape(bool forceRebuild, BulletSim sim, BSPhysObject prim, ShapeData shapeData, PrimitiveBaseShape pbs, ShapeDestructionCallback shapeCallback, BodyDestructionCallback bodyCallback) { @@ -351,19 +351,30 @@ public class BSShapeCollection : IDisposable // Create the geometry information in Bullet for later use. // The objects needs a hull if it's physical otherwise a mesh is enough. - // No locking here because this is done when we know physics is not simulating. - // if 'forceRebuild' is true, the geometry is rebuilt. Otherwise a previously built version is used. + // if 'forceRebuild' is true, the geometry is unconditionally rebuilt. For meshes and hulls, + // shared geometries will be used. If the parameters of the existing shape are the same + // as this request, the shape is not rebuilt. + // 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, BSPrim prim, ShapeData shapeData, + private bool CreateGeom(bool forceRebuild, BSPhysObject prim, ShapeData shapeData, PrimitiveBaseShape pbs, ShapeDestructionCallback shapeCallback) { bool ret = false; bool haveShape = false; bool nativeShapePossible = true; + if (shapeData.Type == ShapeData.PhysicsShapeType.SHAPE_AVATAR) + { + // an avatar capsule is close to a native shape (it is not shared) + ret = GetReferenceToNativeShape(prim, shapeData, ShapeData.PhysicsShapeType.SHAPE_AVATAR, + ShapeData.FixedShapeKey.KEY_CAPSULE, shapeCallback); + haveShape = true; + } // If the prim attributes are simple, this could be a simple Bullet native shape - if (nativeShapePossible + if (!haveShape + && pbs != null + && nativeShapePossible && ((pbs.SculptEntry && !PhysicsScene.ShouldMeshSculptedPrim) || (pbs.ProfileBegin == 0 && pbs.ProfileEnd == 0 && pbs.ProfileHollow == 0 @@ -406,7 +417,7 @@ public class BSShapeCollection : IDisposable // If a simple shape is not happening, create a mesh and possibly a hull. // Note that if it's a native shape, the check for physical/non-physical is not // made. Native shapes are best used in either case. - if (!haveShape) + if (!haveShape && pbs != null) { if (prim.IsPhysical && PhysicsScene.ShouldUseHullsForPhysicalObjects) { @@ -425,8 +436,9 @@ public class BSShapeCollection : IDisposable return ret; } - // Creates a native shape and assignes it to prim.BSShape - private bool GetReferenceToNativeShape( BSPrim prim, ShapeData shapeData, + // 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, ShapeData shapeData, ShapeData.PhysicsShapeType shapeType, ShapeData.FixedShapeKey shapeKey, ShapeDestructionCallback shapeCallback) { @@ -440,10 +452,19 @@ public class BSShapeCollection : IDisposable // release any previous shape DereferenceShape(prim.BSShape, true, shapeCallback); - // Native shapes are always built independently. - newShape = new BulletShape(BulletSimAPI.BuildNativeShape2(PhysicsScene.World.ptr, shapeData), shapeType); - newShape.shapeKey = (System.UInt64)shapeKey; - newShape.isNativeShape = true; + if (shapeType == ShapeData.PhysicsShapeType.SHAPE_AVATAR) + { + newShape = new BulletShape(BulletSimAPI.BuildCapsuleShape2(PhysicsScene.World.ptr, shapeData), shapeType); + newShape.shapeKey = (System.UInt64)shapeKey; + newShape.isNativeShape = true; + } + else + { + // Native shapes are always built independently. + newShape = new BulletShape(BulletSimAPI.BuildNativeShape2(PhysicsScene.World.ptr, shapeData), shapeType); + newShape.shapeKey = (System.UInt64)shapeKey; + newShape.isNativeShape = true; + } // Don't need to do a 'ReferenceShape()' here because native shapes are not tracked. // DetailLog("{0},BSShapeCollection.AddNativeShapeToPrim,create,newshape={1}", shapeData.ID, newShape); @@ -456,7 +477,7 @@ public class BSShapeCollection : IDisposable // 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(BSPrim prim, ShapeData shapeData, PrimitiveBaseShape pbs, + private bool GetReferenceToMesh(BSPhysObject prim, ShapeData shapeData, PrimitiveBaseShape pbs, ShapeDestructionCallback shapeCallback) { BulletShape newShape = new BulletShape(IntPtr.Zero); @@ -526,7 +547,7 @@ public class BSShapeCollection : IDisposable // See that hull shape exists in the physical world and update prim.BSShape. // We could be creating the hull because scale changed or whatever. - private bool GetReferenceToHull(BSPrim prim, ShapeData shapeData, PrimitiveBaseShape pbs, + private bool GetReferenceToHull(BSPhysObject prim, ShapeData shapeData, PrimitiveBaseShape pbs, ShapeDestructionCallback shapeCallback) { BulletShape newShape; @@ -694,7 +715,7 @@ public class BSShapeCollection : IDisposable // 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, BSPrim prim, BulletSim sim, BulletShape shape, + private bool CreateBody(bool forceRebuild, BSPhysObject prim, BulletSim sim, BulletShape shape, ShapeData shapeData, BodyDestructionCallback bodyCallback) { bool ret = false; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs index 276111c..30754a7 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs @@ -223,6 +223,7 @@ public struct ShapeData KEY_SPHERE = 2, KEY_CONE = 3, KEY_CYLINDER = 4, + KEY_CAPSULE = 5, } } [StructLayout(LayoutKind.Sequential)] @@ -282,6 +283,7 @@ public struct ConfigurationParameters public float terrainHitFraction; public float terrainRestitution; public float avatarFriction; + public float avatarStandingFriction; public float avatarDensity; public float avatarRestitution; public float avatarCapsuleRadius; @@ -428,6 +430,7 @@ public delegate void DebugLogCallback([MarshalAs(UnmanagedType.LPStr)]string msg [return: MarshalAs(UnmanagedType.LPStr)] public static extern string GetVersion(); +/* Remove the linkage to the old api methods [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern uint Initialize(Vector3 maxPosition, IntPtr parms, int maxCollisions, IntPtr collisionArray, @@ -531,7 +534,7 @@ public static extern Vector3 RecoverFromPenetration(uint worldID, uint id); // =============================================================================== [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern void DumpBulletStatistics(); - +*/ // Log a debug message [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern void SetDebugLogCallback(DebugLogCallback callback); @@ -562,7 +565,8 @@ public static extern IntPtr GetBodyHandle2(IntPtr world, uint id); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern IntPtr Initialize2(Vector3 maxPosition, IntPtr parms, int maxCollisions, IntPtr collisionArray, - int maxUpdates, IntPtr updateArray); + int maxUpdates, IntPtr updateArray, + DebugLogCallback logRoutine); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern bool UpdateParameter2(IntPtr world, uint localID, String parm, float value); @@ -604,6 +608,9 @@ public static extern IntPtr BuildNativeShape2(IntPtr world, ShapeData shapeData) public static extern bool IsNativeShape2(IntPtr shape); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern IntPtr BuildCapsuleShape2(IntPtr world, ShapeData shapeData); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern IntPtr CreateCompoundShape2(IntPtr sim); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -- cgit v1.1 From eaccfa6d99ac51b4963ae0fa457ff0d2b9ce65e7 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Sun, 14 Oct 2012 19:23:35 -0700 Subject: BulletSim: Fix small problems with last patch: BSScene.World properly initialized and setting of C++ parameters commented out. Comments and logging added. --- OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs | 2 +- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 13 ++++--------- OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs | 2 +- 3 files changed, 6 insertions(+), 11 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index 7c2f856..7bc6b69 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -146,7 +146,7 @@ public class BSCharacter : BSPhysObject ZeroMotion(); - OMV.Vector3 localInertia = BulletSimAPI.CalculateLocalInertia2(BSBody.ptr, MassRaw); + OMV.Vector3 localInertia = BulletSimAPI.CalculateLocalInertia2(BSShape.ptr, MassRaw); BulletSimAPI.SetMassProps2(BSBody.ptr, MassRaw, localInertia); // Set the velocity and compute the proper friction diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index 5158011..7998b08 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -261,10 +261,6 @@ public class BSScene : PhysicsScene, IPhysicsParameters m_maxUpdatesPerFrame, m_updateArrayPinnedHandle.AddrOfPinnedObject(), m_DebugLogCallbackHandle)); - // Initialization to support the transition to a new API which puts most of the logic - // into the C# code so it is easier to modify and add to. - World = new BulletSim(WorldID, this, BulletSimAPI.GetSimHandle2(WorldID)); - Constraints = new BSConstraintCollection(World); TerrainManager = new BSTerrainManager(this); @@ -1251,10 +1247,9 @@ public class BSScene : PhysicsScene, IPhysicsParameters case PhysParameterEntry.APPLY_TO_NONE: defaultLoc = val; // setting only the default value break; - case PhysParameterEntry.APPLY_TO_ALL: - m_log.ErrorFormat("{0} Cannot change parameters of multiple objects. Someday it will be added.", LogHeader); - /* + case PhysParameterEntry.APPLY_TO_ALL: defaultLoc = val; // setting ALL also sets the default value + /* List objectIDs = lIDs; string xparm = parm.ToLower(); float xval = val; @@ -1276,15 +1271,15 @@ public class BSScene : PhysicsScene, IPhysicsParameters // schedule the actual updating of the paramter to when the phys engine is not busy protected void TaintedUpdateParameter(string parm, uint localID, float val) { + /* Settings in the C++ code are not working at the moment. TODO: fix the settings. m_log.ErrorFormat("{0} Cannot change parameters of base objects. Someday it will be added.", LogHeader); - /* uint xlocalID = localID; string xparm = parm.ToLower(); float xval = val; TaintedObject("BSScene.TaintedUpdateParameter", delegate() { BulletSimAPI.UpdateParameter(WorldID, xlocalID, xparm, xval); }); - */ + */ } // Get parameter. diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index 7d0f84a..5a77e52 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -369,6 +369,7 @@ public class BSShapeCollection : IDisposable // an avatar capsule is close to a native shape (it is not shared) ret = GetReferenceToNativeShape(prim, shapeData, ShapeData.PhysicsShapeType.SHAPE_AVATAR, ShapeData.FixedShapeKey.KEY_CAPSULE, shapeCallback); + DetailLog("{0},BSShapeCollection.CreateGeom,avatarCapsule,shape={1}", prim.LocalID, prim.BSShape); haveShape = true; } // If the prim attributes are simple, this could be a simple Bullet native shape @@ -460,7 +461,6 @@ public class BSShapeCollection : IDisposable } else { - // Native shapes are always built independently. newShape = new BulletShape(BulletSimAPI.BuildNativeShape2(PhysicsScene.World.ptr, shapeData), shapeType); newShape.shapeKey = (System.UInt64)shapeKey; newShape.isNativeShape = true; -- cgit v1.1 From fc33afddd360843d05f030750b7075315a526ae1 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Mon, 15 Oct 2012 12:11:00 -0700 Subject: BulletSim: remove code in ShapeCollection that hinted at shape sharing. Add new function to ParameterDefn for calling BulletSimAPI to set values. Tweaking to BSCharacter parameter setting to try and have avatars stand. --- .../Region/Physics/BulletSPlugin/BSCharacter.cs | 56 +++++----- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 16 +-- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 114 ++++++++++++--------- .../Physics/BulletSPlugin/BSShapeCollection.cs | 110 +++++++------------- .../Physics/BulletSPlugin/BSTerrainManager.cs | 3 +- 5 files changed, 138 insertions(+), 161 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index 7bc6b69..8e1171a 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -114,17 +114,9 @@ public class BSCharacter : BSPhysObject PhysicsScene.TaintedObject("BSCharacter.create", delegate() { DetailLog("{0},BSCharacter.create,taint", LocalID); - PhysicsScene.Shapes.GetBodyAndShape(true, PhysicsScene.World, this, shapeData, null, null, null); - + PhysicsScene.Shapes.GetBodyAndShape(true, PhysicsScene.World, this, shapeData, null, null, null); + SetPhysicalProperties(); - - // Set the buoyancy for flying. This will be refactored when all the settings happen in C#. - // If not set at creation, the avatar will stop flying when created after crossing a region boundry. - ForceBuoyancy = _buoyancy; - - // This works here because CreateObject has already put the character into the physical world. - BulletSimAPI.SetCollisionFilterMask2(BSBody.ptr, - (uint)CollisionFilterGroups.AvatarFilter, (uint)CollisionFilterGroups.AvatarMask); }); return; } @@ -146,27 +138,32 @@ public class BSCharacter : BSPhysObject ZeroMotion(); - OMV.Vector3 localInertia = BulletSimAPI.CalculateLocalInertia2(BSShape.ptr, MassRaw); + OMV.Vector3 localInertia = BulletSimAPI.CalculateLocalInertia2(BSShape.ptr, MassRaw); BulletSimAPI.SetMassProps2(BSBody.ptr, MassRaw, localInertia); + ForcePosition = _position; // Set the velocity and compute the proper friction ForceVelocity = _velocity; - - BulletSimAPI.SetFriction2(BSBody.ptr, _currentFriction); BulletSimAPI.SetRestitution2(BSBody.ptr, PhysicsScene.Params.avatarRestitution); - BulletSimAPI.SetLocalScaling2(BSShape.ptr, Scale); BulletSimAPI.SetContactProcessingThreshold2(BSBody.ptr, PhysicsScene.Params.contactProcessingThreshold); - if (PhysicsScene.Params.ccdMotionThreshold > 0f) { BulletSimAPI.SetCcdMotionThreshold2(BSBody.ptr, PhysicsScene.Params.ccdMotionThreshold); BulletSimAPI.SetCcdSweepSphereRadius2(BSBody.ptr, PhysicsScene.Params.ccdSweptSphereRadius); - } - - BulletSimAPI.SetActivationState2(BSBody.ptr, (int)ActivationState.DISABLE_DEACTIVATION); + } + + BulletSimAPI.AddToCollisionFlags2(BSBody.ptr, CollisionFlags.CF_CHARACTER_OBJECT); BulletSimAPI.AddObjectToWorld2(PhysicsScene.World.ptr, BSBody.ptr); + + BulletSimAPI.ForceActivationState2(BSBody.ptr, ActivationState.DISABLE_DEACTIVATION); + BulletSimAPI.UpdateSingleAabb2(PhysicsScene.World.ptr, BSBody.ptr); + + // Do this after the object has been added to the world + BulletSimAPI.SetCollisionFilterMask2(BSBody.ptr, + (uint)CollisionFilterGroups.AvatarFilter, + (uint)CollisionFilterGroups.AvatarMask); } public override void RequestPhysicsterseUpdate() @@ -174,9 +171,7 @@ public class BSCharacter : BSPhysObject base.RequestPhysicsterseUpdate(); } // No one calls this method so I don't know what it could possibly mean - public override bool Stopped { - get { return false; } - } + public override bool Stopped { get { return false; } } public override OMV.Vector3 Size { get { @@ -185,18 +180,14 @@ public class BSCharacter : BSPhysObject } set { - // When an avatar's size is set, only the height is changed - // and that really only depends on the radius. + // When an avatar's size is set, only the height is changed. _size = value; ComputeAvatarScale(_size); - - // TODO: something has to be done with the avatar's vertical position - ComputeAvatarVolumeAndMass(); PhysicsScene.TaintedObject("BSCharacter.setSize", delegate() { - BulletSimAPI.SetLocalScaling2(BSBody.ptr, Scale); + BulletSimAPI.SetLocalScaling2(BSShape.ptr, Scale); OMV.Vector3 localInertia = BulletSimAPI.CalculateLocalInertia2(BSBody.ptr, MassRaw); BulletSimAPI.SetMassProps2(BSBody.ptr, MassRaw, localInertia); }); @@ -300,7 +291,7 @@ public class BSCharacter : BSPhysObject // A version of the sanity check that also makes sure a new position value is // pushed back to the physics engine. This routine would be used by anyone // who is not already pushing the value. - private bool PositionSanityCheck2(bool inTaintTime) + private bool PositionSanityCheck(bool inTaintTime) { bool ret = false; if (PositionSanityCheck()) @@ -378,14 +369,16 @@ public class BSCharacter : BSPhysObject } else { - if (_currentFriction == 999f) + if (_currentFriction != PhysicsScene.Params.avatarFriction) { _currentFriction = PhysicsScene.Params.avatarFriction; BulletSimAPI.SetFriction2(BSBody.ptr, _currentFriction); } } _velocity = value; + // Remember the set velocity so we can suppress the reduction by friction, ... _appliedVelocity = value; + BulletSimAPI.SetLinearVelocity2(BSBody.ptr, _velocity); BulletSimAPI.Activate2(BSBody.ptr, true); } @@ -590,7 +583,8 @@ public class BSCharacter : BSPhysObject // The 1.15 came from ODE but it seems to cause the avatar to float off the ground // Scale.Z = (_size.Z * 1.15f) - (Scale.X + Scale.Y); - newScale.Z = (_size.Z) - (Scale.X + Scale.Y); + // From the total height, remove the capsule half spheres that are at each end + newScale.Z = (size.Z) - (Math.Min(newScale.X, newScale.Y) * 2f); Scale = newScale; } @@ -621,7 +615,7 @@ public class BSCharacter : BSPhysObject _acceleration = entprop.Acceleration; _rotationalVelocity = entprop.RotationalVelocity; // Do some sanity checking for the avatar. Make sure it's above ground and inbounds. - PositionSanityCheck2(true); + PositionSanityCheck(true); // remember the current and last set values LastEntityProperties = CurrentEntityProperties; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 3421e30..b9e1908 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -333,7 +333,7 @@ public sealed class BSPrim : BSPhysObject // just assign to "Position" because of potential call loops. BSScene.TaintCallback sanityOperation = delegate() { - DetailLog("{0},BSPrim.PositionSanityCheck,taint,pos={1},orient={2}", LocalID, _position, _orientation); + DetailLog("{0},BSPrim.PositionSanityCheck,taint,pos={1},orient={2}", LocalID, _position, _orientation); ForcePosition = _position; }; if (inTaintTime) @@ -822,7 +822,7 @@ public sealed class BSPrim : BSPhysObject set { _buoyancy = value; PhysicsScene.TaintedObject("BSPrim.setBuoyancy", delegate() - { + { ForceBuoyancy = _buoyancy; }); } @@ -1286,8 +1286,8 @@ public sealed class BSPrim : BSPhysObject const float VELOCITY_TOLERANCE = 0.001f; const float POSITION_TOLERANCE = 0.05f; const float ACCELERATION_TOLERANCE = 0.01f; - const float ROTATIONAL_VELOCITY_TOLERANCE = 0.01f; - + const float ROTATIONAL_VELOCITY_TOLERANCE = 0.01f; + public override void UpdateProperties(EntityProperties entprop) { /* @@ -1343,10 +1343,10 @@ public sealed class BSPrim : BSPhysObject _orientation = entprop.Rotation; _velocity = entprop.Velocity; _acceleration = entprop.Acceleration; - _rotationalVelocity = entprop.RotationalVelocity; - - // remember the current and last set values - LastEntityProperties = CurrentEntityProperties; + _rotationalVelocity = entprop.RotationalVelocity; + + // remember the current and last set values + LastEntityProperties = CurrentEntityProperties; CurrentEntityProperties = entprop; PositionSanityCheck(true); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index 7998b08..c6e8bc4 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -795,7 +795,8 @@ public class BSScene : PhysicsScene, IPhysicsParameters delegate void ParamUser(BSScene scene, IConfig conf, string paramName, float val); delegate float ParamGet(BSScene scene); - delegate void ParamSet(BSScene scene, string paramName, uint localID, float val); + delegate void ParamSet(BSScene scene, string paramName, uint localID, float val); + delegate void SetOnObject(BSScene scene, BSPhysObject obj, float val); private struct ParameterDefn { @@ -804,7 +805,8 @@ public class BSScene : PhysicsScene, IPhysicsParameters public float defaultValue; // default value if not specified anywhere else public ParamUser userParam; // get the value from the configuration file public ParamGet getter; // return the current value stored for this parameter - public ParamSet setter; // set the current value for this parameter + public ParamSet setter; // set the current value for this parameter + public SetOnObject onObject; // set the value on an object in the physical domain public ParameterDefn(string n, string d, float v, ParamUser u, ParamGet g, ParamSet s) { name = n; @@ -812,7 +814,18 @@ public class BSScene : PhysicsScene, IPhysicsParameters defaultValue = v; userParam = u; getter = g; - setter = s; + setter = s; + onObject = null; + } + public ParameterDefn(string n, string d, float v, ParamUser u, ParamGet g, ParamSet s, SetOnObject o) + { + name = n; + desc = d; + defaultValue = v; + userParam = u; + getter = g; + setter = s; + onObject = o; } } @@ -834,6 +847,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters // // The single letter parameters for the delegates are: // s = BSScene + // o = BSPhysObject // p = string parameter name // l = localID of referenced object // v = float value @@ -943,65 +957,74 @@ public class BSScene : PhysicsScene, IPhysicsParameters -9.80665f, (s,cf,p,v) => { s.m_params[0].gravity = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].gravity; }, - (s,p,l,v) => { s.m_params[0].gravity = v; s.TaintedUpdateParameter(p,l,v); } ), + (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].gravity, p, PhysParameterEntry.APPLY_TO_NONE, v); }, + (s,o,v) => { BulletSimAPI.SetGravity2(s.World.ptr, new Vector3(0f,0f,v)); } ), new ParameterDefn("LinearDamping", "Factor to damp linear movement per second (0.0 - 1.0)", 0f, (s,cf,p,v) => { s.m_params[0].linearDamping = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].linearDamping; }, - (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].linearDamping, p, l, v); } ), + (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].linearDamping, p, l, v); }, + (s,o,v) => { BulletSimAPI.SetDamping2(o.BSBody.ptr, v, v); } ), new ParameterDefn("AngularDamping", "Factor to damp angular movement per second (0.0 - 1.0)", 0f, (s,cf,p,v) => { s.m_params[0].angularDamping = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].angularDamping; }, - (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].angularDamping, p, l, v); } ), + (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].angularDamping, p, l, v); }, + (s,o,v) => { BulletSimAPI.SetDamping2(o.BSBody.ptr, v, v); } ), new ParameterDefn("DeactivationTime", "Seconds before considering an object potentially static", 0.2f, (s,cf,p,v) => { s.m_params[0].deactivationTime = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].deactivationTime; }, - (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].deactivationTime, p, l, v); } ), + (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].deactivationTime, p, l, v); }, + (s,o,v) => { BulletSimAPI.SetDeactivationTime2(o.BSBody.ptr, v); } ), new ParameterDefn("LinearSleepingThreshold", "Seconds to measure linear movement before considering static", 0.8f, (s,cf,p,v) => { s.m_params[0].linearSleepingThreshold = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].linearSleepingThreshold; }, - (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].linearSleepingThreshold, p, l, v); } ), + (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].linearSleepingThreshold, p, l, v); }, + (s,o,v) => { BulletSimAPI.SetSleepingThresholds2(o.BSBody.ptr, v, v); } ), new ParameterDefn("AngularSleepingThreshold", "Seconds to measure angular movement before considering static", 1.0f, (s,cf,p,v) => { s.m_params[0].angularSleepingThreshold = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].angularSleepingThreshold; }, - (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].angularSleepingThreshold, p, l, v); } ), + (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].angularSleepingThreshold, p, l, v); }, + (s,o,v) => { BulletSimAPI.SetSleepingThresholds2(o.BSBody.ptr, v, v); } ), new ParameterDefn("CcdMotionThreshold", "Continuious collision detection threshold (0 means no CCD)" , 0f, // set to zero to disable (s,cf,p,v) => { s.m_params[0].ccdMotionThreshold = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].ccdMotionThreshold; }, - (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].ccdMotionThreshold, p, l, v); } ), + (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].ccdMotionThreshold, p, l, v); }, + (s,o,v) => { BulletSimAPI.SetCcdMotionThreshold2(o.BSBody.ptr, v); } ), new ParameterDefn("CcdSweptSphereRadius", "Continuious collision detection test radius" , 0f, (s,cf,p,v) => { s.m_params[0].ccdSweptSphereRadius = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].ccdSweptSphereRadius; }, - (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].ccdSweptSphereRadius, p, l, v); } ), + (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].ccdSweptSphereRadius, p, l, v); }, + (s,o,v) => { BulletSimAPI.SetCcdSweepSphereRadius2(o.BSBody.ptr, v); } ), new ParameterDefn("ContactProcessingThreshold", "Distance between contacts before doing collision check" , 0.1f, (s,cf,p,v) => { s.m_params[0].contactProcessingThreshold = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].contactProcessingThreshold; }, - (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].contactProcessingThreshold, p, l, v); } ), + (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].contactProcessingThreshold, p, l, v); }, + (s,o,v) => { BulletSimAPI.SetContactProcessingThreshold2(o.BSBody.ptr, v); } ), new ParameterDefn("TerrainFriction", "Factor to reduce movement against terrain surface" , 0.5f, (s,cf,p,v) => { s.m_params[0].terrainFriction = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].terrainFriction; }, - (s,p,l,v) => { s.m_params[0].terrainFriction = v; s.TaintedUpdateParameter(p,l,v); } ), + (s,p,l,v) => { s.m_params[0].terrainFriction = v; /* TODO: set on real terrain */} ), new ParameterDefn("TerrainHitFraction", "Distance to measure hit collisions" , 0.8f, (s,cf,p,v) => { s.m_params[0].terrainHitFraction = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].terrainHitFraction; }, - (s,p,l,v) => { s.m_params[0].terrainHitFraction = v; s.TaintedUpdateParameter(p,l,v); } ), + (s,p,l,v) => { s.m_params[0].terrainHitFraction = v; /* TODO: set on real terrain */ } ), new ParameterDefn("TerrainRestitution", "Bouncyness" , 0f, (s,cf,p,v) => { s.m_params[0].terrainRestitution = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].terrainRestitution; }, - (s,p,l,v) => { s.m_params[0].terrainRestitution = v; s.TaintedUpdateParameter(p,l,v); } ), + (s,p,l,v) => { s.m_params[0].terrainRestitution = v; /* TODO: set on real terrain */ } ), new ParameterDefn("AvatarFriction", "Factor to reduce movement against an avatar. Changed on avatar recreation.", 0.2f, (s,cf,p,v) => { s.m_params[0].avatarFriction = cf.GetFloat(p, v); }, @@ -1228,58 +1251,55 @@ public class BSScene : PhysicsScene, IPhysicsParameters return ret; } - // check to see if we are updating a parameter for a particular or all of the prims - protected void UpdateParameterObject(ref float loc, string parm, uint localID, float val) - { - List operateOn; - lock (PhysObjects) operateOn = new List(PhysObjects.Keys); - UpdateParameterSet(operateOn, ref loc, parm, localID, val); - } - // update all the localIDs specified // If the local ID is APPLY_TO_NONE, just change the default value // If the localID is APPLY_TO_ALL change the default value and apply the new value to all the lIDs // If the localID is a specific object, apply the parameter change to only that object - protected void UpdateParameterSet(List lIDs, ref float defaultLoc, string parm, uint localID, float val) + protected void UpdateParameterObject(ref float defaultLoc, string parm, uint localID, float val) { + List objectIDs = new List(); switch (localID) { case PhysParameterEntry.APPLY_TO_NONE: defaultLoc = val; // setting only the default value + // This will cause a call into the physical world if some operation is specified (SetOnObject). + objectIDs.Add(TERRAIN_ID); + TaintedUpdateParameter(parm, objectIDs, val); break; - case PhysParameterEntry.APPLY_TO_ALL: + case PhysParameterEntry.APPLY_TO_ALL: defaultLoc = val; // setting ALL also sets the default value - /* - List objectIDs = lIDs; - string xparm = parm.ToLower(); - float xval = val; - TaintedObject("BSScene.UpdateParameterSet", delegate() { - foreach (uint lID in objectIDs) - { - BulletSimAPI.UpdateParameter(WorldID, lID, xparm, xval); - } - }); - */ + lock (PhysObjects) objectIDs = new List(PhysObjects.Keys); + TaintedUpdateParameter(parm, objectIDs, val); break; default: - // setting only one localID - TaintedUpdateParameter(parm, localID, val); + // setting only one localID + objectIDs.Add(localID); + TaintedUpdateParameter(parm, objectIDs, val); break; } } // schedule the actual updating of the paramter to when the phys engine is not busy - protected void TaintedUpdateParameter(string parm, uint localID, float val) + protected void TaintedUpdateParameter(string parm, List lIDs, float val) { - /* Settings in the C++ code are not working at the moment. TODO: fix the settings. - m_log.ErrorFormat("{0} Cannot change parameters of base objects. Someday it will be added.", LogHeader); - uint xlocalID = localID; - string xparm = parm.ToLower(); - float xval = val; - TaintedObject("BSScene.TaintedUpdateParameter", delegate() { - BulletSimAPI.UpdateParameter(WorldID, xlocalID, xparm, xval); + float xval = val; + List xlIDs = lIDs; + string xparm = parm; + TaintedObject("BSScene.UpdateParameterSet", delegate() { + ParameterDefn thisParam; + if (TryGetParameter(xparm, out thisParam)) + { + if (thisParam.onObject != null) + { + foreach (uint lID in xlIDs) + { + BSPhysObject theObject = null; + PhysObjects.TryGetValue(lID, out theObject); + thisParam.onObject(this, theObject, xval); + } + } + } }); - */ } // Get parameter. diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index 5a77e52..bbfdac6 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -51,7 +51,7 @@ public class BSShapeCollection : IDisposable } // Description of a hull. - // Meshes and hulls have the same shape hash key but we only need hulls for efficient physical objects + // Meshes and hulls have the same shape hash key but we only need hulls for efficient collision calculations. private struct HullDesc { public IntPtr ptr; @@ -59,17 +59,9 @@ public class BSShapeCollection : IDisposable public DateTime lastReferenced; } - private struct BodyDesc - { - public IntPtr ptr; - // Bodies are only used once so reference count is always either one or zero - public int referenceCount; - public DateTime lastReferenced; - } - + // The sharable set of meshes and hulls. Indexed by their shape hash. private Dictionary Meshes = new Dictionary(); private Dictionary Hulls = new Dictionary(); - private Dictionary Bodies = new Dictionary(); public BSShapeCollection(BSScene physScene) { @@ -92,6 +84,10 @@ public class BSShapeCollection : IDisposable // First checks the shape and updates that if necessary then makes // sure the body is of the right type. // 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, BulletSim sim, BSPhysObject prim, ShapeData shapeData, PrimitiveBaseShape pbs, @@ -103,7 +99,8 @@ public class BSShapeCollection : IDisposable lock (m_collectionActivityLock) { // Do we have the correct geometry for this type of object? - // Updates prim.BSShape with information/pointers to requested shape + // Updates prim.BSShape with information/pointers to shape. + // CreateGeom returns 'true' of BSShape as changed to a new shape. bool newGeom = CreateGeom(forceRebuild, prim, shapeData, pbs, shapeCallback); // If we had to select a new shape geometry for the object, // rebuild the body around it. @@ -125,35 +122,19 @@ public class BSShapeCollection : IDisposable { lock (m_collectionActivityLock) { - BodyDesc bodyDesc; - if (Bodies.TryGetValue(body.ID, out bodyDesc)) + DetailLog("{0},BSShapeCollection.ReferenceBody,newBody", body.ID, body); + BSScene.TaintCallback createOperation = delegate() { - bodyDesc.referenceCount++; - DetailLog("{0},BSShapeCollection.ReferenceBody,existingBody,body={1},ref={2}", body.ID, body, bodyDesc.referenceCount); - } - else - { - // New entry - bodyDesc.ptr = body.ptr; - bodyDesc.referenceCount = 1; - DetailLog("{0},BSShapeCollection.ReferenceBody,newBody,ref={2}", - body.ID, body, bodyDesc.referenceCount); - BSScene.TaintCallback createOperation = delegate() + if (!BulletSimAPI.IsInWorld2(body.ptr)) { - if (!BulletSimAPI.IsInWorld2(body.ptr)) - { - BulletSimAPI.AddObjectToWorld2(PhysicsScene.World.ptr, body.ptr); - DetailLog("{0},BSShapeCollection.ReferenceBody,addedToWorld,ref={1}", - body.ID, body); - } - }; - if (inTaintTime) - createOperation(); - else - PhysicsScene.TaintedObject("BSShapeCollection.ReferenceBody", createOperation); - } - bodyDesc.lastReferenced = System.DateTime.Now; - Bodies[body.ID] = bodyDesc; + BulletSimAPI.AddObjectToWorld2(PhysicsScene.World.ptr, body.ptr); + DetailLog("{0},BSShapeCollection.ReferenceBody,addedToWorld,ref={1}", body.ID, body); + } + }; + if (inTaintTime) + createOperation(); + else + PhysicsScene.TaintedObject("BSShapeCollection.ReferenceBody", createOperation); } } @@ -166,43 +147,25 @@ public class BSShapeCollection : IDisposable lock (m_collectionActivityLock) { - BodyDesc bodyDesc; - if (Bodies.TryGetValue(body.ID, out bodyDesc)) + BSScene.TaintCallback removeOperation = delegate() { - bodyDesc.referenceCount--; - bodyDesc.lastReferenced = System.DateTime.Now; - Bodies[body.ID] = bodyDesc; - DetailLog("{0},BSShapeCollection.DereferenceBody,ref={1}", body.ID, bodyDesc.referenceCount); - - // If body is no longer being used, free it -- bodies can never be shared. - if (bodyDesc.referenceCount == 0) - { - Bodies.Remove(body.ID); - BSScene.TaintCallback removeOperation = delegate() - { - DetailLog("{0},BSShapeCollection.DereferenceBody,DestroyingBody. ptr={1}, inTaintTime={2}", - body.ID, body.ptr.ToString("X"), inTaintTime); - // If the caller needs to know the old body is going away, pass the event up. - if (bodyCallback != null) bodyCallback(body); - - // It may have already been removed from the world in which case the next is a NOOP. - BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.ptr, body.ptr); - - // Zero any reference to the shape so it is not freed when the body is deleted. - BulletSimAPI.SetCollisionShape2(PhysicsScene.World.ptr, body.ptr, IntPtr.Zero); - BulletSimAPI.DestroyObject2(PhysicsScene.World.ptr, body.ptr); - }; - // If already in taint-time, do the operations now. Otherwise queue for later. - if (inTaintTime) - removeOperation(); - else - PhysicsScene.TaintedObject("BSShapeCollection.DereferenceBody", removeOperation); - } - } + DetailLog("{0},BSShapeCollection.DereferenceBody,DestroyingBody. ptr={1}, inTaintTime={2}", + body.ID, body.ptr.ToString("X"), inTaintTime); + // If the caller needs to know the old body is going away, pass the event up. + if (bodyCallback != null) bodyCallback(body); + + // It may have already been removed from the world in which case the next is a NOOP. + BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.ptr, body.ptr); + + // Zero any reference to the shape so it is not freed when the body is deleted. + BulletSimAPI.SetCollisionShape2(PhysicsScene.World.ptr, body.ptr, IntPtr.Zero); + BulletSimAPI.DestroyObject2(PhysicsScene.World.ptr, body.ptr); + }; + // If already in taint-time, do the operations now. Otherwise queue for later. + if (inTaintTime) + removeOperation(); else - { - DetailLog("{0},BSShapeCollection.DereferenceBody,DID NOT FIND BODY", body.ID, bodyDesc.referenceCount); - } + PhysicsScene.TaintedObject("BSShapeCollection.DereferenceBody", removeOperation); } } @@ -271,7 +234,6 @@ public class BSShapeCollection : IDisposable } // Release the usage of a shape. - // The collisionObject is released since it is a copy of the real collision shape. public void DereferenceShape(BulletShape shape, bool inTaintTime, ShapeDestructionCallback shapeCallback) { if (shape.ptr == IntPtr.Zero) diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs index caf411e..9743d94 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs @@ -334,7 +334,8 @@ public class BSTerrainManager // Make sure the new shape is processed. // BulletSimAPI.Activate2(mapInfo.terrainBody.ptr, true); - BulletSimAPI.ForceActivationState2(mapInfo.terrainBody.ptr, ActivationState.DISABLE_SIMULATION); + BulletSimAPI.ForceActivationState2(mapInfo.terrainBody.ptr, ActivationState.ISLAND_SLEEPING); + // BulletSimAPI.ForceActivationState2(mapInfo.terrainBody.ptr, ActivationState.DISABLE_SIMULATION); m_terrainModified = true; }; -- cgit v1.1 From e87a179c893ef246dae8338e0f56c3fe20458fbc Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Wed, 17 Oct 2012 08:30:10 -0700 Subject: BulletSim: change nonimal physics frame rate to 55 to give same numbers as ODE. Change character scaling to represent size of capsule (diameter rather than radius) Modify create capsule call to pass radius and height. Eliminate errors when calculating shape inertia (should have some type checking). --- .../Region/Physics/BulletSPlugin/BSCharacter.cs | 46 ++++++++++++---------- .../Region/Physics/BulletSPlugin/BSPhysObject.cs | 14 +++---- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 14 +++---- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 26 ++++++------ .../Physics/BulletSPlugin/BSShapeCollection.cs | 7 +++- .../Region/Physics/BulletSPlugin/BulletSimAPI.cs | 2 +- 6 files changed, 57 insertions(+), 52 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index 8e1171a..e7bff6e 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -89,13 +89,15 @@ public class BSCharacter : BSPhysObject _appliedVelocity = OMV.Vector3.Zero; _buoyancy = ComputeBuoyancyFromFlying(isFlying); _currentFriction = PhysicsScene.Params.avatarStandingFriction; + _avatarDensity = PhysicsScene.Params.avatarDensity; // The dimensions of the avatar capsule are kept in the scale. // Physics creates a unit capsule which is scaled by the physics engine. ComputeAvatarScale(_size); - _avatarDensity = PhysicsScene.Params.avatarDensity; // set _avatarVolume and _mass based on capsule size, _density and Scale ComputeAvatarVolumeAndMass(); + DetailLog("{0},BSCharacter.create,call,size={1},scale={2},density={3},volume={4},mass={5}", + LocalID, _size, Scale, _avatarDensity, _avatarVolume, MassRaw); ShapeData shapeData = new ShapeData(); shapeData.ID = LocalID; @@ -103,6 +105,7 @@ public class BSCharacter : BSPhysObject shapeData.Position = _position; shapeData.Rotation = _orientation; shapeData.Velocity = _velocity; + shapeData.Size = Scale; shapeData.Scale = Scale; shapeData.Mass = _mass; shapeData.Buoyancy = _buoyancy; @@ -114,8 +117,9 @@ public class BSCharacter : BSPhysObject PhysicsScene.TaintedObject("BSCharacter.create", delegate() { DetailLog("{0},BSCharacter.create,taint", LocalID); - PhysicsScene.Shapes.GetBodyAndShape(true, PhysicsScene.World, this, shapeData, null, null, null); - + // New body and shape into BSBody and BSShape + PhysicsScene.Shapes.GetBodyAndShape(true, PhysicsScene.World, this, shapeData, null, null, null); + SetPhysicalProperties(); }); return; @@ -138,7 +142,7 @@ public class BSCharacter : BSPhysObject ZeroMotion(); - OMV.Vector3 localInertia = BulletSimAPI.CalculateLocalInertia2(BSShape.ptr, MassRaw); + OMV.Vector3 localInertia = BulletSimAPI.CalculateLocalInertia2(BSShape.ptr, MassRaw); BulletSimAPI.SetMassProps2(BSBody.ptr, MassRaw, localInertia); ForcePosition = _position; @@ -151,13 +155,13 @@ public class BSCharacter : BSPhysObject { BulletSimAPI.SetCcdMotionThreshold2(BSBody.ptr, PhysicsScene.Params.ccdMotionThreshold); BulletSimAPI.SetCcdSweepSphereRadius2(BSBody.ptr, PhysicsScene.Params.ccdSweptSphereRadius); - } - + } + BulletSimAPI.AddToCollisionFlags2(BSBody.ptr, CollisionFlags.CF_CHARACTER_OBJECT); BulletSimAPI.AddObjectToWorld2(PhysicsScene.World.ptr, BSBody.ptr); - BulletSimAPI.ForceActivationState2(BSBody.ptr, ActivationState.DISABLE_DEACTIVATION); + BulletSimAPI.ForceActivationState2(BSBody.ptr, ActivationState.ACTIVE_TAG); BulletSimAPI.UpdateSingleAabb2(PhysicsScene.World.ptr, BSBody.ptr); // Do this after the object has been added to the world @@ -176,7 +180,7 @@ public class BSCharacter : BSPhysObject get { // Avatar capsule size is kept in the scale parameter. - return new OMV.Vector3(Scale.X * 2, Scale.Y * 2, Scale.Z); + return _size; } set { @@ -184,11 +188,13 @@ public class BSCharacter : BSPhysObject _size = value; ComputeAvatarScale(_size); ComputeAvatarVolumeAndMass(); + DetailLog("{0},BSCharacter.setSize,call,scale={1},density={2},volume={3},mass={4}", + LocalID, Scale, _avatarDensity, _avatarVolume, MassRaw); PhysicsScene.TaintedObject("BSCharacter.setSize", delegate() { BulletSimAPI.SetLocalScaling2(BSShape.ptr, Scale); - OMV.Vector3 localInertia = BulletSimAPI.CalculateLocalInertia2(BSBody.ptr, MassRaw); + OMV.Vector3 localInertia = BulletSimAPI.CalculateLocalInertia2(BSShape.ptr, MassRaw); BulletSimAPI.SetMassProps2(BSBody.ptr, MassRaw, localInertia); }); @@ -578,13 +584,13 @@ public class BSCharacter : BSPhysObject private void ComputeAvatarScale(OMV.Vector3 size) { OMV.Vector3 newScale = OMV.Vector3.Zero; - newScale.X = PhysicsScene.Params.avatarCapsuleRadius; - newScale.Y = PhysicsScene.Params.avatarCapsuleRadius; + // Scale wants the diameter so mult radius by two + newScale.X = PhysicsScene.Params.avatarCapsuleRadius * 2f; + newScale.Y = PhysicsScene.Params.avatarCapsuleRadius * 2f; - // The 1.15 came from ODE but it seems to cause the avatar to float off the ground - // Scale.Z = (_size.Z * 1.15f) - (Scale.X + Scale.Y); - // From the total height, remove the capsule half spheres that are at each end - newScale.Z = (size.Z) - (Math.Min(newScale.X, newScale.Y) * 2f); + // From the total height, add the capsule half spheres that are at each end + // newScale.Z = (size.Z) - Math.Min(newScale.X, newScale.Y); + newScale.Z = (size.Z * 2f); Scale = newScale; } @@ -593,14 +599,14 @@ public class BSCharacter : BSPhysObject { _avatarVolume = (float)( Math.PI - * Scale.X - * Scale.Y // the area of capsule cylinder + * (Scale.X / 2f) + * (Scale.Y / 2f) // the area of capsule cylinder * Scale.Z // times height of capsule cylinder + 1.33333333f * Math.PI - * Scale.X - * Math.Min(Scale.X, Scale.Y) - * Scale.Y // plus the volume of the capsule end caps + * (Scale.X / 2f) + * (Math.Min(Scale.X, Scale.Y) / 2f) + * (Scale.Y / 2f) // plus the volume of the capsule end caps ); _mass = _avatarDensity * _avatarVolume; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index 34dec26..b8ef338 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -141,18 +141,15 @@ public abstract class BSPhysObject : PhysicsActor // if someone has subscribed for collision events.... if (SubscribedEvents()) { CollisionCollection.AddCollider(collidingWith, new ContactPoint(contactPoint, contactNormal, pentrationDepth)); - // DetailLog("{0},{1}.Collison.AddCollider,call,with={2},point={3},normal={4},depth={5}", - // LocalID, TypeName, collidingWith, contactPoint, contactNormal, pentrationDepth); + DetailLog("{0},{1}.Collison.AddCollider,call,with={2},point={3},normal={4},depth={5}", + LocalID, TypeName, collidingWith, contactPoint, contactNormal, pentrationDepth); ret = true; } return ret; } - // Routine to send the collected collisions into the simulator. - // Also handles removal of this from the collection of objects with collisions if - // there are no collisions from this object. Mechanism is create one last - // collision event to make collision_end work. + // Send the collected collisions into the simulator. // Called at taint time from within the Step() function thus no locking problems // with CollisionCollection and ObjectsWithNoMoreCollisions. // Return 'true' if there were some actual collisions passed up @@ -161,10 +158,9 @@ public abstract class BSPhysObject : PhysicsActor bool ret = true; // throttle the collisions to the number of milliseconds specified in the subscription - int nowTime = PhysicsScene.SimulationNowTime; - if (nowTime >= NextCollisionOkTime) + if (PhysicsScene.SimulationNowTime >= NextCollisionOkTime) { - NextCollisionOkTime = nowTime + SubscribedEventsMs; + NextCollisionOkTime = PhysicsScene.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. diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index b9e1908..8013e68 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -48,10 +48,10 @@ public sealed class BSPrim : BSPhysObject private PrimitiveBaseShape _pbs; - // _size is what the user passed. _scale is what we pass to the physics engine with the mesh. - // Often _scale is unity because the meshmerizer will apply _size when creating the mesh. + // _size is what the user passed. Scale is what we pass to the physics engine with the mesh. + // Often Scale is unity because the meshmerizer will apply _size when creating the mesh. private OMV.Vector3 _size; // the multiplier for each mesh dimension as passed by the user - private OMV.Vector3 _scale; // the multiplier for each mesh dimension for the mesh as created by the meshmerizer + // private OMV.Vector3 _scale; // the multiplier for each mesh dimension for the mesh as created by the meshmerizer private bool _grabbed; private bool _isSelected; @@ -98,7 +98,7 @@ public sealed class BSPrim : BSPhysObject _physicsActorType = (int)ActorTypes.Prim; _position = pos; _size = size; - _scale = new OMV.Vector3(1f, 1f, 1f); // the scale will be set by CreateGeom depending on object type + Scale = new OMV.Vector3(1f, 1f, 1f); // the scale will be set by CreateGeom depending on object type _orientation = rotation; _buoyancy = 1f; _velocity = OMV.Vector3.Zero; @@ -166,7 +166,7 @@ public sealed class BSPrim : BSPhysObject // Since _size changed, the mesh needs to be rebuilt. If rebuilt, all the correct // scale and margins are set. CreateGeomAndObject(true); - // DetailLog("{0},BSPrim.setSize,size={1},scale={2},mass={3},physical={4}", LocalID, _size, _scale, _mass, IsPhysical); + // DetailLog("{0},BSPrim.setSize,size={1},scale={2},mass={3},physical={4}", LocalID, _size, Scale, _mass, IsPhysical); }); } } @@ -1224,7 +1224,8 @@ public sealed class BSPrim : BSPhysObject shape.Position = _position; shape.Rotation = _orientation; shape.Velocity = _velocity; - shape.Scale = _scale; + shape.Size = _size; + shape.Scale = Scale; shape.Mass = _isPhysical ? _mass : 0f; shape.Buoyancy = _buoyancy; shape.HullKey = 0; @@ -1234,7 +1235,6 @@ public sealed class BSPrim : BSPhysObject shape.Collidable = (!IsPhantom) ? ShapeData.numericTrue : ShapeData.numericFalse; shape.Static = _isPhysical ? ShapeData.numericFalse : ShapeData.numericTrue; shape.Solid = IsSolid ? ShapeData.numericFalse : ShapeData.numericTrue; - shape.Size = _size; } // Rebuild the geometry and object. // This is called when the shape changes so we need to recreate the mesh/hull. diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index c6e8bc4..ab2835c 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -533,7 +533,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters } // This is a kludge to get avatar movement updates. - // the simulator expects collisions for avatars even if there are have been no collisions. This updates + // The simulator expects collisions for avatars even if there are have been no collisions. This 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) @@ -577,9 +577,9 @@ public 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. - // We multiply by 45 to give a recognizable running rate (45 or less). - return numSubSteps * m_fixedTimeStep * 1000 * 45; - // return timeStep * 1000 * 45; + // We multiply by 55 to give a recognizable running rate (55 or less). + return numSubSteps * m_fixedTimeStep * 1000 * 55; + // return timeStep * 1000 * 55; } // Something has collided @@ -795,7 +795,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters delegate void ParamUser(BSScene scene, IConfig conf, string paramName, float val); delegate float ParamGet(BSScene scene); - delegate void ParamSet(BSScene scene, string paramName, uint localID, float val); + delegate void ParamSet(BSScene scene, string paramName, uint localID, float val); delegate void SetOnObject(BSScene scene, BSPhysObject obj, float val); private struct ParameterDefn @@ -805,7 +805,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters public float defaultValue; // default value if not specified anywhere else public ParamUser userParam; // get the value from the configuration file public ParamGet getter; // return the current value stored for this parameter - public ParamSet setter; // set the current value for this parameter + public ParamSet setter; // set the current value for this parameter public SetOnObject onObject; // set the value on an object in the physical domain public ParameterDefn(string n, string d, float v, ParamUser u, ParamGet g, ParamSet s) { @@ -814,7 +814,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters defaultValue = v; userParam = u; getter = g; - setter = s; + setter = s; onObject = null; } public ParameterDefn(string n, string d, float v, ParamUser u, ParamGet g, ParamSet s, SetOnObject o) @@ -824,7 +824,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters defaultValue = v; userParam = u; getter = g; - setter = s; + setter = s; onObject = o; } } @@ -1266,13 +1266,13 @@ public class BSScene : PhysicsScene, IPhysicsParameters objectIDs.Add(TERRAIN_ID); TaintedUpdateParameter(parm, objectIDs, val); break; - case PhysParameterEntry.APPLY_TO_ALL: + case PhysParameterEntry.APPLY_TO_ALL: defaultLoc = val; // setting ALL also sets the default value - lock (PhysObjects) objectIDs = new List(PhysObjects.Keys); + lock (PhysObjects) objectIDs = new List(PhysObjects.Keys); TaintedUpdateParameter(parm, objectIDs, val); break; default: - // setting only one localID + // setting only one localID objectIDs.Add(localID); TaintedUpdateParameter(parm, objectIDs, val); break; @@ -1282,8 +1282,8 @@ public class BSScene : PhysicsScene, IPhysicsParameters // schedule the actual updating of the paramter to when the phys engine is not busy protected void TaintedUpdateParameter(string parm, List lIDs, float val) { - float xval = val; - List xlIDs = lIDs; + float xval = val; + List xlIDs = lIDs; string xparm = parm; TaintedObject("BSScene.UpdateParameterSet", delegate() { ParameterDefn thisParam; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index bbfdac6..3d15eaa 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -417,7 +417,10 @@ public class BSShapeCollection : IDisposable if (shapeType == ShapeData.PhysicsShapeType.SHAPE_AVATAR) { - newShape = new BulletShape(BulletSimAPI.BuildCapsuleShape2(PhysicsScene.World.ptr, shapeData), shapeType); + // The radius is scaled by 1/2 because we scale by the diameter. + newShape = new BulletShape( + BulletSimAPI.BuildCapsuleShape2(PhysicsScene.World.ptr, 0.5f, 1.0f, shapeData.Scale), + shapeType); newShape.shapeKey = (System.UInt64)shapeKey; newShape.isNativeShape = true; } @@ -428,7 +431,7 @@ public class BSShapeCollection : IDisposable newShape.isNativeShape = true; } - // Don't need to do a 'ReferenceShape()' here because native shapes are not tracked. + // Don't need to do a 'ReferenceShape()' here because native shapes are not shared. // DetailLog("{0},BSShapeCollection.AddNativeShapeToPrim,create,newshape={1}", shapeData.ID, newShape); prim.BSShape = newShape; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs index 30754a7..24d8db6 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs @@ -608,7 +608,7 @@ public static extern IntPtr BuildNativeShape2(IntPtr world, ShapeData shapeData) public static extern bool IsNativeShape2(IntPtr shape); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern IntPtr BuildCapsuleShape2(IntPtr world, ShapeData shapeData); +public static extern IntPtr BuildCapsuleShape2(IntPtr world, float radius, float height, Vector3 scale); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern IntPtr CreateCompoundShape2(IntPtr sim); -- cgit v1.1 From f422b9b388fe67c61e610c79efabd5e07512884b Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Fri, 19 Oct 2012 10:48:45 -0700 Subject: BulletSim: reorder avatar collision checking to eliminate double collision_end. Various tweekings to avatar shape/mass/inertia/etc. Remove change from avatar radius to diameter. But still the avatar sinks. Collision_end now happens immediately rather than at the next subscription time. --- .../Region/Physics/BulletSPlugin/BSCharacter.cs | 33 +++++++++++----------- .../Region/Physics/BulletSPlugin/BSPhysObject.cs | 4 ++- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 30 +++++++++++--------- .../Physics/BulletSPlugin/BSShapeCollection.cs | 8 +++--- .../Physics/BulletSPlugin/BSTerrainManager.cs | 1 + .../Region/Physics/BulletSPlugin/BulletSimAPI.cs | 2 +- 6 files changed, 43 insertions(+), 35 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index e7bff6e..fc4526b 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -141,10 +141,6 @@ public class BSCharacter : BSPhysObject BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.ptr, BSBody.ptr); ZeroMotion(); - - OMV.Vector3 localInertia = BulletSimAPI.CalculateLocalInertia2(BSShape.ptr, MassRaw); - BulletSimAPI.SetMassProps2(BSBody.ptr, MassRaw, localInertia); - ForcePosition = _position; // Set the velocity and compute the proper friction ForceVelocity = _velocity; @@ -157,6 +153,9 @@ public class BSCharacter : BSPhysObject BulletSimAPI.SetCcdSweepSphereRadius2(BSBody.ptr, PhysicsScene.Params.ccdSweptSphereRadius); } + OMV.Vector3 localInertia = BulletSimAPI.CalculateLocalInertia2(BSShape.ptr, MassRaw); + BulletSimAPI.SetMassProps2(BSBody.ptr, MassRaw, localInertia); + BulletSimAPI.AddToCollisionFlags2(BSBody.ptr, CollisionFlags.CF_CHARACTER_OBJECT); BulletSimAPI.AddObjectToWorld2(PhysicsScene.World.ptr, BSBody.ptr); @@ -583,14 +582,16 @@ public class BSCharacter : BSPhysObject private void ComputeAvatarScale(OMV.Vector3 size) { + // The 'size' given by the simulator is the mid-point of the avatar + // and X and Y are unspecified. + OMV.Vector3 newScale = OMV.Vector3.Zero; - // Scale wants the diameter so mult radius by two - newScale.X = PhysicsScene.Params.avatarCapsuleRadius * 2f; - newScale.Y = PhysicsScene.Params.avatarCapsuleRadius * 2f; + newScale.X = PhysicsScene.Params.avatarCapsuleRadius; + newScale.Y = PhysicsScene.Params.avatarCapsuleRadius; - // From the total height, add the capsule half spheres that are at each end - // newScale.Z = (size.Z) - Math.Min(newScale.X, newScale.Y); - newScale.Z = (size.Z * 2f); + // From the total height, remote the capsule half spheres that are at each end + newScale.Z = (size.Z * 2f) - Math.Min(newScale.X, newScale.Y); + // newScale.Z = (size.Z * 2f); Scale = newScale; } @@ -599,14 +600,14 @@ public class BSCharacter : BSPhysObject { _avatarVolume = (float)( Math.PI - * (Scale.X / 2f) - * (Scale.Y / 2f) // the area of capsule cylinder - * Scale.Z // times height of capsule cylinder + * Scale.X + * Scale.Y // the area of capsule cylinder + * Scale.Z // times height of capsule cylinder + 1.33333333f * Math.PI - * (Scale.X / 2f) - * (Math.Min(Scale.X, Scale.Y) / 2f) - * (Scale.Y / 2f) // plus the volume of the capsule end caps + * Scale.X + * Math.Min(Scale.X, Scale.Y) + * Scale.Y // plus the volume of the capsule end caps ); _mass = _avatarDensity * _avatarVolume; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index b8ef338..202052d 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -156,9 +156,11 @@ public abstract class BSPhysObject : PhysicsActor public virtual bool SendCollisions() { bool ret = true; + // If the 'no collision' call, force it to happen right now so quick collision_end + bool force = CollisionCollection.Count == 0; // throttle the collisions to the number of milliseconds specified in the subscription - if (PhysicsScene.SimulationNowTime >= NextCollisionOkTime) + if (force || (PhysicsScene.SimulationNowTime >= NextCollisionOkTime)) { NextCollisionOkTime = PhysicsScene.SimulationNowTime + SubscribedEventsMs; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index ab2835c..6621d39 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -532,26 +532,26 @@ public class BSScene : PhysicsScene, IPhysicsParameters } } - // This is a kludge to get avatar movement updates. - // The simulator expects collisions for avatars even if there are have been no collisions. This 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) - bsp.SendCollisions(); - // 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 (!m_avatars.Contains(bsp)) // don't call avatars twice - if (!bsp.SendCollisions()) - { - // If the object is done colliding, see that it's removed from the colliding list - ObjectsWithNoMoreCollisions.Add(bsp); - } + 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. if (ObjectsWithNoMoreCollisions.Count > 0) @@ -575,6 +575,10 @@ public class BSScene : PhysicsScene, IPhysicsParameters } } + // This 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. + // BulletSimAPI.DumpAllInfo2(World.ptr); // DEBUG DEBUG DEBUG + // 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. // We multiply by 55 to give a recognizable running rate (55 or less). diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index 3d15eaa..861ffe7 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -417,10 +417,9 @@ public class BSShapeCollection : IDisposable if (shapeType == ShapeData.PhysicsShapeType.SHAPE_AVATAR) { - // The radius is scaled by 1/2 because we scale by the diameter. newShape = new BulletShape( - BulletSimAPI.BuildCapsuleShape2(PhysicsScene.World.ptr, 0.5f, 1.0f, shapeData.Scale), - shapeType); + BulletSimAPI.BuildCapsuleShape2(PhysicsScene.World.ptr, 1.0f, 1.0f, shapeData.Scale), + shapeType); newShape.shapeKey = (System.UInt64)shapeKey; newShape.isNativeShape = true; } @@ -432,7 +431,8 @@ public class BSShapeCollection : IDisposable } // Don't need to do a 'ReferenceShape()' here because native shapes are not shared. - // DetailLog("{0},BSShapeCollection.AddNativeShapeToPrim,create,newshape={1}", shapeData.ID, newShape); + DetailLog("{0},BSShapeCollection.AddNativeShapeToPrim,create,newshape={1},scale={2}", + shapeData.ID, newShape, shapeData.Scale); prim.BSShape = newShape; return true; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs index 9743d94..4106534 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs @@ -114,6 +114,7 @@ public class BSTerrainManager BulletSimAPI.CreateBodyWithDefaultMotionState2(groundPlaneShape.ptr, BSScene.GROUNDPLANE_ID, Vector3.Zero, Quaternion.Identity)); BulletSimAPI.AddObjectToWorld2(PhysicsScene.World.ptr, m_groundPlane.ptr); + BulletSimAPI.UpdateSingleAabb2(PhysicsScene.World.ptr, m_groundPlane.ptr); // Ground plane does not move BulletSimAPI.ForceActivationState2(m_groundPlane.ptr, ActivationState.DISABLE_SIMULATION); // Everything collides with the ground plane. diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs index 24d8db6..5ffd591 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs @@ -390,7 +390,7 @@ public enum CollisionFilterGroups : uint VolumeDetectMask = ~BSensorTrigger, TerrainFilter = BTerrainFilter, TerrainMask = BAllFilter & ~BStaticFilter, - GroundPlaneFilter = BAllFilter, + GroundPlaneFilter = BGroundPlaneFilter, GroundPlaneMask = BAllFilter }; -- cgit v1.1 From d94c4646ccf0703019dd5a7915afb43706a4de35 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Fri, 19 Oct 2012 15:43:31 -0700 Subject: BulletSim: add asset fetching so BulletSim works with new physics asset handling. Refactor some names to make them available for the asset tracking and fetching. --- .../Region/Physics/BulletSPlugin/BSCharacter.cs | 3 +- .../Region/Physics/BulletSPlugin/BSPhysObject.cs | 10 + OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 96 +++---- .../Physics/BulletSPlugin/BSShapeCollection.cs | 296 +++++++++++++-------- 4 files changed, 240 insertions(+), 165 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index fc4526b..623ac8f 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -200,10 +200,9 @@ public class BSCharacter : BSPhysObject } } public override OMV.Vector3 Scale { get; set; } - private PrimitiveBaseShape _pbs; public override PrimitiveBaseShape Shape { - set { _pbs = value;} + set { BaseShape = value; } } public override bool Grabbed { diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index 202052d..ead6a08 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -47,6 +47,7 @@ public abstract class BSPhysObject : PhysicsActor TypeName = typeName; Linkset = new BSLinkset(PhysicsScene, this); + LastAssetBuildFailed = false; CollisionCollection = new CollisionEventUpdate(); SubscribedEventsMs = 0; @@ -69,6 +70,13 @@ public abstract class BSPhysObject : PhysicsActor // Reference to the physical shape (btCollisionShape) of this object public BulletShape BSShape; + // 'true' if the mesh's underlying asset failed to build. + // This will keep us from looping after the first time the build failed. + public bool LastAssetBuildFailed { get; set; } + + // The objects base shape information. Null if not a prim type shape. + public PrimitiveBaseShape BaseShape { get; protected set; } + // 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. @@ -101,6 +109,8 @@ public abstract class BSPhysObject : PhysicsActor public abstract float ForceBuoyancy { get; set; } + public virtual bool ForceBodyShapeRebuild(bool inTaintTime) { return false; } + #region Collisions // Requested number of milliseconds between collision events. Zero means disabled. diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 8013e68..aeeb4dd 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -46,8 +46,6 @@ public sealed class BSPrim : BSPhysObject private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static readonly string LogHeader = "[BULLETS PRIM]"; - private PrimitiveBaseShape _pbs; - // _size is what the user passed. Scale is what we pass to the physics engine with the mesh. // Often Scale is unity because the meshmerizer will apply _size when creating the mesh. private OMV.Vector3 _size; // the multiplier for each mesh dimension as passed by the user @@ -103,7 +101,7 @@ public sealed class BSPrim : BSPhysObject _buoyancy = 1f; _velocity = OMV.Vector3.Zero; _rotationalVelocity = OMV.Vector3.Zero; - _pbs = pbs; + BaseShape = pbs; _isPhysical = pisPhysical; _isVolumeDetect = false; _friction = PhysicsScene.Params.defaultFriction; // TODO: compute based on object material @@ -160,14 +158,7 @@ public sealed class BSPrim : BSPhysObject get { return _size; } set { _size = value; - PhysicsScene.TaintedObject("BSPrim.setSize", delegate() - { - _mass = CalculateMass(); // changing size changes the mass - // Since _size changed, the mesh needs to be rebuilt. If rebuilt, all the correct - // scale and margins are set. - CreateGeomAndObject(true); - // DetailLog("{0},BSPrim.setSize,size={1},scale={2},mass={3},physical={4}", LocalID, _size, Scale, _mass, IsPhysical); - }); + ForceBodyShapeRebuild(false); } } // Scale is what we set in the physics engine. It is different than 'size' in that @@ -176,14 +167,23 @@ public sealed class BSPrim : BSPhysObject public override PrimitiveBaseShape Shape { set { - _pbs = value; - PhysicsScene.TaintedObject("BSPrim.setShape", delegate() - { - _mass = CalculateMass(); // changing the shape changes the mass - CreateGeomAndObject(true); - }); + BaseShape = value; + ForceBodyShapeRebuild(false); } } + public override bool ForceBodyShapeRebuild(bool inTaintTime) + { + BSScene.TaintCallback rebuildOperation = delegate() + { + _mass = CalculateMass(); // changing the shape changes the mass + CreateGeomAndObject(true); + }; + if (inTaintTime) + rebuildOperation(); + else + PhysicsScene.TaintedObject("BSPrim.ForceBodyShapeRebuild", rebuildOperation); + return true; + } public override bool Grabbed { set { _grabbed = value; } @@ -924,19 +924,19 @@ public sealed class BSPrim : BSPhysObject float tmp; float returnMass = 0; - float hollowAmount = (float)_pbs.ProfileHollow * 2.0e-5f; + float hollowAmount = (float)BaseShape.ProfileHollow * 2.0e-5f; float hollowVolume = hollowAmount * hollowAmount; - switch (_pbs.ProfileShape) + switch (BaseShape.ProfileShape) { case ProfileShape.Square: // default box - if (_pbs.PathCurve == (byte)Extrusion.Straight) + if (BaseShape.PathCurve == (byte)Extrusion.Straight) { if (hollowAmount > 0.0) { - switch (_pbs.HollowShape) + switch (BaseShape.HollowShape) { case HollowShape.Square: case HollowShape.Same: @@ -960,19 +960,19 @@ public sealed class BSPrim : BSPhysObject } } - else if (_pbs.PathCurve == (byte)Extrusion.Curve1) + else if (BaseShape.PathCurve == (byte)Extrusion.Curve1) { //a tube - volume *= 0.78539816339e-2f * (float)(200 - _pbs.PathScaleX); - tmp= 1.0f -2.0e-2f * (float)(200 - _pbs.PathScaleY); + volume *= 0.78539816339e-2f * (float)(200 - BaseShape.PathScaleX); + tmp= 1.0f -2.0e-2f * (float)(200 - BaseShape.PathScaleY); volume -= volume*tmp*tmp; if (hollowAmount > 0.0) { hollowVolume *= hollowAmount; - switch (_pbs.HollowShape) + switch (BaseShape.HollowShape) { case HollowShape.Square: case HollowShape.Same: @@ -997,13 +997,13 @@ public sealed class BSPrim : BSPhysObject case ProfileShape.Circle: - if (_pbs.PathCurve == (byte)Extrusion.Straight) + if (BaseShape.PathCurve == (byte)Extrusion.Straight) { volume *= 0.78539816339f; // elipse base if (hollowAmount > 0.0) { - switch (_pbs.HollowShape) + switch (BaseShape.HollowShape) { case HollowShape.Same: case HollowShape.Circle: @@ -1025,10 +1025,10 @@ public sealed class BSPrim : BSPhysObject } } - else if (_pbs.PathCurve == (byte)Extrusion.Curve1) + else if (BaseShape.PathCurve == (byte)Extrusion.Curve1) { - volume *= 0.61685027506808491367715568749226e-2f * (float)(200 - _pbs.PathScaleX); - tmp = 1.0f - .02f * (float)(200 - _pbs.PathScaleY); + volume *= 0.61685027506808491367715568749226e-2f * (float)(200 - BaseShape.PathScaleX); + tmp = 1.0f - .02f * (float)(200 - BaseShape.PathScaleY); volume *= (1.0f - tmp * tmp); if (hollowAmount > 0.0) @@ -1037,7 +1037,7 @@ public sealed class BSPrim : BSPhysObject // calculate the hollow volume by it's shape compared to the prim shape hollowVolume *= hollowAmount; - switch (_pbs.HollowShape) + switch (BaseShape.HollowShape) { case HollowShape.Same: case HollowShape.Circle: @@ -1061,7 +1061,7 @@ public sealed class BSPrim : BSPhysObject break; case ProfileShape.HalfCircle: - if (_pbs.PathCurve == (byte)Extrusion.Curve1) + if (BaseShape.PathCurve == (byte)Extrusion.Curve1) { volume *= 0.52359877559829887307710723054658f; } @@ -1069,7 +1069,7 @@ public sealed class BSPrim : BSPhysObject case ProfileShape.EquilateralTriangle: - if (_pbs.PathCurve == (byte)Extrusion.Straight) + if (BaseShape.PathCurve == (byte)Extrusion.Straight) { volume *= 0.32475953f; @@ -1077,7 +1077,7 @@ public sealed class BSPrim : BSPhysObject { // calculate the hollow volume by it's shape compared to the prim shape - switch (_pbs.HollowShape) + switch (BaseShape.HollowShape) { case HollowShape.Same: case HollowShape.Triangle: @@ -1102,11 +1102,11 @@ public sealed class BSPrim : BSPhysObject volume *= (1.0f - hollowVolume); } } - else if (_pbs.PathCurve == (byte)Extrusion.Curve1) + else if (BaseShape.PathCurve == (byte)Extrusion.Curve1) { volume *= 0.32475953f; - volume *= 0.01f * (float)(200 - _pbs.PathScaleX); - tmp = 1.0f - .02f * (float)(200 - _pbs.PathScaleY); + volume *= 0.01f * (float)(200 - BaseShape.PathScaleX); + tmp = 1.0f - .02f * (float)(200 - BaseShape.PathScaleY); volume *= (1.0f - tmp * tmp); if (hollowAmount > 0.0) @@ -1114,7 +1114,7 @@ public sealed class BSPrim : BSPhysObject hollowVolume *= hollowAmount; - switch (_pbs.HollowShape) + switch (BaseShape.HollowShape) { case HollowShape.Same: case HollowShape.Triangle: @@ -1154,26 +1154,26 @@ public sealed class BSPrim : BSPhysObject float profileBegin; float profileEnd; - if (_pbs.PathCurve == (byte)Extrusion.Straight || _pbs.PathCurve == (byte)Extrusion.Flexible) + if (BaseShape.PathCurve == (byte)Extrusion.Straight || BaseShape.PathCurve == (byte)Extrusion.Flexible) { - taperX1 = _pbs.PathScaleX * 0.01f; + taperX1 = BaseShape.PathScaleX * 0.01f; if (taperX1 > 1.0f) taperX1 = 2.0f - taperX1; taperX = 1.0f - taperX1; - taperY1 = _pbs.PathScaleY * 0.01f; + taperY1 = BaseShape.PathScaleY * 0.01f; if (taperY1 > 1.0f) taperY1 = 2.0f - taperY1; taperY = 1.0f - taperY1; } else { - taperX = _pbs.PathTaperX * 0.01f; + taperX = BaseShape.PathTaperX * 0.01f; if (taperX < 0.0f) taperX = -taperX; taperX1 = 1.0f - taperX; - taperY = _pbs.PathTaperY * 0.01f; + taperY = BaseShape.PathTaperY * 0.01f; if (taperY < 0.0f) taperY = -taperY; taperY1 = 1.0f - taperY; @@ -1183,13 +1183,13 @@ public sealed class BSPrim : BSPhysObject volume *= (taperX1 * taperY1 + 0.5f * (taperX1 * taperY + taperX * taperY1) + 0.3333333333f * taperX * taperY); - pathBegin = (float)_pbs.PathBegin * 2.0e-5f; - pathEnd = 1.0f - (float)_pbs.PathEnd * 2.0e-5f; + pathBegin = (float)BaseShape.PathBegin * 2.0e-5f; + pathEnd = 1.0f - (float)BaseShape.PathEnd * 2.0e-5f; volume *= (pathEnd - pathBegin); // this is crude aproximation - profileBegin = (float)_pbs.ProfileBegin * 2.0e-5f; - profileEnd = 1.0f - (float)_pbs.ProfileEnd * 2.0e-5f; + profileBegin = (float)BaseShape.ProfileBegin * 2.0e-5f; + profileEnd = 1.0f - (float)BaseShape.ProfileEnd * 2.0e-5f; volume *= (profileEnd - profileBegin); returnMass = _density * volume; @@ -1251,7 +1251,7 @@ public sealed class BSPrim : BSPhysObject // Create the correct physical representation for this type of object. // Updates BSBody and BSShape with the new information. // Ignore 'forceRebuild'. This routine makes the right choices and changes of necessary. - PhysicsScene.Shapes.GetBodyAndShape(false, PhysicsScene.World, this, shapeData, _pbs, + PhysicsScene.Shapes.GetBodyAndShape(false, PhysicsScene.World, this, shapeData, BaseShape, null, delegate(BulletBody dBody) { // Called if the current prim body is about to be destroyed. diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index 861ffe7..d3ba273 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -117,7 +117,7 @@ public class BSShapeCollection : IDisposable // Track another user of a body // We presume the caller has allocated the body. - // Bodies only have one user so the reference count is either 1 or 0. + // Bodies only have one user so the body is just put into the world if not already there. public void ReferenceBody(BulletBody body, bool inTaintTime) { lock (m_collectionActivityLock) @@ -241,26 +241,32 @@ public class BSShapeCollection : IDisposable BSScene.TaintCallback dereferenceOperation = delegate() { - switch (shape.type) + if (shape.ptr != IntPtr.Zero) { - case ShapeData.PhysicsShapeType.SHAPE_HULL: - DereferenceHull(shape, shapeCallback); - break; - case ShapeData.PhysicsShapeType.SHAPE_MESH: - DereferenceMesh(shape, shapeCallback); - break; - case ShapeData.PhysicsShapeType.SHAPE_UNKNOWN: - break; - default: + if (shape.isNativeShape) + { // Native shapes are not tracked and are released immediately - if (shape.ptr != IntPtr.Zero & shape.isNativeShape) + DetailLog("{0},BSShapeCollection.DereferenceShape,deleteNativeShape,ptr={1},taintTime={2}", + BSScene.DetailLogZero, shape.ptr.ToString("X"), inTaintTime); + if (shapeCallback != null) shapeCallback(shape); + BulletSimAPI.DeleteCollisionShape2(PhysicsScene.World.ptr, shape.ptr); + } + else + { + switch (shape.type) { - DetailLog("{0},BSShapeCollection.DereferenceShape,deleteNativeShape,ptr={1},taintTime={2}", - BSScene.DetailLogZero, shape.ptr.ToString("X"), inTaintTime); - if (shapeCallback != null) shapeCallback(shape); - BulletSimAPI.DeleteCollisionShape2(PhysicsScene.World.ptr, shape.ptr); + case ShapeData.PhysicsShapeType.SHAPE_HULL: + DereferenceHull(shape, shapeCallback); + break; + case ShapeData.PhysicsShapeType.SHAPE_MESH: + DereferenceMesh(shape, shapeCallback); + break; + case ShapeData.PhysicsShapeType.SHAPE_UNKNOWN: + break; + default: + break; } - break; + } } }; if (inTaintTime) @@ -405,7 +411,6 @@ public class BSShapeCollection : IDisposable ShapeData.PhysicsShapeType shapeType, ShapeData.FixedShapeKey shapeKey, ShapeDestructionCallback shapeCallback) { - BulletShape newShape; shapeData.Type = shapeType; // Bullet native objects are scaled by the Bullet engine so pass the size in @@ -415,27 +420,35 @@ public class BSShapeCollection : IDisposable // release any previous shape DereferenceShape(prim.BSShape, true, shapeCallback); + BulletShape newShape = BuildPhysicalNativeShape(shapeType, shapeData, shapeKey); + + // Don't need to do a 'ReferenceShape()' here because native shapes are not shared. + DetailLog("{0},BSShapeCollection.AddNativeShapeToPrim,create,newshape={1},scale={2}", + shapeData.ID, newShape, shapeData.Scale); + + prim.BSShape = newShape; + return true; + } + + private BulletShape BuildPhysicalNativeShape(ShapeData.PhysicsShapeType shapeType, + ShapeData shapeData, ShapeData.FixedShapeKey shapeKey) + { + BulletShape newShape; + if (shapeType == ShapeData.PhysicsShapeType.SHAPE_AVATAR) { newShape = new BulletShape( BulletSimAPI.BuildCapsuleShape2(PhysicsScene.World.ptr, 1.0f, 1.0f, shapeData.Scale), shapeType); - newShape.shapeKey = (System.UInt64)shapeKey; - newShape.isNativeShape = true; } else { newShape = new BulletShape(BulletSimAPI.BuildNativeShape2(PhysicsScene.World.ptr, shapeData), shapeType); - newShape.shapeKey = (System.UInt64)shapeKey; - newShape.isNativeShape = true; } + newShape.shapeKey = (System.UInt64)shapeKey; + newShape.isNativeShape = true; - // Don't need to do a 'ReferenceShape()' here because native shapes are not shared. - DetailLog("{0},BSShapeCollection.AddNativeShapeToPrim,create,newshape={1},scale={2}", - shapeData.ID, newShape, shapeData.Scale); - - prim.BSShape = newShape; - return true; + return newShape; } // Builds a mesh shape in the physical world and updates prim.BSShape. @@ -461,6 +474,8 @@ public class BSShapeCollection : IDisposable DereferenceShape(prim.BSShape, true, shapeCallback); newShape = CreatePhysicalMesh(prim.PhysObjectName, newMeshKey, pbs, shapeData.Size, lod); + // Take evasive action if the mesh was not constructed. + newShape = VerifyMeshCreated(newShape, prim, shapeData, pbs); ReferenceShape(newShape); @@ -474,7 +489,7 @@ public class BSShapeCollection : IDisposable private BulletShape CreatePhysicalMesh(string objName, System.UInt64 newMeshKey, PrimitiveBaseShape pbs, OMV.Vector3 size, float lod) { IMesh meshData = null; - IntPtr meshPtr; + IntPtr meshPtr = IntPtr.Zero; MeshDesc meshDesc; if (Meshes.TryGetValue(newMeshKey, out meshDesc)) { @@ -486,23 +501,26 @@ public class BSShapeCollection : IDisposable // Pass false for physicalness as this creates some sort of bounding box which we don't need meshData = PhysicsScene.mesher.CreateMesh(objName, pbs, size, lod, false); - int[] indices = meshData.getIndexListAsInt(); - List vertices = meshData.getVertexList(); - - float[] verticesAsFloats = new float[vertices.Count * 3]; - int vi = 0; - foreach (OMV.Vector3 vv in vertices) + if (meshData != null) { - verticesAsFloats[vi++] = vv.X; - verticesAsFloats[vi++] = vv.Y; - verticesAsFloats[vi++] = vv.Z; - } + int[] indices = meshData.getIndexListAsInt(); + List vertices = meshData.getVertexList(); - // m_log.DebugFormat("{0}: CreateGeomMesh: calling CreateMesh. lid={1}, key={2}, indices={3}, vertices={4}", - // LogHeader, prim.LocalID, newMeshKey, indices.Length, vertices.Count); + float[] verticesAsFloats = new float[vertices.Count * 3]; + int vi = 0; + foreach (OMV.Vector3 vv in vertices) + { + verticesAsFloats[vi++] = vv.X; + verticesAsFloats[vi++] = vv.Y; + verticesAsFloats[vi++] = vv.Z; + } + + // m_log.DebugFormat("{0}: CreateGeomMesh: calling CreateMesh. lid={1}, key={2}, indices={3}, vertices={4}", + // LogHeader, prim.LocalID, newMeshKey, indices.Length, vertices.Count); - meshPtr = BulletSimAPI.CreateMeshShape2(PhysicsScene.World.ptr, - indices.GetLength(0), indices, vertices.Count, verticesAsFloats); + meshPtr = BulletSimAPI.CreateMeshShape2(PhysicsScene.World.ptr, + indices.GetLength(0), indices, vertices.Count, verticesAsFloats); + } } BulletShape newShape = new BulletShape(meshPtr, ShapeData.PhysicsShapeType.SHAPE_MESH); newShape.shapeKey = newMeshKey; @@ -531,6 +549,7 @@ public class BSShapeCollection : IDisposable DereferenceShape(prim.BSShape, true, shapeCallback); newShape = CreatePhysicalHull(prim.PhysObjectName, newHullKey, pbs, shapeData.Size, lod); + newShape = VerifyMeshCreated(newShape, prim, shapeData, pbs); ReferenceShape(newShape); @@ -544,7 +563,7 @@ public class BSShapeCollection : IDisposable private BulletShape CreatePhysicalHull(string objName, System.UInt64 newHullKey, PrimitiveBaseShape pbs, OMV.Vector3 size, float lod) { - IntPtr hullPtr; + IntPtr hullPtr = IntPtr.Zero; HullDesc hullDesc; if (Hulls.TryGetValue(newHullKey, out hullDesc)) { @@ -556,86 +575,89 @@ public class BSShapeCollection : IDisposable // Build a new hull in the physical world // Pass false for physicalness as this creates some sort of bounding box which we don't need IMesh meshData = PhysicsScene.mesher.CreateMesh(objName, pbs, size, lod, false); - - 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) + if (meshData != null) { - 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; - ConvexBuilder convexBuilder = new ConvexBuilder(HullReturn); - // create the hull into the _hulls variable - convexBuilder.process(dcomp); - - // 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]; + int[] indices = meshData.getIndexListAsInt(); + List vertices = meshData.getVertexList(); - 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) + //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++) { - verts[kk++] = ff; + convIndices.Add(indices[ii]); + } + foreach (OMV.Vector3 vv in vertices) + { + convVertices.Add(new float3(vv.X, vv.Y, vv.Z)); } - // 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) + // setup and do convex hull conversion + m_hulls = new List(); + DecompDesc dcomp = new DecompDesc(); + dcomp.mIndices = convIndices; + dcomp.mVertices = convVertices; + ConvexBuilder convexBuilder = new ConvexBuilder(HullReturn); + // create the hull into the _hulls variable + convexBuilder.process(dcomp); + + // 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[jj++] = verts[ind].x; - convHulls[jj++] = verts[ind].y; - convHulls[jj++] = verts[ind].z; + 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 + hullPtr = BulletSimAPI.CreateHullShape2(PhysicsScene.World.ptr, hullCount, convHulls); } - // create the hull data structure in Bullet - hullPtr = BulletSimAPI.CreateHullShape2(PhysicsScene.World.ptr, hullCount, convHulls); } BulletShape newShape = new BulletShape(hullPtr, ShapeData.PhysicsShapeType.SHAPE_HULL); @@ -676,6 +698,50 @@ public class BSShapeCollection : IDisposable return ComputeShapeKey(shapeData, pbs, out lod); } + private BulletShape VerifyMeshCreated(BulletShape newShape, BSPhysObject prim, ShapeData shapeData, PrimitiveBaseShape pbs) + { + // If the shape was successfully created, nothing more to do + if (newShape.ptr != IntPtr.Zero) + return newShape; + + // The most common reason for failure is that an underlying asset is not available + + // If this mesh has an underlying asset and we have not failed getting it before, fetch the asset + if (pbs.SculptEntry && !prim.LastAssetBuildFailed && pbs.SculptTexture != OMV.UUID.Zero) + { + prim.LastAssetBuildFailed = true; + 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) + { + if (!yprim.BaseShape.SculptEntry) + return; + if (yprim.BaseShape.SculptTexture.ToString() != asset.ID) + return; + + yprim.BaseShape.SculptData = new byte[asset.Data.Length]; + asset.Data.CopyTo(yprim.BaseShape.SculptData, 0); + // This will cause the prim to see that the filler shape is not the right + // one and try again to build the object. + yprim.ForceBodyShapeRebuild(false); + + }); + } + }); + } + + // While we figure out the real problem, stick a simple native shape on the object. + BulletShape fillinShape = + BuildPhysicalNativeShape(ShapeData.PhysicsShapeType.SHAPE_SPHERE, shapeData, ShapeData.FixedShapeKey.KEY_SPHERE); + + 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. -- cgit v1.1 From d2b19f00dafe2c7c89c07b6a713fdd359cf9dcab Mon Sep 17 00:00:00 2001 From: Justin Clark-Casey (justincc) Date: Sat, 20 Oct 2012 02:49:16 +0100 Subject: Fix minor issues from commit 28483150 Fix spelling of collide, change to more self-documenting property BadMeshAssetCollideBits, add method doc, change to private to reduce code analysis complexity --- OpenSim/Region/Physics/OdePlugin/ODEPrim.cs | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs b/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs index 5a1fdf9..d11dff1 100644 --- a/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs +++ b/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs @@ -67,6 +67,17 @@ namespace OpenSim.Region.Physics.OdePlugin private int m_expectedCollisionContacts = 0; /// + /// Gets collide bits so that we can still perform land collisions if a mesh fails to load. + /// + /// + /// The bad asset collide bits. + /// + private int BadMeshAssetCollideBits + { + get { return m_isphysical ? (int)CollisionCategories.Land : 0; } + } + + /// /// Is this prim subject to physics? Even if not, it's still solid for collision purposes. /// public override bool IsPhysical @@ -344,11 +355,10 @@ namespace OpenSim.Region.Physics.OdePlugin if (m_assetFailed) { d.GeomSetCategoryBits(prim_geom, 0); - d.GeomSetCollideBits(prim_geom, BadAssetColideBits()); + d.GeomSetCollideBits(prim_geom, BadMeshAssetCollideBits); } else { - d.GeomSetCategoryBits(prim_geom, (int)m_collisionCategories); d.GeomSetCollideBits(prim_geom, (int)m_collisionFlags); } @@ -418,7 +428,7 @@ namespace OpenSim.Region.Physics.OdePlugin if (m_assetFailed) { d.GeomSetCategoryBits(prim_geom, 0); - d.GeomSetCollideBits(prim_geom, BadAssetColideBits()); + d.GeomSetCollideBits(prim_geom, BadMeshAssetCollideBits); } else { @@ -851,11 +861,6 @@ namespace OpenSim.Region.Physics.OdePlugin private static Dictionary m_MeshToTriMeshMap = new Dictionary(); - public int BadAssetColideBits() - { - return (m_isphysical ? (int)CollisionCategories.Land : 0); - } - private void setMesh(OdeScene parent_scene, IMesh mesh) { // m_log.DebugFormat("[ODE PRIM]: Setting mesh on {0} to {1}", Name, mesh); @@ -1137,7 +1142,7 @@ Console.WriteLine("ZProcessTaints for " + Name); if (prm.m_assetFailed) { d.GeomSetCategoryBits(prm.prim_geom, 0); - d.GeomSetCollideBits(prm.prim_geom, prm.BadAssetColideBits()); + d.GeomSetCollideBits(prm.prim_geom, prm.BadMeshAssetCollideBits); } else { @@ -1191,7 +1196,7 @@ Console.WriteLine("ZProcessTaints for " + Name); if (m_assetFailed) { d.GeomSetCategoryBits(prim_geom, 0); - d.GeomSetCollideBits(prim_geom, BadAssetColideBits()); + d.GeomSetCollideBits(prim_geom, BadMeshAssetCollideBits); } else { @@ -1393,7 +1398,7 @@ Console.WriteLine("ZProcessTaints for " + Name); if (m_assetFailed) { d.GeomSetCategoryBits(prim_geom, 0); - d.GeomSetCollideBits(prim_geom, BadAssetColideBits()); + d.GeomSetCollideBits(prim_geom, BadMeshAssetCollideBits); } else { @@ -2137,7 +2142,7 @@ Console.WriteLine(" JointCreateFixed"); } if (m_assetFailed) - d.GeomSetCollideBits(prim_geom, BadAssetColideBits()); + d.GeomSetCollideBits(prim_geom, BadMeshAssetCollideBits); else d.GeomSetCollideBits(prim_geom, (int)m_collisionFlags); -- cgit v1.1 From 5bc07a15f508f4860de4defd328f23c4300b33c0 Mon Sep 17 00:00:00 2001 From: Justin Clark-Casey (justincc) Date: Sat, 20 Oct 2012 02:52:38 +0100 Subject: minor: remove unnecessary bit of method doc from OdePrim.BadMeshAssetCollideBits that monodevelop inserted automatically --- OpenSim/Region/Physics/OdePlugin/ODEPrim.cs | 3 --- 1 file changed, 3 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs b/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs index d11dff1..2548648 100644 --- a/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs +++ b/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs @@ -69,9 +69,6 @@ namespace OpenSim.Region.Physics.OdePlugin /// /// Gets collide bits so that we can still perform land collisions if a mesh fails to load. /// - /// - /// The bad asset collide bits. - /// private int BadMeshAssetCollideBits { get { return m_isphysical ? (int)CollisionCategories.Land : 0; } -- cgit v1.1 From a61f20ac74836049cbd24397670c2dcd75fb22da Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Sun, 21 Oct 2012 16:12:06 -0700 Subject: BulletSim: Create LinkSet abstract class and sparate constraint based linksets into own subclass. Will eventually add manual movement linkset subclass. --- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 355 ++---------------- .../Physics/BulletSPlugin/BSLinksetConstraints.cs | 396 +++++++++++++++++++++ .../Region/Physics/BulletSPlugin/BSPhysObject.cs | 2 +- 3 files changed, 434 insertions(+), 319 deletions(-) create mode 100755 OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index 43b1262..2e6b104 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -32,10 +32,27 @@ using OMV = OpenMetaverse; namespace OpenSim.Region.Physics.BulletSPlugin { -public class BSLinkset +public abstract class BSLinkset { // private static string LogHeader = "[BULLETSIM LINKSET]"; + // Create the correct type of linkset for this child + public static BSLinkset Factory(BSScene physScene, BSPhysObject parent) + { + BSLinkset ret = null; + /* + if (parent.IsPhysical) + ret = new BSLinksetConstraints(physScene, parent); + else + ret = new BSLinksetManual(physScene, parent); + */ + + // at the moment, there is only one + ret = new BSLinksetConstraints(physScene, parent); + + return ret; + } + public BSPhysObject LinksetRoot { get; protected set; } public BSScene PhysicsScene { get; private set; } @@ -52,16 +69,16 @@ public class BSLinkset // the physical 'taint' children separately. // After taint processing and before the simulation step, these // two lists must be the same. - private HashSet m_children; - private HashSet m_taintChildren; + protected HashSet m_children; + protected HashSet m_taintChildren; // We lock the diddling of linkset classes to prevent any badness. // This locks the modification of the instances of this class. Changes // to the physical representation is done via the tainting mechenism. - private object m_linksetActivityLock = new Object(); + protected object m_linksetActivityLock = new Object(); // We keep the prim's mass in the linkset structure since it could be dependent on other prims - private float m_mass; + protected float m_mass; public float LinksetMass { get @@ -81,7 +98,7 @@ public class BSLinkset get { return ComputeLinksetGeometricCenter(); } } - public BSLinkset(BSScene scene, BSPhysObject parent) + protected void Initialize(BSScene scene, BSPhysObject parent) { // A simple linkset of one (no children) LinksetID = m_nextLinksetID++; @@ -128,7 +145,7 @@ public class BSLinkset } // The child is down to a linkset of just itself - return new BSLinkset(PhysicsScene, child); + return BSLinkset.Factory(PhysicsScene, child); } // Return 'true' if the passed object is the root object of this linkset @@ -163,24 +180,7 @@ public class BSLinkset // When physical properties are changed the linkset needs to recalculate // its internal properties. // May be called at runtime or taint-time (just pass the appropriate flag). - public void Refresh(BSPhysObject requestor, bool inTaintTime) - { - // If there are no children, not physical or not root, I am not the one that recomputes the constraints - // (For the moment, static linksets do create constraints so remove the test for physical.) - if (!HasAnyChildren || /*!requestor.IsPhysical ||*/ !IsRoot(requestor)) - return; - - BSScene.TaintCallback refreshOperation = delegate() - { - RecomputeLinksetConstraintVariables(); - DetailLog("{0},BSLinkset.Refresh,complete,rBody={1}", - LinksetRoot.LocalID, LinksetRoot.BSBody.ptr.ToString("X")); - }; - if (inTaintTime) - refreshOperation(); - else - PhysicsScene.TaintedObject("BSLinkSet.Refresh", refreshOperation); - } + public abstract void Refresh(BSPhysObject requestor, bool inTaintTime); // The object is going dynamic (physical). Do any setup necessary // for a dynamic linkset. @@ -188,102 +188,36 @@ public class BSLinkset // has not yet been fully constructed. // Return 'true' if any properties updated on the passed object. // Called at taint-time! - public bool MakeDynamic(BSPhysObject child) - { - // What is done for each object in BSPrim is what we want. - return false; - } + public abstract bool MakeDynamic(BSPhysObject child); // The object is going static (non-physical). Do any setup necessary // for a static linkset. // Return 'true' if any properties updated on the passed object. // Called at taint-time! - public bool MakeStatic(BSPhysObject child) - { - // What is done for each object in BSPrim is what we want. - return false; - } + public abstract bool MakeStatic(BSPhysObject child); // If the software is handling the movement of all the objects in a linkset // (like if one doesn't use constraints for static linksets), this is called // when an update for the root of the linkset is received. // Called at taint-time!! - public void UpdateProperties(BSPhysObject physObject) - { - // The root local properties have been updated. Apply to the children if appropriate. - if (IsRoot(physObject) && HasAnyChildren) - { - if (!physObject.IsPhysical) - { - // TODO: implement software linkset update for static object linksets - } - } - } + public abstract void UpdateProperties(BSPhysObject physObject); // Routine used when rebuilding the body of the root of the linkset // Destroy all the constraints have have been made to root. // This is called when the root body is changing. // Returns 'true' of something eas actually removed and would need restoring // Called at taint-time!! - public bool RemoveBodyDependencies(BSPrim child) - { - bool ret = false; - - lock (m_linksetActivityLock) - { - if (IsRoot(child)) - { - // If the one with the dependency is root, must undo all children - DetailLog("{0},BSLinkset.RemoveBodyDependencies,removeChildrenForRoot,rID={1},rBody={2}", - child.LocalID, LinksetRoot.LocalID, LinksetRoot.BSBody.ptr.ToString("X")); - - ret = PhysicallyUnlinkAllChildrenFromRoot(LinksetRoot); - } - else - { - DetailLog("{0},BSLinkset.RemoveBodyDependencies,removeSingleChild,rID={1},rBody={2},cID={3},cBody={4}", - child.LocalID, - LinksetRoot.LocalID, LinksetRoot.BSBody.ptr.ToString("X"), - child.LocalID, child.BSBody.ptr.ToString("X")); - // ret = PhysicallyUnlinkAChildFromRoot(LinksetRoot, child); - // Despite the function name, this removes any link to the specified object. - ret = PhysicallyUnlinkAllChildrenFromRoot(child); - } - } - return ret; - } + public abstract bool RemoveBodyDependencies(BSPrim child); // Companion to RemoveBodyDependencies(). If RemoveBodyDependencies() returns 'true', // this routine will restore the removed constraints. // Called at taint-time!! - public void RestoreBodyDependencies(BSPrim child) - { - lock (m_linksetActivityLock) - { - if (IsRoot(child)) - { - DetailLog("{0},BSLinkset.RestoreBodyDependencies,restoreChildrenForRoot,rID={1},numChild={2}", - child.LocalID, LinksetRoot.LocalID, m_taintChildren.Count); - foreach (BSPhysObject bpo in m_taintChildren) - { - PhysicallyLinkAChildToRoot(LinksetRoot, bpo); - } - } - else - { - DetailLog("{0},BSLinkset.RestoreBodyDependencies,restoreSingleChild,rID={1},rBody={2},cID={3},cBody={4}", - LinksetRoot.LocalID, - LinksetRoot.LocalID, LinksetRoot.BSBody.ptr.ToString("X"), - child.LocalID, child.BSBody.ptr.ToString("X")); - PhysicallyLinkAChildToRoot(LinksetRoot, child); - } - } - } + public abstract void RestoreBodyDependencies(BSPrim child); // ================================================================ // Below this point is internal magic - private float ComputeLinksetMass() + protected virtual float ComputeLinksetMass() { float mass; lock (m_linksetActivityLock) @@ -297,7 +231,7 @@ public class BSLinkset return mass; } - private OMV.Vector3 ComputeLinksetCenterOfMass() + protected virtual OMV.Vector3 ComputeLinksetCenterOfMass() { OMV.Vector3 com; lock (m_linksetActivityLock) @@ -317,7 +251,7 @@ public class BSLinkset return com; } - private OMV.Vector3 ComputeLinksetGeometricCenter() + protected virtual OMV.Vector3 ComputeLinksetGeometricCenter() { OMV.Vector3 com; lock (m_linksetActivityLock) @@ -336,236 +270,21 @@ public class BSLinkset // I am the root of a linkset and a new child is being added // Called while LinkActivity is locked. - private void AddChildToLinkset(BSPhysObject child) - { - if (!HasChild(child)) - { - m_children.Add(child); - - BSPhysObject rootx = LinksetRoot; // capture the root as of now - BSPhysObject childx = child; - - DetailLog("{0},AddChildToLinkset,call,child={1}", LinksetRoot.LocalID, child.LocalID); - - PhysicsScene.TaintedObject("AddChildToLinkset", delegate() - { - DetailLog("{0},AddChildToLinkset,taint,rID={1},rBody={2},cID={3},cBody={4}", - rootx.LocalID, - rootx.LocalID, rootx.BSBody.ptr.ToString("X"), - childx.LocalID, childx.BSBody.ptr.ToString("X")); - // Since this is taint-time, the body and shape could have changed for the child - rootx.ForcePosition = rootx.Position; // DEBUG - childx.ForcePosition = childx.Position; // DEBUG - PhysicallyLinkAChildToRoot(rootx, childx); - m_taintChildren.Add(child); - }); - } - return; - } + protected abstract void AddChildToLinkset(BSPhysObject child); // Forcefully removing a child from a linkset. // This is not being called by the child so we have to make sure the child doesn't think // it's still connected to the linkset. // Normal OpenSimulator operation will never do this because other SceneObjectPart information // also has to be updated (like pointer to prim's parent). - private void RemoveChildFromOtherLinkset(BSPhysObject pchild) - { - pchild.Linkset = new BSLinkset(PhysicsScene, pchild); - RemoveChildFromLinkset(pchild); - } + protected abstract void RemoveChildFromOtherLinkset(BSPhysObject pchild); // 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. - private void RemoveChildFromLinkset(BSPhysObject child) - { - if (m_children.Remove(child)) - { - BSPhysObject rootx = LinksetRoot; // capture the root and body as of now - BSPhysObject childx = child; - - DetailLog("{0},RemoveChildFromLinkset,call,rID={1},rBody={2},cID={3},cBody={4}", - childx.LocalID, - rootx.LocalID, rootx.BSBody.ptr.ToString("X"), - childx.LocalID, childx.BSBody.ptr.ToString("X")); - - PhysicsScene.TaintedObject("RemoveChildFromLinkset", delegate() - { - m_taintChildren.Remove(child); - PhysicallyUnlinkAChildFromRoot(rootx, childx); - RecomputeLinksetConstraintVariables(); - }); - - } - else - { - // This will happen if we remove the root of the linkset first. Non-fatal occurance. - // PhysicsScene.Logger.ErrorFormat("{0}: Asked to remove child from linkset that was not in linkset", LogHeader); - } - return; - } - - // Create a constraint between me (root of linkset) and the passed prim (the child). - // Called at taint time! - private void PhysicallyLinkAChildToRoot(BSPhysObject rootPrim, BSPhysObject childPrim) - { - // Zero motion for children so they don't interpolate - childPrim.ZeroMotion(); - - // 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},BSLinkset.PhysicallyLinkAChildToRoot,taint,root={1},rBody={2},child={3},cBody={4},rLoc={5},cLoc={6},midLoc={7}", - rootPrim.LocalID, - rootPrim.LocalID, rootPrim.BSBody.ptr.ToString("X"), - childPrim.LocalID, childPrim.BSBody.ptr.ToString("X"), - 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 - - BS6DofConstraint constrain = new BS6DofConstraint( - PhysicsScene.World, rootPrim.BSBody, childPrim.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 as a warning to 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); - - // create a constraint that allows no freedom of movement between the two objects - // http://bulletphysics.org/Bullet/phpBB3/viewtopic.php?t=4818 - DetailLog("{0},BSLinkset.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), - // A point half way between the parent and child - // childRelativePosition/2, - // childRelativeRotation, - // childRelativePosition/2, - // inverseChildRelativeRotation, - true, - true - ); - // ================================================================================== - */ - - 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); - constrain.SetAngularLimits(OMV.Vector3.Zero, OMV.Vector3.Zero); - - // tweek the constraint to increase stability - constrain.UseFrameOffset(PhysicsScene.BoolNumeric(PhysicsScene.Params.linkConstraintUseFrameOffset)); - constrain.TranslationalLimitMotor(PhysicsScene.BoolNumeric(PhysicsScene.Params.linkConstraintEnableTransMotor), - PhysicsScene.Params.linkConstraintTransMotorMaxVel, - PhysicsScene.Params.linkConstraintTransMotorMaxForce); - constrain.SetCFMAndERP(PhysicsScene.Params.linkConstraintCFM, PhysicsScene.Params.linkConstraintERP); - if (PhysicsScene.Params.linkConstraintSolverIterations != 0f) - { - constrain.SetSolverIterations(PhysicsScene.Params.linkConstraintSolverIterations); - } - } - - // Remove linkage between myself and a particular child - // The root and child bodies are passed in because we need to remove the constraint between - // the bodies that were at unlink time. - // Called at taint time! - private bool PhysicallyUnlinkAChildFromRoot(BSPhysObject rootPrim, BSPhysObject childPrim) - { - bool ret = false; - DetailLog("{0},BSLinkset.PhysicallyUnlinkAChildFromRoot,taint,root={1},rBody={2},child={3},cBody={4}", - rootPrim.LocalID, - rootPrim.LocalID, rootPrim.BSBody.ptr.ToString("X"), - childPrim.LocalID, childPrim.BSBody.ptr.ToString("X")); - - // Find the constraint for this link and get rid of it from the overall collection and from my list - if (PhysicsScene.Constraints.RemoveAndDestroyConstraint(rootPrim.BSBody, childPrim.BSBody)) - { - // Make the child refresh its location - BulletSimAPI.PushUpdate2(childPrim.BSBody.ptr); - ret = true; - } - - return ret; - } - - // Remove linkage between myself and any possible children I might have. - // Called at taint time! - private bool PhysicallyUnlinkAllChildrenFromRoot(BSPhysObject rootPrim) - { - DetailLog("{0},BSLinkset.PhysicallyUnlinkAllChildren,taint", rootPrim.LocalID); - bool ret = false; - - if (PhysicsScene.Constraints.RemoveAndDestroyConstraint(rootPrim.BSBody)) - { - ret = true; - } - return ret; - } - - // Call each of the constraints that make up this linkset and recompute the - // various transforms and variables. Used when objects are added or removed - // from a linkset to make sure the constraints know about the new mass and - // geometry. - // Must only be called at taint time!! - private void RecomputeLinksetConstraintVariables() - { - float linksetMass = LinksetMass; - foreach (BSPhysObject child in m_taintChildren) - { - BSConstraint constrain; - if (PhysicsScene.Constraints.TryGetConstraint(LinksetRoot.BSBody, child.BSBody, out constrain)) - { - // DetailLog("{0},BSLinkset.RecomputeLinksetConstraintVariables,taint,child={1},mass={2},A={3},B={4}", - // LinksetRoot.LocalID, child.LocalID, linksetMass, constrain.Body1.ID, constrain.Body2.ID); - constrain.RecomputeConstraintVariables(linksetMass); - } - else - { - // Non-fatal error that happens when children are being added to the linkset but - // their constraints have not been created yet. - break; - } - } - - // If the whole linkset is not here, doesn't make sense to recompute linkset wide values - if (m_children.Count == m_taintChildren.Count) - { - // If this is a multiple object linkset, set everybody's center of mass to the set's center of mass - OMV.Vector3 centerOfMass = ComputeLinksetCenterOfMass(); - BulletSimAPI.SetCenterOfMassByPosRot2(LinksetRoot.BSBody.ptr, - centerOfMass, OMV.Quaternion.Identity); - DetailLog("{0},BSLinkset.RecomputeLinksetConstraintVariables,setCenterOfMass,COM={1},rBody={2}", - LinksetRoot.LocalID, centerOfMass, LinksetRoot.BSBody.ptr.ToString("X")); - foreach (BSPhysObject child in m_taintChildren) - { - BulletSimAPI.SetCenterOfMassByPosRot2(child.BSBody.ptr, - centerOfMass, OMV.Quaternion.Identity); - } - - // BulletSimAPI.DumpAllInfo2(PhysicsScene.World.ptr); // DEBUG DEBUG DEBUG - } - return; - } - + protected abstract void RemoveChildFromLinkset(BSPhysObject child); // Invoke the detailed logger and output something if it's enabled. - private void DetailLog(string msg, params Object[] args) + protected void DetailLog(string msg, params Object[] args) { if (PhysicsScene.PhysicsLogging.Enabled) PhysicsScene.DetailLog(msg, args); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs new file mode 100755 index 0000000..ee53d92 --- /dev/null +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs @@ -0,0 +1,396 @@ +/* + * 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 OMV = OpenMetaverse; + +namespace OpenSim.Region.Physics.BulletSPlugin +{ +public class BSLinksetConstraints : BSLinkset +{ + // private static string LogHeader = "[BULLETSIM LINKSET CONSTRAINTS]"; + + public BSLinksetConstraints(BSScene scene, BSPhysObject parent) + { + base.Initialize(scene, parent); + } + + // When physical properties are changed the linkset needs to recalculate + // its internal properties. + // May be called at runtime or taint-time (just pass the appropriate flag). + public override void Refresh(BSPhysObject requestor, bool inTaintTime) + { + // If there are no children, not physical or not root, I am not the one that recomputes the constraints + // (For the moment, static linksets do create constraints so remove the test for physical.) + if (!HasAnyChildren || /*!requestor.IsPhysical ||*/ !IsRoot(requestor)) + return; + + BSScene.TaintCallback refreshOperation = delegate() + { + RecomputeLinksetConstraintVariables(); + DetailLog("{0},BSLinkset.Refresh,complete,rBody={1}", + LinksetRoot.LocalID, LinksetRoot.BSBody.ptr.ToString("X")); + }; + if (inTaintTime) + refreshOperation(); + else + PhysicsScene.TaintedObject("BSLinkSet.Refresh", refreshOperation); + } + + // The object is going dynamic (physical). Do any setup necessary + // for a dynamic linkset. + // Only the state of the passed object can be modified. The rest of the linkset + // has not yet been fully constructed. + // Return 'true' if any properties updated on the passed object. + // Called at taint-time! + public override bool MakeDynamic(BSPhysObject child) + { + // 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. + // Return 'true' if any properties updated on the passed object. + // Called at taint-time! + public override bool MakeStatic(BSPhysObject child) + { + // What is done for each object in BSPrim is what we want. + return false; + } + + // If the software is handling the movement of all the objects in a linkset + // (like if one doesn't use constraints for static linksets), this is called + // when an update for the root of the linkset is received. + // Called at taint-time!! + public override void UpdateProperties(BSPhysObject physObject) + { + // The root local properties have been updated. Apply to the children if appropriate. + if (IsRoot(physObject) && HasAnyChildren) + { + if (!physObject.IsPhysical) + { + // TODO: implement software linkset update for static object linksets + } + } + } + + // Routine used when rebuilding the body of the root of the linkset + // Destroy all the constraints have have been made to root. + // This is called when the root body is changing. + // Returns 'true' of something eas actually removed and would need restoring + // Called at taint-time!! + public override bool RemoveBodyDependencies(BSPrim child) + { + bool ret = false; + + lock (m_linksetActivityLock) + { + if (IsRoot(child)) + { + // If the one with the dependency is root, must undo all children + DetailLog("{0},BSLinkset.RemoveBodyDependencies,removeChildrenForRoot,rID={1},rBody={2}", + child.LocalID, LinksetRoot.LocalID, LinksetRoot.BSBody.ptr.ToString("X")); + + ret = PhysicallyUnlinkAllChildrenFromRoot(LinksetRoot); + } + else + { + DetailLog("{0},BSLinkset.RemoveBodyDependencies,removeSingleChild,rID={1},rBody={2},cID={3},cBody={4}", + child.LocalID, + LinksetRoot.LocalID, LinksetRoot.BSBody.ptr.ToString("X"), + child.LocalID, child.BSBody.ptr.ToString("X")); + // ret = PhysicallyUnlinkAChildFromRoot(LinksetRoot, child); + // Despite the function name, this removes any link to the specified object. + ret = PhysicallyUnlinkAllChildrenFromRoot(child); + } + } + return ret; + } + + // Companion to RemoveBodyDependencies(). If RemoveBodyDependencies() returns 'true', + // this routine will restore the removed constraints. + // Called at taint-time!! + public override void RestoreBodyDependencies(BSPrim child) + { + lock (m_linksetActivityLock) + { + if (IsRoot(child)) + { + DetailLog("{0},BSLinkset.RestoreBodyDependencies,restoreChildrenForRoot,rID={1},numChild={2}", + child.LocalID, LinksetRoot.LocalID, m_taintChildren.Count); + foreach (BSPhysObject bpo in m_taintChildren) + { + PhysicallyLinkAChildToRoot(LinksetRoot, bpo); + } + } + else + { + DetailLog("{0},BSLinkset.RestoreBodyDependencies,restoreSingleChild,rID={1},rBody={2},cID={3},cBody={4}", + LinksetRoot.LocalID, + LinksetRoot.LocalID, LinksetRoot.BSBody.ptr.ToString("X"), + child.LocalID, child.BSBody.ptr.ToString("X")); + PhysicallyLinkAChildToRoot(LinksetRoot, child); + } + } + } + + // ================================================================ + // Below this point is internal magic + + // I am the root of a linkset and a new child is being added + // Called while LinkActivity is locked. + protected override void AddChildToLinkset(BSPhysObject child) + { + if (!HasChild(child)) + { + m_children.Add(child); + + BSPhysObject rootx = LinksetRoot; // capture the root as of now + BSPhysObject childx = child; + + DetailLog("{0},AddChildToLinkset,call,child={1}", LinksetRoot.LocalID, child.LocalID); + + PhysicsScene.TaintedObject("AddChildToLinkset", delegate() + { + DetailLog("{0},AddChildToLinkset,taint,rID={1},rBody={2},cID={3},cBody={4}", + rootx.LocalID, + rootx.LocalID, rootx.BSBody.ptr.ToString("X"), + childx.LocalID, childx.BSBody.ptr.ToString("X")); + // Since this is taint-time, the body and shape could have changed for the child + rootx.ForcePosition = rootx.Position; // DEBUG + childx.ForcePosition = childx.Position; // DEBUG + PhysicallyLinkAChildToRoot(rootx, childx); + m_taintChildren.Add(child); + }); + } + return; + } + + // Forcefully removing a child from a linkset. + // This is not being called by the child so we have to make sure the child doesn't think + // it's still connected to the linkset. + // Normal OpenSimulator operation will never do this because other SceneObjectPart information + // also has to be updated (like pointer to prim's parent). + protected override void RemoveChildFromOtherLinkset(BSPhysObject pchild) + { + pchild.Linkset = BSLinkset.Factory(PhysicsScene, pchild); + RemoveChildFromLinkset(pchild); + } + + // 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 override void RemoveChildFromLinkset(BSPhysObject child) + { + if (m_children.Remove(child)) + { + BSPhysObject rootx = LinksetRoot; // capture the root and body as of now + BSPhysObject childx = child; + + DetailLog("{0},RemoveChildFromLinkset,call,rID={1},rBody={2},cID={3},cBody={4}", + childx.LocalID, + rootx.LocalID, rootx.BSBody.ptr.ToString("X"), + childx.LocalID, childx.BSBody.ptr.ToString("X")); + + PhysicsScene.TaintedObject("RemoveChildFromLinkset", delegate() + { + m_taintChildren.Remove(child); + PhysicallyUnlinkAChildFromRoot(rootx, childx); + RecomputeLinksetConstraintVariables(); + }); + + } + else + { + // This will happen if we remove the root of the linkset first. Non-fatal occurance. + // PhysicsScene.Logger.ErrorFormat("{0}: Asked to remove child from linkset that was not in linkset", LogHeader); + } + return; + } + + // Create a constraint between me (root of linkset) and the passed prim (the child). + // Called at taint time! + private void PhysicallyLinkAChildToRoot(BSPhysObject rootPrim, BSPhysObject childPrim) + { + // Zero motion for children so they don't interpolate + childPrim.ZeroMotion(); + + // 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},BSLinkset.PhysicallyLinkAChildToRoot,taint,root={1},rBody={2},child={3},cBody={4},rLoc={5},cLoc={6},midLoc={7}", + rootPrim.LocalID, + rootPrim.LocalID, rootPrim.BSBody.ptr.ToString("X"), + childPrim.LocalID, childPrim.BSBody.ptr.ToString("X"), + 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 + + BS6DofConstraint constrain = new BS6DofConstraint( + PhysicsScene.World, rootPrim.BSBody, childPrim.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 as a warning to 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); + + // create a constraint that allows no freedom of movement between the two objects + // http://bulletphysics.org/Bullet/phpBB3/viewtopic.php?t=4818 + DetailLog("{0},BSLinkset.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), + // A point half way between the parent and child + // childRelativePosition/2, + // childRelativeRotation, + // childRelativePosition/2, + // inverseChildRelativeRotation, + true, + true + ); + // ================================================================================== + */ + + 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); + constrain.SetAngularLimits(OMV.Vector3.Zero, OMV.Vector3.Zero); + + // tweek the constraint to increase stability + constrain.UseFrameOffset(PhysicsScene.BoolNumeric(PhysicsScene.Params.linkConstraintUseFrameOffset)); + constrain.TranslationalLimitMotor(PhysicsScene.BoolNumeric(PhysicsScene.Params.linkConstraintEnableTransMotor), + PhysicsScene.Params.linkConstraintTransMotorMaxVel, + PhysicsScene.Params.linkConstraintTransMotorMaxForce); + constrain.SetCFMAndERP(PhysicsScene.Params.linkConstraintCFM, PhysicsScene.Params.linkConstraintERP); + if (PhysicsScene.Params.linkConstraintSolverIterations != 0f) + { + constrain.SetSolverIterations(PhysicsScene.Params.linkConstraintSolverIterations); + } + } + + // Remove linkage between myself and a particular child + // The root and child bodies are passed in because we need to remove the constraint between + // the bodies that were at unlink time. + // Called at taint time! + private bool PhysicallyUnlinkAChildFromRoot(BSPhysObject rootPrim, BSPhysObject childPrim) + { + bool ret = false; + DetailLog("{0},BSLinkset.PhysicallyUnlinkAChildFromRoot,taint,root={1},rBody={2},child={3},cBody={4}", + rootPrim.LocalID, + rootPrim.LocalID, rootPrim.BSBody.ptr.ToString("X"), + childPrim.LocalID, childPrim.BSBody.ptr.ToString("X")); + + // Find the constraint for this link and get rid of it from the overall collection and from my list + if (PhysicsScene.Constraints.RemoveAndDestroyConstraint(rootPrim.BSBody, childPrim.BSBody)) + { + // Make the child refresh its location + BulletSimAPI.PushUpdate2(childPrim.BSBody.ptr); + ret = true; + } + + return ret; + } + + // Remove linkage between myself and any possible children I might have. + // Called at taint time! + private bool PhysicallyUnlinkAllChildrenFromRoot(BSPhysObject rootPrim) + { + DetailLog("{0},BSLinkset.PhysicallyUnlinkAllChildren,taint", rootPrim.LocalID); + bool ret = false; + + if (PhysicsScene.Constraints.RemoveAndDestroyConstraint(rootPrim.BSBody)) + { + ret = true; + } + return ret; + } + + // Call each of the constraints that make up this linkset and recompute the + // various transforms and variables. Used when objects are added or removed + // from a linkset to make sure the constraints know about the new mass and + // geometry. + // Must only be called at taint time!! + private void RecomputeLinksetConstraintVariables() + { + float linksetMass = LinksetMass; + foreach (BSPhysObject child in m_taintChildren) + { + BSConstraint constrain; + if (PhysicsScene.Constraints.TryGetConstraint(LinksetRoot.BSBody, child.BSBody, out constrain)) + { + // DetailLog("{0},BSLinkset.RecomputeLinksetConstraintVariables,taint,child={1},mass={2},A={3},B={4}", + // LinksetRoot.LocalID, child.LocalID, linksetMass, constrain.Body1.ID, constrain.Body2.ID); + constrain.RecomputeConstraintVariables(linksetMass); + } + else + { + // Non-fatal error that happens when children are being added to the linkset but + // their constraints have not been created yet. + break; + } + } + + // If the whole linkset is not here, doesn't make sense to recompute linkset wide values + if (m_children.Count == m_taintChildren.Count) + { + // If this is a multiple object linkset, set everybody's center of mass to the set's center of mass + OMV.Vector3 centerOfMass = ComputeLinksetCenterOfMass(); + BulletSimAPI.SetCenterOfMassByPosRot2(LinksetRoot.BSBody.ptr, + centerOfMass, OMV.Quaternion.Identity); + DetailLog("{0},BSLinkset.RecomputeLinksetConstraintVariables,setCenterOfMass,COM={1},rBody={2}", + LinksetRoot.LocalID, centerOfMass, LinksetRoot.BSBody.ptr.ToString("X")); + foreach (BSPhysObject child in m_taintChildren) + { + BulletSimAPI.SetCenterOfMassByPosRot2(child.BSBody.ptr, + centerOfMass, OMV.Quaternion.Identity); + } + + // BulletSimAPI.DumpAllInfo2(PhysicsScene.World.ptr); // DEBUG DEBUG DEBUG + } + return; + } +} +} diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index ead6a08..51b9196 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -46,7 +46,7 @@ public abstract class BSPhysObject : PhysicsActor PhysObjectName = name; TypeName = typeName; - Linkset = new BSLinkset(PhysicsScene, this); + Linkset = BSLinkset.Factory(PhysicsScene, this); LastAssetBuildFailed = false; CollisionCollection = new CollisionEventUpdate(); -- cgit v1.1 From c245178eeee530e2be90ef9395ee885e0a79b7df Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Sun, 21 Oct 2012 16:13:22 -0700 Subject: BulletSim: encorporate UBit's suggestion to save a copy of mesh raw data. --- OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index d3ba273..7b808eb 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -724,8 +724,7 @@ public class BSShapeCollection : IDisposable if (yprim.BaseShape.SculptTexture.ToString() != asset.ID) return; - yprim.BaseShape.SculptData = new byte[asset.Data.Length]; - asset.Data.CopyTo(yprim.BaseShape.SculptData, 0); + 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. yprim.ForceBodyShapeRebuild(false); -- cgit v1.1 From 65c131c4a362bed347a6240184ce40b9ddeaaae1 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Mon, 22 Oct 2012 08:23:21 -0700 Subject: BulletSim: remove trailing spaces to make git happy. --- OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs | 10 +++++----- OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs | 2 +- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 10 +++++----- .../Physics/BulletSPlugin/BSLinksetConstraints.cs | 10 +++++----- OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs | 6 +++--- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 10 +++++----- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 4 ++-- .../Physics/BulletSPlugin/BSShapeCollection.cs | 20 ++++++++++---------- 8 files changed, 36 insertions(+), 36 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index 623ac8f..07dd613 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -165,7 +165,7 @@ public class BSCharacter : BSPhysObject // Do this after the object has been added to the world BulletSimAPI.SetCollisionFilterMask2(BSBody.ptr, - (uint)CollisionFilterGroups.AvatarFilter, + (uint)CollisionFilterGroups.AvatarFilter, (uint)CollisionFilterGroups.AvatarMask); } @@ -269,7 +269,7 @@ public class BSCharacter : BSPhysObject private bool PositionSanityCheck() { bool ret = false; - + // If below the ground, move the avatar up float terrainHeight = PhysicsScene.TerrainManager.GetTerrainHeightAtXYZ(_position); if (Position.Z < terrainHeight) @@ -413,7 +413,7 @@ public class BSCharacter : BSPhysObject }); } } - // Go directly to Bullet to get/set the value. + // Go directly to Bullet to get/set the value. public override OMV.Quaternion ForceOrientation { get @@ -478,7 +478,7 @@ public class BSCharacter : BSPhysObject set { _collidingObj = value; } } public override bool FloatOnWater { - set { + set { _floatOnWater = value; PhysicsScene.TaintedObject("BSCharacter.setFloatOnWater", delegate() { @@ -588,7 +588,7 @@ public class BSCharacter : BSPhysObject newScale.X = PhysicsScene.Params.avatarCapsuleRadius; newScale.Y = PhysicsScene.Params.avatarCapsuleRadius; - // From the total height, remote the capsule half spheres that are at each end + // From the total height, remote the capsule half spheres that are at each end newScale.Z = (size.Z * 2f) - Math.Min(newScale.X, newScale.Y); // newScale.Z = (size.Z * 2f); Scale = newScale; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs b/OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs index a20be3a..b58745a 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs @@ -53,7 +53,7 @@ public abstract class BSConstraint : IDisposable { bool success = BulletSimAPI.DestroyConstraint2(m_world.ptr, m_constraint.ptr); m_world.physicsScene.DetailLog("{0},BSConstraint.Dispose,taint,id1={1},body1={2},id2={3},body2={4},success={5}", - BSScene.DetailLogZero, + BSScene.DetailLogZero, m_body1.ID, m_body1.ptr.ToString("X"), m_body2.ID, m_body2.ptr.ToString("X"), success); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index 56342b8..f71f3b0 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -23,7 +23,7 @@ * 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. - */ + * /* RA: June 14, 2011. Copied from ODEDynamics.cs and converted to * call the BulletSim system. @@ -352,7 +352,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin // m_bankingMix = 1; // m_bankingTimescale = 1; // m_referenceFrame = Quaternion.Identity; - m_flags |= (VehicleFlag.NO_DEFLECTION_UP + m_flags |= (VehicleFlag.NO_DEFLECTION_UP | VehicleFlag.LIMIT_ROLL_ONLY | VehicleFlag.LIMIT_MOTOR_UP); m_flags &= ~(VehicleFlag.HOVER_WATER_ONLY | VehicleFlag.HOVER_TERRAIN_ONLY | VehicleFlag.HOVER_GLOBAL_HEIGHT); @@ -382,7 +382,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin // m_bankingTimescale = 1; // m_referenceFrame = Quaternion.Identity; m_flags &= ~(VehicleFlag.HOVER_TERRAIN_ONLY - | VehicleFlag.HOVER_GLOBAL_HEIGHT + | VehicleFlag.HOVER_GLOBAL_HEIGHT | VehicleFlag.LIMIT_ROLL_ONLY | VehicleFlag.HOVER_UP_ONLY); m_flags |= (VehicleFlag.NO_DEFLECTION_UP @@ -458,7 +458,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin // Do any updating needed for a vehicle public void Refresh() { - if (!IsActive) + if (!IsActive) return; // Set the prim's inertia to zero. The vehicle code handles that and this @@ -791,7 +791,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin // Sum velocities m_lastAngularVelocity = m_angularMotorVelocity + vertattr; // + bank + deflection - + if ((m_flags & (VehicleFlag.NO_DEFLECTION_UP)) != 0) { m_lastAngularVelocity.X = 0; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs index ee53d92..8eeeb73 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs @@ -54,7 +54,7 @@ public class BSLinksetConstraints : BSLinkset BSScene.TaintCallback refreshOperation = delegate() { RecomputeLinksetConstraintVariables(); - DetailLog("{0},BSLinkset.Refresh,complete,rBody={1}", + DetailLog("{0},BSLinkset.Refresh,complete,rBody={1}", LinksetRoot.LocalID, LinksetRoot.BSBody.ptr.ToString("X")); }; if (inTaintTime) @@ -179,7 +179,7 @@ public class BSLinksetConstraints : BSLinkset PhysicsScene.TaintedObject("AddChildToLinkset", delegate() { - DetailLog("{0},AddChildToLinkset,taint,rID={1},rBody={2},cID={3},cBody={4}", + DetailLog("{0},AddChildToLinkset,taint,rID={1},rBody={2},cID={3},cBody={4}", rootx.LocalID, rootx.LocalID, rootx.BSBody.ptr.ToString("X"), childx.LocalID, childx.BSBody.ptr.ToString("X")); @@ -213,7 +213,7 @@ public class BSLinksetConstraints : BSLinkset BSPhysObject rootx = LinksetRoot; // capture the root and body as of now BSPhysObject childx = child; - DetailLog("{0},RemoveChildFromLinkset,call,rID={1},rBody={2},cID={3},cBody={4}", + DetailLog("{0},RemoveChildFromLinkset,call,rID={1},rBody={2},cID={3},cBody={4}", childx.LocalID, rootx.LocalID, rootx.BSBody.ptr.ToString("X"), childx.LocalID, childx.BSBody.ptr.ToString("X")); @@ -378,13 +378,13 @@ public class BSLinksetConstraints : BSLinkset { // If this is a multiple object linkset, set everybody's center of mass to the set's center of mass OMV.Vector3 centerOfMass = ComputeLinksetCenterOfMass(); - BulletSimAPI.SetCenterOfMassByPosRot2(LinksetRoot.BSBody.ptr, + BulletSimAPI.SetCenterOfMassByPosRot2(LinksetRoot.BSBody.ptr, centerOfMass, OMV.Quaternion.Identity); DetailLog("{0},BSLinkset.RecomputeLinksetConstraintVariables,setCenterOfMass,COM={1},rBody={2}", LinksetRoot.LocalID, centerOfMass, LinksetRoot.BSBody.ptr.ToString("X")); foreach (BSPhysObject child in m_taintChildren) { - BulletSimAPI.SetCenterOfMassByPosRot2(child.BSBody.ptr, + BulletSimAPI.SetCenterOfMassByPosRot2(child.BSBody.ptr, centerOfMass, OMV.Quaternion.Identity); } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index 51b9196..538f905 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -78,7 +78,7 @@ public abstract class BSPhysObject : PhysicsActor public PrimitiveBaseShape BaseShape { get; protected set; } // When the physical properties are updated, an EntityProperty holds the update values. - // Keep the current and last EntityProperties to enable computation of differences + // Keep the current and last EntityProperties to enable computation of differences // between the current update and the previous values. public EntityProperties CurrentEntityProperties { get; set; } public EntityProperties LastEntityProperties { get; set; } @@ -213,7 +213,7 @@ public abstract class BSPhysObject : PhysicsActor UnSubscribeEvents(); } } - public override void UnSubscribeEvents() { + public override void UnSubscribeEvents() { // DetailLog("{0},{1}.UnSubscribeEvents,unsubscribing", LocalID, TypeName); SubscribedEventsMs = 0; PhysicsScene.TaintedObject(TypeName+".UnSubscribeEvents", delegate() @@ -222,7 +222,7 @@ public abstract class BSPhysObject : PhysicsActor }); } // Return 'true' if the simulator wants collision events - public override bool SubscribedEvents() { + public override bool SubscribedEvents() { return (SubscribedEventsMs > 0); } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index aeeb4dd..7b211fa 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -295,7 +295,7 @@ public sealed class BSPrim : BSPhysObject private bool PositionSanityCheck() { bool ret = false; - + // If totally below the ground, move the prim up // TODO: figure out the right solution for this... only for dynamic objects? /* @@ -510,7 +510,7 @@ public sealed class BSPrim : BSPhysObject }); } } - // Go directly to Bullet to get/set the value. + // Go directly to Bullet to get/set the value. public override OMV.Quaternion ForceOrientation { get @@ -768,7 +768,7 @@ public sealed class BSPrim : BSPhysObject } } public override bool FloatOnWater { - set { + set { _floatOnWater = value; PhysicsScene.TaintedObject("BSPrim.setFloatOnWater", delegate() { @@ -971,7 +971,7 @@ public sealed class BSPrim : BSPhysObject if (hollowAmount > 0.0) { hollowVolume *= hollowAmount; - + switch (BaseShape.HollowShape) { case HollowShape.Square: @@ -1251,7 +1251,7 @@ public sealed class BSPrim : BSPhysObject // Create the correct physical representation for this type of object. // Updates BSBody and BSShape with the new information. // Ignore 'forceRebuild'. This routine makes the right choices and changes of necessary. - PhysicsScene.Shapes.GetBodyAndShape(false, PhysicsScene.World, this, shapeData, BaseShape, + PhysicsScene.Shapes.GetBodyAndShape(false, PhysicsScene.World, this, shapeData, BaseShape, null, delegate(BulletBody dBody) { // Called if the current prim body is about to be destroyed. diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index 6621d39..233f1ca 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -320,7 +320,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters { m_log.Debug("[BULLETS UNMANAGED]:" + msg); } - + // Called directly from unmanaged code so don't do much private void BulletLoggerPhysLog(string msg) { @@ -545,7 +545,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters } // This is a kludge to get avatar movement updates. - // The simulator expects collisions for avatars even if there are have been no collisions. + // 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) diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index 7b808eb..86bbf46 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -89,7 +89,7 @@ public class BSShapeCollection : IDisposable // 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, BulletSim sim, BSPhysObject prim, + public bool GetBodyAndShape(bool forceRebuild, BulletSim sim, BSPhysObject prim, ShapeData shapeData, PrimitiveBaseShape pbs, ShapeDestructionCallback shapeCallback, BodyDestructionCallback bodyCallback) { @@ -105,7 +105,7 @@ public class BSShapeCollection : IDisposable // 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 - bool newBody = CreateBody((newGeom || forceRebuild), prim, PhysicsScene.World, + bool newBody = CreateBody((newGeom || forceRebuild), prim, PhysicsScene.World, prim.BSShape, shapeData, bodyCallback); ret = newGeom || newBody; } @@ -325,7 +325,7 @@ public 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, ShapeData shapeData, + private bool CreateGeom(bool forceRebuild, BSPhysObject prim, ShapeData shapeData, PrimitiveBaseShape pbs, ShapeDestructionCallback shapeCallback) { bool ret = false; @@ -335,7 +335,7 @@ public class BSShapeCollection : IDisposable if (shapeData.Type == ShapeData.PhysicsShapeType.SHAPE_AVATAR) { // an avatar capsule is close to a native shape (it is not shared) - ret = GetReferenceToNativeShape(prim, shapeData, ShapeData.PhysicsShapeType.SHAPE_AVATAR, + ret = GetReferenceToNativeShape(prim, shapeData, ShapeData.PhysicsShapeType.SHAPE_AVATAR, ShapeData.FixedShapeKey.KEY_CAPSULE, shapeCallback); DetailLog("{0},BSShapeCollection.CreateGeom,avatarCapsule,shape={1}", prim.LocalID, prim.BSShape); haveShape = true; @@ -362,7 +362,7 @@ public class BSShapeCollection : IDisposable || prim.BSShape.type != ShapeData.PhysicsShapeType.SHAPE_SPHERE ) { - ret = GetReferenceToNativeShape(prim, shapeData, ShapeData.PhysicsShapeType.SHAPE_SPHERE, + ret = GetReferenceToNativeShape(prim, shapeData, ShapeData.PhysicsShapeType.SHAPE_SPHERE, ShapeData.FixedShapeKey.KEY_SPHERE, shapeCallback); DetailLog("{0},BSShapeCollection.CreateGeom,sphere,force={1},shape={2}", prim.LocalID, forceRebuild, prim.BSShape); @@ -376,7 +376,7 @@ public class BSShapeCollection : IDisposable || prim.BSShape.type != ShapeData.PhysicsShapeType.SHAPE_BOX ) { - ret = GetReferenceToNativeShape( prim, shapeData, ShapeData.PhysicsShapeType.SHAPE_BOX, + ret = GetReferenceToNativeShape( prim, shapeData, ShapeData.PhysicsShapeType.SHAPE_BOX, ShapeData.FixedShapeKey.KEY_BOX, shapeCallback); DetailLog("{0},BSShapeCollection.CreateGeom,box,force={1},shape={2}", prim.LocalID, forceRebuild, prim.BSShape); @@ -423,14 +423,14 @@ public class BSShapeCollection : IDisposable BulletShape newShape = BuildPhysicalNativeShape(shapeType, shapeData, shapeKey); // Don't need to do a 'ReferenceShape()' here because native shapes are not shared. - DetailLog("{0},BSShapeCollection.AddNativeShapeToPrim,create,newshape={1},scale={2}", + DetailLog("{0},BSShapeCollection.AddNativeShapeToPrim,create,newshape={1},scale={2}", shapeData.ID, newShape, shapeData.Scale); prim.BSShape = newShape; return true; } - private BulletShape BuildPhysicalNativeShape(ShapeData.PhysicsShapeType shapeType, + private BulletShape BuildPhysicalNativeShape(ShapeData.PhysicsShapeType shapeType, ShapeData shapeData, ShapeData.FixedShapeKey shapeKey) { BulletShape newShape; @@ -438,7 +438,7 @@ public class BSShapeCollection : IDisposable if (shapeType == ShapeData.PhysicsShapeType.SHAPE_AVATAR) { newShape = new BulletShape( - BulletSimAPI.BuildCapsuleShape2(PhysicsScene.World.ptr, 1.0f, 1.0f, shapeData.Scale), + BulletSimAPI.BuildCapsuleShape2(PhysicsScene.World.ptr, 1.0f, 1.0f, shapeData.Scale), shapeType); } else @@ -745,7 +745,7 @@ public class BSShapeCollection : IDisposable // 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, BulletSim sim, BulletShape shape, + private bool CreateBody(bool forceRebuild, BSPhysObject prim, BulletSim sim, BulletShape shape, ShapeData shapeData, BodyDestructionCallback bodyCallback) { bool ret = false; -- cgit v1.1 From 7272a4cae835f2d3d2a696241c6e6eb5f4b5af54 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Mon, 22 Oct 2012 09:12:06 -0700 Subject: BulletSim: fix problem of not rebuilding shape by clearing last rebuild failed flag in BSPrim.ForceBodyShapeRebuild() --- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 1 + OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs | 9 +++++++-- 2 files changed, 8 insertions(+), 2 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 7b211fa..3c5e6e5 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -173,6 +173,7 @@ public sealed class BSPrim : BSPhysObject } public override bool ForceBodyShapeRebuild(bool inTaintTime) { + LastAssetBuildFailed = false; BSScene.TaintCallback rebuildOperation = delegate() { _mass = CalculateMass(); // changing the shape changes the mass diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index 86bbf46..89d0d3e 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -698,14 +698,19 @@ public class BSShapeCollection : IDisposable return ComputeShapeKey(shapeData, 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 decompressing JPEG2000s). + // The first case causes the asset to be fetched. The second case just requires + // 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, ShapeData shapeData, PrimitiveBaseShape pbs) { // If the shape was successfully created, nothing more to do if (newShape.ptr != IntPtr.Zero) return newShape; - // The most common reason for failure is that an underlying asset is not available - // If this mesh has an underlying asset and we have not failed getting it before, fetch the asset if (pbs.SculptEntry && !prim.LastAssetBuildFailed && pbs.SculptTexture != OMV.UUID.Zero) { -- cgit v1.1 From 14eeb8b31b865f7b1927703028b03b6f61693cb6 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Mon, 22 Oct 2012 16:33:21 -0700 Subject: BulletSim: fix bug that caused error (and a crash on 32 bit Linux) when mesh assets weren't already in the cache. Comment cleanups. --- .../Region/Physics/BulletSPlugin/BSConstraint.cs | 4 ++- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 5 ++-- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 13 +++++---- .../Physics/BulletSPlugin/BSLinksetConstraints.cs | 19 +++---------- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 9 ++++--- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 1 + .../Physics/BulletSPlugin/BSShapeCollection.cs | 31 ++++++++++++++++++---- .../Physics/BulletSPlugin/BSTerrainManager.cs | 4 +-- 8 files changed, 51 insertions(+), 35 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs b/OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs index b58745a..f017cdd 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs @@ -34,6 +34,8 @@ namespace OpenSim.Region.Physics.BulletSPlugin public abstract class BSConstraint : IDisposable { + private static string LogHeader = "[BULLETSIM CONSTRAINT]"; + protected BulletSim m_world; protected BulletBody m_body1; protected BulletBody m_body2; @@ -124,7 +126,7 @@ public abstract class BSConstraint : IDisposable } else { - m_world.physicsScene.Logger.ErrorFormat("[BULLETSIM CONSTRAINT] CalculateTransforms failed. A={0}, B={1}", Body1.ID, Body2.ID); + m_world.physicsScene.Logger.ErrorFormat("{0} CalculateTransforms failed. A={1}, B={2}", LogHeader, Body1.ID, Body2.ID); } } return ret; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index f71f3b0..117c878 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -464,8 +464,9 @@ namespace OpenSim.Region.Physics.BulletSPlugin // Set the prim's inertia to zero. The vehicle code handles that and this // removes the motion and torque actions introduced by Bullet. Vector3 inertia = Vector3.Zero; - BulletSimAPI.SetMassProps2(Prim.BSBody.ptr, Prim.MassRaw, inertia); - BulletSimAPI.UpdateInertiaTensor2(Prim.BSBody.ptr); + // comment out for DEBUG test + // BulletSimAPI.SetMassProps2(Prim.BSBody.ptr, Prim.MassRaw, inertia); + // BulletSimAPI.UpdateInertiaTensor2(Prim.BSBody.ptr); } // One step of the vehicle properties for the next 'pTimestep' seconds. diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index 2e6b104..c984824 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -165,6 +165,9 @@ public abstract class BSLinkset bool ret = false; lock (m_linksetActivityLock) { + if (m_children.Contains(child)) + ret = true; + /* foreach (BSPhysObject bp in m_children) { if (child.LocalID == bp.LocalID) @@ -173,6 +176,7 @@ public abstract class BSLinkset break; } } + */ } return ret; } @@ -196,21 +200,20 @@ public abstract class BSLinkset // Called at taint-time! public abstract bool MakeStatic(BSPhysObject child); - // If the software is handling the movement of all the objects in a linkset - // (like if one doesn't use constraints for static linksets), this is called - // when an update for the root of the linkset is received. + // Called when a parameter update comes from the physics engine for any object + // of the linkset is received. // Called at taint-time!! public abstract void UpdateProperties(BSPhysObject physObject); // Routine used when rebuilding the body of the root of the linkset // Destroy all the constraints have have been made to root. // This is called when the root body is changing. - // Returns 'true' of something eas actually removed and would need restoring + // Returns 'true' of something was actually removed and would need restoring // Called at taint-time!! public abstract bool RemoveBodyDependencies(BSPrim child); // Companion to RemoveBodyDependencies(). If RemoveBodyDependencies() returns 'true', - // this routine will restore the removed constraints. + // this routine will restore the removed constraints. // Called at taint-time!! public abstract void RestoreBodyDependencies(BSPrim child); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs index 8eeeb73..8a750b5 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs @@ -46,9 +46,8 @@ public class BSLinksetConstraints : BSLinkset // May be called at runtime or taint-time (just pass the appropriate flag). public override void Refresh(BSPhysObject requestor, bool inTaintTime) { - // If there are no children, not physical or not root, I am not the one that recomputes the constraints - // (For the moment, static linksets do create constraints so remove the test for physical.) - if (!HasAnyChildren || /*!requestor.IsPhysical ||*/ !IsRoot(requestor)) + // If there are no children or not root, I am not the one that recomputes the constraints + if (!HasAnyChildren || !IsRoot(requestor)) return; BSScene.TaintCallback refreshOperation = delegate() @@ -85,20 +84,10 @@ public class BSLinksetConstraints : BSLinkset return false; } - // If the software is handling the movement of all the objects in a linkset - // (like if one doesn't use constraints for static linksets), this is called - // when an update for the root of the linkset is received. // Called at taint-time!! - public override void UpdateProperties(BSPhysObject physObject) + public override void UpdateProperties(BSPhysObject updated) { - // The root local properties have been updated. Apply to the children if appropriate. - if (IsRoot(physObject) && HasAnyChildren) - { - if (!physObject.IsPhysical) - { - // TODO: implement software linkset update for static object linksets - } - } + // Nothing to do for constraints on property updates } // Routine used when rebuilding the body of the root of the linkset diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 3c5e6e5..8401c69 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -399,7 +399,7 @@ public sealed class BSPrim : BSPhysObject { // 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. - this._vehicle.ProcessTypeChange(type); + _vehicle.ProcessTypeChange(type); }); } } @@ -1246,12 +1246,13 @@ public sealed class BSPrim : BSPhysObject FillShapeInfo(out shapeData); // If this prim is part of a linkset, we must remove and restore the physical - // links of the body is rebuilt. + // links if the body is rebuilt. bool needToRestoreLinkset = false; // Create the correct physical representation for this type of object. // Updates BSBody and BSShape with the new information. // Ignore 'forceRebuild'. This routine makes the right choices and changes of necessary. + // Returns 'true' if either the body or the shape was changed. PhysicsScene.Shapes.GetBodyAndShape(false, PhysicsScene.World, this, shapeData, BaseShape, null, delegate(BulletBody dBody) { @@ -1355,7 +1356,7 @@ public sealed class BSPrim : BSPhysObject DetailLog("{0},BSPrim.UpdateProperties,call,pos={1},orient={2},vel={3},accel={4},rotVel={5}", LocalID, _position, _orientation, _velocity, _acceleration, _rotationalVelocity); - // BulletSimAPI.DumpRigidBody2(Scene.World.Ptr, BSBody.Ptr); + BulletSimAPI.DumpRigidBody2(PhysicsScene.World.ptr, BSBody.ptr); // DEBUG DEBUG DEBUG base.RequestPhysicsterseUpdate(); } @@ -1368,8 +1369,8 @@ public sealed class BSPrim : BSPhysObject entprop.Acceleration, entprop.RotationalVelocity); } */ - // The linkset implimentation might want to know about this. + // The linkset implimentation might want to know about this. Linkset.UpdateProperties(this); } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index 233f1ca..48ee6f6 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -716,6 +716,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters } catch (Exception e) { + DetailLog("{0},BSScene.ProcessTaints,doTaintException,id={1}", DetailLogZero, oneCallback.ident); // DEBUG DEBUG DEBUG m_log.ErrorFormat("{0}: ProcessTaints: {1}: Exception: {2}", LogHeader, oneCallback.ident, e); } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index 89d0d3e..b1833c5 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -36,7 +36,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin { public class BSShapeCollection : IDisposable { - // private static string LogHeader = "[BULLETSIM SHAPE COLLECTION]"; + private static string LogHeader = "[BULLETSIM SHAPE COLLECTION]"; protected BSScene PhysicsScene { get; set; } @@ -434,16 +434,26 @@ public class BSShapeCollection : IDisposable ShapeData shapeData, ShapeData.FixedShapeKey shapeKey) { BulletShape newShape; + // Need to make sure the passed shape information is for the native type. + ShapeData nativeShapeData = shapeData; + nativeShapeData.Type = shapeType; + nativeShapeData.MeshKey = (ulong)shapeKey; + nativeShapeData.HullKey = (ulong)shapeKey; if (shapeType == ShapeData.PhysicsShapeType.SHAPE_AVATAR) { newShape = new BulletShape( - BulletSimAPI.BuildCapsuleShape2(PhysicsScene.World.ptr, 1.0f, 1.0f, shapeData.Scale), - shapeType); + BulletSimAPI.BuildCapsuleShape2(PhysicsScene.World.ptr, 1.0f, 1.0f, nativeShapeData.Scale), shapeType); + DetailLog("{0},BSShapeCollection.BuiletPhysicalNativeShape,capsule,scale={1}", nativeShapeData.ID, nativeShapeData.Scale); } else { - newShape = new BulletShape(BulletSimAPI.BuildNativeShape2(PhysicsScene.World.ptr, shapeData), shapeType); + newShape = new BulletShape(BulletSimAPI.BuildNativeShape2(PhysicsScene.World.ptr, nativeShapeData), shapeType); + } + if (newShape.ptr == IntPtr.Zero) + { + PhysicsScene.Logger.ErrorFormat("{0} BuildPhysicalNativeShape failed. ID={1}, shape={2}", + LogHeader, nativeShapeData.ID, nativeShapeData.Type); } newShape.shapeKey = (System.UInt64)shapeKey; newShape.isNativeShape = true; @@ -716,6 +726,8 @@ public class BSShapeCollection : IDisposable { prim.LastAssetBuildFailed = true; BSPhysObject xprim = prim; + DetailLog("{0},BSShapeCollection.VerifyMeshCreated,fetchAsset,lID={1},lastFailed={2}", + LogHeader, shapeData.ID.ToString("X"), prim.LastAssetBuildFailed); Util.FireAndForget(delegate { RequestAssetDelegate assetProvider = PhysicsScene.RequestAssetMethod; @@ -732,16 +744,25 @@ public class BSShapeCollection : IDisposable 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 native sphere setting since the rebuild is at taint time. yprim.ForceBodyShapeRebuild(false); }); } }); } + else + { + if (prim.LastAssetBuildFailed) + { + PhysicsScene.Logger.ErrorFormat("{0} Mesh failed to fetch asset. lID={1}, texture={2}", + LogHeader, shapeData.ID, pbs.SculptTexture); + } + } // While we figure out the real problem, stick a simple native shape on the object. BulletShape fillinShape = - BuildPhysicalNativeShape(ShapeData.PhysicsShapeType.SHAPE_SPHERE, shapeData, ShapeData.FixedShapeKey.KEY_SPHERE); + BuildPhysicalNativeShape(ShapeData.PhysicsShapeType.SHAPE_BOX, shapeData, ShapeData.FixedShapeKey.KEY_BOX); return fillinShape; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs index 4106534..ae267e3 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs @@ -201,9 +201,7 @@ public class BSTerrainManager // If called with a mapInfo in m_heightMaps and there is an existing terrain body, a new // terrain shape is created and added to the body. // This call is most often used to update the heightMap and parameters of the terrain. - // The 'doNow' boolean says whether to do all the unmanaged activities right now (like when - // calling this routine from initialization or taint-time routines) or whether to delay - // all the unmanaged activities to taint-time. + // (The above does suggest that some simplification/refactoring is in order.) private void UpdateOrCreateTerrain(uint id, float[] heightMap, Vector3 minCoords, Vector3 maxCoords, bool inTaintTime) { DetailLog("{0},BSTerrainManager.UpdateOrCreateTerrain,call,minC={1},maxC={2},inTaintTime={3}", -- cgit v1.1 From 36bfd3667c44f7cd4e66e880c45c34903ed34842 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Mon, 22 Oct 2012 22:22:48 -0700 Subject: BulletSim: remove chatty debug message. --- OpenSim/Region/Physics/BulletSPlugin/BSPrim.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/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 8401c69..38ab3de 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -1356,7 +1356,7 @@ public sealed class BSPrim : BSPhysObject DetailLog("{0},BSPrim.UpdateProperties,call,pos={1},orient={2},vel={3},accel={4},rotVel={5}", LocalID, _position, _orientation, _velocity, _acceleration, _rotationalVelocity); - BulletSimAPI.DumpRigidBody2(PhysicsScene.World.ptr, BSBody.ptr); // DEBUG DEBUG DEBUG + // BulletSimAPI.DumpRigidBody2(PhysicsScene.World.ptr, BSBody.ptr); // DEBUG DEBUG DEBUG base.RequestPhysicsterseUpdate(); } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index 48ee6f6..e686f2f 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -1334,7 +1334,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters // Add the Flush() if debugging crashes to get all the messages written out. // PhysicsLogging.Flush(); } - // used to fill in the LocalID when there isn't one + // 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 b49f8a377b9ac542096a0bc8ad30b11942c27413 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 23 Oct 2012 08:02:26 -0700 Subject: BulletSim: minor change to insure avatar body recreation when shape changes. --- OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index b1833c5..d9427e1 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -338,6 +338,7 @@ public class BSShapeCollection : IDisposable ret = GetReferenceToNativeShape(prim, shapeData, ShapeData.PhysicsShapeType.SHAPE_AVATAR, ShapeData.FixedShapeKey.KEY_CAPSULE, shapeCallback); DetailLog("{0},BSShapeCollection.CreateGeom,avatarCapsule,shape={1}", prim.LocalID, prim.BSShape); + ret = true; haveShape = true; } // If the prim attributes are simple, this could be a simple Bullet native shape @@ -411,15 +412,14 @@ public class BSShapeCollection : IDisposable ShapeData.PhysicsShapeType shapeType, ShapeData.FixedShapeKey shapeKey, ShapeDestructionCallback shapeCallback) { + // release any previous shape + DereferenceShape(prim.BSShape, true, shapeCallback); shapeData.Type = shapeType; // Bullet native objects are scaled by the Bullet engine so pass the size in prim.Scale = shapeData.Size; shapeData.Scale = shapeData.Size; - // release any previous shape - DereferenceShape(prim.BSShape, true, shapeCallback); - BulletShape newShape = BuildPhysicalNativeShape(shapeType, shapeData, shapeKey); // Don't need to do a 'ReferenceShape()' here because native shapes are not shared. -- cgit v1.1 From b6fc5bad000e7e7af992e7f29eeb2de9f716fcc4 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 23 Oct 2012 17:30:43 -0700 Subject: BulletSim: fix problem with avatars sinking into the ground. Change terrain activation state to DISABLE_SIMULATION for better performance. --- .../Region/Physics/BulletSPlugin/BSCharacter.cs | 27 ++++++++++++++-------- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 3 +-- .../Physics/BulletSPlugin/BSShapeCollection.cs | 4 ++-- .../Physics/BulletSPlugin/BSTerrainManager.cs | 4 ++-- 4 files changed, 23 insertions(+), 15 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index 07dd613..a041ba8 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -105,7 +105,7 @@ public class BSCharacter : BSPhysObject shapeData.Position = _position; shapeData.Rotation = _orientation; shapeData.Velocity = _velocity; - shapeData.Size = Scale; + shapeData.Size = Scale; // capsule is a native shape but scale is not just <1,1,1> shapeData.Scale = Scale; shapeData.Mass = _mass; shapeData.Buoyancy = _buoyancy; @@ -144,7 +144,9 @@ public class BSCharacter : BSPhysObject ForcePosition = _position; // Set the velocity and compute the proper friction ForceVelocity = _velocity; + BulletSimAPI.SetRestitution2(BSBody.ptr, PhysicsScene.Params.avatarRestitution); + BulletSimAPI.SetMargin2(BSShape.ptr, PhysicsScene.Params.collisionMargin); BulletSimAPI.SetLocalScaling2(BSShape.ptr, Scale); BulletSimAPI.SetContactProcessingThreshold2(BSBody.ptr, PhysicsScene.Params.contactProcessingThreshold); if (PhysicsScene.Params.ccdMotionThreshold > 0f) @@ -156,11 +158,15 @@ public class BSCharacter : BSPhysObject OMV.Vector3 localInertia = BulletSimAPI.CalculateLocalInertia2(BSShape.ptr, MassRaw); BulletSimAPI.SetMassProps2(BSBody.ptr, MassRaw, localInertia); + // Make so capsule does not fall over + BulletSimAPI.SetAngularFactorV2(BSBody.ptr, OMV.Vector3.Zero); + BulletSimAPI.AddToCollisionFlags2(BSBody.ptr, CollisionFlags.CF_CHARACTER_OBJECT); BulletSimAPI.AddObjectToWorld2(PhysicsScene.World.ptr, BSBody.ptr); - BulletSimAPI.ForceActivationState2(BSBody.ptr, ActivationState.ACTIVE_TAG); + // BulletSimAPI.ForceActivationState2(BSBody.ptr, ActivationState.ACTIVE_TAG); + BulletSimAPI.ForceActivationState2(BSBody.ptr, ActivationState.DISABLE_DEACTIVATION); BulletSimAPI.UpdateSingleAabb2(PhysicsScene.World.ptr, BSBody.ptr); // Do this after the object has been added to the world @@ -175,11 +181,13 @@ public class BSCharacter : BSPhysObject } // No one calls this method so I don't know what it could possibly mean public override bool Stopped { get { return false; } } + public override OMV.Vector3 Size { get { // Avatar capsule size is kept in the scale parameter. - return _size; + // return _size; + return new OMV.Vector3(Scale.X * 2f, Scale.Y * 2f, Scale.Z); } set { @@ -199,7 +207,9 @@ public class BSCharacter : BSPhysObject } } + public override OMV.Vector3 Scale { get; set; } + public override PrimitiveBaseShape Shape { set { BaseShape = value; } @@ -264,7 +274,7 @@ public class BSCharacter : BSPhysObject // Check that the current position is sane and, if not, modify the position to make it so. - // Check for being below terrain and being out of bounds. + // Check for being below terrain or on water. // Returns 'true' of the position was made sane by some action. private bool PositionSanityCheck() { @@ -335,7 +345,7 @@ public class BSCharacter : BSPhysObject } // Avatars don't do vehicles - public override int VehicleType { get { return 0; } set { return; } } + public override int VehicleType { get { return (int)Vehicle.TYPE_NONE; } set { return; } } public override void VehicleFloatParam(int param, float value) { } public override void VehicleVectorParam(int param, OMV.Vector3 value) {} public override void VehicleRotationParam(int param, OMV.Quaternion rotation) { } @@ -588,9 +598,8 @@ public class BSCharacter : BSPhysObject newScale.X = PhysicsScene.Params.avatarCapsuleRadius; newScale.Y = PhysicsScene.Params.avatarCapsuleRadius; - // From the total height, remote the capsule half spheres that are at each end - newScale.Z = (size.Z * 2f) - Math.Min(newScale.X, newScale.Y); - // newScale.Z = (size.Z * 2f); + // From the total height, remove the capsule half spheres that are at each end + newScale.Z = size.Z- (newScale.X + newScale.Y); Scale = newScale; } @@ -636,7 +645,7 @@ public class BSCharacter : BSPhysObject BulletSimAPI.SetLinearVelocity2(BSBody.ptr, avVel); } - // Tell the linkset about this + // Tell the linkset about value changes Linkset.UpdateProperties(this); // Avatars don't report their changes the usual way. Changes are checked for in the heartbeat loop. diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index e686f2f..db0c99e 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -692,7 +692,6 @@ public class BSScene : PhysicsScene, IPhysicsParameters { if (_taintedObjects.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 int taintCount = m_taintsToProcessPerStep; TaintCallbackEntry oneCallback = new TaintCallbackEntry(); while (_taintedObjects.Count > 0 && taintCount-- > 0) @@ -711,7 +710,7 @@ public class BSScene : PhysicsScene, IPhysicsParameters { try { - DetailLog("{0},BSScene.ProcessTaints,doTaint,id={1}", DetailLogZero, oneCallback.ident); // DEBUG DEBUG DEBUG + DetailLog("{0},BSScene.ProcessTaints,doTaint,id={1}", DetailLogZero, oneCallback.ident); oneCallback.callback(); } catch (Exception e) diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index d9427e1..30fa50a 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -443,7 +443,8 @@ public class BSShapeCollection : IDisposable if (shapeType == ShapeData.PhysicsShapeType.SHAPE_AVATAR) { newShape = new BulletShape( - BulletSimAPI.BuildCapsuleShape2(PhysicsScene.World.ptr, 1.0f, 1.0f, nativeShapeData.Scale), shapeType); + BulletSimAPI.BuildCapsuleShape2(PhysicsScene.World.ptr, 1f, 1f, nativeShapeData.Scale) + , shapeType); DetailLog("{0},BSShapeCollection.BuiletPhysicalNativeShape,capsule,scale={1}", nativeShapeData.ID, nativeShapeData.Scale); } else @@ -790,7 +791,6 @@ public class BSShapeCollection : IDisposable // If the collisionObject is not the correct type for solidness, rebuild what's there mustRebuild = true; } - } if (mustRebuild || forceRebuild) diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs index ae267e3..880859a 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs @@ -333,8 +333,8 @@ public class BSTerrainManager // Make sure the new shape is processed. // BulletSimAPI.Activate2(mapInfo.terrainBody.ptr, true); - BulletSimAPI.ForceActivationState2(mapInfo.terrainBody.ptr, ActivationState.ISLAND_SLEEPING); - // BulletSimAPI.ForceActivationState2(mapInfo.terrainBody.ptr, ActivationState.DISABLE_SIMULATION); + // BulletSimAPI.ForceActivationState2(mapInfo.terrainBody.ptr, ActivationState.ISLAND_SLEEPING); + BulletSimAPI.ForceActivationState2(mapInfo.terrainBody.ptr, ActivationState.DISABLE_SIMULATION); m_terrainModified = true; }; -- cgit v1.1 From aeeed29d627f7d40bbcc160bf446a019b54e8b32 Mon Sep 17 00:00:00 2001 From: Justin Clark-Casey (justincc) Date: Tue, 30 Oct 2012 01:07:14 +0000 Subject: correct ODEPrim.MeshAssetReveived -> MeshAssetReceived --- OpenSim/Region/Physics/OdePlugin/ODEPrim.cs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs b/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs index 2548648..7c46ff8 100644 --- a/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs +++ b/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs @@ -3335,7 +3335,6 @@ Console.WriteLine(" JointCreateFixed"); m_material = pMaterial; } - private void CheckMeshAsset() { if (_pbs.SculptEntry && !m_assetFailed && _pbs.SculptTexture != UUID.Zero) @@ -3345,12 +3344,12 @@ Console.WriteLine(" JointCreateFixed"); { RequestAssetDelegate assetProvider = _parent_scene.RequestAssetMethod; if (assetProvider != null) - assetProvider(_pbs.SculptTexture, MeshAssetReveived); + assetProvider(_pbs.SculptTexture, MeshAssetReceived); }); } } - void MeshAssetReveived(AssetBase asset) + void MeshAssetReceived(AssetBase asset) { if (asset.Data != null && asset.Data.Length > 0) { -- cgit v1.1 From 37de965233ad6c25c2ce7a29d89762aa478a6147 Mon Sep 17 00:00:00 2001 From: Justin Clark-Casey (justincc) Date: Tue, 30 Oct 2012 01:08:00 +0000 Subject: Make MeshAssetReceived private. Keep methods private unless they need to be opened up to external callers. Reduces analysis complexity. --- OpenSim/Region/Physics/OdePlugin/ODEPrim.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs b/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs index 7c46ff8..5b49e3b 100644 --- a/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs +++ b/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs @@ -3349,7 +3349,7 @@ Console.WriteLine(" JointCreateFixed"); } } - void MeshAssetReceived(AssetBase asset) + private void MeshAssetReceived(AssetBase asset) { if (asset.Data != null && asset.Data.Length > 0) { -- cgit v1.1 From cccf6953276eda0af34fb7b8e95c2c4351db5546 Mon Sep 17 00:00:00 2001 From: Justin Clark-Casey (justincc) Date: Tue, 30 Oct 2012 01:14:48 +0000 Subject: Add asset != null check to ODEPrim.MeshAssetReceived instead of throwing exception. In some cases (such as failure to receive response from asset service), it is possible for a null to be returned from IAssetService.Get(string, object, AssetRetrieved). --- OpenSim/Region/Physics/OdePlugin/ODEPrim.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs b/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs index 5b49e3b..2637295 100644 --- a/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs +++ b/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs @@ -3351,7 +3351,7 @@ Console.WriteLine(" JointCreateFixed"); private void MeshAssetReceived(AssetBase asset) { - if (asset.Data != null && asset.Data.Length > 0) + if (asset != null && asset.Data != null && asset.Data.Length > 0) { if (!_pbs.SculptEntry) return; -- cgit v1.1 From ff6c69000e3f192f81e7408a522b78d91521a5ff Mon Sep 17 00:00:00 2001 From: Justin Clark-Casey (justincc) Date: Tue, 30 Oct 2012 01:40:59 +0000 Subject: Log warning if mesh/sculpt asset couldn't be found by ODEPrim.MeshAssetReceived() callback. Presumably this is now more useful if the false positive from the old method of loading mesh assets have been eliminated. --- OpenSim/Region/Physics/OdePlugin/ODEPrim.cs | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs b/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs index 2637295..5a0b8d1 100644 --- a/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs +++ b/OpenSim/Region/Physics/OdePlugin/ODEPrim.cs @@ -3364,6 +3364,12 @@ Console.WriteLine(" JointCreateFixed"); m_taintshape = true; _parent_scene.AddPhysicsActorTaint(this); } + else + { + m_log.WarnFormat( + "[ODE PRIM]: Could not get mesh/sculpt asset {0} for {1} at {2} in {3}", + _pbs.SculptTexture, Name, _position, _parent_scene.Name); + } } } } \ No newline at end of file -- cgit v1.1 From ffe4d738fbcd27e3c037693ab6812df1d9fbb977 Mon Sep 17 00:00:00 2001 From: Dan Lake Date: Wed, 31 Oct 2012 17:13:18 -0700 Subject: Add TargetVelocity to PhysicsActor interface to support distributed physics. No change to existing functions. --- OpenSim/Region/Physics/Manager/PhysicsActor.cs | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/Manager/PhysicsActor.cs b/OpenSim/Region/Physics/Manager/PhysicsActor.cs index 0587054..34413e5 100644 --- a/OpenSim/Region/Physics/Manager/PhysicsActor.cs +++ b/OpenSim/Region/Physics/Manager/PhysicsActor.cs @@ -257,6 +257,12 @@ namespace OpenSim.Region.Physics.Manager /// Getting this returns the velocity calculated by physics scene updates, using factors such as target velocity, /// time to accelerate and collisions. /// + public virtual Vector3 TargetVelocity + { + get { return Velocity; } + set { Velocity = value; } + } + public abstract Vector3 Velocity { get; set; } public abstract Vector3 Torque { get; set; } -- cgit v1.1 From 804b332d45c3989958f5ec08e1509ba373fb84b1 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Thu, 25 Oct 2012 08:04:20 -0700 Subject: BulletSim: Add banking and other new code to vechile dynamics. Add third party license and contributor in for for Aurora-Sim project for physics code. --- .../Physics/BulletSPlugin/BS6DofConstraint.cs | 2 +- .../Region/Physics/BulletSPlugin/BSCharacter.cs | 2 +- .../BulletSPlugin/BSConstraintCollection.cs | 2 +- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 489 +++++++++++++-------- .../Physics/BulletSPlugin/BSHingeConstraint.cs | 2 +- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 2 + .../Physics/BulletSPlugin/BSLinksetConstraints.cs | 2 +- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 4 +- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 2 +- .../Physics/BulletSPlugin/BSShapeCollection.cs | 2 +- .../Physics/BulletSPlugin/BSTerrainManager.cs | 2 +- 11 files changed, 323 insertions(+), 188 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BS6DofConstraint.cs b/OpenSim/Region/Physics/BulletSPlugin/BS6DofConstraint.cs index 3306a97..310df3d 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BS6DofConstraint.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BS6DofConstraint.cs @@ -32,7 +32,7 @@ using OpenMetaverse; namespace OpenSim.Region.Physics.BulletSPlugin { -public class BS6DofConstraint : BSConstraint +public sealed class BS6DofConstraint : BSConstraint { private static string LogHeader = "[BULLETSIM 6DOF CONSTRAINT]"; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index a041ba8..9fea9b8 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -34,7 +34,7 @@ using OpenSim.Region.Physics.Manager; namespace OpenSim.Region.Physics.BulletSPlugin { -public class BSCharacter : BSPhysObject +public sealed class BSCharacter : BSPhysObject { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static readonly string LogHeader = "[BULLETS CHAR]"; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSConstraintCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSConstraintCollection.cs index 22ea367..b9add06 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSConstraintCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSConstraintCollection.cs @@ -33,7 +33,7 @@ using OpenMetaverse; namespace OpenSim.Region.Physics.BulletSPlugin { -public class BSConstraintCollection : IDisposable +public sealed class BSConstraintCollection : IDisposable { // private static readonly ILog m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // private static readonly string LogHeader = "[CONSTRAINT COLLECTION]"; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index 117c878..9b59bef 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -52,7 +52,7 @@ using OpenSim.Region.Physics.Manager; namespace OpenSim.Region.Physics.BulletSPlugin { - public class BSDynamics + public sealed class BSDynamics { private BSScene PhysicsScene { get; set; } // the prim this dynamic controller belongs to @@ -72,8 +72,11 @@ namespace OpenSim.Region.Physics.BulletSPlugin // LIMIT_ROLL_ONLY private Vector3 m_BlockingEndPoint = Vector3.Zero; private Quaternion m_RollreferenceFrame = Quaternion.Identity; + private Quaternion m_referenceFrame = Quaternion.Identity; + // Linear properties private Vector3 m_linearMotorDirection = Vector3.Zero; // velocity requested by LSL, decayed by time + private Vector3 m_linearMotorOffset = Vector3.Zero; // the point of force can be offset from the center private Vector3 m_linearMotorDirectionLASTSET = Vector3.Zero; // velocity requested by LSL private Vector3 m_newVelocity = Vector3.Zero; // velocity computed to be applied to body private Vector3 m_linearFrictionTimescale = Vector3.Zero; @@ -95,19 +98,19 @@ namespace OpenSim.Region.Physics.BulletSPlugin private Vector3 m_lastVertAttractor = Vector3.Zero; // what VA was last applied to body //Deflection properties - // private float m_angularDeflectionEfficiency = 0; - // private float m_angularDeflectionTimescale = 0; - // private float m_linearDeflectionEfficiency = 0; - // private float m_linearDeflectionTimescale = 0; + private float m_angularDeflectionEfficiency = 0; + private float m_angularDeflectionTimescale = 0; + private float m_linearDeflectionEfficiency = 0; + private float m_linearDeflectionTimescale = 0; //Banking properties - // private float m_bankingEfficiency = 0; - // private float m_bankingMix = 0; - // private float m_bankingTimescale = 0; + private float m_bankingEfficiency = 0; + private float m_bankingMix = 0; + private float m_bankingTimescale = 0; //Hover and Buoyancy properties private float m_VhoverHeight = 0f; -// private float m_VhoverEfficiency = 0f; + private float m_VhoverEfficiency = 0f; private float m_VhoverTimescale = 0f; private float m_VhoverTargetHeight = -1.0f; // if <0 then no hover, else its the current target height private float m_VehicleBuoyancy = 0f; //KF: m_VehicleBuoyancy is set by VEHICLE_BUOYANCY for a vehicle. @@ -138,10 +141,10 @@ namespace OpenSim.Region.Physics.BulletSPlugin switch (pParam) { case Vehicle.ANGULAR_DEFLECTION_EFFICIENCY: - // m_angularDeflectionEfficiency = Math.Max(pValue, 0.01f); + m_angularDeflectionEfficiency = Math.Max(pValue, 0.01f); break; case Vehicle.ANGULAR_DEFLECTION_TIMESCALE: - // m_angularDeflectionTimescale = Math.Max(pValue, 0.01f); + m_angularDeflectionTimescale = Math.Max(pValue, 0.01f); break; case Vehicle.ANGULAR_MOTOR_DECAY_TIMESCALE: m_angularMotorDecayTimescale = Math.Max(pValue, 0.01f); @@ -150,20 +153,20 @@ namespace OpenSim.Region.Physics.BulletSPlugin m_angularMotorTimescale = Math.Max(pValue, 0.01f); break; case Vehicle.BANKING_EFFICIENCY: - // m_bankingEfficiency = Math.Max(pValue, 0.01f); + m_bankingEfficiency = Math.Max(-1f, Math.Min(pValue, 1f)); break; case Vehicle.BANKING_MIX: - // m_bankingMix = Math.Max(pValue, 0.01f); + m_bankingMix = Math.Max(pValue, 0.01f); break; case Vehicle.BANKING_TIMESCALE: - // m_bankingTimescale = Math.Max(pValue, 0.01f); + m_bankingTimescale = Math.Max(pValue, 0.01f); break; case Vehicle.BUOYANCY: m_VehicleBuoyancy = Math.Max(-1f, Math.Min(pValue, 1f)); break; -// case Vehicle.HOVER_EFFICIENCY: -// m_VhoverEfficiency = Math.Max(0f, Math.Min(pValue, 1f)); -// break; + case Vehicle.HOVER_EFFICIENCY: + m_VhoverEfficiency = Math.Max(0f, Math.Min(pValue, 1f)); + break; case Vehicle.HOVER_HEIGHT: m_VhoverHeight = pValue; break; @@ -171,10 +174,10 @@ 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 = Math.Max(pValue, 0.01f); break; case Vehicle.LINEAR_DEFLECTION_TIMESCALE: - // m_linearDeflectionTimescale = Math.Max(pValue, 0.01f); + m_linearDeflectionTimescale = Math.Max(pValue, 0.01f); break; case Vehicle.LINEAR_MOTOR_DECAY_TIMESCALE: m_linearMotorDecayTimescale = Math.Max(pValue, 0.01f); @@ -196,7 +199,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin break; case Vehicle.ANGULAR_MOTOR_DIRECTION: m_angularMotorDirection = new Vector3(pValue, pValue, pValue); - m_angularMotorApply = 10; + m_angularMotorApply = 100; break; case Vehicle.LINEAR_FRICTION_TIMESCALE: m_linearFrictionTimescale = new Vector3(pValue, pValue, pValue); @@ -206,7 +209,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin m_linearMotorDirectionLASTSET = new Vector3(pValue, pValue, pValue); break; case Vehicle.LINEAR_MOTOR_OFFSET: - // m_linearMotorOffset = new Vector3(pValue, pValue, pValue); + m_linearMotorOffset = new Vector3(pValue, pValue, pValue); break; } @@ -221,15 +224,12 @@ namespace OpenSim.Region.Physics.BulletSPlugin m_angularFrictionTimescale = new Vector3(pValue.X, pValue.Y, pValue.Z); break; case Vehicle.ANGULAR_MOTOR_DIRECTION: - m_angularMotorDirection = new Vector3(pValue.X, pValue.Y, pValue.Z); // Limit requested angular speed to 2 rps= 4 pi rads/sec - if (m_angularMotorDirection.X > 12.56f) m_angularMotorDirection.X = 12.56f; - if (m_angularMotorDirection.X < - 12.56f) m_angularMotorDirection.X = - 12.56f; - if (m_angularMotorDirection.Y > 12.56f) m_angularMotorDirection.Y = 12.56f; - if (m_angularMotorDirection.Y < - 12.56f) m_angularMotorDirection.Y = - 12.56f; - if (m_angularMotorDirection.Z > 12.56f) m_angularMotorDirection.Z = 12.56f; - if (m_angularMotorDirection.Z < - 12.56f) m_angularMotorDirection.Z = - 12.56f; - m_angularMotorApply = 10; + pValue.X = Math.Max(-12.56f, Math.Min(pValue.X, 12.56f)); + pValue.Y = Math.Max(-12.56f, Math.Min(pValue.Y, 12.56f)); + pValue.Z = Math.Max(-12.56f, Math.Min(pValue.Z, 12.56f)); + m_angularMotorDirection = new Vector3(pValue.X, pValue.Y, pValue.Z); + m_angularMotorApply = 100; break; case Vehicle.LINEAR_FRICTION_TIMESCALE: m_linearFrictionTimescale = new Vector3(pValue.X, pValue.Y, pValue.Z); @@ -239,7 +239,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin m_linearMotorDirectionLASTSET = new Vector3(pValue.X, pValue.Y, pValue.Z); break; case Vehicle.LINEAR_MOTOR_OFFSET: - // m_linearMotorOffset = new Vector3(pValue.X, pValue.Y, pValue.Z); + m_linearMotorOffset = new Vector3(pValue.X, pValue.Y, pValue.Z); break; case Vehicle.BLOCK_EXIT: m_BlockingEndPoint = new Vector3(pValue.X, pValue.Y, pValue.Z); @@ -253,7 +253,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin switch (pParam) { case Vehicle.REFERENCE_FRAME: - // m_referenceFrame = pValue; + m_referenceFrame = pValue; break; case Vehicle.ROLL_FRAME: m_RollreferenceFrame = pValue; @@ -265,21 +265,16 @@ namespace OpenSim.Region.Physics.BulletSPlugin { VDetailLog("{0},ProcessVehicleFlags,param={1},remove={2}", Prim.LocalID, pParam, remove); VehicleFlag parm = (VehicleFlag)pParam; - if (remove) + if (pParam == -1) + m_flags = (VehicleFlag)0; + else { - if (pParam == -1) - { - m_flags = (VehicleFlag)0; - } - else - { + if (remove) m_flags &= ~parm; - } - } - else { - m_flags |= parm; + else + m_flags |= parm; } - }//end ProcessVehicleFlags + } internal void ProcessTypeChange(Vehicle pType) { @@ -288,99 +283,142 @@ namespace OpenSim.Region.Physics.BulletSPlugin Type = pType; switch (pType) { - case Vehicle.TYPE_NONE: - m_linearFrictionTimescale = new Vector3(0, 0, 0); - m_angularFrictionTimescale = new Vector3(0, 0, 0); + case Vehicle.TYPE_NONE: m_linearMotorDirection = Vector3.Zero; m_linearMotorTimescale = 0; m_linearMotorDecayTimescale = 0; + m_linearFrictionTimescale = new Vector3(0, 0, 0); + m_angularMotorDirection = Vector3.Zero; - m_angularMotorTimescale = 0; m_angularMotorDecayTimescale = 0; + m_angularMotorTimescale = 0; + m_angularFrictionTimescale = new Vector3(0, 0, 0); + m_VhoverHeight = 0; + m_VhoverEfficiency = 0; m_VhoverTimescale = 0; m_VehicleBuoyancy = 0; + + m_linearDeflectionEfficiency = 1; + m_linearDeflectionTimescale = 1; + + m_angularDeflectionEfficiency = 0; + m_angularDeflectionTimescale = 1000; + + m_verticalAttractionEfficiency = 0; + m_verticalAttractionTimescale = 0; + + m_bankingEfficiency = 0; + m_bankingTimescale = 1000; + m_bankingMix = 1; + + m_referenceFrame = Quaternion.Identity; m_flags = (VehicleFlag)0; break; case Vehicle.TYPE_SLED: - m_linearFrictionTimescale = new Vector3(30, 1, 1000); - m_angularFrictionTimescale = new Vector3(1000, 1000, 1000); m_linearMotorDirection = Vector3.Zero; m_linearMotorTimescale = 1000; m_linearMotorDecayTimescale = 120; + m_linearFrictionTimescale = new Vector3(30, 1, 1000); + m_angularMotorDirection = Vector3.Zero; m_angularMotorTimescale = 1000; m_angularMotorDecayTimescale = 120; + m_angularFrictionTimescale = new Vector3(1000, 1000, 1000); + m_VhoverHeight = 0; -// m_VhoverEfficiency = 1; + m_VhoverEfficiency = 10; // TODO: this looks wrong!! m_VhoverTimescale = 10; m_VehicleBuoyancy = 0; - // m_linearDeflectionEfficiency = 1; - // m_linearDeflectionTimescale = 1; - // m_angularDeflectionEfficiency = 1; - // m_angularDeflectionTimescale = 1000; - // m_bankingEfficiency = 0; - // m_bankingMix = 1; - // m_bankingTimescale = 10; - // m_referenceFrame = Quaternion.Identity; + + m_linearDeflectionEfficiency = 1; + m_linearDeflectionTimescale = 1; + + m_angularDeflectionEfficiency = 1; + m_angularDeflectionTimescale = 1000; + + m_verticalAttractionEfficiency = 0; + m_verticalAttractionTimescale = 0; + + m_bankingEfficiency = 0; + m_bankingTimescale = 10; + m_bankingMix = 1; + + m_referenceFrame = Quaternion.Identity; m_flags |= (VehicleFlag.NO_DEFLECTION_UP | VehicleFlag.LIMIT_ROLL_ONLY | VehicleFlag.LIMIT_MOTOR_UP); m_flags &= ~(VehicleFlag.HOVER_WATER_ONLY | VehicleFlag.HOVER_TERRAIN_ONLY | VehicleFlag.HOVER_GLOBAL_HEIGHT | VehicleFlag.HOVER_UP_ONLY); break; case Vehicle.TYPE_CAR: - m_linearFrictionTimescale = new Vector3(100, 2, 1000); - m_angularFrictionTimescale = new Vector3(1000, 1000, 1000); m_linearMotorDirection = Vector3.Zero; m_linearMotorTimescale = 1; m_linearMotorDecayTimescale = 60; + m_linearFrictionTimescale = new Vector3(100, 2, 1000); + m_angularMotorDirection = Vector3.Zero; m_angularMotorTimescale = 1; m_angularMotorDecayTimescale = 0.8f; + m_angularFrictionTimescale = new Vector3(1000, 1000, 1000); + m_VhoverHeight = 0; -// m_VhoverEfficiency = 0; + m_VhoverEfficiency = 0; m_VhoverTimescale = 1000; m_VehicleBuoyancy = 0; - // // m_linearDeflectionEfficiency = 1; - // // m_linearDeflectionTimescale = 2; - // // m_angularDeflectionEfficiency = 0; - // m_angularDeflectionTimescale = 10; + + m_linearDeflectionEfficiency = 1; + m_linearDeflectionTimescale = 2; + + m_angularDeflectionEfficiency = 0; + m_angularDeflectionTimescale = 10; + m_verticalAttractionEfficiency = 1f; m_verticalAttractionTimescale = 10f; - // m_bankingEfficiency = -0.2f; - // m_bankingMix = 1; - // m_bankingTimescale = 1; - // m_referenceFrame = Quaternion.Identity; + + m_bankingEfficiency = -0.2f; + m_bankingMix = 1; + m_bankingTimescale = 1; + + m_referenceFrame = Quaternion.Identity; + m_flags &= ~(VehicleFlag.HOVER_WATER_ONLY + | VehicleFlag.HOVER_TERRAIN_ONLY + | VehicleFlag.HOVER_GLOBAL_HEIGHT); m_flags |= (VehicleFlag.NO_DEFLECTION_UP | VehicleFlag.LIMIT_ROLL_ONLY - | VehicleFlag.LIMIT_MOTOR_UP); - m_flags &= ~(VehicleFlag.HOVER_WATER_ONLY | VehicleFlag.HOVER_TERRAIN_ONLY | VehicleFlag.HOVER_GLOBAL_HEIGHT); - m_flags |= (VehicleFlag.HOVER_UP_ONLY); + | VehicleFlag.LIMIT_MOTOR_UP + | VehicleFlag.HOVER_UP_ONLY); break; case Vehicle.TYPE_BOAT: - m_linearFrictionTimescale = new Vector3(10, 3, 2); - m_angularFrictionTimescale = new Vector3(10,10,10); m_linearMotorDirection = Vector3.Zero; m_linearMotorTimescale = 5; m_linearMotorDecayTimescale = 60; + m_linearFrictionTimescale = new Vector3(10, 3, 2); + m_angularMotorDirection = Vector3.Zero; m_angularMotorTimescale = 4; m_angularMotorDecayTimescale = 4; + m_angularFrictionTimescale = new Vector3(10,10,10); + m_VhoverHeight = 0; -// m_VhoverEfficiency = 0.5f; + m_VhoverEfficiency = 0.5f; m_VhoverTimescale = 2; m_VehicleBuoyancy = 1; - // m_linearDeflectionEfficiency = 0.5f; - // m_linearDeflectionTimescale = 3; - // m_angularDeflectionEfficiency = 0.5f; - // m_angularDeflectionTimescale = 5; + + m_linearDeflectionEfficiency = 0.5f; + m_linearDeflectionTimescale = 3; + + m_angularDeflectionEfficiency = 0.5f; + m_angularDeflectionTimescale = 5; + m_verticalAttractionEfficiency = 0.5f; m_verticalAttractionTimescale = 5f; - // m_bankingEfficiency = -0.3f; - // m_bankingMix = 0.8f; - // m_bankingTimescale = 1; - // m_referenceFrame = Quaternion.Identity; + + m_bankingEfficiency = -0.3f; + m_bankingMix = 0.8f; + m_bankingTimescale = 1; + + m_referenceFrame = Quaternion.Identity; m_flags &= ~(VehicleFlag.HOVER_TERRAIN_ONLY | VehicleFlag.HOVER_GLOBAL_HEIGHT | VehicleFlag.LIMIT_ROLL_ONLY @@ -390,28 +428,35 @@ namespace OpenSim.Region.Physics.BulletSPlugin | VehicleFlag.HOVER_WATER_ONLY); break; case Vehicle.TYPE_AIRPLANE: - m_linearFrictionTimescale = new Vector3(200, 10, 5); - m_angularFrictionTimescale = new Vector3(20, 20, 20); m_linearMotorDirection = Vector3.Zero; m_linearMotorTimescale = 2; m_linearMotorDecayTimescale = 60; + m_linearFrictionTimescale = new Vector3(200, 10, 5); + m_angularMotorDirection = Vector3.Zero; m_angularMotorTimescale = 4; m_angularMotorDecayTimescale = 4; + m_angularFrictionTimescale = new Vector3(20, 20, 20); + m_VhoverHeight = 0; -// m_VhoverEfficiency = 0.5f; + m_VhoverEfficiency = 0.5f; m_VhoverTimescale = 1000; m_VehicleBuoyancy = 0; - // m_linearDeflectionEfficiency = 0.5f; - // m_linearDeflectionTimescale = 3; - // m_angularDeflectionEfficiency = 1; - // m_angularDeflectionTimescale = 2; + + m_linearDeflectionEfficiency = 0.5f; + m_linearDeflectionTimescale = 3; + + m_angularDeflectionEfficiency = 1; + m_angularDeflectionTimescale = 2; + m_verticalAttractionEfficiency = 0.9f; m_verticalAttractionTimescale = 2f; - // m_bankingEfficiency = 1; - // m_bankingMix = 0.7f; - // m_bankingTimescale = 2; - // m_referenceFrame = Quaternion.Identity; + + m_bankingEfficiency = 1; + m_bankingMix = 0.7f; + m_bankingTimescale = 2; + + m_referenceFrame = Quaternion.Identity; m_flags &= ~(VehicleFlag.HOVER_WATER_ONLY | VehicleFlag.HOVER_TERRAIN_ONLY | VehicleFlag.HOVER_GLOBAL_HEIGHT @@ -421,28 +466,36 @@ namespace OpenSim.Region.Physics.BulletSPlugin m_flags |= (VehicleFlag.LIMIT_ROLL_ONLY); break; case Vehicle.TYPE_BALLOON: - m_linearFrictionTimescale = new Vector3(5, 5, 5); - m_angularFrictionTimescale = new Vector3(10, 10, 10); m_linearMotorDirection = Vector3.Zero; m_linearMotorTimescale = 5; + m_linearFrictionTimescale = new Vector3(5, 5, 5); m_linearMotorDecayTimescale = 60; + m_angularMotorDirection = Vector3.Zero; m_angularMotorTimescale = 6; + m_angularFrictionTimescale = new Vector3(10, 10, 10); m_angularMotorDecayTimescale = 10; + m_VhoverHeight = 5; -// m_VhoverEfficiency = 0.8f; + m_VhoverEfficiency = 0.8f; m_VhoverTimescale = 10; m_VehicleBuoyancy = 1; - // m_linearDeflectionEfficiency = 0; - // m_linearDeflectionTimescale = 5; - // m_angularDeflectionEfficiency = 0; - // m_angularDeflectionTimescale = 5; + + m_linearDeflectionEfficiency = 0; + m_linearDeflectionTimescale = 5; + + m_angularDeflectionEfficiency = 0; + m_angularDeflectionTimescale = 5; + m_verticalAttractionEfficiency = 1f; m_verticalAttractionTimescale = 100f; - // m_bankingEfficiency = 0; - // m_bankingMix = 0.7f; - // m_bankingTimescale = 5; - // m_referenceFrame = Quaternion.Identity; + + m_bankingEfficiency = 0; + m_bankingMix = 0.7f; + m_bankingTimescale = 5; + m_referenceFrame = Quaternion.Identity; + + m_referenceFrame = Quaternion.Identity; m_flags &= ~(VehicleFlag.HOVER_WATER_ONLY | VehicleFlag.HOVER_TERRAIN_ONLY | VehicleFlag.HOVER_UP_ONLY @@ -452,21 +505,27 @@ namespace OpenSim.Region.Physics.BulletSPlugin | VehicleFlag.HOVER_GLOBAL_HEIGHT); break; } - }//end SetDefaultsForType + } // Some of the properties of this prim may have changed. // Do any updating needed for a vehicle public void Refresh() { - if (!IsActive) - return; - - // Set the prim's inertia to zero. The vehicle code handles that and this - // removes the motion and torque actions introduced by Bullet. - Vector3 inertia = Vector3.Zero; - // comment out for DEBUG test - // BulletSimAPI.SetMassProps2(Prim.BSBody.ptr, Prim.MassRaw, inertia); - // BulletSimAPI.UpdateInertiaTensor2(Prim.BSBody.ptr); + /* + * Doesnt work unless BSDynamics senses and corrects for all collisions + if (IsActive) + BulletSimAPI.AddToCollisionFlags2(Prim.BSBody.ptr, CollisionFlags.CF_KINEMATIC_OBJECT); + else + BulletSimAPI.RemoveFromCollisionFlags2(Prim.BSBody.ptr, CollisionFlags.CF_KINEMATIC_OBJECT); + */ + /* + * Doesn't work because with zero inertia, Bullet will not apply any forces to the object. + if (IsActive) + { + BulletSimAPI.SetMassProps2(Prim.BSBody.ptr, Prim.MassRaw, Vector3.Zero); + BulletSimAPI.UpdateInertiaTensor2(Prim.BSBody.ptr); + } + */ } // One step of the vehicle properties for the next 'pTimestep' seconds. @@ -478,6 +537,22 @@ namespace OpenSim.Region.Physics.BulletSPlugin MoveAngular(pTimestep); LimitRotation(pTimestep); + /* Experimental + // Wonder if Bullet could handle collision penetration while this applies the forces. + // Apply the computed forces on the vehicle + Prim.ForcePosition += Prim.ForceVelocity * Prim.MassRaw * pTimestep; + + if (Prim.ForceRotationalVelocity != Vector3.Zero) + { + Quaternion newOrientation = Prim.ForceOrientation; + newOrientation.Normalize(); + Quaternion appliedRotation = new Quaternion((Prim.ForceRotationalVelocity * pTimestep), 0f); + newOrientation += (appliedRotation * newOrientation) * 0.5f; + newOrientation.Normalize(); + Prim.ForceOrientation = newOrientation; + } + */ + // remember the position so next step we can limit absolute movement effects m_lastPositionVector = Prim.ForcePosition; @@ -489,59 +564,46 @@ namespace OpenSim.Region.Physics.BulletSPlugin // Also does hover and float. private void MoveLinear(float pTimestep) { - // m_linearMotorDirection is the direction we are moving relative to the vehicle coordinates - // m_lastLinearVelocityVector is the speed we are moving in that direction + // m_linearMotorDirection is the target direction we are moving relative to the vehicle coordinates + // m_lastLinearVelocityVector is the current speed we are moving in that direction if (m_linearMotorDirection.LengthSquared() > 0.001f) { Vector3 origDir = m_linearMotorDirection; Vector3 origVel = m_lastLinearVelocityVector; // add drive to body - // Vector3 addAmount = m_linearMotorDirection/(m_linearMotorTimescale / pTimestep); Vector3 addAmount = (m_linearMotorDirection - m_lastLinearVelocityVector)/(m_linearMotorTimescale / pTimestep); // lastLinearVelocityVector is the current body velocity vector - // RA: Not sure what the *10 is for. A correction for pTimestep? - // m_lastLinearVelocityVector += (addAmount*10); m_lastLinearVelocityVector += addAmount; - // Limit the velocity vector to less than the last set linear motor direction - if (Math.Abs(m_lastLinearVelocityVector.X) > Math.Abs(m_linearMotorDirectionLASTSET.X)) - m_lastLinearVelocityVector.X = m_linearMotorDirectionLASTSET.X; - if (Math.Abs(m_lastLinearVelocityVector.Y) > Math.Abs(m_linearMotorDirectionLASTSET.Y)) - m_lastLinearVelocityVector.Y = m_linearMotorDirectionLASTSET.Y; - if (Math.Abs(m_lastLinearVelocityVector.Z) > Math.Abs(m_linearMotorDirectionLASTSET.Z)) - m_lastLinearVelocityVector.Z = m_linearMotorDirectionLASTSET.Z; - - /* - // decay applied velocity - Vector3 decayfraction = Vector3.One/(m_linearMotorDecayTimescale / pTimestep); - // (RA: do not know where the 0.5f comes from) - m_linearMotorDirection -= m_linearMotorDirection * decayfraction * 0.5f; - */ float keepfraction = 1.0f - (1.0f / (m_linearMotorDecayTimescale / pTimestep)); m_linearMotorDirection *= keepfraction; VDetailLog("{0},MoveLinear,nonZero,origdir={1},origvel={2},add={3},notDecay={4},dir={5},vel={6}", Prim.LocalID, origDir, origVel, addAmount, keepfraction, m_linearMotorDirection, m_lastLinearVelocityVector); + + // convert requested object velocity to object relative vector + m_newVelocity = m_lastLinearVelocityVector * Prim.ForceOrientation; } else { // if what remains of direction is very small, zero it. m_linearMotorDirection = Vector3.Zero; m_lastLinearVelocityVector = Vector3.Zero; + m_newVelocity = Vector3.Zero; + VDetailLog("{0},MoveLinear,zeroed", Prim.LocalID); } - // convert requested object velocity to object relative vector - Quaternion rotq = Prim.ForceOrientation; - m_newVelocity = m_lastLinearVelocityVector * rotq; + // m_newVelocity is velocity computed from linear motor // Add the various forces into m_dir which will be our new direction vector (velocity) // add Gravity and Buoyancy // There is some gravity, make a gravity force vector that is applied after object velocity. // m_VehicleBuoyancy: -1=2g; 0=1g; 1=0g; - Vector3 grav = Prim.PhysicsScene.DefaultGravity * (Prim.Linkset.LinksetMass * (1f - m_VehicleBuoyancy)); + // Vector3 grav = Prim.PhysicsScene.DefaultGravity * (Prim.Linkset.LinksetMass * (1f - m_VehicleBuoyancy)); + Vector3 grav = Prim.PhysicsScene.DefaultGravity * (1f - m_VehicleBuoyancy); /* * RA: Not sure why one would do this @@ -567,6 +629,8 @@ namespace OpenSim.Region.Physics.BulletSPlugin } // Check if hovering + // m_VhoverEfficiency: 0=bouncy, 1=totally damped + // m_VhoverTimescale: time to achieve height if ((m_flags & (VehicleFlag.HOVER_WATER_ONLY | VehicleFlag.HOVER_TERRAIN_ONLY | VehicleFlag.HOVER_GLOBAL_HEIGHT)) != 0) { // We should hover, get the target height @@ -597,13 +661,19 @@ namespace OpenSim.Region.Physics.BulletSPlugin } else { - float herr0 = pos.Z - m_VhoverTargetHeight; + float horizontalError = pos.Z - m_VhoverTargetHeight; + // RA: where does the 50 come from> + float horizontalCorrectionVelocity = ((horizontalError * 50.0f) / (m_VhoverTimescale / pTimestep)); // Replace Vertical speed with correction figure if significant - if (Math.Abs(herr0) > 0.01f) + if (Math.Abs(horizontalError) > 0.01f) { - m_newVelocity.Z = -((herr0 * pTimestep * 50.0f) / m_VhoverTimescale); + m_newVelocity.Z += horizontalCorrectionVelocity; //KF: m_VhoverEfficiency is not yet implemented } + else if (horizontalError < -0.01) + { + m_newVelocity.Z -= horizontalCorrectionVelocity; + } else { m_newVelocity.Z = 0f; @@ -678,16 +748,14 @@ namespace OpenSim.Region.Physics.BulletSPlugin if ((m_flags & (VehicleFlag.NO_Z)) != 0) m_newVelocity.Z = 0; - // Apply velocity - Prim.ForceVelocity = m_newVelocity; - // apply gravity force - // Why is this set here? The physics engine already does gravity. - Prim.AddForce(grav, false, true); - // Apply friction Vector3 keepFraction = Vector3.One - (Vector3.One / (m_linearFrictionTimescale / pTimestep)); m_lastLinearVelocityVector *= keepFraction; + // Apply velocity + // Prim.ForceVelocity = m_newVelocity; + Prim.AddForce(m_newVelocity, false); + VDetailLog("{0},MoveLinear,done,lmDir={1},lmVel={2},newVel={3},grav={4},1Mdecay={5}", Prim.LocalID, m_linearMotorDirection, m_lastLinearVelocityVector, m_newVelocity, grav, keepFraction); @@ -717,11 +785,9 @@ namespace OpenSim.Region.Physics.BulletSPlugin Vector3 origDir = m_angularMotorDirection; // ramp up to new value - // new velocity += error / ( time to get there / step interval) - // requested speed - last motor speed - m_angularMotorVelocity.X += (m_angularMotorDirection.X - m_angularMotorVelocity.X) / (m_angularMotorTimescale / pTimestep); - m_angularMotorVelocity.Y += (m_angularMotorDirection.Y - m_angularMotorVelocity.Y) / (m_angularMotorTimescale / pTimestep); - m_angularMotorVelocity.Z += (m_angularMotorDirection.Z - m_angularMotorVelocity.Z) / (m_angularMotorTimescale / pTimestep); + // new velocity += error / ( time to get there / step interval) + // requested speed - last motor speed + m_angularMotorVelocity += (m_angularMotorDirection - m_angularMotorVelocity) / (m_angularMotorTimescale / pTimestep); VDetailLog("{0},MoveAngular,angularMotorApply,apply={1},angTScale={2},timeStep={3},origvel={4},origDir={5},vel={6}", Prim.LocalID, m_angularMotorApply, m_angularMotorTimescale, pTimestep, origVel, origDir, m_angularMotorVelocity); @@ -732,46 +798,50 @@ namespace OpenSim.Region.Physics.BulletSPlugin { // No motor recently applied, keep the body velocity // and decay the velocity - m_angularMotorVelocity -= m_angularMotorVelocity / (m_angularMotorDecayTimescale / pTimestep); - if (m_angularMotorVelocity.LengthSquared() < 0.00001) + if (m_angularMotorVelocity.LengthSquared() < 0.0001) m_angularMotorVelocity = Vector3.Zero; + else + m_angularMotorVelocity -= m_angularMotorVelocity / (m_angularMotorDecayTimescale / pTimestep); } // end motor section - // Vertical attractor section + #region Vertical attactor + Vector3 vertattr = Vector3.Zero; Vector3 deflection = Vector3.Zero; Vector3 banking = Vector3.Zero; if (m_verticalAttractionTimescale < 300 && m_lastAngularVelocity != Vector3.Zero) { - float VAservo = 0.2f / (m_verticalAttractionTimescale / pTimestep); + float VAservo = 0.2f; + if (Prim.Linkset.LinksetIsColliding) + VAservo = 0.05f / (m_verticalAttractionTimescale / pTimestep); + VAservo *= (m_verticalAttractionEfficiency * m_verticalAttractionEfficiency); // get present body rotation Quaternion rotq = Prim.ForceOrientation; // vector pointing up - Vector3 verterr = Vector3.Zero; - verterr.Z = 1.0f; + Vector3 verticalError = Vector3.UnitZ; // rotate it to Body Angle - verterr = verterr * rotq; - // verterr.X and .Y are the World error amounts. They are 0 when there is no error (Vehicle Body is 'vertical'), and .Z will be 1. + verticalError = verticalError * rotq; + // verticalError.X and .Y are the World error amounts. They are 0 when there is no error (Vehicle Body is 'vertical'), and .Z will be 1. // As the body leans to its side |.X| will increase to 1 and .Z fall to 0. As body inverts |.X| will fall and .Z will go // negative. Similar for tilt and |.Y|. .X and .Y must be modulated to prevent a stable inverted body. // Error is 0 (no error) to +/- 2 (max error) - if (verterr.Z < 0.0f) + if (verticalError.Z < 0.0f) { - verterr.X = 2.0f - verterr.X; - verterr.Y = 2.0f - verterr.Y; + verticalError.X = 2.0f - verticalError.X; + verticalError.Y = 2.0f - verticalError.Y; } // scale it by VAservo - verterr = verterr * VAservo; + verticalError = verticalError * VAservo; - // As the body rotates around the X axis, then verterr.Y increases; Rotated around Y then .X increases, so + // As the body rotates around the X axis, then verticalError.Y increases; Rotated around Y then .X increases, so // Change Body angular velocity X based on Y, and Y based on X. Z is not changed. - vertattr.X = verterr.Y; - vertattr.Y = - verterr.X; + vertattr.X = verticalError.Y; + vertattr.Y = - verticalError.X; vertattr.Z = 0f; // scaling appears better usingsquare-law @@ -779,10 +849,77 @@ namespace OpenSim.Region.Physics.BulletSPlugin vertattr.X += bounce * angularVelocity.X; vertattr.Y += bounce * angularVelocity.Y; - VDetailLog("{0},MoveAngular,verticalAttraction,verterr={1},bounce={2},vertattr={3}", - Prim.LocalID, verterr, bounce, vertattr); + VDetailLog("{0},MoveAngular,verticalAttraction,verticalError={1},bounce={2},vertattr={3}", + Prim.LocalID, verticalError, bounce, vertattr); + + } + #endregion // Vertical attactor + + #region Deflection + + //Forward is the prefered direction, but if the reference frame has changed, we need to take this into account as well + Vector3 PreferredAxisOfMotion = + new Vector3((10*(m_angularDeflectionEfficiency/m_angularDeflectionTimescale)), 0, 0); + PreferredAxisOfMotion *= Quaternion.Add(Prim.ForceOrientation, m_referenceFrame); + + //Multiply it so that it scales linearly + //deflection = PreferredAxisOfMotion; + + //deflection = ((PreferredAxisOfMotion * m_angularDeflectionEfficiency) / (m_angularDeflectionTimescale / pTimestep)); + + #endregion - } // else vertical attractor is off + #region Banking + + if (m_bankingEfficiency != 0) + { + Vector3 dir = Vector3.One * Prim.ForceOrientation; + float mult = (m_bankingMix*m_bankingMix)*-1*(m_bankingMix < 0 ? -1 : 1); + //Changes which way it banks in and out of turns + + //Use the square of the efficiency, as it looks much more how SL banking works + float effSquared = (m_bankingEfficiency*m_bankingEfficiency); + if (m_bankingEfficiency < 0) + effSquared *= -1; //Keep the negative! + + float mix = Math.Abs(m_bankingMix); + if (m_angularMotorVelocity.X == 0) + { + /*if (!parent.Orientation.ApproxEquals(this.m_referenceFrame, 0.25f)) + { + Vector3 axisAngle; + float angle; + parent.Orientation.GetAxisAngle(out axisAngle, out angle); + Vector3 rotatedVel = parent.Velocity * parent.Orientation; + if ((rotatedVel.X < 0 && axisAngle.Y > 0) || (rotatedVel.X > 0 && axisAngle.Y < 0)) + m_angularMotorVelocity.X += (effSquared * (mult * mix)) * (1f) * 10; + else + m_angularMotorVelocity.X += (effSquared * (mult * mix)) * (-1f) * 10; + }*/ + } + else + banking.Z += (effSquared*(mult*mix))*(m_angularMotorVelocity.X) * 4; + if (!Prim.Linkset.LinksetIsColliding && Math.Abs(m_angularMotorVelocity.X) > mix) + //If they are colliding, we probably shouldn't shove the prim around... probably + { + float angVelZ = m_angularMotorVelocity.X*-1; + /*if(angVelZ > mix) + angVelZ = mix; + else if(angVelZ < -mix) + angVelZ = -mix;*/ + //This controls how fast and how far the banking occurs + Vector3 bankingRot = new Vector3(angVelZ*(effSquared*mult), 0, 0); + if (bankingRot.X > 3) + bankingRot.X = 3; + else if (bankingRot.X < -3) + bankingRot.X = -3; + bankingRot *= Prim.ForceOrientation; + banking += bankingRot; + } + m_angularMotorVelocity.X *= m_bankingEfficiency == 1 ? 0.0f : 1 - m_bankingEfficiency; + } + + #endregion m_lastVertAttractor = vertattr; @@ -811,7 +948,8 @@ namespace OpenSim.Region.Physics.BulletSPlugin m_lastAngularVelocity -= m_lastAngularVelocity * decayamount; // Apply to the body - Prim.ForceRotationalVelocity = m_lastAngularVelocity; + // Prim.ForceRotationalVelocity = m_lastAngularVelocity; + Prim.AddAngularForce(m_lastAngularVelocity, false); VDetailLog("{0},MoveAngular,done,decay={1},lastAngular={2}", Prim.LocalID, decayamount, m_lastAngularVelocity); } //end MoveAngular @@ -820,38 +958,31 @@ namespace OpenSim.Region.Physics.BulletSPlugin { Quaternion rotq = Prim.ForceOrientation; Quaternion m_rot = rotq; - bool changed = false; if (m_RollreferenceFrame != Quaternion.Identity) { if (rotq.X >= m_RollreferenceFrame.X) { m_rot.X = rotq.X - (m_RollreferenceFrame.X / 2); - changed = true; } if (rotq.Y >= m_RollreferenceFrame.Y) { m_rot.Y = rotq.Y - (m_RollreferenceFrame.Y / 2); - changed = true; } if (rotq.X <= -m_RollreferenceFrame.X) { m_rot.X = rotq.X + (m_RollreferenceFrame.X / 2); - changed = true; } if (rotq.Y <= -m_RollreferenceFrame.Y) { m_rot.Y = rotq.Y + (m_RollreferenceFrame.Y / 2); - changed = true; } - changed = true; } if ((m_flags & VehicleFlag.LOCK_ROTATION) != 0) { m_rot.X = 0; m_rot.Y = 0; - changed = true; } - if (changed) + if (rotq != m_rot) { Prim.ForceOrientation = m_rot; VDetailLog("{0},LimitRotation,done,orig={1},new={2}", Prim.LocalID, rotq, m_rot); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSHingeConstraint.cs b/OpenSim/Region/Physics/BulletSPlugin/BSHingeConstraint.cs index 7c8a215..76bd930 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSHingeConstraint.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSHingeConstraint.cs @@ -32,7 +32,7 @@ using OpenMetaverse; namespace OpenSim.Region.Physics.BulletSPlugin { -class BSHingeConstraint : BSConstraint +public sealed class BSHingeConstraint : BSConstraint { public override ConstraintType Type { get { return ConstraintType.HINGE_CONSTRAINT_TYPE; } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index c984824..24fe6b9 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -88,6 +88,8 @@ public abstract class BSLinkset } } + public virtual bool LinksetIsColliding { get { return false; } } + public OMV.Vector3 CenterOfMass { get { return ComputeLinksetCenterOfMass(); } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs index 8a750b5..003c294 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs @@ -32,7 +32,7 @@ using OMV = OpenMetaverse; namespace OpenSim.Region.Physics.BulletSPlugin { -public class BSLinksetConstraints : BSLinkset +public sealed class BSLinksetConstraints : BSLinkset { // private static string LogHeader = "[BULLETSIM LINKSET CONSTRAINTS]"; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 38ab3de..39d20dc 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -311,6 +311,7 @@ public sealed class BSPrim : BSPhysObject if ((CurrentCollisionFlags & CollisionFlags.BS_FLOATS_ON_WATER) != 0) { float waterHeight = PhysicsScene.GetWaterLevelAtXYZ(_position); + // TODO: a floating motor so object will bob in the water if (Position.Z < waterHeight) { _position.Z = waterHeight; @@ -902,7 +903,8 @@ public sealed class BSPrim : BSPhysObject } // DetailLog("{0},BSPrim.AddObjectForce,taint,force={1}", LocalID, fSum); // For unknown reasons, "ApplyCentralForce" adds this force to the total force on the object. - BulletSimAPI.ApplyCentralForce2(BSBody.ptr, fSum); + if (fSum != OMV.Vector3.Zero) + BulletSimAPI.ApplyCentralForce2(BSBody.ptr, fSum); }; if (inTaintTime) addForceOperation(); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index db0c99e..9e95ce5 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -62,7 +62,7 @@ using OpenMetaverse; // namespace OpenSim.Region.Physics.BulletSPlugin { -public class BSScene : PhysicsScene, IPhysicsParameters +public sealed class BSScene : PhysicsScene, IPhysicsParameters { private static readonly ILog m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly string LogHeader = "[BULLETS SCENE]"; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index 30fa50a..1c0e6f5 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -34,7 +34,7 @@ using OpenSim.Region.Physics.ConvexDecompositionDotNet; namespace OpenSim.Region.Physics.BulletSPlugin { -public class BSShapeCollection : IDisposable +public sealed class BSShapeCollection : IDisposable { private static string LogHeader = "[BULLETSIM SHAPE COLLECTION]"; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs index 880859a..11298fe 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs @@ -40,7 +40,7 @@ using OpenMetaverse; namespace OpenSim.Region.Physics.BulletSPlugin { -public class BSTerrainManager +public sealed class BSTerrainManager { static string LogHeader = "[BULLETSIM TERRAIN MANAGER]"; -- cgit v1.1 From b83449ae9ad3073abaa06167a99c47943c3199c2 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Fri, 26 Oct 2012 13:47:28 -0700 Subject: BulletSim: correct spelling of Bullet call. It's 'swept' not 'sweep'. --- OpenSim/Region/Physics/BulletSPlugin/BS6DofConstraint.cs | 4 ++++ OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs | 2 +- OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs | 4 ++-- 3 files changed, 7 insertions(+), 3 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BS6DofConstraint.cs b/OpenSim/Region/Physics/BulletSPlugin/BS6DofConstraint.cs index 310df3d..ecb3ec8 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BS6DofConstraint.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BS6DofConstraint.cs @@ -135,7 +135,11 @@ public sealed class BS6DofConstraint : BSConstraint bool ret = false; float onOff = enable ? ConfigurationParameters.numericTrue : ConfigurationParameters.numericFalse; if (m_enabled) + { ret = BulletSimAPI.TranslationalLimitMotor2(m_constraint.ptr, onOff, targetVelocity, maxMotorForce); + m_world.physicsScene.DetailLog("{0},BS6DOFConstraint,TransLimitMotor,enable={1},vel={2},maxForce={3}", + BSScene.DetailLogZero, enable, targetVelocity, maxMotorForce); + } return ret; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index 9fea9b8..8bb4b21 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -152,7 +152,7 @@ public sealed class BSCharacter : BSPhysObject if (PhysicsScene.Params.ccdMotionThreshold > 0f) { BulletSimAPI.SetCcdMotionThreshold2(BSBody.ptr, PhysicsScene.Params.ccdMotionThreshold); - BulletSimAPI.SetCcdSweepSphereRadius2(BSBody.ptr, PhysicsScene.Params.ccdSweptSphereRadius); + BulletSimAPI.SetCcdSweptSphereRadius2(BSBody.ptr, PhysicsScene.Params.ccdSweptSphereRadius); } OMV.Vector3 localInertia = BulletSimAPI.CalculateLocalInertia2(BSShape.ptr, MassRaw); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs index 5ffd591..be3a5ad 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs @@ -881,10 +881,10 @@ public static extern float GetCcdMotionThreshold2(IntPtr obj); public static extern void SetCcdMotionThreshold2(IntPtr obj, float val); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern float GetCcdSweepSphereRadius2(IntPtr obj); +public static extern float GetCcdSweptSphereRadius2(IntPtr obj); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern void SetCcdSweepSphereRadius2(IntPtr obj, float val); +public static extern void SetCcdSweptSphereRadius2(IntPtr obj, float val); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern IntPtr GetUserPointer2(IntPtr obj); -- cgit v1.1 From 8fa83cf43045401ee02321e0fb1191402db5bb05 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Fri, 26 Oct 2012 13:49:57 -0700 Subject: BulletSim: Add activations after vehicle properties change. Problem was the vehicle was going to sleep while waiting for commands. Make AddAngularForce work the same way as AddForce -- accumulates values and pushes them once into Bullet. --- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 74 +++++++++++++++++++++----- 1 file changed, 62 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 39d20dc..44937df 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -242,8 +242,8 @@ public sealed class BSPrim : BSPhysObject _acceleration = OMV.Vector3.Zero; _rotationalVelocity = OMV.Vector3.Zero; - // Zero some other properties directly into the physics engine - BulletSimAPI.ClearForces2(BSBody.ptr); + // Zero some other properties in the physics engine + BulletSimAPI.ClearAllForces2(BSBody.ptr); } public override void LockAngularMotion(OMV.Vector3 axis) @@ -275,6 +275,7 @@ public sealed class BSPrim : BSPhysObject { // DetailLog("{0},BSPrim.SetPosition,taint,pos={1},orient={2}", LocalID, _position, _orientation); BulletSimAPI.SetTranslation2(BSBody.ptr, _position, _orientation); + ActivateIfPhysical(false); }); } } @@ -287,6 +288,7 @@ public sealed class BSPrim : BSPhysObject _position = value; PositionSanityCheck(); BulletSimAPI.SetTranslation2(BSBody.ptr, _position, _orientation); + ActivateIfPhysical(false); } } @@ -401,6 +403,7 @@ public sealed class BSPrim : BSPhysObject // 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. _vehicle.ProcessTypeChange(type); + ActivateIfPhysical(false); }); } } @@ -409,6 +412,7 @@ public sealed class BSPrim : BSPhysObject PhysicsScene.TaintedObject("BSPrim.VehicleFloatParam", delegate() { _vehicle.ProcessFloatVehicleParam((Vehicle)param, value); + ActivateIfPhysical(false); }); } public override void VehicleVectorParam(int param, OMV.Vector3 value) @@ -416,6 +420,7 @@ public sealed class BSPrim : BSPhysObject PhysicsScene.TaintedObject("BSPrim.VehicleVectorParam", delegate() { _vehicle.ProcessVectorVehicleParam((Vehicle)param, value); + ActivateIfPhysical(false); }); } public override void VehicleRotationParam(int param, OMV.Quaternion rotation) @@ -423,6 +428,7 @@ public sealed class BSPrim : BSPhysObject PhysicsScene.TaintedObject("BSPrim.VehicleRotationParam", delegate() { _vehicle.ProcessRotationVehicleParam((Vehicle)param, rotation); + ActivateIfPhysical(false); }); } public override void VehicleFlags(int param, bool remove) @@ -540,6 +546,8 @@ public sealed class BSPrim : BSPhysObject { // DetailLog("{0},setIsPhysical,taint,isPhys={1}", LocalID, _isPhysical); SetObjectDynamic(true); + // whether phys-to-static or static-to-phys, the object is not moving. + ZeroMotion(); }); } } @@ -623,7 +631,7 @@ public sealed class BSPrim : BSPhysObject // Become a Bullet 'static' object type CurrentCollisionFlags = BulletSimAPI.AddToCollisionFlags2(BSBody.ptr, CollisionFlags.CF_STATIC_OBJECT); // Stop all movement - BulletSimAPI.ClearAllForces2(BSBody.ptr); + ZeroMotion(); // Center of mass is at the center of the object BulletSimAPI.SetCenterOfMassByPosRot2(Linkset.LinksetRoot.BSBody.ptr, _position, _orientation); // Mass is zero which disables a bunch of physics stuff in Bullet @@ -634,7 +642,7 @@ public sealed class BSPrim : BSPhysObject if (PhysicsScene.Params.ccdMotionThreshold > 0f) { BulletSimAPI.SetCcdMotionThreshold2(BSBody.ptr, PhysicsScene.Params.ccdMotionThreshold); - BulletSimAPI.SetCcdSweepSphereRadius2(BSBody.ptr, PhysicsScene.Params.ccdSweptSphereRadius); + BulletSimAPI.SetCcdSweptSphereRadius2(BSBody.ptr, PhysicsScene.Params.ccdSweptSphereRadius); } // There can be special things needed for implementing linksets Linkset.MakeStatic(this); @@ -656,14 +664,14 @@ public sealed class BSPrim : BSPhysObject BulletSimAPI.SetRestitution2(BSBody.ptr, PhysicsScene.Params.defaultRestitution); // per http://www.bulletphysics.org/Bullet/phpBB3/viewtopic.php?t=3382 - BulletSimAPI.ClearAllForces2(BSBody.ptr); + // Since this can be called multiple times, only zero forces when becoming physical + // BulletSimAPI.ClearAllForces2(BSBody.ptr); // For good measure, make sure the transform is set through to the motion state BulletSimAPI.SetTranslation2(BSBody.ptr, _position, _orientation); // A dynamic object has mass - IntPtr collisionShapePtr = BulletSimAPI.GetCollisionShape2(BSBody.ptr); - OMV.Vector3 inertia = BulletSimAPI.CalculateLocalInertia2(collisionShapePtr, Mass); + OMV.Vector3 inertia = BulletSimAPI.CalculateLocalInertia2(BSShape.ptr, Mass); BulletSimAPI.SetMassProps2(BSBody.ptr, _mass, inertia); BulletSimAPI.UpdateInertiaTensor2(BSBody.ptr); @@ -671,7 +679,7 @@ public sealed class BSPrim : BSPhysObject if (PhysicsScene.Params.ccdMotionThreshold > 0f) { BulletSimAPI.SetCcdMotionThreshold2(BSBody.ptr, PhysicsScene.Params.ccdMotionThreshold); - BulletSimAPI.SetCcdSweepSphereRadius2(BSBody.ptr, PhysicsScene.Params.ccdSweptSphereRadius); + BulletSimAPI.SetCcdSweptSphereRadius2(BSBody.ptr, PhysicsScene.Params.ccdSweptSphereRadius); } // Various values for simulation limits @@ -721,6 +729,15 @@ public sealed 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) + BulletSimAPI.Activate2(BSBody.ptr, forceIt); + } + // Turn on or off the flag controlling whether collision events are returned to the simulator. private void EnableCollisions(bool wantsCollisionEvents) { @@ -901,8 +918,7 @@ public sealed class BSPrim : BSPhysObject } m_accumulatedForces.Clear(); } - // DetailLog("{0},BSPrim.AddObjectForce,taint,force={1}", LocalID, fSum); - // For unknown reasons, "ApplyCentralForce" adds this force to the total force on the object. + DetailLog("{0},BSPrim.AddForce,taint,force={1}", LocalID, fSum); if (fSum != OMV.Vector3.Zero) BulletSimAPI.ApplyCentralForce2(BSBody.ptr, fSum); }; @@ -912,9 +928,43 @@ public sealed class BSPrim : BSPhysObject PhysicsScene.TaintedObject("BSPrim.AddForce", addForceOperation); } + private List m_accumulatedAngularForces = new List(); public override void AddAngularForce(OMV.Vector3 force, bool pushforce) { - // DetailLog("{0},BSPrim.AddAngularForce,call,angForce={1},push={2}", LocalID, force, pushforce); - // m_log.DebugFormat("{0}: AddAngularForce. f={1}, push={2}", LogHeader, force, pushforce); + AddAngularForce(force, pushforce, false); + } + public void AddAngularForce(OMV.Vector3 force, bool pushforce, bool inTaintTime) + { + if (force.IsFinite()) + { + // _force += force; + lock (m_accumulatedAngularForces) + m_accumulatedAngularForces.Add(new OMV.Vector3(force)); + } + else + { + m_log.WarnFormat("{0}: Got a NaN force applied to a prim. LocalID={1}", LogHeader, LocalID); + return; + } + BSScene.TaintCallback addAngularForceOperation = delegate() + { + OMV.Vector3 fSum = OMV.Vector3.Zero; + lock (m_accumulatedAngularForces) + { + // Sum the accumulated additional forces for one big force to apply once. + foreach (OMV.Vector3 v in m_accumulatedAngularForces) + { + fSum += v; + } + m_accumulatedAngularForces.Clear(); + } + // DetailLog("{0},BSPrim.AddAngularForce,taint,aForce={1}", LocalID, fSum); + if (fSum != OMV.Vector3.Zero) + BulletSimAPI.ApplyTorque2(BSBody.ptr, fSum); + }; + if (inTaintTime) + addAngularForceOperation(); + else + PhysicsScene.TaintedObject("BSPrim.AddForce", addAngularForceOperation); } public override void SetMomentum(OMV.Vector3 momentum) { // DetailLog("{0},BSPrim.SetMomentum,call,mom={1}", LocalID, momentum); -- cgit v1.1 From 2b75035aefceeae44e35364036a0748dfd5fb786 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Fri, 26 Oct 2012 13:54:54 -0700 Subject: BulletSim: add ForEachMember(action) call for linkset. --- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 36 ++++++++++++++++++----- 1 file changed, 28 insertions(+), 8 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index 24fe6b9..d0e514b 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -167,9 +167,8 @@ public abstract class BSLinkset bool ret = false; lock (m_linksetActivityLock) { - if (m_children.Contains(child)) - ret = true; - /* + ret = m_children.Contains(child); + /* Safer version but the above should work foreach (BSPhysObject bp in m_children) { if (child.LocalID == bp.LocalID) @@ -183,6 +182,25 @@ public abstract class BSLinkset return ret; } + // Perform an action on each member of the linkset including root prim. + // The action is performed only on the objects that are physically in the linkset. + // Depends on the action on whether this should be done at taint time. + public delegate bool ForEachMemberAction(BSPhysObject obj); + public virtual bool ForEachMember(ForEachMemberAction action) + { + bool ret = false; + lock (m_linksetActivityLock) + { + action(LinksetRoot); + foreach (BSPhysObject po in m_taintChildren) + { + if (action(po)) + break; + } + } + return ret; + } + // When physical properties are changed the linkset needs to recalculate // its internal properties. // May be called at runtime or taint-time (just pass the appropriate flag). @@ -224,13 +242,15 @@ public abstract class BSLinkset protected virtual float ComputeLinksetMass() { - float mass; - lock (m_linksetActivityLock) + float mass = LinksetRoot.MassRaw; + if (HasAnyChildren) { - mass = LinksetRoot.MassRaw; - foreach (BSPhysObject bp in m_taintChildren) + lock (m_linksetActivityLock) { - mass += bp.MassRaw; + foreach (BSPhysObject bp in m_children) + { + mass += bp.MassRaw; + } } } return mass; -- cgit v1.1 From 92d3c611e57fc320bf20b6b500c275eaebf912aa Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Fri, 26 Oct 2012 13:55:20 -0700 Subject: BulletSim: many small changes for vehicles simulation. --- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 71 ++++++++++++---------- 1 file changed, 40 insertions(+), 31 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index 9b59bef..8bd8117 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -526,6 +526,12 @@ namespace OpenSim.Region.Physics.BulletSPlugin BulletSimAPI.UpdateInertiaTensor2(Prim.BSBody.ptr); } */ + if (IsActive) + { + // Friction effects are handled by this vehicle code + BulletSimAPI.SetFriction2(Prim.BSBody.ptr, 0f); + BulletSimAPI.SetHitFraction2(Prim.BSBody.ptr, 0f); + } } // One step of the vehicle properties for the next 'pTimestep' seconds. @@ -552,6 +558,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin Prim.ForceOrientation = newOrientation; } */ + BulletSimAPI.SetInterpolationVelocity2(Prim.BSBody.ptr, m_newVelocity, m_lastAngularVelocity); // remember the position so next step we can limit absolute movement effects m_lastPositionVector = Prim.ForcePosition; @@ -570,17 +577,21 @@ namespace OpenSim.Region.Physics.BulletSPlugin { Vector3 origDir = m_linearMotorDirection; Vector3 origVel = m_lastLinearVelocityVector; + Vector3 vehicleVelocity = Prim.ForceVelocity * Quaternion.Inverse(Prim.ForceOrientation); // DEBUG // add drive to body Vector3 addAmount = (m_linearMotorDirection - m_lastLinearVelocityVector)/(m_linearMotorTimescale / pTimestep); // lastLinearVelocityVector is the current body velocity vector m_lastLinearVelocityVector += addAmount; - float keepfraction = 1.0f - (1.0f / (m_linearMotorDecayTimescale / pTimestep)); - m_linearMotorDirection *= keepfraction; + float decayFactor = (1.0f / m_linearMotorDecayTimescale) * pTimestep; + m_linearMotorDirection *= (1f - decayFactor); - VDetailLog("{0},MoveLinear,nonZero,origdir={1},origvel={2},add={3},notDecay={4},dir={5},vel={6}", - Prim.LocalID, origDir, origVel, addAmount, keepfraction, m_linearMotorDirection, m_lastLinearVelocityVector); + Vector3 frictionFactor = (Vector3.One / m_linearFrictionTimescale) * pTimestep; + m_lastLinearVelocityVector *= (Vector3.One - frictionFactor); + + VDetailLog("{0},MoveLinear,nonZero,origdir={1},origvel={2},vehVel={3},add={4},decay={5},lmDir={6},lmVel={7}", + Prim.LocalID, origDir, origVel, vehicleVelocity, addAmount, decayFactor, m_linearMotorDirection, m_lastLinearVelocityVector); // convert requested object velocity to object relative vector m_newVelocity = m_lastLinearVelocityVector * Prim.ForceOrientation; @@ -661,18 +672,18 @@ namespace OpenSim.Region.Physics.BulletSPlugin } else { - float horizontalError = pos.Z - m_VhoverTargetHeight; + float verticalError = pos.Z - m_VhoverTargetHeight; // RA: where does the 50 come from> - float horizontalCorrectionVelocity = ((horizontalError * 50.0f) / (m_VhoverTimescale / pTimestep)); + float verticalCorrectionVelocity = pTimestep * ((verticalError * 50.0f) / m_VhoverTimescale); // Replace Vertical speed with correction figure if significant - if (Math.Abs(horizontalError) > 0.01f) + if (Math.Abs(verticalError) > 0.01f) { - m_newVelocity.Z += horizontalCorrectionVelocity; + m_newVelocity.Z += verticalCorrectionVelocity; //KF: m_VhoverEfficiency is not yet implemented } - else if (horizontalError < -0.01) + else if (verticalError < -0.01) { - m_newVelocity.Z -= horizontalCorrectionVelocity; + m_newVelocity.Z -= verticalCorrectionVelocity; } else { @@ -748,16 +759,13 @@ namespace OpenSim.Region.Physics.BulletSPlugin if ((m_flags & (VehicleFlag.NO_Z)) != 0) m_newVelocity.Z = 0; - // Apply friction - Vector3 keepFraction = Vector3.One - (Vector3.One / (m_linearFrictionTimescale / pTimestep)); - m_lastLinearVelocityVector *= keepFraction; - // Apply velocity - // Prim.ForceVelocity = m_newVelocity; - Prim.AddForce(m_newVelocity, false); + Prim.ForceVelocity = m_newVelocity; + // Prim.AddForce(m_newVelocity * Prim.Linkset.LinksetMass, false); + // Prim.AddForce(grav * Prim.Linkset.LinksetMass, false); - VDetailLog("{0},MoveLinear,done,lmDir={1},lmVel={2},newVel={3},grav={4},1Mdecay={5}", - Prim.LocalID, m_linearMotorDirection, m_lastLinearVelocityVector, m_newVelocity, grav, keepFraction); + VDetailLog("{0},MoveLinear,done,lmDir={1},lmVel={2},newVel={3},grav={4}", + Prim.LocalID, m_linearMotorDirection, m_lastLinearVelocityVector, m_newVelocity, grav); } // end MoveLinear() @@ -858,14 +866,17 @@ namespace OpenSim.Region.Physics.BulletSPlugin #region Deflection //Forward is the prefered direction, but if the reference frame has changed, we need to take this into account as well - Vector3 PreferredAxisOfMotion = - new Vector3((10*(m_angularDeflectionEfficiency/m_angularDeflectionTimescale)), 0, 0); - PreferredAxisOfMotion *= Quaternion.Add(Prim.ForceOrientation, m_referenceFrame); + if (m_angularDeflectionEfficiency != 0) + { + Vector3 preferredAxisOfMotion = + new Vector3((pTimestep * 10 * (m_angularDeflectionEfficiency / m_angularDeflectionTimescale)), 0, 0); + preferredAxisOfMotion *= Quaternion.Add(Prim.ForceOrientation, m_referenceFrame); - //Multiply it so that it scales linearly - //deflection = PreferredAxisOfMotion; + deflection = (preferredAxisOfMotion * (m_angularDeflectionEfficiency) / m_angularDeflectionTimescale) * pTimestep; - //deflection = ((PreferredAxisOfMotion * m_angularDeflectionEfficiency) / (m_angularDeflectionTimescale / pTimestep)); + VDetailLog("{0},MoveAngular,Deflection,perfAxis={1},deflection={2}", + Prim.LocalID, preferredAxisOfMotion, deflection); + } #endregion @@ -917,18 +928,16 @@ namespace OpenSim.Region.Physics.BulletSPlugin banking += bankingRot; } m_angularMotorVelocity.X *= m_bankingEfficiency == 1 ? 0.0f : 1 - m_bankingEfficiency; + VDetailLog("{0},MoveAngular,Banking,bEff={1},angMotVel={2},banking={3}", + Prim.LocalID, m_bankingEfficiency, m_angularMotorVelocity, banking); } #endregion m_lastVertAttractor = vertattr; - // Bank section tba - - // Deflection section tba - // Sum velocities - m_lastAngularVelocity = m_angularMotorVelocity + vertattr; // + bank + deflection + m_lastAngularVelocity = m_angularMotorVelocity + vertattr + banking + deflection; if ((m_flags & (VehicleFlag.NO_DEFLECTION_UP)) != 0) { @@ -948,8 +957,8 @@ namespace OpenSim.Region.Physics.BulletSPlugin m_lastAngularVelocity -= m_lastAngularVelocity * decayamount; // Apply to the body - // Prim.ForceRotationalVelocity = m_lastAngularVelocity; - Prim.AddAngularForce(m_lastAngularVelocity, false); + // The above calculates the absolute angular velocity needed + Prim.ForceRotationalVelocity = m_lastAngularVelocity; VDetailLog("{0},MoveAngular,done,decay={1},lastAngular={2}", Prim.LocalID, decayamount, m_lastAngularVelocity); } //end MoveAngular -- cgit v1.1 From 7af28724acf12245977fc44576c36ec0de320a8a Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Fri, 26 Oct 2012 16:09:08 -0700 Subject: BulletSim: rename constraint classes so they show up together alphabetically. --- .../Physics/BulletSPlugin/BS6DofConstraint.cs | 154 --------------------- .../Physics/BulletSPlugin/BSConstraint6Dof.cs | 154 +++++++++++++++++++++ .../Physics/BulletSPlugin/BSConstraintHinge.cs | 57 ++++++++ .../Physics/BulletSPlugin/BSHingeConstraint.cs | 57 -------- .../Physics/BulletSPlugin/BSLinksetConstraints.cs | 2 +- 5 files changed, 212 insertions(+), 212 deletions(-) delete mode 100755 OpenSim/Region/Physics/BulletSPlugin/BS6DofConstraint.cs create mode 100755 OpenSim/Region/Physics/BulletSPlugin/BSConstraint6Dof.cs create mode 100755 OpenSim/Region/Physics/BulletSPlugin/BSConstraintHinge.cs delete mode 100755 OpenSim/Region/Physics/BulletSPlugin/BSHingeConstraint.cs (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BS6DofConstraint.cs b/OpenSim/Region/Physics/BulletSPlugin/BS6DofConstraint.cs deleted file mode 100755 index ecb3ec8..0000000 --- a/OpenSim/Region/Physics/BulletSPlugin/BS6DofConstraint.cs +++ /dev/null @@ -1,154 +0,0 @@ -/* - * 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 BS6DofConstraint : BSConstraint -{ - private static string LogHeader = "[BULLETSIM 6DOF CONSTRAINT]"; - - public override ConstraintType Type { get { return ConstraintType.D6_CONSTRAINT_TYPE; } } - - // Create a btGeneric6DofConstraint - public BS6DofConstraint(BulletSim world, BulletBody obj1, BulletBody obj2, - Vector3 frame1, Quaternion frame1rot, - Vector3 frame2, Quaternion frame2rot, - bool useLinearReferenceFrameA, bool disableCollisionsBetweenLinkedBodies) - { - m_world = world; - m_body1 = obj1; - m_body2 = obj2; - m_constraint = new BulletConstraint( - BulletSimAPI.Create6DofConstraint2(m_world.ptr, m_body1.ptr, m_body2.ptr, - frame1, frame1rot, - 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, - obj1.ID, obj1.ptr.ToString("X"), obj2.ID, obj2.ptr.ToString("X")); - } - - public BS6DofConstraint(BulletSim world, BulletBody obj1, BulletBody obj2, - Vector3 joinPoint, - bool useLinearReferenceFrameA, bool disableCollisionsBetweenLinkedBodies) - { - m_world = world; - m_body1 = obj1; - m_body2 = obj2; - if (obj1.ptr == IntPtr.Zero || obj2.ptr == IntPtr.Zero) - { - world.physicsScene.DetailLog("{0},BS6DOFConstraint,badBodyPtr,wID={1}, rID={2}, rBody={3}, cID={4}, cBody={5}", - BSScene.DetailLogZero, world.worldID, - obj1.ID, obj1.ptr.ToString("X"), obj2.ID, obj2.ptr.ToString("X")); - world.physicsScene.Logger.ErrorFormat("{0} Attempt to build 6DOF constraint with missing bodies: wID={1}, rID={2}, rBody={3}, cID={4}, cBody={5}", - "[BULLETSIM 6DOF CONSTRAINT]", world.worldID, - obj1.ID, obj1.ptr.ToString("X"), obj2.ID, obj2.ptr.ToString("X")); - m_enabled = false; - } - else - { - m_constraint = new BulletConstraint( - BulletSimAPI.Create6DofConstraintToPoint2(m_world.ptr, m_body1.ptr, m_body2.ptr, - joinPoint, - useLinearReferenceFrameA, disableCollisionsBetweenLinkedBodies)); - world.physicsScene.DetailLog("{0},BS6DofConstraint,createMidPoint,wID={1}, csrt={2}, rID={3}, rBody={4}, cID={5}, cBody={6}", - BSScene.DetailLogZero, world.worldID, m_constraint.ptr.ToString("X"), - obj1.ID, obj1.ptr.ToString("X"), obj2.ID, obj2.ptr.ToString("X")); - if (m_constraint.ptr == IntPtr.Zero) - { - world.physicsScene.Logger.ErrorFormat("{0} Failed creation of 6Dof constraint. rootID={1}, childID={2}", - LogHeader, obj1.ID, obj2.ID); - m_enabled = false; - } - else - { - m_enabled = true; - } - } - } - - public bool SetFrames(Vector3 frameA, Quaternion frameArot, Vector3 frameB, Quaternion frameBrot) - { - bool ret = false; - if (m_enabled) - { - BulletSimAPI.SetFrames2(m_constraint.ptr, frameA, frameArot, frameB, frameBrot); - ret = true; - } - return ret; - } - - public bool SetCFMAndERP(float cfm, float erp) - { - bool ret = false; - if (m_enabled) - { - BulletSimAPI.SetConstraintParam2(m_constraint.ptr, ConstraintParams.BT_CONSTRAINT_STOP_CFM, cfm, ConstraintParamAxis.AXIS_ALL); - BulletSimAPI.SetConstraintParam2(m_constraint.ptr, ConstraintParams.BT_CONSTRAINT_STOP_ERP, erp, ConstraintParamAxis.AXIS_ALL); - BulletSimAPI.SetConstraintParam2(m_constraint.ptr, ConstraintParams.BT_CONSTRAINT_CFM, cfm, ConstraintParamAxis.AXIS_ALL); - ret = true; - } - return ret; - } - - public bool UseFrameOffset(bool useOffset) - { - bool ret = false; - float onOff = useOffset ? ConfigurationParameters.numericTrue : ConfigurationParameters.numericFalse; - if (m_enabled) - ret = BulletSimAPI.UseFrameOffset2(m_constraint.ptr, onOff); - return ret; - } - - public bool TranslationalLimitMotor(bool enable, float targetVelocity, float maxMotorForce) - { - bool ret = false; - float onOff = enable ? ConfigurationParameters.numericTrue : ConfigurationParameters.numericFalse; - if (m_enabled) - { - ret = BulletSimAPI.TranslationalLimitMotor2(m_constraint.ptr, onOff, targetVelocity, maxMotorForce); - m_world.physicsScene.DetailLog("{0},BS6DOFConstraint,TransLimitMotor,enable={1},vel={2},maxForce={3}", - BSScene.DetailLogZero, enable, targetVelocity, maxMotorForce); - } - return ret; - } - - public bool SetBreakingImpulseThreshold(float threshold) - { - bool ret = false; - if (m_enabled) - ret = BulletSimAPI.SetBreakingImpulseThreshold2(m_constraint.ptr, threshold); - return ret; - } -} -} diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSConstraint6Dof.cs b/OpenSim/Region/Physics/BulletSPlugin/BSConstraint6Dof.cs new file mode 100755 index 0000000..3c37d76 --- /dev/null +++ b/OpenSim/Region/Physics/BulletSPlugin/BSConstraint6Dof.cs @@ -0,0 +1,154 @@ +/* + * 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 BSConstraint6Dof : BSConstraint +{ + private static string LogHeader = "[BULLETSIM 6DOF CONSTRAINT]"; + + public override ConstraintType Type { get { return ConstraintType.D6_CONSTRAINT_TYPE; } } + + // Create a btGeneric6DofConstraint + public BSConstraint6Dof(BulletSim world, BulletBody obj1, BulletBody obj2, + Vector3 frame1, Quaternion frame1rot, + Vector3 frame2, Quaternion frame2rot, + bool useLinearReferenceFrameA, bool disableCollisionsBetweenLinkedBodies) + { + m_world = world; + m_body1 = obj1; + m_body2 = obj2; + m_constraint = new BulletConstraint( + BulletSimAPI.Create6DofConstraint2(m_world.ptr, m_body1.ptr, m_body2.ptr, + frame1, frame1rot, + 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, + obj1.ID, obj1.ptr.ToString("X"), obj2.ID, obj2.ptr.ToString("X")); + } + + public BSConstraint6Dof(BulletSim world, BulletBody obj1, BulletBody obj2, + Vector3 joinPoint, + bool useLinearReferenceFrameA, bool disableCollisionsBetweenLinkedBodies) + { + m_world = world; + m_body1 = obj1; + m_body2 = obj2; + if (obj1.ptr == IntPtr.Zero || obj2.ptr == IntPtr.Zero) + { + world.physicsScene.DetailLog("{0},BS6DOFConstraint,badBodyPtr,wID={1}, rID={2}, rBody={3}, cID={4}, cBody={5}", + BSScene.DetailLogZero, world.worldID, + obj1.ID, obj1.ptr.ToString("X"), obj2.ID, obj2.ptr.ToString("X")); + world.physicsScene.Logger.ErrorFormat("{0} Attempt to build 6DOF constraint with missing bodies: wID={1}, rID={2}, rBody={3}, cID={4}, cBody={5}", + "[BULLETSIM 6DOF CONSTRAINT]", world.worldID, + obj1.ID, obj1.ptr.ToString("X"), obj2.ID, obj2.ptr.ToString("X")); + m_enabled = false; + } + else + { + m_constraint = new BulletConstraint( + BulletSimAPI.Create6DofConstraintToPoint2(m_world.ptr, m_body1.ptr, m_body2.ptr, + joinPoint, + useLinearReferenceFrameA, disableCollisionsBetweenLinkedBodies)); + world.physicsScene.DetailLog("{0},BS6DofConstraint,createMidPoint,wID={1}, csrt={2}, rID={3}, rBody={4}, cID={5}, cBody={6}", + BSScene.DetailLogZero, world.worldID, m_constraint.ptr.ToString("X"), + obj1.ID, obj1.ptr.ToString("X"), obj2.ID, obj2.ptr.ToString("X")); + if (m_constraint.ptr == IntPtr.Zero) + { + world.physicsScene.Logger.ErrorFormat("{0} Failed creation of 6Dof constraint. rootID={1}, childID={2}", + LogHeader, obj1.ID, obj2.ID); + m_enabled = false; + } + else + { + m_enabled = true; + } + } + } + + public bool SetFrames(Vector3 frameA, Quaternion frameArot, Vector3 frameB, Quaternion frameBrot) + { + bool ret = false; + if (m_enabled) + { + BulletSimAPI.SetFrames2(m_constraint.ptr, frameA, frameArot, frameB, frameBrot); + ret = true; + } + return ret; + } + + public bool SetCFMAndERP(float cfm, float erp) + { + bool ret = false; + if (m_enabled) + { + BulletSimAPI.SetConstraintParam2(m_constraint.ptr, ConstraintParams.BT_CONSTRAINT_STOP_CFM, cfm, ConstraintParamAxis.AXIS_ALL); + BulletSimAPI.SetConstraintParam2(m_constraint.ptr, ConstraintParams.BT_CONSTRAINT_STOP_ERP, erp, ConstraintParamAxis.AXIS_ALL); + BulletSimAPI.SetConstraintParam2(m_constraint.ptr, ConstraintParams.BT_CONSTRAINT_CFM, cfm, ConstraintParamAxis.AXIS_ALL); + ret = true; + } + return ret; + } + + public bool UseFrameOffset(bool useOffset) + { + bool ret = false; + float onOff = useOffset ? ConfigurationParameters.numericTrue : ConfigurationParameters.numericFalse; + if (m_enabled) + ret = BulletSimAPI.UseFrameOffset2(m_constraint.ptr, onOff); + return ret; + } + + public bool TranslationalLimitMotor(bool enable, float targetVelocity, float maxMotorForce) + { + bool ret = false; + float onOff = enable ? ConfigurationParameters.numericTrue : ConfigurationParameters.numericFalse; + if (m_enabled) + { + ret = BulletSimAPI.TranslationalLimitMotor2(m_constraint.ptr, onOff, targetVelocity, maxMotorForce); + m_world.physicsScene.DetailLog("{0},BS6DOFConstraint,TransLimitMotor,enable={1},vel={2},maxForce={3}", + BSScene.DetailLogZero, enable, targetVelocity, maxMotorForce); + } + return ret; + } + + public bool SetBreakingImpulseThreshold(float threshold) + { + bool ret = false; + if (m_enabled) + ret = BulletSimAPI.SetBreakingImpulseThreshold2(m_constraint.ptr, threshold); + return ret; + } +} +} diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSConstraintHinge.cs b/OpenSim/Region/Physics/BulletSPlugin/BSConstraintHinge.cs new file mode 100755 index 0000000..ed3ffa7 --- /dev/null +++ b/OpenSim/Region/Physics/BulletSPlugin/BSConstraintHinge.cs @@ -0,0 +1,57 @@ +/* + * 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 BSConstraintHinge : BSConstraint +{ + public override ConstraintType Type { get { return ConstraintType.HINGE_CONSTRAINT_TYPE; } } + + public BSConstraintHinge(BulletSim world, BulletBody obj1, BulletBody obj2, + Vector3 pivotInA, Vector3 pivotInB, + Vector3 axisInA, Vector3 axisInB, + bool useLinearReferenceFrameA, bool disableCollisionsBetweenLinkedBodies) + { + m_world = world; + m_body1 = obj1; + m_body2 = obj2; + m_constraint = new BulletConstraint( + BulletSimAPI.CreateHingeConstraint2(m_world.ptr, m_body1.ptr, m_body2.ptr, + pivotInA, pivotInB, + axisInA, axisInB, + useLinearReferenceFrameA, disableCollisionsBetweenLinkedBodies)); + m_enabled = true; + } + +} + +} diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSHingeConstraint.cs b/OpenSim/Region/Physics/BulletSPlugin/BSHingeConstraint.cs deleted file mode 100755 index 76bd930..0000000 --- a/OpenSim/Region/Physics/BulletSPlugin/BSHingeConstraint.cs +++ /dev/null @@ -1,57 +0,0 @@ -/* - * 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 BSHingeConstraint : BSConstraint -{ - public override ConstraintType Type { get { return ConstraintType.HINGE_CONSTRAINT_TYPE; } } - - public BSHingeConstraint(BulletSim world, BulletBody obj1, BulletBody obj2, - Vector3 pivotInA, Vector3 pivotInB, - Vector3 axisInA, Vector3 axisInB, - bool useLinearReferenceFrameA, bool disableCollisionsBetweenLinkedBodies) - { - m_world = world; - m_body1 = obj1; - m_body2 = obj2; - m_constraint = new BulletConstraint( - BulletSimAPI.CreateHingeConstraint2(m_world.ptr, m_body1.ptr, m_body2.ptr, - pivotInA, pivotInB, - axisInA, axisInB, - useLinearReferenceFrameA, disableCollisionsBetweenLinkedBodies)); - m_enabled = true; - } - -} - -} diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs index 003c294..67979b3 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs @@ -246,7 +246,7 @@ public sealed class BSLinksetConstraints : BSLinkset // create a constraint that allows no freedom of movement between the two objects // http://bulletphysics.org/Bullet/phpBB3/viewtopic.php?t=4818 - BS6DofConstraint constrain = new BS6DofConstraint( + BSConstraint6Dof constrain = new BSConstraint6Dof( PhysicsScene.World, rootPrim.BSBody, childPrim.BSBody, midPoint, true, true ); /* NOTE: below is an attempt to build constraint with full frame computation, etc. -- cgit v1.1 From e20bad12cc0584c6368e46e0f326e6b616133e8f Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Mon, 29 Oct 2012 11:30:47 -0700 Subject: BulletSim: centralize mass/inertia computation with UpdatePhysicalMassProperties() function. Didn't add setMassRaw because assignment with side effect is dirty. --- .../Region/Physics/BulletSPlugin/BSCharacter.cs | 15 ++++++--- .../Region/Physics/BulletSPlugin/BSPhysObject.cs | 2 ++ OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 39 ++++++++++++++-------- 3 files changed, 38 insertions(+), 18 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index 8bb4b21..b9013ab 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -155,8 +155,7 @@ public sealed class BSCharacter : BSPhysObject BulletSimAPI.SetCcdSweptSphereRadius2(BSBody.ptr, PhysicsScene.Params.ccdSweptSphereRadius); } - OMV.Vector3 localInertia = BulletSimAPI.CalculateLocalInertia2(BSShape.ptr, MassRaw); - BulletSimAPI.SetMassProps2(BSBody.ptr, MassRaw, localInertia); + UpdatePhysicalMassProperties(MassRaw); // Make so capsule does not fall over BulletSimAPI.SetAngularFactorV2(BSBody.ptr, OMV.Vector3.Zero); @@ -201,8 +200,7 @@ public sealed class BSCharacter : BSPhysObject PhysicsScene.TaintedObject("BSCharacter.setSize", delegate() { BulletSimAPI.SetLocalScaling2(BSShape.ptr, Scale); - OMV.Vector3 localInertia = BulletSimAPI.CalculateLocalInertia2(BSShape.ptr, MassRaw); - BulletSimAPI.SetMassProps2(BSBody.ptr, MassRaw, localInertia); + UpdatePhysicalMassProperties(MassRaw); }); } @@ -329,7 +327,14 @@ 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 MassRaw { get {return _mass; } } + public override float MassRaw { + get {return _mass; } + } + public override void UpdatePhysicalMassProperties(float physMass) + { + OMV.Vector3 localInertia = BulletSimAPI.CalculateLocalInertia2(BSShape.ptr, physMass); + BulletSimAPI.SetMassProps2(BSBody.ptr, physMass, localInertia); + } public override OMV.Vector3 Force { get { return _force; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index 538f905..be8d64b 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -64,6 +64,8 @@ public abstract class BSPhysObject : PhysicsActor // Return the object mass without calculating it or having side effects public abstract float MassRaw { get; } + // Set the raw mass but also update physical mass properties (inertia, ...) + public abstract void UpdatePhysicalMassProperties(float mass); // Reference to the physical body (btCollisionObject) of this object public BulletBody BSBody; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 44937df..ad09a61 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -356,13 +356,32 @@ public sealed class BSPrim : BSPhysObject { get { - // return Linkset.LinksetMass; - return _mass; + return Linkset.LinksetMass; + // return _mass; } } // used when we only want this prim's mass and not the linkset thing - public override float MassRaw { get { return _mass; } } + public override float MassRaw { + get { return _mass; } + } + // Set the physical mass to the passed mass. + // Note that this does not change _mass! + public override void UpdatePhysicalMassProperties(float physMass) + { + if (IsStatic) + { + BulletSimAPI.SetMassProps2(BSBody.ptr, 0f, OMV.Vector3.Zero); + BulletSimAPI.UpdateInertiaTensor2(BSBody.ptr); + } + else + { + OMV.Vector3 localInertia = BulletSimAPI.CalculateLocalInertia2(BSShape.ptr, physMass); + BulletSimAPI.SetMassProps2(BSBody.ptr, physMass, localInertia); + BulletSimAPI.UpdateInertiaTensor2(BSBody.ptr); + DetailLog("{0},BSPrim.UpdateMassProperties,mass={1},localInertia={2}", LocalID, physMass, localInertia); + } + } // Is this used? public override OMV.Vector3 CenterOfMass @@ -613,7 +632,7 @@ public sealed class BSPrim : BSPhysObject // Recompute any linkset parameters. // When going from non-physical to physical, this re-enables the constraints that // had been automatically disabled when the mass was set to zero. - Linkset.Refresh(this, true); + Linkset.Refresh(this); DetailLog("{0},BSPrim.UpdatePhysicalParameters,exit,static={1},solid={2},mass={3},collide={4},cf={5:X},body={6},shape={7}", LocalID, IsStatic, IsSolid, _mass, SubscribedEvents(), CurrentCollisionFlags, BSBody, BSShape); @@ -635,9 +654,7 @@ public sealed class BSPrim : BSPhysObject // Center of mass is at the center of the object BulletSimAPI.SetCenterOfMassByPosRot2(Linkset.LinksetRoot.BSBody.ptr, _position, _orientation); // Mass is zero which disables a bunch of physics stuff in Bullet - BulletSimAPI.SetMassProps2(BSBody.ptr, 0f, OMV.Vector3.Zero); - // There is no inertia in a static object - BulletSimAPI.UpdateInertiaTensor2(BSBody.ptr); + UpdatePhysicalMassProperties(0f); // Set collision detection parameters if (PhysicsScene.Params.ccdMotionThreshold > 0f) { @@ -671,9 +688,7 @@ public sealed class BSPrim : BSPhysObject BulletSimAPI.SetTranslation2(BSBody.ptr, _position, _orientation); // A dynamic object has mass - OMV.Vector3 inertia = BulletSimAPI.CalculateLocalInertia2(BSShape.ptr, Mass); - BulletSimAPI.SetMassProps2(BSBody.ptr, _mass, inertia); - BulletSimAPI.UpdateInertiaTensor2(BSBody.ptr); + UpdatePhysicalMassProperties(MassRaw); // Set collision detection parameters if (PhysicsScene.Params.ccdMotionThreshold > 0f) @@ -1247,9 +1262,7 @@ public sealed class BSPrim : BSPhysObject returnMass = _density * volume; - /* - * This change means each object keeps its own mass and the Mass property - * will return the sum if we're part of a linkset. + /* Comment out code that computes the mass of the linkset. That is done in the Linkset class. if (IsRootOfLinkset) { foreach (BSPrim prim in _childrenPrims) -- cgit v1.1 From 2f25f70316ff712d338bbff3f6d02650480a340b Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Mon, 29 Oct 2012 11:31:50 -0700 Subject: BulletSim: remove unneeded parameter from Refresh(). --- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index d0e514b..569d2e7 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -204,7 +204,7 @@ public abstract class BSLinkset // When physical properties are changed the linkset needs to recalculate // its internal properties. // May be called at runtime or taint-time (just pass the appropriate flag). - public abstract void Refresh(BSPhysObject requestor, bool inTaintTime); + public abstract void Refresh(BSPhysObject requestor); // The object is going dynamic (physical). Do any setup necessary // for a dynamic linkset. -- cgit v1.1 From 9568f24c2628312f366c99ce6beb5c193aace33c Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Mon, 29 Oct 2012 11:38:01 -0700 Subject: BulletSim: add post taint taints and post step taints. The post taints operation is most useful and is used by linksets to build and rebuild only once before the simulation step. --- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 138 +++++++++++++++++++++--- 1 file changed, 122 insertions(+), 16 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index 9e95ce5..cb52937 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -171,7 +171,9 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters } } private Object _taintLock = new Object(); // lock for using the next object - private List _taintedObjects; + private List _taintOperations; + private Dictionary _postTaintOperations; + private List _postStepOperations; // A pointer to an instance if this structure is passed to the C++ code // Used to pass basic configuration values to the unmanaged code. @@ -203,7 +205,9 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters public override void Initialise(IMesher meshmerizer, IConfigSource config) { mesher = meshmerizer; - _taintedObjects = new List(); + _taintOperations = new List(); + _postTaintOperations = new Dictionary(); + _postStepOperations = new List(); PhysObjects = new Dictionary(); Shapes = new BSShapeCollection(this); @@ -475,23 +479,21 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters if (!m_initialized) return 5.0f; // update the prim states while we know the physics engine is not busy - int numTaints = _taintedObjects.Count; + int numTaints = _taintOperations.Count; ProcessTaints(); // Some of the prims operate with special vehicle properties ProcessVehicles(timeStep); - numTaints += _taintedObjects.Count; + numTaints += _taintOperations.Count; ProcessTaints(); // the vehicles might have added taints // step the physical world one interval m_simulationStep++; int numSubSteps = 0; - // DEBUG - // DetailLog("{0},BSScene.Simulate,beforeStep,ntaimts={1},step={2}", DetailLogZero, numTaints, m_simulationStep); - try { + // DumpVehicles(); // DEBUG if (PhysicsLogging.Enabled) beforeTime = Util.EnvironmentTickCount(); numSubSteps = BulletSimAPI.PhysicsStep2(World.ptr, timeStep, m_maxSubSteps, m_fixedTimeStep, @@ -500,6 +502,7 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters if (PhysicsLogging.Enabled) simTime = Util.EnvironmentTickCountSubtract(beforeTime); DetailLog("{0},Simulate,call, frame={1}, nTaints={2}, simTime={3}, substeps={4}, updates={5}, colliders={6}", DetailLogZero, m_simulationStep, numTaints, simTime, numSubSteps, updatedEntityCount, collidersCount); + // DumpVehicles(); // DEBUG } catch (Exception e) { @@ -579,6 +582,8 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters // Only enable this in a limited test world with few objects. // BulletSimAPI.DumpAllInfo2(World.ptr); // DEBUG DEBUG DEBUG + ProcessPostStepTaints(); + // 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. // We multiply by 55 to give a recognizable running rate (55 or less). @@ -670,6 +675,8 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters public override bool IsThreaded { get { return false; } } + #region Taints + // 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. @@ -679,7 +686,7 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters lock (_taintLock) { - _taintedObjects.Add(new TaintCallbackEntry(ident, callback)); + _taintOperations.Add(new TaintCallbackEntry(ident, callback)); } return; @@ -690,19 +697,25 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters // here just before the physics engine is called to step the simulation. public void ProcessTaints() { - if (_taintedObjects.Count > 0) // save allocating new list if there is nothing to process + ProcessRegularTaints(); + ProcessPostTaintTaints(); + } + + private void ProcessRegularTaints() + { + if (_taintOperations.Count > 0) // save allocating new list if there is nothing to process { int taintCount = m_taintsToProcessPerStep; TaintCallbackEntry oneCallback = new TaintCallbackEntry(); - while (_taintedObjects.Count > 0 && taintCount-- > 0) + while (_taintOperations.Count > 0 && taintCount-- > 0) { bool gotOne = false; lock (_taintLock) { - if (_taintedObjects.Count > 0) + if (_taintOperations.Count > 0) { - oneCallback = _taintedObjects[0]; - _taintedObjects.RemoveAt(0); + oneCallback = _taintOperations[0]; + _taintOperations.RemoveAt(0); gotOne = true; } } @@ -746,6 +759,89 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters } } + // Schedule an update to happen after all the regular taints are processed. + // Note that new requests for the same operation ("ident") for the same object ("ID") + // will replace any previous operation by the same object. + public void PostTaintObject(String ident, uint ID, TaintCallback callback) + { + if (!m_initialized) return; + + lock (_taintLock) + { + _postTaintOperations[ident] = new TaintCallbackEntry(ident + "-" + ID.ToString(), callback); + } + + return; + } + + private void ProcessPostTaintTaints() + { + if (_postTaintOperations.Count > 0) + { + Dictionary oldList; + lock (_taintLock) + { + oldList = _postTaintOperations; + _postTaintOperations = new Dictionary(); + } + + foreach (KeyValuePair kvp in oldList) + { + try + { + DetailLog("{0},BSScene.ProcessPostTaintTaints,doTaint,id={1}", DetailLogZero, kvp.Key); // DEBUG DEBUG DEBUG + kvp.Value.callback(); + } + catch (Exception e) + { + m_log.ErrorFormat("{0}: ProcessPostTaintTaints: {1}: Exception: {2}", LogHeader, kvp.Key, e); + } + } + oldList.Clear(); + } + } + + public void PostStepTaintObject(String ident, TaintCallback callback) + { + if (!m_initialized) return; + + lock (_taintLock) + { + _postStepOperations.Add(new TaintCallbackEntry(ident, callback)); + } + + return; + } + + private void ProcessPostStepTaints() + { + if (_postStepOperations.Count > 0) + { + List oldList; + lock (_taintLock) + { + oldList = _postStepOperations; + _postStepOperations = new List(); + } + + foreach (TaintCallbackEntry tcbe in oldList) + { + try + { + DetailLog("{0},BSScene.ProcessPostStepTaints,doTaint,id={1}", DetailLogZero, tcbe.ident); // DEBUG DEBUG DEBUG + tcbe.callback(); + } + catch (Exception e) + { + m_log.ErrorFormat("{0}: ProcessPostStepTaints: {1}: Exception: {2}", LogHeader, tcbe.ident, e); + } + } + oldList.Clear(); + } + } + + #endregion // Taints + #region Vehicles public void VehicleInSceneTypeChanged(BSPrim vehic, Vehicle newType) @@ -1006,7 +1102,7 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters (s,cf,p,v) => { s.m_params[0].ccdSweptSphereRadius = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].ccdSweptSphereRadius; }, (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].ccdSweptSphereRadius, p, l, v); }, - (s,o,v) => { BulletSimAPI.SetCcdSweepSphereRadius2(o.BSBody.ptr, v); } ), + (s,o,v) => { BulletSimAPI.SetCcdSweptSphereRadius2(o.BSBody.ptr, v); } ), new ParameterDefn("ContactProcessingThreshold", "Distance between contacts before doing collision check" , 0.1f, (s,cf,p,v) => { s.m_params[0].contactProcessingThreshold = cf.GetFloat(p, v); }, @@ -1128,12 +1224,12 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters (s) => { return s.m_params[0].linkConstraintTransMotorMaxForce; }, (s,p,l,v) => { s.m_params[0].linkConstraintTransMotorMaxForce = v; } ), new ParameterDefn("LinkConstraintCFM", "Amount constraint can be violated. 0=no violation, 1=infinite. Default=0.1", - 0.001f, + 0.1f, (s,cf,p,v) => { s.m_params[0].linkConstraintCFM = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].linkConstraintCFM; }, (s,p,l,v) => { s.m_params[0].linkConstraintCFM = v; } ), new ParameterDefn("LinkConstraintERP", "Amount constraint is corrected each tick. 0=none, 1=all. Default = 0.2", - 0.8f, + 0.1f, (s,cf,p,v) => { s.m_params[0].linkConstraintERP = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].linkConstraintERP; }, (s,p,l,v) => { s.m_params[0].linkConstraintERP = v; } ), @@ -1326,6 +1422,16 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters #endregion Runtime settable parameters + // Debugging routine for dumping detailed physical information for vehicle prims + private void DumpVehicles() + { + foreach (BSPrim prim in m_vehicles) + { + BulletSimAPI.DumpRigidBody2(World.ptr, prim.BSBody.ptr); + BulletSimAPI.DumpCollisionShape2(World.ptr, prim.BSShape.ptr); + } + } + // Invoke the detailed logger and output something if it's enabled. public void DetailLog(string msg, params Object[] args) { -- cgit v1.1 From 8c9e4c1f7bdde47c9f29a9dfcf917421b943bb32 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Mon, 29 Oct 2012 11:41:25 -0700 Subject: BulletSim: Use Refresh/PostTaints to cause recomputing of constraint variables before the simulation step. Update logging and messages to properly name LinksetConstraints. Use UpdatePhysicalMassProperties to put the whole linkset mass into all the physical linkset members so they have the inertia to move the whole linkset. --- .../Physics/BulletSPlugin/BSLinksetConstraints.cs | 65 ++++++++++++---------- 1 file changed, 36 insertions(+), 29 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs index 67979b3..086aa12 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs @@ -43,23 +43,20 @@ public sealed class BSLinksetConstraints : BSLinkset // When physical properties are changed the linkset needs to recalculate // its internal properties. - // May be called at runtime or taint-time (just pass the appropriate flag). - public override void Refresh(BSPhysObject requestor, bool inTaintTime) + // This is queued in such a way that the + // refresh will only happen once after all the other taints are applied. + public override void Refresh(BSPhysObject requestor) { - // If there are no children or not root, I am not the one that recomputes the constraints - if (!HasAnyChildren || !IsRoot(requestor)) + // If there are no children, there are no constraints to recompute. + if (!HasAnyChildren) return; - BSScene.TaintCallback refreshOperation = delegate() + // Queue to happen after all the other taint processing + PhysicsScene.PostTaintObject("BSLinksetContraints.Refresh", requestor.LocalID, delegate() { RecomputeLinksetConstraintVariables(); - DetailLog("{0},BSLinkset.Refresh,complete,rBody={1}", - LinksetRoot.LocalID, LinksetRoot.BSBody.ptr.ToString("X")); - }; - if (inTaintTime) - refreshOperation(); - else - PhysicsScene.TaintedObject("BSLinkSet.Refresh", refreshOperation); + }); + } // The object is going dynamic (physical). Do any setup necessary @@ -104,14 +101,14 @@ public sealed class BSLinksetConstraints : BSLinkset if (IsRoot(child)) { // If the one with the dependency is root, must undo all children - DetailLog("{0},BSLinkset.RemoveBodyDependencies,removeChildrenForRoot,rID={1},rBody={2}", + DetailLog("{0},BSLinksetConstraint.RemoveBodyDependencies,removeChildrenForRoot,rID={1},rBody={2}", child.LocalID, LinksetRoot.LocalID, LinksetRoot.BSBody.ptr.ToString("X")); ret = PhysicallyUnlinkAllChildrenFromRoot(LinksetRoot); } else { - DetailLog("{0},BSLinkset.RemoveBodyDependencies,removeSingleChild,rID={1},rBody={2},cID={3},cBody={4}", + DetailLog("{0},BSLinksetConstraint.RemoveBodyDependencies,removeSingleChild,rID={1},rBody={2},cID={3},cBody={4}", child.LocalID, LinksetRoot.LocalID, LinksetRoot.BSBody.ptr.ToString("X"), child.LocalID, child.BSBody.ptr.ToString("X")); @@ -132,7 +129,7 @@ public sealed class BSLinksetConstraints : BSLinkset { if (IsRoot(child)) { - DetailLog("{0},BSLinkset.RestoreBodyDependencies,restoreChildrenForRoot,rID={1},numChild={2}", + DetailLog("{0},BSLinksetConstraint.RestoreBodyDependencies,restoreChildrenForRoot,rID={1},numChild={2}", child.LocalID, LinksetRoot.LocalID, m_taintChildren.Count); foreach (BSPhysObject bpo in m_taintChildren) { @@ -141,7 +138,7 @@ public sealed class BSLinksetConstraints : BSLinkset } else { - DetailLog("{0},BSLinkset.RestoreBodyDependencies,restoreSingleChild,rID={1},rBody={2},cID={3},cBody={4}", + DetailLog("{0},BSLinksetConstraint.RestoreBodyDependencies,restoreSingleChild,rID={1},rBody={2},cID={3},cBody={4}", LinksetRoot.LocalID, LinksetRoot.LocalID, LinksetRoot.BSBody.ptr.ToString("X"), child.LocalID, child.BSBody.ptr.ToString("X")); @@ -178,6 +175,7 @@ public sealed class BSLinksetConstraints : BSLinkset PhysicallyLinkAChildToRoot(rootx, childx); m_taintChildren.Add(child); }); + Refresh(LinksetRoot); } return; } @@ -211,9 +209,9 @@ public sealed class BSLinksetConstraints : BSLinkset { m_taintChildren.Remove(child); PhysicallyUnlinkAChildFromRoot(rootx, childx); - RecomputeLinksetConstraintVariables(); }); - + // See that the linkset parameters are recomputed at the end of the taint time. + Refresh(LinksetRoot); } else { @@ -237,7 +235,7 @@ public sealed class BSLinksetConstraints : BSLinkset // real world coordinate of midpoint between the two objects OMV.Vector3 midPoint = rootPrim.Position + (childRelativePosition / 2); - DetailLog("{0},BSLinkset.PhysicallyLinkAChildToRoot,taint,root={1},rBody={2},child={3},cBody={4},rLoc={5},cLoc={6},midLoc={7}", + DetailLog("{0},BSLinksetConstraint.PhysicallyLinkAChildToRoot,taint,root={1},rBody={2},child={3},cBody={4},rLoc={5},cLoc={6},midLoc={7}", rootPrim.LocalID, rootPrim.LocalID, rootPrim.BSBody.ptr.ToString("X"), childPrim.LocalID, childPrim.BSBody.ptr.ToString("X"), @@ -248,6 +246,7 @@ public sealed class BSLinksetConstraints : BSLinkset BSConstraint6Dof constrain = new BSConstraint6Dof( PhysicsScene.World, rootPrim.BSBody, childPrim.BSBody, 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 @@ -264,7 +263,7 @@ public sealed class BSLinksetConstraints : BSLinkset // create a constraint that allows no freedom of movement between the two objects // http://bulletphysics.org/Bullet/phpBB3/viewtopic.php?t=4818 - DetailLog("{0},BSLinkset.PhysicallyLinkAChildToRoot,taint,root={1},child={2}", rootPrim.LocalID, rootPrim.LocalID, childPrim.LocalID); + 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, @@ -307,7 +306,7 @@ public sealed class BSLinksetConstraints : BSLinkset private bool PhysicallyUnlinkAChildFromRoot(BSPhysObject rootPrim, BSPhysObject childPrim) { bool ret = false; - DetailLog("{0},BSLinkset.PhysicallyUnlinkAChildFromRoot,taint,root={1},rBody={2},child={3},cBody={4}", + DetailLog("{0},BSLinksetConstraint.PhysicallyUnlinkAChildFromRoot,taint,root={1},rBody={2},child={3},cBody={4}", rootPrim.LocalID, rootPrim.LocalID, rootPrim.BSBody.ptr.ToString("X"), childPrim.LocalID, childPrim.BSBody.ptr.ToString("X")); @@ -327,7 +326,7 @@ public sealed class BSLinksetConstraints : BSLinkset // Called at taint time! private bool PhysicallyUnlinkAllChildrenFromRoot(BSPhysObject rootPrim) { - DetailLog("{0},BSLinkset.PhysicallyUnlinkAllChildren,taint", rootPrim.LocalID); + DetailLog("{0},BSLinksetConstraint.PhysicallyUnlinkAllChildren,taint", rootPrim.LocalID); bool ret = false; if (PhysicsScene.Constraints.RemoveAndDestroyConstraint(rootPrim.BSBody)) @@ -350,7 +349,7 @@ public sealed class BSLinksetConstraints : BSLinkset BSConstraint constrain; if (PhysicsScene.Constraints.TryGetConstraint(LinksetRoot.BSBody, child.BSBody, out constrain)) { - // DetailLog("{0},BSLinkset.RecomputeLinksetConstraintVariables,taint,child={1},mass={2},A={3},B={4}", + // DetailLog("{0},BSLinksetConstraint.RecomputeLinksetConstraintVariables,taint,child={1},mass={2},A={3},B={4}", // LinksetRoot.LocalID, child.LocalID, linksetMass, constrain.Body1.ID, constrain.Body2.ID); constrain.RecomputeConstraintVariables(linksetMass); } @@ -367,15 +366,23 @@ public sealed class BSLinksetConstraints : BSLinkset { // If this is a multiple object linkset, set everybody's center of mass to the set's center of mass OMV.Vector3 centerOfMass = ComputeLinksetCenterOfMass(); - BulletSimAPI.SetCenterOfMassByPosRot2(LinksetRoot.BSBody.ptr, - centerOfMass, OMV.Quaternion.Identity); - DetailLog("{0},BSLinkset.RecomputeLinksetConstraintVariables,setCenterOfMass,COM={1},rBody={2}", - LinksetRoot.LocalID, centerOfMass, LinksetRoot.BSBody.ptr.ToString("X")); + BulletSimAPI.SetCenterOfMassByPosRot2(LinksetRoot.BSBody.ptr, centerOfMass, OMV.Quaternion.Identity); + // BulletSimAPI.SetCollisionFilterMask2(LinksetRoot.BSBody.ptr, + // (uint)CollisionFilterGroups.LinksetFilter, (uint)CollisionFilterGroups.LinksetMask); + DetailLog("{0},BSLinksetConstraint.RecomputeLinksetConstraintVariables,setCenterOfMass,COM={1},rBody={2},linksetMass={3}", + LinksetRoot.LocalID, centerOfMass, LinksetRoot.BSBody.ptr.ToString("X"), linksetMass); foreach (BSPhysObject child in m_taintChildren) { - BulletSimAPI.SetCenterOfMassByPosRot2(child.BSBody.ptr, - centerOfMass, OMV.Quaternion.Identity); + BulletSimAPI.SetCenterOfMassByPosRot2(child.BSBody.ptr, centerOfMass, OMV.Quaternion.Identity); + // 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. + child.UpdatePhysicalMassProperties(linksetMass); + // DEBUG: see of inter-linkset collisions are causing problems + // BulletSimAPI.SetCollisionFilterMask2(child.BSBody.ptr, + // (uint)CollisionFilterGroups.LinksetFilter, (uint)CollisionFilterGroups.LinksetMask); } + // Also update the root's physical mass to the whole linkset + LinksetRoot.UpdatePhysicalMassProperties(linksetMass); // BulletSimAPI.DumpAllInfo2(PhysicsScene.World.ptr); // DEBUG DEBUG DEBUG } -- cgit v1.1 From bc43c7007d3d8ffc2f497a6d37004eb3d3544e00 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Mon, 29 Oct 2012 14:27:48 -0700 Subject: BulletSim: code rearrangement --- OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs | 12 ++++++------ .../Region/Physics/BulletSPlugin/BSConstraintCollection.cs | 2 -- 2 files changed, 6 insertions(+), 8 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs b/OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs index f017cdd..65fac00 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSConstraint.cs @@ -42,6 +42,12 @@ public abstract class BSConstraint : IDisposable protected BulletConstraint m_constraint; protected bool m_enabled = false; + public BulletBody Body1 { get { return m_body1; } } + public BulletBody Body2 { get { return m_body2; } } + public BulletConstraint Constraint { get { return m_constraint; } } + public abstract ConstraintType Type { get; } + public bool IsEnabled { get { return m_enabled; } } + public BSConstraint() { } @@ -64,12 +70,6 @@ public abstract class BSConstraint : IDisposable } } - public BulletBody Body1 { get { return m_body1; } } - public BulletBody Body2 { get { return m_body2; } } - public BulletConstraint Constraint { get { return m_constraint; } } - public abstract ConstraintType Type { get; } - - public virtual bool SetLinearLimits(Vector3 low, Vector3 high) { bool ret = false; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSConstraintCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSConstraintCollection.cs index b9add06..a9fd826 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSConstraintCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSConstraintCollection.cs @@ -143,8 +143,6 @@ public sealed class BSConstraintCollection : IDisposable // Return 'true' if any constraints were destroyed. public bool RemoveAndDestroyConstraint(BulletBody body1) { - // return BulletSimAPI.RemoveConstraintByID(m_world.ID, obj.ID); - List toRemove = new List(); uint lookingID = body1.ID; lock (m_constraints) -- cgit v1.1 From 4cfa3be4efbca49e4670b92ec2c110f65f658b8e Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Mon, 29 Oct 2012 14:28:24 -0700 Subject: BulletSim: add definitions for linkset collision mask --- OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs | 3 +++ 1 file changed, 3 insertions(+) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs index be3a5ad..9b7ba03 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs @@ -378,6 +378,7 @@ public enum CollisionFilterGroups : uint BTerrainFilter = 1 << 11, BRaycastFilter = 1 << 12, BSolidFilter = 1 << 13, + BLinksetFilter = 1 << 14, // The collsion filters and masked are defined in one place -- don't want them scattered AvatarFilter = BCharacterFilter, @@ -386,6 +387,8 @@ public enum CollisionFilterGroups : uint ObjectMask = BAllFilter, StaticObjectFilter = BStaticFilter, StaticObjectMask = BAllFilter, + LinksetFilter = BLinksetFilter, + LinksetMask = BAllFilter & ~BLinksetFilter, VolumeDetectFilter = BSensorTrigger, VolumeDetectMask = ~BSensorTrigger, TerrainFilter = BTerrainFilter, -- cgit v1.1 From dae038a117c3110970d6fe0b743e20f342df2269 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Mon, 29 Oct 2012 14:30:16 -0700 Subject: BulletSim: fix problem with multiple linksets stepping on each other if they are built at the same time. --- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index cb52937..c27b5f0 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -578,12 +578,12 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters } } + ProcessPostStepTaints(); + // This 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. // BulletSimAPI.DumpAllInfo2(World.ptr); // DEBUG DEBUG DEBUG - ProcessPostStepTaints(); - // 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. // We multiply by 55 to give a recognizable running rate (55 or less). @@ -766,9 +766,10 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters { if (!m_initialized) return; + string uniqueIdent = ident + "-" + ID.ToString(); lock (_taintLock) { - _postTaintOperations[ident] = new TaintCallbackEntry(ident + "-" + ID.ToString(), callback); + _postTaintOperations[uniqueIdent] = new TaintCallbackEntry(uniqueIdent, callback); } return; -- cgit v1.1 From 42d65840c843f2cac6f02fc1b6012140c9cb240e Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Mon, 29 Oct 2012 14:32:07 -0700 Subject: BulletSim: Add gravity force to vehicle. Some debugging additions. --- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 8 ++++++-- 1 file changed, 6 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 8bd8117..4981007 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -539,6 +539,8 @@ namespace OpenSim.Region.Physics.BulletSPlugin { if (!IsActive) return; + m_lastAngularVelocity = Prim.ForceRotationalVelocity; // DEBUG: account for what Bullet did last time + MoveLinear(pTimestep); MoveAngular(pTimestep); LimitRotation(pTimestep); @@ -558,7 +560,8 @@ namespace OpenSim.Region.Physics.BulletSPlugin Prim.ForceOrientation = newOrientation; } */ - BulletSimAPI.SetInterpolationVelocity2(Prim.BSBody.ptr, m_newVelocity, m_lastAngularVelocity); + // DEBUG: Trying to figure out why Bullet goes crazy when the root prim is moved. + BulletSimAPI.SetInterpolationVelocity2(Prim.BSBody.ptr, m_newVelocity, m_lastAngularVelocity); // DEBUG DEBUG DEBUG // remember the position so next step we can limit absolute movement effects m_lastPositionVector = Prim.ForcePosition; @@ -762,13 +765,14 @@ namespace OpenSim.Region.Physics.BulletSPlugin // Apply velocity Prim.ForceVelocity = m_newVelocity; // Prim.AddForce(m_newVelocity * Prim.Linkset.LinksetMass, false); - // Prim.AddForce(grav * Prim.Linkset.LinksetMass, false); + Prim.AddForce(grav * Prim.Linkset.LinksetMass, false); VDetailLog("{0},MoveLinear,done,lmDir={1},lmVel={2},newVel={3},grav={4}", Prim.LocalID, m_linearMotorDirection, m_lastLinearVelocityVector, m_newVelocity, grav); } // end MoveLinear() + // ======================================================================= // Apply the effect of the angular motor. private void MoveAngular(float pTimestep) { -- cgit v1.1 From 93fe384cce42e91337f446fd658ef29ca3d9f733 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Mon, 29 Oct 2012 14:33:31 -0700 Subject: BulletSim: Use the PostTaints operation to build the linkset once before the next simulation step. This eliminates the management of children vs taintChildren and simplifies the constratin creation code. --- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 52 +++----- .../Physics/BulletSPlugin/BSLinksetConstraints.cs | 140 +++++++-------------- 2 files changed, 68 insertions(+), 124 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index 569d2e7..187951e 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -61,16 +61,7 @@ public abstract class BSLinkset public int LinksetID { get; private set; } // The children under the root in this linkset. - // There are two lists of children: the current children at runtime - // and the children at taint-time. For instance, if you delink a - // child from the linkset, the child is removed from m_children - // but the constraint won't be removed until taint time. - // Two lists lets this track the 'current' children and - // the physical 'taint' children separately. - // After taint processing and before the simulation step, these - // two lists must be the same. protected HashSet m_children; - protected HashSet m_taintChildren; // We lock the diddling of linkset classes to prevent any badness. // This locks the modification of the instances of this class. Changes @@ -110,7 +101,6 @@ public abstract class BSLinkset PhysicsScene = scene; LinksetRoot = parent; m_children = new HashSet(); - m_taintChildren = new HashSet(); m_mass = parent.MassRaw; } @@ -192,7 +182,7 @@ public abstract class BSLinkset lock (m_linksetActivityLock) { action(LinksetRoot); - foreach (BSPhysObject po in m_taintChildren) + foreach (BSPhysObject po in m_children) { if (action(po)) break; @@ -201,9 +191,24 @@ public abstract class BSLinkset 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(BSPhysObject child); + + // Forcefully removing a child from a linkset. + // This is not being called by the child so we have to make sure the child doesn't think + // it's still connected to the linkset. + // Normal OpenSimulator operation will never do this because other SceneObjectPart information + // also has to be updated (like pointer to prim's parent). + protected abstract void RemoveChildFromOtherLinkset(BSPhysObject pchild); + + // 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(BSPhysObject child); + // When physical properties are changed the linkset needs to recalculate // its internal properties. - // May be called at runtime or taint-time (just pass the appropriate flag). + // May be called at runtime or taint-time. public abstract void Refresh(BSPhysObject requestor); // The object is going dynamic (physical). Do any setup necessary @@ -238,8 +243,6 @@ public abstract class BSLinkset public abstract void RestoreBodyDependencies(BSPrim child); // ================================================================ - // Below this point is internal magic - protected virtual float ComputeLinksetMass() { float mass = LinksetRoot.MassRaw; @@ -264,7 +267,7 @@ public abstract class BSLinkset com = LinksetRoot.Position * LinksetRoot.MassRaw; float totalMass = LinksetRoot.MassRaw; - foreach (BSPhysObject bp in m_taintChildren) + foreach (BSPhysObject bp in m_children) { com += bp.Position * bp.MassRaw; totalMass += bp.MassRaw; @@ -283,31 +286,16 @@ public abstract class BSLinkset { com = LinksetRoot.Position; - foreach (BSPhysObject bp in m_taintChildren) + foreach (BSPhysObject bp in m_children) { com += bp.Position * bp.MassRaw; } - com /= (m_taintChildren.Count + 1); + com /= (m_children.Count + 1); } return com; } - // I am the root of a linkset and a new child is being added - // Called while LinkActivity is locked. - protected abstract void AddChildToLinkset(BSPhysObject child); - - // Forcefully removing a child from a linkset. - // This is not being called by the child so we have to make sure the child doesn't think - // it's still connected to the linkset. - // Normal OpenSimulator operation will never do this because other SceneObjectPart information - // also has to be updated (like pointer to prim's parent). - protected abstract void RemoveChildFromOtherLinkset(BSPhysObject pchild); - - // 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(BSPhysObject child); - // 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 086aa12..6c1fa2a 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs @@ -54,7 +54,7 @@ public sealed class BSLinksetConstraints : BSLinkset // Queue to happen after all the other taint processing PhysicsScene.PostTaintObject("BSLinksetContraints.Refresh", requestor.LocalID, delegate() { - RecomputeLinksetConstraintVariables(); + RecomputeLinksetConstraints(); }); } @@ -98,24 +98,13 @@ public sealed class BSLinksetConstraints : BSLinkset lock (m_linksetActivityLock) { - if (IsRoot(child)) - { - // If the one with the dependency is root, must undo all children - DetailLog("{0},BSLinksetConstraint.RemoveBodyDependencies,removeChildrenForRoot,rID={1},rBody={2}", - child.LocalID, LinksetRoot.LocalID, LinksetRoot.BSBody.ptr.ToString("X")); + // Just undo all the constraints for this linkset. Rebuild at the end of the step. + DetailLog("{0},BSLinksetConstraint.RemoveBodyDependencies,removeChildrenForRoot,rID={1},rBody={2}", + child.LocalID, LinksetRoot.LocalID, LinksetRoot.BSBody.ptr.ToString("X")); - ret = PhysicallyUnlinkAllChildrenFromRoot(LinksetRoot); - } - else - { - DetailLog("{0},BSLinksetConstraint.RemoveBodyDependencies,removeSingleChild,rID={1},rBody={2},cID={3},cBody={4}", - child.LocalID, - LinksetRoot.LocalID, LinksetRoot.BSBody.ptr.ToString("X"), - child.LocalID, child.BSBody.ptr.ToString("X")); - // ret = PhysicallyUnlinkAChildFromRoot(LinksetRoot, child); - // Despite the function name, this removes any link to the specified object. - ret = PhysicallyUnlinkAllChildrenFromRoot(child); - } + ret = PhysicallyUnlinkAllChildrenFromRoot(LinksetRoot); + // Cause the constraints, et al to be rebuilt before the next simulation step. + Refresh(LinksetRoot); } return ret; } @@ -125,26 +114,7 @@ public sealed class BSLinksetConstraints : BSLinkset // Called at taint-time!! public override void RestoreBodyDependencies(BSPrim child) { - lock (m_linksetActivityLock) - { - if (IsRoot(child)) - { - DetailLog("{0},BSLinksetConstraint.RestoreBodyDependencies,restoreChildrenForRoot,rID={1},numChild={2}", - child.LocalID, LinksetRoot.LocalID, m_taintChildren.Count); - foreach (BSPhysObject bpo in m_taintChildren) - { - PhysicallyLinkAChildToRoot(LinksetRoot, bpo); - } - } - else - { - DetailLog("{0},BSLinksetConstraint.RestoreBodyDependencies,restoreSingleChild,rID={1},rBody={2},cID={3},cBody={4}", - LinksetRoot.LocalID, - LinksetRoot.LocalID, LinksetRoot.BSBody.ptr.ToString("X"), - child.LocalID, child.BSBody.ptr.ToString("X")); - PhysicallyLinkAChildToRoot(LinksetRoot, child); - } - } + // The Refresh operation will build any missing constraints. } // ================================================================ @@ -163,18 +133,7 @@ public sealed class BSLinksetConstraints : BSLinkset DetailLog("{0},AddChildToLinkset,call,child={1}", LinksetRoot.LocalID, child.LocalID); - PhysicsScene.TaintedObject("AddChildToLinkset", delegate() - { - DetailLog("{0},AddChildToLinkset,taint,rID={1},rBody={2},cID={3},cBody={4}", - rootx.LocalID, - rootx.LocalID, rootx.BSBody.ptr.ToString("X"), - childx.LocalID, childx.BSBody.ptr.ToString("X")); - // Since this is taint-time, the body and shape could have changed for the child - rootx.ForcePosition = rootx.Position; // DEBUG - childx.ForcePosition = childx.Position; // DEBUG - PhysicallyLinkAChildToRoot(rootx, childx); - m_taintChildren.Add(child); - }); + // Cause constraints and assorted properties to be recomputed before the next simulation step. Refresh(LinksetRoot); } return; @@ -207,7 +166,6 @@ public sealed class BSLinksetConstraints : BSLinkset PhysicsScene.TaintedObject("RemoveChildFromLinkset", delegate() { - m_taintChildren.Remove(child); PhysicallyUnlinkAChildFromRoot(rootx, childx); }); // See that the linkset parameters are recomputed at the end of the taint time. @@ -225,6 +183,12 @@ public sealed class BSLinksetConstraints : BSLinkset // Called at taint time! private void PhysicallyLinkAChildToRoot(BSPhysObject rootPrim, BSPhysObject childPrim) { + // Don't build the constraint when asked. Put it off until just before the simulation step. + Refresh(rootPrim); + } + + private BSConstraint BuildConstraint(BSPhysObject rootPrim, BSPhysObject childPrim) + { // Zero motion for children so they don't interpolate childPrim.ZeroMotion(); @@ -235,7 +199,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.PhysicallyLinkAChildToRoot,taint,root={1},rBody={2},child={3},cBody={4},rLoc={5},cLoc={6},midLoc={7}", + DetailLog("{0},BSLinksetConstraint.BuildConstraint,taint,root={1},rBody={2},child={3},cBody={4},rLoc={5},cLoc={6},midLoc={7}", rootPrim.LocalID, rootPrim.LocalID, rootPrim.BSBody.ptr.ToString("X"), childPrim.LocalID, childPrim.BSBody.ptr.ToString("X"), @@ -297,6 +261,7 @@ public sealed class BSLinksetConstraints : BSLinkset { constrain.SetSolverIterations(PhysicsScene.Params.linkConstraintSolverIterations); } + return constrain; } // Remove linkage between myself and a particular child @@ -337,56 +302,47 @@ public sealed class BSLinksetConstraints : BSLinkset } // Call each of the constraints that make up this linkset and recompute the - // various transforms and variables. Used when objects are added or removed - // from a linkset to make sure the constraints know about the new mass and - // geometry. + // various transforms and variables. Create constraints of not created yet. + // Called before the simulation step to make sure the constraint based linkset + // is all initialized. // Must only be called at taint time!! - private void RecomputeLinksetConstraintVariables() + private void RecomputeLinksetConstraints() { float linksetMass = LinksetMass; - foreach (BSPhysObject child in m_taintChildren) + LinksetRoot.UpdatePhysicalMassProperties(linksetMass); + + // For a multiple object linkset, set everybody's center of mass to the set's center of mass + OMV.Vector3 centerOfMass = ComputeLinksetCenterOfMass(); + BulletSimAPI.SetCenterOfMassByPosRot2(LinksetRoot.BSBody.ptr, centerOfMass, OMV.Quaternion.Identity); + + // BulletSimAPI.SetCollisionFilterMask2(LinksetRoot.BSBody.ptr, + // (uint)CollisionFilterGroups.LinksetFilter, (uint)CollisionFilterGroups.LinksetMask); + DetailLog("{0},BSLinksetConstraint.RecomputeLinksetConstraints,setCenterOfMass,COM={1},rBody={2},linksetMass={3}", + LinksetRoot.LocalID, centerOfMass, LinksetRoot.BSBody.ptr.ToString("X"), linksetMass); + + foreach (BSPhysObject 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.) + BulletSimAPI.SetCenterOfMassByPosRot2(child.BSBody.ptr, centerOfMass, OMV.Quaternion.Identity); + child.UpdatePhysicalMassProperties(linksetMass); + BSConstraint constrain; - if (PhysicsScene.Constraints.TryGetConstraint(LinksetRoot.BSBody, child.BSBody, out constrain)) - { - // DetailLog("{0},BSLinksetConstraint.RecomputeLinksetConstraintVariables,taint,child={1},mass={2},A={3},B={4}", - // LinksetRoot.LocalID, child.LocalID, linksetMass, constrain.Body1.ID, constrain.Body2.ID); - constrain.RecomputeConstraintVariables(linksetMass); - } - else + if (!PhysicsScene.Constraints.TryGetConstraint(LinksetRoot.BSBody, child.BSBody, out constrain)) { - // Non-fatal error that happens when children are being added to the linkset but - // their constraints have not been created yet. - break; + // If constraint doesn't exist yet, create it. + constrain = BuildConstraint(LinksetRoot, child); } - } + constrain.RecomputeConstraintVariables(linksetMass); - // If the whole linkset is not here, doesn't make sense to recompute linkset wide values - if (m_children.Count == m_taintChildren.Count) - { - // If this is a multiple object linkset, set everybody's center of mass to the set's center of mass - OMV.Vector3 centerOfMass = ComputeLinksetCenterOfMass(); - BulletSimAPI.SetCenterOfMassByPosRot2(LinksetRoot.BSBody.ptr, centerOfMass, OMV.Quaternion.Identity); - // BulletSimAPI.SetCollisionFilterMask2(LinksetRoot.BSBody.ptr, - // (uint)CollisionFilterGroups.LinksetFilter, (uint)CollisionFilterGroups.LinksetMask); - DetailLog("{0},BSLinksetConstraint.RecomputeLinksetConstraintVariables,setCenterOfMass,COM={1},rBody={2},linksetMass={3}", - LinksetRoot.LocalID, centerOfMass, LinksetRoot.BSBody.ptr.ToString("X"), linksetMass); - foreach (BSPhysObject child in m_taintChildren) - { - BulletSimAPI.SetCenterOfMassByPosRot2(child.BSBody.ptr, centerOfMass, OMV.Quaternion.Identity); - // 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. - child.UpdatePhysicalMassProperties(linksetMass); - // DEBUG: see of inter-linkset collisions are causing problems - // BulletSimAPI.SetCollisionFilterMask2(child.BSBody.ptr, - // (uint)CollisionFilterGroups.LinksetFilter, (uint)CollisionFilterGroups.LinksetMask); - } - // Also update the root's physical mass to the whole linkset - LinksetRoot.UpdatePhysicalMassProperties(linksetMass); + // DEBUG: see of inter-linkset collisions are causing problems + // BulletSimAPI.SetCollisionFilterMask2(child.BSBody.ptr, + // (uint)CollisionFilterGroups.LinksetFilter, (uint)CollisionFilterGroups.LinksetMask); - // BulletSimAPI.DumpAllInfo2(PhysicsScene.World.ptr); // DEBUG DEBUG DEBUG + // BulletSimAPI.DumpConstraint2(PhysicsScene.World.ptr, constrain.Constraint.ptr); // DEBUG DEBUG } - return; + } } } -- cgit v1.1 From 52be581f71b3c8da6113e4f4b193694683e6f8cc Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 30 Oct 2012 09:12:07 -0700 Subject: BulletSim: remove center-of-mass setting for linksets because it causes the constraint calculation to pull the objects together. --- .../Physics/BulletSPlugin/BSConstraint6Dof.cs | 3 +- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 1 - .../Physics/BulletSPlugin/BSLinksetConstraints.cs | 79 ++++++++-------------- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 2 +- .../Physics/BulletSPlugin/BSShapeCollection.cs | 2 +- 5 files changed, 33 insertions(+), 54 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSConstraint6Dof.cs b/OpenSim/Region/Physics/BulletSPlugin/BSConstraint6Dof.cs index 3c37d76..23ef052 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSConstraint6Dof.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSConstraint6Dof.cs @@ -71,8 +71,7 @@ public sealed class BSConstraint6Dof : BSConstraint BSScene.DetailLogZero, world.worldID, obj1.ID, obj1.ptr.ToString("X"), obj2.ID, obj2.ptr.ToString("X")); world.physicsScene.Logger.ErrorFormat("{0} Attempt to build 6DOF constraint with missing bodies: wID={1}, rID={2}, rBody={3}, cID={4}, cBody={5}", - "[BULLETSIM 6DOF CONSTRAINT]", world.worldID, - obj1.ID, obj1.ptr.ToString("X"), obj2.ID, obj2.ptr.ToString("X")); + LogHeader, world.worldID, obj1.ID, obj1.ptr.ToString("X"), obj2.ID, obj2.ptr.ToString("X")); m_enabled = false; } else diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index 187951e..6d84fcc 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -132,7 +132,6 @@ public abstract class BSLinkset // Cannot remove the root from a linkset. return this; } - RemoveChildFromLinkset(child); } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs index 6c1fa2a..ecb6ad4 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs @@ -43,20 +43,16 @@ public sealed class BSLinksetConstraints : BSLinkset // When physical properties are changed the linkset needs to recalculate // its internal properties. - // This is queued in such a way that the - // refresh will only happen once after all the other taints are applied. + // This is queued in the 'post taint' queue so the + // refresh will happen once after all the other taints are applied. public override void Refresh(BSPhysObject requestor) { - // If there are no children, there are no constraints to recompute. - if (!HasAnyChildren) - return; - // Queue to happen after all the other taint processing PhysicsScene.PostTaintObject("BSLinksetContraints.Refresh", requestor.LocalID, delegate() { - RecomputeLinksetConstraints(); + if (HasAnyChildren && IsRoot(requestor)) + RecomputeLinksetConstraints(); }); - } // The object is going dynamic (physical). Do any setup necessary @@ -71,9 +67,10 @@ public sealed class BSLinksetConstraints : BSLinkset return false; } - // The object is going static (non-physical). Do any setup necessary - // for a static linkset. + // The object is going static (non-physical). Do any setup necessary for a static linkset. // Return 'true' if any properties updated on the passed object. + // This doesn't normally happen -- OpenSim removes the objects from the physical + // world if it is a static linkset. // Called at taint-time! public override bool MakeStatic(BSPhysObject child) { @@ -87,21 +84,21 @@ public sealed class BSLinksetConstraints : BSLinkset // Nothing to do for constraints on property updates } - // Routine used when rebuilding the body of the root of the linkset - // Destroy all the constraints have have been made to root. - // This is called when the root body is changing. - // Returns 'true' of something eas actually removed and would need restoring + // Routine called when rebuilding the body of some member of the linkset. + // Destroy all the constraints have have been made to root and set + // 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(BSPrim child) { bool ret = false; + DetailLog("{0},BSLinksetConstraint.RemoveBodyDependencies,removeChildrenForRoot,rID={1},rBody={2}", + child.LocalID, LinksetRoot.LocalID, LinksetRoot.BSBody.ptr.ToString("X")); + lock (m_linksetActivityLock) { // Just undo all the constraints for this linkset. Rebuild at the end of the step. - DetailLog("{0},BSLinksetConstraint.RemoveBodyDependencies,removeChildrenForRoot,rID={1},rBody={2}", - child.LocalID, LinksetRoot.LocalID, LinksetRoot.BSBody.ptr.ToString("X")); - ret = PhysicallyUnlinkAllChildrenFromRoot(LinksetRoot); // Cause the constraints, et al to be rebuilt before the next simulation step. Refresh(LinksetRoot); @@ -114,13 +111,12 @@ public sealed class BSLinksetConstraints : BSLinkset // Called at taint-time!! public override void RestoreBodyDependencies(BSPrim child) { - // The Refresh operation will build any missing constraints. + // The Refresh operation queued by RemoveBodyDependencies() will build any missing constraints. } // ================================================================ - // Below this point is internal magic - // I am the root of a linkset and a new child is being added + // Add a new child to the linkset. // Called while LinkActivity is locked. protected override void AddChildToLinkset(BSPhysObject child) { @@ -131,7 +127,7 @@ public sealed class BSLinksetConstraints : BSLinkset BSPhysObject rootx = LinksetRoot; // capture the root as of now BSPhysObject childx = child; - DetailLog("{0},AddChildToLinkset,call,child={1}", LinksetRoot.LocalID, child.LocalID); + 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); @@ -150,7 +146,7 @@ public sealed class BSLinksetConstraints : BSLinkset RemoveChildFromLinkset(pchild); } - // I am the root of a linkset and one of my children is being removed. + // Remove the specified child from the linkset. // Safe to call even if the child is not really in my linkset. protected override void RemoveChildFromLinkset(BSPhysObject child) { @@ -159,12 +155,12 @@ public sealed class BSLinksetConstraints : BSLinkset BSPhysObject rootx = LinksetRoot; // capture the root and body as of now BSPhysObject childx = child; - DetailLog("{0},RemoveChildFromLinkset,call,rID={1},rBody={2},cID={3},cBody={4}", + DetailLog("{0},BSLinksetConstraints.RemoveChildFromLinkset,call,rID={1},rBody={2},cID={3},cBody={4}", childx.LocalID, rootx.LocalID, rootx.BSBody.ptr.ToString("X"), childx.LocalID, childx.BSBody.ptr.ToString("X")); - PhysicsScene.TaintedObject("RemoveChildFromLinkset", delegate() + PhysicsScene.TaintedObject("BSLinksetConstraints.RemoveChildFromLinkset", delegate() { PhysicallyUnlinkAChildFromRoot(rootx, childx); }); @@ -173,7 +169,7 @@ public sealed class BSLinksetConstraints : BSLinkset } else { - // This will happen if we remove the root of the linkset first. Non-fatal occurance. + // Non-fatal occurance. // PhysicsScene.Logger.ErrorFormat("{0}: Asked to remove child from linkset that was not in linkset", LogHeader); } return; @@ -215,7 +211,7 @@ public sealed class BSLinksetConstraints : BSLinkset /* 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 as a warning to future programmers. + * Code left for future programmers. // ================================================================================== // relative position normalized to the root prim OMV.Quaternion invThisOrientation = OMV.Quaternion.Inverse(rootPrim.Orientation); @@ -225,8 +221,6 @@ public sealed class BSLinksetConstraints : BSLinkset OMV.Quaternion childRelativeRotation = invThisOrientation * childPrim.Orientation; OMV.Quaternion inverseChildRelativeRotation = OMV.Quaternion.Inverse(childRelativeRotation); - // create a constraint that allows no freedom of movement between the two objects - // http://bulletphysics.org/Bullet/phpBB3/viewtopic.php?t=4818 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, @@ -234,11 +228,6 @@ public sealed class BSLinksetConstraints : BSLinkset OMV.Quaternion.Inverse(rootPrim.Orientation), OMV.Vector3.Zero, OMV.Quaternion.Inverse(childPrim.Orientation), - // A point half way between the parent and child - // childRelativePosition/2, - // childRelativeRotation, - // childRelativePosition/2, - // inverseChildRelativeRotation, true, true ); @@ -264,9 +253,9 @@ public sealed class BSLinksetConstraints : BSLinkset return constrain; } - // Remove linkage between myself and a particular child + // Remove linkage between the linkset root and a particular child // The root and child bodies are passed in because we need to remove the constraint between - // the bodies that were at unlink time. + // the bodies that were present at unlink time. // Called at taint time! private bool PhysicallyUnlinkAChildFromRoot(BSPhysObject rootPrim, BSPhysObject childPrim) { @@ -288,44 +277,36 @@ public sealed class BSLinksetConstraints : BSLinkset } // Remove linkage between myself and any possible children I might have. + // Returns 'true' of any constraints were destroyed. // Called at taint time! private bool PhysicallyUnlinkAllChildrenFromRoot(BSPhysObject rootPrim) { DetailLog("{0},BSLinksetConstraint.PhysicallyUnlinkAllChildren,taint", rootPrim.LocalID); - bool ret = false; - if (PhysicsScene.Constraints.RemoveAndDestroyConstraint(rootPrim.BSBody)) - { - ret = true; - } - return ret; + return PhysicsScene.Constraints.RemoveAndDestroyConstraint(rootPrim.BSBody); } // Call each of the constraints that make up this linkset and recompute the // various transforms and variables. Create constraints of not created yet. // Called before the simulation step to make sure the constraint based linkset // is all initialized. - // Must only be called at taint time!! + // Called at taint time!! private void RecomputeLinksetConstraints() { float linksetMass = LinksetMass; LinksetRoot.UpdatePhysicalMassProperties(linksetMass); - // For a multiple object linkset, set everybody's center of mass to the set's center of mass - OMV.Vector3 centerOfMass = ComputeLinksetCenterOfMass(); - BulletSimAPI.SetCenterOfMassByPosRot2(LinksetRoot.BSBody.ptr, centerOfMass, OMV.Quaternion.Identity); - + // DEBUG: see of inter-linkset collisions are causing problems // BulletSimAPI.SetCollisionFilterMask2(LinksetRoot.BSBody.ptr, // (uint)CollisionFilterGroups.LinksetFilter, (uint)CollisionFilterGroups.LinksetMask); - DetailLog("{0},BSLinksetConstraint.RecomputeLinksetConstraints,setCenterOfMass,COM={1},rBody={2},linksetMass={3}", - LinksetRoot.LocalID, centerOfMass, LinksetRoot.BSBody.ptr.ToString("X"), linksetMass); + DetailLog("{0},BSLinksetConstraint.RecomputeLinksetConstraints,setCenterOfMass,rBody={1},linksetMass={2}", + LinksetRoot.LocalID, LinksetRoot.BSBody.ptr.ToString("X"), linksetMass); foreach (BSPhysObject 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.) - BulletSimAPI.SetCenterOfMassByPosRot2(child.BSBody.ptr, centerOfMass, OMV.Quaternion.Identity); child.UpdatePhysicalMassProperties(linksetMass); BSConstraint constrain; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index ad09a61..7851a40 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -634,7 +634,7 @@ public sealed class BSPrim : BSPhysObject // had been automatically disabled when the mass was set to zero. Linkset.Refresh(this); - DetailLog("{0},BSPrim.UpdatePhysicalParameters,exit,static={1},solid={2},mass={3},collide={4},cf={5:X},body={6},shape={7}", + DetailLog("{0},BSPrim.UpdatePhysicalParameters,taintExit,static={1},solid={2},mass={3},collide={4},cf={5:X},body={6},shape={7}", LocalID, IsStatic, IsSolid, _mass, SubscribedEvents(), CurrentCollisionFlags, BSBody, BSShape); } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index 1c0e6f5..1219fc0 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -109,7 +109,7 @@ public sealed class BSShapeCollection : IDisposable prim.BSShape, shapeData, bodyCallback); ret = newGeom || newBody; } - DetailLog("{0},BSShapeCollection.GetBodyAndShape,force={1},ret={2},body={3},shape={4}", + DetailLog("{0},BSShapeCollection.GetBodyAndShape,taintExit,force={1},ret={2},body={3},shape={4}", prim.LocalID, forceRebuild, ret, prim.BSBody, prim.BSShape); return ret; -- cgit v1.1 From 28e2cd3fa21835b124552dec024745f5784f6b3a Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Wed, 31 Oct 2012 09:26:58 -0700 Subject: BulletSim: vehicle tweeking. Add AddTorque() method to BSPrim. Remove some manual motor actions in computing angular force (will eventually be replaced with motor class). Remove some experimental changes. --- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 136 ++++++++------------- .../Physics/BulletSPlugin/BSLinksetConstraints.cs | 2 +- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 45 +++++-- 3 files changed, 90 insertions(+), 93 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index 4981007..5c61774 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -511,21 +511,6 @@ namespace OpenSim.Region.Physics.BulletSPlugin // Do any updating needed for a vehicle public void Refresh() { - /* - * Doesnt work unless BSDynamics senses and corrects for all collisions - if (IsActive) - BulletSimAPI.AddToCollisionFlags2(Prim.BSBody.ptr, CollisionFlags.CF_KINEMATIC_OBJECT); - else - BulletSimAPI.RemoveFromCollisionFlags2(Prim.BSBody.ptr, CollisionFlags.CF_KINEMATIC_OBJECT); - */ - /* - * Doesn't work because with zero inertia, Bullet will not apply any forces to the object. - if (IsActive) - { - BulletSimAPI.SetMassProps2(Prim.BSBody.ptr, Prim.MassRaw, Vector3.Zero); - BulletSimAPI.UpdateInertiaTensor2(Prim.BSBody.ptr); - } - */ if (IsActive) { // Friction effects are handled by this vehicle code @@ -539,29 +524,21 @@ namespace OpenSim.Region.Physics.BulletSPlugin { if (!IsActive) return; - m_lastAngularVelocity = Prim.ForceRotationalVelocity; // DEBUG: account for what Bullet did last time + // DEBUG + // Because Bullet does apply forces to the vehicle, our last computed + // linear and angular velocities are not what is happening now. + // Vector3 externalAngularVelocity = Prim.ForceRotationalVelocity - m_lastAngularVelocity; + // m_lastAngularVelocity += (externalAngularVelocity * 0.5f) * pTimestep; + // m_lastAngularVelocity = Prim.ForceRotationalVelocity; // DEBUG: account for what Bullet did last time + // m_lastLinearVelocityVector = Prim.ForceVelocity * Quaternion.Inverse(Prim.ForceOrientation); // DEBUG: + // END DEBUG MoveLinear(pTimestep); MoveAngular(pTimestep); LimitRotation(pTimestep); - /* Experimental - // Wonder if Bullet could handle collision penetration while this applies the forces. - // Apply the computed forces on the vehicle - Prim.ForcePosition += Prim.ForceVelocity * Prim.MassRaw * pTimestep; - - if (Prim.ForceRotationalVelocity != Vector3.Zero) - { - Quaternion newOrientation = Prim.ForceOrientation; - newOrientation.Normalize(); - Quaternion appliedRotation = new Quaternion((Prim.ForceRotationalVelocity * pTimestep), 0f); - newOrientation += (appliedRotation * newOrientation) * 0.5f; - newOrientation.Normalize(); - Prim.ForceOrientation = newOrientation; - } - */ // DEBUG: Trying to figure out why Bullet goes crazy when the root prim is moved. - BulletSimAPI.SetInterpolationVelocity2(Prim.BSBody.ptr, m_newVelocity, m_lastAngularVelocity); // DEBUG DEBUG DEBUG + // BulletSimAPI.SetInterpolationVelocity2(Prim.BSBody.ptr, m_newVelocity, m_lastAngularVelocity); // DEBUG DEBUG DEBUG // remember the position so next step we can limit absolute movement effects m_lastPositionVector = Prim.ForcePosition; @@ -583,7 +560,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin Vector3 vehicleVelocity = Prim.ForceVelocity * Quaternion.Inverse(Prim.ForceOrientation); // DEBUG // add drive to body - Vector3 addAmount = (m_linearMotorDirection - m_lastLinearVelocityVector)/(m_linearMotorTimescale / pTimestep); + Vector3 addAmount = (m_linearMotorDirection - m_lastLinearVelocityVector)/(m_linearMotorTimescale) * pTimestep; // lastLinearVelocityVector is the current body velocity vector m_lastLinearVelocityVector += addAmount; @@ -593,11 +570,12 @@ namespace OpenSim.Region.Physics.BulletSPlugin Vector3 frictionFactor = (Vector3.One / m_linearFrictionTimescale) * pTimestep; m_lastLinearVelocityVector *= (Vector3.One - frictionFactor); - VDetailLog("{0},MoveLinear,nonZero,origdir={1},origvel={2},vehVel={3},add={4},decay={5},lmDir={6},lmVel={7}", - Prim.LocalID, origDir, origVel, vehicleVelocity, addAmount, decayFactor, m_linearMotorDirection, m_lastLinearVelocityVector); - - // convert requested object velocity to object relative vector + // Rotate new object velocity from vehicle relative to world coordinates m_newVelocity = m_lastLinearVelocityVector * Prim.ForceOrientation; + + VDetailLog("{0},MoveLinear,nonZero,origdir={1},origvel={2},vehVel={3},add={4},decay={5},frict={6},lmDir={7},lmVel={8},newVel={9}", + Prim.LocalID, origDir, origVel, vehicleVelocity, addAmount, decayFactor, frictionFactor, + m_linearMotorDirection, m_lastLinearVelocityVector, m_newVelocity); } else { @@ -609,18 +587,15 @@ namespace OpenSim.Region.Physics.BulletSPlugin VDetailLog("{0},MoveLinear,zeroed", Prim.LocalID); } - // m_newVelocity is velocity computed from linear motor + // m_newVelocity is velocity computed from linear motor in world coordinates - // Add the various forces into m_dir which will be our new direction vector (velocity) - - // add Gravity and Buoyancy + // Gravity and Buoyancy // There is some gravity, make a gravity force vector that is applied after object velocity. // m_VehicleBuoyancy: -1=2g; 0=1g; 1=0g; - // Vector3 grav = Prim.PhysicsScene.DefaultGravity * (Prim.Linkset.LinksetMass * (1f - m_VehicleBuoyancy)); Vector3 grav = Prim.PhysicsScene.DefaultGravity * (1f - m_VehicleBuoyancy); /* - * RA: Not sure why one would do this + * RA: Not sure why one would do this unless we are hoping external forces are doing gravity, ... // Preserve the current Z velocity Vector3 vel_now = m_prim.Velocity; m_dir.Z = vel_now.Z; // Preserve the accumulated falling velocity @@ -676,7 +651,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin else { float verticalError = pos.Z - m_VhoverTargetHeight; - // RA: where does the 50 come from> + // RA: where does the 50 come from? float verticalCorrectionVelocity = pTimestep * ((verticalError * 50.0f) / m_VhoverTimescale); // Replace Vertical speed with correction figure if significant if (Math.Abs(verticalError) > 0.01f) @@ -784,37 +759,24 @@ namespace OpenSim.Region.Physics.BulletSPlugin // m_angularFrictionTimescale // body angular velocity decay rate // m_lastAngularVelocity // what was last applied to body - // Get what the body is doing, this includes 'external' influences - Vector3 angularVelocity = Prim.ForceRotationalVelocity; - - if (m_angularMotorApply > 0) + if (m_angularMotorDirection.LengthSquared() > 0.0001) { - // Rather than snapping the angular motor velocity from the old value to - // a newly set velocity, this routine steps the value from the previous - // value (m_angularMotorVelocity) to the requested value (m_angularMotorDirection). - // There are m_angularMotorApply steps. Vector3 origVel = m_angularMotorVelocity; Vector3 origDir = m_angularMotorDirection; - // ramp up to new value // new velocity += error / ( time to get there / step interval) // requested speed - last motor speed m_angularMotorVelocity += (m_angularMotorDirection - m_angularMotorVelocity) / (m_angularMotorTimescale / pTimestep); + // decay requested direction + m_angularMotorDirection *= (1.0f - (pTimestep * 1.0f/m_angularMotorDecayTimescale)); - VDetailLog("{0},MoveAngular,angularMotorApply,apply={1},angTScale={2},timeStep={3},origvel={4},origDir={5},vel={6}", - Prim.LocalID, m_angularMotorApply, m_angularMotorTimescale, pTimestep, origVel, origDir, m_angularMotorVelocity); - - m_angularMotorApply--; + VDetailLog("{0},MoveAngular,angularMotorApply,angTScale={1},timeStep={2},origvel={3},origDir={4},vel={5}", + Prim.LocalID, m_angularMotorTimescale, pTimestep, origVel, origDir, m_angularMotorVelocity); } else { - // No motor recently applied, keep the body velocity - // and decay the velocity - if (m_angularMotorVelocity.LengthSquared() < 0.0001) - m_angularMotorVelocity = Vector3.Zero; - else - m_angularMotorVelocity -= m_angularMotorVelocity / (m_angularMotorDecayTimescale / pTimestep); - } // end motor section + m_angularMotorVelocity = Vector3.Zero; + } #region Vertical attactor @@ -824,22 +786,19 @@ namespace OpenSim.Region.Physics.BulletSPlugin if (m_verticalAttractionTimescale < 300 && m_lastAngularVelocity != Vector3.Zero) { - float VAservo = 0.2f; + float VAservo = pTimestep * 0.2f / m_verticalAttractionTimescale; if (Prim.Linkset.LinksetIsColliding) - VAservo = 0.05f / (m_verticalAttractionTimescale / pTimestep); + VAservo = pTimestep * 0.05f / (m_verticalAttractionTimescale); VAservo *= (m_verticalAttractionEfficiency * m_verticalAttractionEfficiency); - // get present body rotation - Quaternion rotq = Prim.ForceOrientation; - // vector pointing up - Vector3 verticalError = Vector3.UnitZ; - - // rotate it to Body Angle - verticalError = verticalError * rotq; - // verticalError.X and .Y are the World error amounts. They are 0 when there is no error (Vehicle Body is 'vertical'), and .Z will be 1. - // As the body leans to its side |.X| will increase to 1 and .Z fall to 0. As body inverts |.X| will fall and .Z will go - // negative. Similar for tilt and |.Y|. .X and .Y must be modulated to prevent a stable inverted body. + // Create a vector of the vehicle "up" in world coordinates + Vector3 verticalError = Vector3.UnitZ * Prim.ForceOrientation; + // verticalError.X and .Y are the World error amounts. They are 0 when there is no + // error (Vehicle Body is 'vertical'), and .Z will be 1. As the body leans to its + // side |.X| will increase to 1 and .Z fall to 0. As body inverts |.X| will fall + // and .Z will go // negative. Similar for tilt and |.Y|. .X and .Y must be + // modulated to prevent a stable inverted body. // Error is 0 (no error) to +/- 2 (max error) if (verticalError.Z < 0.0f) @@ -850,13 +809,15 @@ namespace OpenSim.Region.Physics.BulletSPlugin // scale it by VAservo verticalError = verticalError * VAservo; - // As the body rotates around the X axis, then verticalError.Y increases; Rotated around Y then .X increases, so - // Change Body angular velocity X based on Y, and Y based on X. Z is not changed. + // As the body rotates around the X axis, then verticalError.Y increases; Rotated around Y + // then .X increases, so change Body angular velocity X based on Y, and Y based on X. + // Z is not changed. vertattr.X = verticalError.Y; vertattr.Y = - verticalError.X; vertattr.Z = 0f; // scaling appears better usingsquare-law + Vector3 angularVelocity = Prim.ForceRotationalVelocity; float bounce = 1.0f - (m_verticalAttractionEfficiency * m_verticalAttractionEfficiency); vertattr.X += bounce * angularVelocity.X; vertattr.Y += bounce * angularVelocity.Y; @@ -956,15 +917,22 @@ namespace OpenSim.Region.Physics.BulletSPlugin VDetailLog("{0},MoveAngular,zeroSmallValues,lastAngular={1}", Prim.LocalID, m_lastAngularVelocity); } - // apply friction - Vector3 decayamount = Vector3.One / (m_angularFrictionTimescale / pTimestep); - m_lastAngularVelocity -= m_lastAngularVelocity * decayamount; - // Apply to the body // The above calculates the absolute angular velocity needed - Prim.ForceRotationalVelocity = m_lastAngularVelocity; + // Prim.ForceRotationalVelocity = m_lastAngularVelocity; + + // Apply a force to overcome current angular velocity + Vector3 applyAngularForce = (m_lastAngularVelocity - Prim.ForceRotationalVelocity) * Prim.Linkset.LinksetMass; + // Vector3 applyAngularForce = (m_lastAngularVelocity - Prim.ForceRotationalVelocity); + // Prim.AddAngularForce(applyAngularForce, false); + Prim.ApplyTorqueImpulse(applyAngularForce, false); + + // Apply friction for next time + Vector3 decayamount = (Vector3.One / m_angularFrictionTimescale) * pTimestep; + m_lastAngularVelocity *= Vector3.One - decayamount; - VDetailLog("{0},MoveAngular,done,decay={1},lastAngular={2}", Prim.LocalID, decayamount, m_lastAngularVelocity); + VDetailLog("{0},MoveAngular,done,applyAForce={1},decay={2},lastAngular={3}", + Prim.LocalID, applyAngularForce, decayamount, m_lastAngularVelocity); } //end MoveAngular internal void LimitRotation(float timestep) diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs index ecb6ad4..8cdbd9b 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs @@ -299,7 +299,7 @@ public sealed class BSLinksetConstraints : BSLinkset // DEBUG: see of inter-linkset collisions are causing problems // BulletSimAPI.SetCollisionFilterMask2(LinksetRoot.BSBody.ptr, // (uint)CollisionFilterGroups.LinksetFilter, (uint)CollisionFilterGroups.LinksetMask); - DetailLog("{0},BSLinksetConstraint.RecomputeLinksetConstraints,setCenterOfMass,rBody={1},linksetMass={2}", + DetailLog("{0},BSLinksetConstraint.RecomputeLinksetConstraints,set,rBody={1},linksetMass={2}", LinksetRoot.LocalID, LinksetRoot.BSBody.ptr.ToString("X"), linksetMass); foreach (BSPhysObject child in m_children) diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 7851a40..9ced61fa 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -378,7 +378,9 @@ public sealed class BSPrim : BSPhysObject { OMV.Vector3 localInertia = BulletSimAPI.CalculateLocalInertia2(BSShape.ptr, physMass); BulletSimAPI.SetMassProps2(BSBody.ptr, physMass, localInertia); - BulletSimAPI.UpdateInertiaTensor2(BSBody.ptr); + // center of mass is at the zero of the object + BulletSimAPI.SetCenterOfMassByPosRot2(BSBody.ptr, ForcePosition, ForceOrientation); + // BulletSimAPI.UpdateInertiaTensor2(BSBody.ptr); DetailLog("{0},BSPrim.UpdateMassProperties,mass={1},localInertia={2}", LocalID, physMass, localInertia); } } @@ -462,9 +464,16 @@ public sealed class BSPrim : BSPhysObject // Called from Scene when doing simulation step so we're in taint processing time. public override void StepVehicle(float timeStep) { - if (IsPhysical) + if (IsPhysical && _vehicle.IsActive) { _vehicle.Step(timeStep); + /* // TEST TEST DEBUG DEBUG -- trying to reduce the extra action of Bullet simulation step + PhysicsScene.PostTaintObject("BSPrim.StepVehicles", LocalID, delegate() + { + // This resets the interpolation values and recomputes the tensor variables + BulletSimAPI.SetCenterOfMassByPosRot2(BSBody.ptr, ForcePosition, ForceOrientation); + }); + */ } } @@ -502,7 +511,9 @@ public sealed class BSPrim : BSPhysObject } public override OMV.Vector3 Torque { get { return _torque; } - set { _torque = value; + set { + _torque = value; + AddAngularForce(_torque, false, false); // DetailLog("{0},BSPrim.SetTorque,call,torque={1}", LocalID, _torque); } } @@ -831,7 +842,7 @@ public sealed class BSPrim : BSPhysObject // m_log.DebugFormat("{0}: RotationalVelocity={1}", LogHeader, _rotationalVelocity); PhysicsScene.TaintedObject("BSPrim.setRotationalVelocity", delegate() { - // DetailLog("{0},BSPrim.SetRotationalVel,taint,rotvel={1}", LocalID, _rotationalVelocity); + DetailLog("{0},BSPrim.SetRotationalVel,taint,rotvel={1}", LocalID, _rotationalVelocity); BulletSimAPI.SetAngularVelocity2(BSBody.ptr, _rotationalVelocity); }); } @@ -972,14 +983,31 @@ public sealed class BSPrim : BSPhysObject } m_accumulatedAngularForces.Clear(); } - // DetailLog("{0},BSPrim.AddAngularForce,taint,aForce={1}", LocalID, fSum); + DetailLog("{0},BSPrim.AddAngularForce,taint,aForce={1}", LocalID, fSum); if (fSum != OMV.Vector3.Zero) + { BulletSimAPI.ApplyTorque2(BSBody.ptr, fSum); + _torque = fSum; + } }; if (inTaintTime) addAngularForceOperation(); else - PhysicsScene.TaintedObject("BSPrim.AddForce", addAngularForceOperation); + PhysicsScene.TaintedObject("BSPrim.AddAngularForce", addAngularForceOperation); + } + // A torque impulse. + public void ApplyTorqueImpulse(OMV.Vector3 impulse, bool inTaintTime) + { + OMV.Vector3 applyImpulse = impulse; + BSScene.TaintCallback applyTorqueImpulseOperation = delegate() + { + DetailLog("{0},BSPrim.ApplyTorqueImpulse,taint,tImpulse={1}", LocalID, applyImpulse); + BulletSimAPI.ApplyTorqueImpulse2(BSBody.ptr, applyImpulse); + }; + if (inTaintTime) + applyTorqueImpulseOperation(); + else + PhysicsScene.TaintedObject("BSPrim.ApplyTorqueImpulse", applyTorqueImpulseOperation); } public override void SetMomentum(OMV.Vector3 momentum) { // DetailLog("{0},BSPrim.SetMomentum,call,mom={1}", LocalID, momentum); @@ -1418,8 +1446,9 @@ public sealed class BSPrim : BSPhysObject PositionSanityCheck(true); - DetailLog("{0},BSPrim.UpdateProperties,call,pos={1},orient={2},vel={3},accel={4},rotVel={5}", - LocalID, _position, _orientation, _velocity, _acceleration, _rotationalVelocity); + OMV.Vector3 direction = OMV.Vector3.UnitX * _orientation; + DetailLog("{0},BSPrim.UpdateProperties,call,pos={1},orient={2},dir={3},vel={4},rotVel={5}", + LocalID, _position, _orientation, direction, _velocity, _rotationalVelocity); // BulletSimAPI.DumpRigidBody2(PhysicsScene.World.ptr, BSBody.ptr); // DEBUG DEBUG DEBUG -- cgit v1.1 From 364a7c308804a3e331199ca60c6dfafa406b5d0d Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Wed, 31 Oct 2012 14:49:28 -0700 Subject: BulletSim: rename BSBody and BSShape to PhysBody and PhysShape. Add skeleton of BSLinksetCompound. --- .../Region/Physics/BulletSPlugin/BSCharacter.cs | 78 +++++----- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 4 +- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 7 - .../Physics/BulletSPlugin/BSLinksetCompound.cs | 173 +++++++++++++++++++++ .../Physics/BulletSPlugin/BSLinksetConstraints.cs | 40 ++--- .../Region/Physics/BulletSPlugin/BSPhysObject.cs | 8 +- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 128 +++++++-------- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 20 +-- .../Physics/BulletSPlugin/BSShapeCollection.cs | 46 +++--- 9 files changed, 328 insertions(+), 176 deletions(-) create mode 100755 OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index b9013ab..8c7061d 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -131,45 +131,45 @@ public sealed class BSCharacter : BSPhysObject DetailLog("{0},BSCharacter.Destroy", LocalID); PhysicsScene.TaintedObject("BSCharacter.destroy", delegate() { - PhysicsScene.Shapes.DereferenceBody(BSBody, true, null); - PhysicsScene.Shapes.DereferenceShape(BSShape, true, null); + PhysicsScene.Shapes.DereferenceBody(PhysBody, true, null); + PhysicsScene.Shapes.DereferenceShape(PhysShape, true, null); }); } private void SetPhysicalProperties() { - BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.ptr, BSBody.ptr); + BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.ptr, PhysBody.ptr); ZeroMotion(); ForcePosition = _position; // Set the velocity and compute the proper friction ForceVelocity = _velocity; - BulletSimAPI.SetRestitution2(BSBody.ptr, PhysicsScene.Params.avatarRestitution); - BulletSimAPI.SetMargin2(BSShape.ptr, PhysicsScene.Params.collisionMargin); - BulletSimAPI.SetLocalScaling2(BSShape.ptr, Scale); - BulletSimAPI.SetContactProcessingThreshold2(BSBody.ptr, PhysicsScene.Params.contactProcessingThreshold); + BulletSimAPI.SetRestitution2(PhysBody.ptr, PhysicsScene.Params.avatarRestitution); + BulletSimAPI.SetMargin2(PhysShape.ptr, PhysicsScene.Params.collisionMargin); + BulletSimAPI.SetLocalScaling2(PhysShape.ptr, Scale); + BulletSimAPI.SetContactProcessingThreshold2(PhysBody.ptr, PhysicsScene.Params.contactProcessingThreshold); if (PhysicsScene.Params.ccdMotionThreshold > 0f) { - BulletSimAPI.SetCcdMotionThreshold2(BSBody.ptr, PhysicsScene.Params.ccdMotionThreshold); - BulletSimAPI.SetCcdSweptSphereRadius2(BSBody.ptr, PhysicsScene.Params.ccdSweptSphereRadius); + BulletSimAPI.SetCcdMotionThreshold2(PhysBody.ptr, PhysicsScene.Params.ccdMotionThreshold); + BulletSimAPI.SetCcdSweptSphereRadius2(PhysBody.ptr, PhysicsScene.Params.ccdSweptSphereRadius); } UpdatePhysicalMassProperties(MassRaw); // Make so capsule does not fall over - BulletSimAPI.SetAngularFactorV2(BSBody.ptr, OMV.Vector3.Zero); + BulletSimAPI.SetAngularFactorV2(PhysBody.ptr, OMV.Vector3.Zero); - BulletSimAPI.AddToCollisionFlags2(BSBody.ptr, CollisionFlags.CF_CHARACTER_OBJECT); + BulletSimAPI.AddToCollisionFlags2(PhysBody.ptr, CollisionFlags.CF_CHARACTER_OBJECT); - BulletSimAPI.AddObjectToWorld2(PhysicsScene.World.ptr, BSBody.ptr); + BulletSimAPI.AddObjectToWorld2(PhysicsScene.World.ptr, PhysBody.ptr); // BulletSimAPI.ForceActivationState2(BSBody.ptr, ActivationState.ACTIVE_TAG); - BulletSimAPI.ForceActivationState2(BSBody.ptr, ActivationState.DISABLE_DEACTIVATION); - BulletSimAPI.UpdateSingleAabb2(PhysicsScene.World.ptr, BSBody.ptr); + BulletSimAPI.ForceActivationState2(PhysBody.ptr, ActivationState.DISABLE_DEACTIVATION); + BulletSimAPI.UpdateSingleAabb2(PhysicsScene.World.ptr, PhysBody.ptr); // Do this after the object has been added to the world - BulletSimAPI.SetCollisionFilterMask2(BSBody.ptr, + BulletSimAPI.SetCollisionFilterMask2(PhysBody.ptr, (uint)CollisionFilterGroups.AvatarFilter, (uint)CollisionFilterGroups.AvatarMask); } @@ -199,7 +199,7 @@ public sealed class BSCharacter : BSPhysObject PhysicsScene.TaintedObject("BSCharacter.setSize", delegate() { - BulletSimAPI.SetLocalScaling2(BSShape.ptr, Scale); + BulletSimAPI.SetLocalScaling2(PhysShape.ptr, Scale); UpdatePhysicalMassProperties(MassRaw); }); @@ -234,10 +234,10 @@ public sealed class BSCharacter : BSPhysObject _rotationalVelocity = OMV.Vector3.Zero; // Zero some other properties directly into the physics engine - BulletSimAPI.SetLinearVelocity2(BSBody.ptr, OMV.Vector3.Zero); - BulletSimAPI.SetAngularVelocity2(BSBody.ptr, OMV.Vector3.Zero); - BulletSimAPI.SetInterpolationVelocity2(BSBody.ptr, OMV.Vector3.Zero, OMV.Vector3.Zero); - BulletSimAPI.ClearForces2(BSBody.ptr); + BulletSimAPI.SetLinearVelocity2(PhysBody.ptr, OMV.Vector3.Zero); + BulletSimAPI.SetAngularVelocity2(PhysBody.ptr, OMV.Vector3.Zero); + BulletSimAPI.SetInterpolationVelocity2(PhysBody.ptr, OMV.Vector3.Zero, OMV.Vector3.Zero); + BulletSimAPI.ClearForces2(PhysBody.ptr); } public override void LockAngularMotion(OMV.Vector3 axis) { return; } @@ -254,19 +254,19 @@ public sealed class BSCharacter : BSPhysObject PhysicsScene.TaintedObject("BSCharacter.setPosition", delegate() { DetailLog("{0},BSCharacter.SetPosition,taint,pos={1},orient={2}", LocalID, _position, _orientation); - BulletSimAPI.SetTranslation2(BSBody.ptr, _position, _orientation); + BulletSimAPI.SetTranslation2(PhysBody.ptr, _position, _orientation); }); } } public override OMV.Vector3 ForcePosition { get { - _position = BulletSimAPI.GetPosition2(BSBody.ptr); + _position = BulletSimAPI.GetPosition2(PhysBody.ptr); return _position; } set { _position = value; PositionSanityCheck(); - BulletSimAPI.SetTranslation2(BSBody.ptr, _position, _orientation); + BulletSimAPI.SetTranslation2(PhysBody.ptr, _position, _orientation); } } @@ -313,7 +313,7 @@ public sealed class BSCharacter : BSPhysObject BSScene.TaintCallback sanityOperation = delegate() { DetailLog("{0},BSCharacter.PositionSanityCheck,taint,pos={1},orient={2}", LocalID, _position, _orientation); - BulletSimAPI.SetTranslation2(BSBody.ptr, _position, _orientation); + BulletSimAPI.SetTranslation2(PhysBody.ptr, _position, _orientation); }; if (inTaintTime) sanityOperation(); @@ -332,8 +332,8 @@ public sealed class BSCharacter : BSPhysObject } public override void UpdatePhysicalMassProperties(float physMass) { - OMV.Vector3 localInertia = BulletSimAPI.CalculateLocalInertia2(BSShape.ptr, physMass); - BulletSimAPI.SetMassProps2(BSBody.ptr, physMass, localInertia); + OMV.Vector3 localInertia = BulletSimAPI.CalculateLocalInertia2(PhysShape.ptr, physMass); + BulletSimAPI.SetMassProps2(PhysBody.ptr, physMass, localInertia); } public override OMV.Vector3 Force { @@ -344,7 +344,7 @@ public sealed class BSCharacter : BSPhysObject PhysicsScene.TaintedObject("BSCharacter.SetForce", delegate() { DetailLog("{0},BSCharacter.setForce,taint,force={1}", LocalID, _force); - BulletSimAPI.SetObjectForce2(BSBody.ptr, _force); + BulletSimAPI.SetObjectForce2(PhysBody.ptr, _force); }); } } @@ -383,7 +383,7 @@ public sealed class BSCharacter : BSPhysObject if (_currentFriction != PhysicsScene.Params.avatarStandingFriction) { _currentFriction = PhysicsScene.Params.avatarStandingFriction; - BulletSimAPI.SetFriction2(BSBody.ptr, _currentFriction); + BulletSimAPI.SetFriction2(PhysBody.ptr, _currentFriction); } } else @@ -391,15 +391,15 @@ public sealed class BSCharacter : BSPhysObject if (_currentFriction != PhysicsScene.Params.avatarFriction) { _currentFriction = PhysicsScene.Params.avatarFriction; - BulletSimAPI.SetFriction2(BSBody.ptr, _currentFriction); + BulletSimAPI.SetFriction2(PhysBody.ptr, _currentFriction); } } _velocity = value; // Remember the set velocity so we can suppress the reduction by friction, ... _appliedVelocity = value; - BulletSimAPI.SetLinearVelocity2(BSBody.ptr, _velocity); - BulletSimAPI.Activate2(BSBody.ptr, true); + BulletSimAPI.SetLinearVelocity2(PhysBody.ptr, _velocity); + BulletSimAPI.Activate2(PhysBody.ptr, true); } } public override OMV.Vector3 Torque { @@ -424,7 +424,7 @@ public sealed class BSCharacter : BSPhysObject PhysicsScene.TaintedObject("BSCharacter.setOrientation", delegate() { // _position = BulletSimAPI.GetPosition2(BSBody.ptr); - BulletSimAPI.SetTranslation2(BSBody.ptr, _position, _orientation); + BulletSimAPI.SetTranslation2(PhysBody.ptr, _position, _orientation); }); } } @@ -433,13 +433,13 @@ public sealed class BSCharacter : BSPhysObject { get { - _orientation = BulletSimAPI.GetOrientation2(BSBody.ptr); + _orientation = BulletSimAPI.GetOrientation2(PhysBody.ptr); return _orientation; } set { _orientation = value; - BulletSimAPI.SetTranslation2(BSBody.ptr, _position, _orientation); + BulletSimAPI.SetTranslation2(PhysBody.ptr, _position, _orientation); } } public override int PhysicsActorType { @@ -498,9 +498,9 @@ public sealed class BSCharacter : BSPhysObject PhysicsScene.TaintedObject("BSCharacter.setFloatOnWater", delegate() { if (_floatOnWater) - CurrentCollisionFlags = BulletSimAPI.AddToCollisionFlags2(BSBody.ptr, CollisionFlags.BS_FLOATS_ON_WATER); + CurrentCollisionFlags = BulletSimAPI.AddToCollisionFlags2(PhysBody.ptr, CollisionFlags.BS_FLOATS_ON_WATER); else - CurrentCollisionFlags = BulletSimAPI.RemoveFromCollisionFlags2(BSBody.ptr, CollisionFlags.BS_FLOATS_ON_WATER); + CurrentCollisionFlags = BulletSimAPI.RemoveFromCollisionFlags2(PhysBody.ptr, CollisionFlags.BS_FLOATS_ON_WATER); }); } } @@ -533,7 +533,7 @@ public sealed class BSCharacter : BSPhysObject DetailLog("{0},BSCharacter.setForceBuoyancy,taint,buoy={1}", LocalID, _buoyancy); // Buoyancy is faked by changing the gravity applied to the object float grav = PhysicsScene.Params.gravity * (1f - _buoyancy); - BulletSimAPI.SetGravity2(BSBody.ptr, new OMV.Vector3(0f, 0f, grav)); + BulletSimAPI.SetGravity2(PhysBody.ptr, new OMV.Vector3(0f, 0f, grav)); } } @@ -579,7 +579,7 @@ public sealed class BSCharacter : BSPhysObject PhysicsScene.TaintedObject("BSCharacter.AddForce", delegate() { DetailLog("{0},BSCharacter.setAddForce,taint,addedForce={1}", LocalID, _force); - BulletSimAPI.SetObjectForce2(BSBody.ptr, _force); + BulletSimAPI.SetObjectForce2(PhysBody.ptr, _force); }); } else @@ -647,7 +647,7 @@ public sealed class BSCharacter : BSPhysObject // That's just the way they are defined. OMV.Vector3 avVel = new OMV.Vector3(_appliedVelocity.X, _appliedVelocity.Y, entprop.Velocity.Z); _velocity = avVel; - BulletSimAPI.SetLinearVelocity2(BSBody.ptr, avVel); + BulletSimAPI.SetLinearVelocity2(PhysBody.ptr, avVel); } // Tell the linkset about value changes diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index 5c61774..38609e3 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -514,8 +514,8 @@ namespace OpenSim.Region.Physics.BulletSPlugin if (IsActive) { // Friction effects are handled by this vehicle code - BulletSimAPI.SetFriction2(Prim.BSBody.ptr, 0f); - BulletSimAPI.SetHitFraction2(Prim.BSBody.ptr, 0f); + BulletSimAPI.SetFriction2(Prim.PhysBody.ptr, 0f); + BulletSimAPI.SetHitFraction2(Prim.PhysBody.ptr, 0f); } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index 6d84fcc..525ec28 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -194,13 +194,6 @@ public abstract class BSLinkset // Called while LinkActivity is locked. protected abstract void AddChildToLinkset(BSPhysObject child); - // Forcefully removing a child from a linkset. - // This is not being called by the child so we have to make sure the child doesn't think - // it's still connected to the linkset. - // Normal OpenSimulator operation will never do this because other SceneObjectPart information - // also has to be updated (like pointer to prim's parent). - protected abstract void RemoveChildFromOtherLinkset(BSPhysObject pchild); - // 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(BSPhysObject child); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs new file mode 100755 index 0000000..1c569b5 --- /dev/null +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs @@ -0,0 +1,173 @@ +/* + * 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 OMV = OpenMetaverse; + +namespace OpenSim.Region.Physics.BulletSPlugin +{ +public sealed class BSLinksetCompound : BSLinkset +{ + // private static string LogHeader = "[BULLETSIM LINKSET CONSTRAINTS]"; + + public BSLinksetCompound(BSScene scene, BSPhysObject parent) + { + base.Initialize(scene, parent); + } + + // When physical properties are changed the linkset needs to recalculate + // its internal properties. + // This is queued in the 'post taint' queue so the + // refresh will happen once after all the other taints are applied. + public override void Refresh(BSPhysObject requestor) + { + // Queue to happen after all the other taint processing + PhysicsScene.PostTaintObject("BSLinksetcompound.Refresh", requestor.LocalID, delegate() + { + if (HasAnyChildren && IsRoot(requestor)) + RecomputeLinksetCompound(); + }); + } + + // The object is going dynamic (physical). Do any setup necessary + // for a dynamic linkset. + // Only the state of the passed object can be modified. The rest of the linkset + // has not yet been fully constructed. + // Return 'true' if any properties updated on the passed object. + // Called at taint-time! + public override bool MakeDynamic(BSPhysObject child) + { + // 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. + // Return 'true' if any properties updated on the passed object. + // This doesn't normally happen -- OpenSim removes the objects from the physical + // world if it is a static linkset. + // Called at taint-time! + public override bool MakeStatic(BSPhysObject child) + { + // What is done for each object in BSPrim is what we want. + return false; + } + + // Called at taint-time!! + public override void UpdateProperties(BSPhysObject updated) + { + // Nothing to do for constraints on property updates + } + + // Routine called when rebuilding the body of some member of the linkset. + // Destroy all the constraints have have been made to root and set + // 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(BSPrim child) + { + bool ret = false; + + DetailLog("{0},BSLinksetcompound.RemoveBodyDependencies,removeChildrenForRoot,rID={1},rBody={2}", + child.LocalID, LinksetRoot.LocalID, LinksetRoot.PhysBody.ptr.ToString("X")); + + // Cause the current shape to be freed and the new one to be built. + Refresh(LinksetRoot); + + return ret; + } + + // Companion to RemoveBodyDependencies(). If RemoveBodyDependencies() returns 'true', + // this routine will restore the removed constraints. + // Called at taint-time!! + public override void RestoreBodyDependencies(BSPrim child) + { + // The Refresh operation queued by RemoveBodyDependencies() will build any missing constraints. + } + + // ================================================================ + + // Add a new child to the linkset. + // Called while LinkActivity is locked. + protected override void AddChildToLinkset(BSPhysObject child) + { + if (!HasChild(child)) + { + m_children.Add(child); + + DetailLog("{0},BSLinksetCompound.AddChildToLinkset,call,child={1}", LinksetRoot.LocalID, child.LocalID); + + // Cause constraints and assorted properties to be recomputed before the next simulation step. + Refresh(LinksetRoot); + } + return; + } + + // Remove the specified child from the linkset. + // Safe to call even if the child is not really in my linkset. + protected override void RemoveChildFromLinkset(BSPhysObject child) + { + if (m_children.Remove(child)) + { + DetailLog("{0},BSLinksetCompound.RemoveChildFromLinkset,call,rID={1},rBody={2},cID={3},cBody={4}", + child.LocalID, + LinksetRoot.LocalID, LinksetRoot.PhysBody.ptr.ToString("X"), + child.LocalID, child.PhysBody.ptr.ToString("X")); + + // See that the linkset parameters are recomputed at the end of the taint time. + Refresh(LinksetRoot); + } + else + { + // Non-fatal occurance. + // PhysicsScene.Logger.ErrorFormat("{0}: Asked to remove child from linkset that was not in linkset", LogHeader); + } + return; + } + + + // Call each of the constraints that make up this linkset and recompute the + // various transforms and variables. Create constraints of not created yet. + // Called before the simulation step to make sure the constraint based linkset + // is all initialized. + // Called at taint time!! + private void RecomputeLinksetCompound() + { + float linksetMass = LinksetMass; + LinksetRoot.UpdatePhysicalMassProperties(linksetMass); + + // DEBUG: see of inter-linkset collisions are causing problems + // BulletSimAPI.SetCollisionFilterMask2(LinksetRoot.BSBody.ptr, + // (uint)CollisionFilterGroups.LinksetFilter, (uint)CollisionFilterGroups.LinksetMask); + DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,set,rBody={1},linksetMass={2}", + LinksetRoot.LocalID, LinksetRoot.PhysBody.ptr.ToString("X"), linksetMass); + + + } +} +} \ No newline at end of file diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs index 8cdbd9b..65aed77 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs @@ -94,7 +94,7 @@ public sealed class BSLinksetConstraints : BSLinkset bool ret = false; DetailLog("{0},BSLinksetConstraint.RemoveBodyDependencies,removeChildrenForRoot,rID={1},rBody={2}", - child.LocalID, LinksetRoot.LocalID, LinksetRoot.BSBody.ptr.ToString("X")); + child.LocalID, LinksetRoot.LocalID, LinksetRoot.PhysBody.ptr.ToString("X")); lock (m_linksetActivityLock) { @@ -124,9 +124,6 @@ public sealed class BSLinksetConstraints : BSLinkset { m_children.Add(child); - BSPhysObject rootx = LinksetRoot; // capture the root as of now - BSPhysObject childx = child; - DetailLog("{0},BSLinksetConstraints.AddChildToLinkset,call,child={1}", LinksetRoot.LocalID, child.LocalID); // Cause constraints and assorted properties to be recomputed before the next simulation step. @@ -135,17 +132,6 @@ public sealed class BSLinksetConstraints : BSLinkset return; } - // Forcefully removing a child from a linkset. - // This is not being called by the child so we have to make sure the child doesn't think - // it's still connected to the linkset. - // Normal OpenSimulator operation will never do this because other SceneObjectPart information - // also has to be updated (like pointer to prim's parent). - protected override void RemoveChildFromOtherLinkset(BSPhysObject pchild) - { - pchild.Linkset = BSLinkset.Factory(PhysicsScene, pchild); - RemoveChildFromLinkset(pchild); - } - // Remove the specified child from the linkset. // Safe to call even if the child is not really in my linkset. protected override void RemoveChildFromLinkset(BSPhysObject child) @@ -157,8 +143,8 @@ public sealed class BSLinksetConstraints : BSLinkset DetailLog("{0},BSLinksetConstraints.RemoveChildFromLinkset,call,rID={1},rBody={2},cID={3},cBody={4}", childx.LocalID, - rootx.LocalID, rootx.BSBody.ptr.ToString("X"), - childx.LocalID, childx.BSBody.ptr.ToString("X")); + rootx.LocalID, rootx.PhysBody.ptr.ToString("X"), + childx.LocalID, childx.PhysBody.ptr.ToString("X")); PhysicsScene.TaintedObject("BSLinksetConstraints.RemoveChildFromLinkset", delegate() { @@ -197,15 +183,15 @@ public sealed class BSLinksetConstraints : BSLinkset DetailLog("{0},BSLinksetConstraint.BuildConstraint,taint,root={1},rBody={2},child={3},cBody={4},rLoc={5},cLoc={6},midLoc={7}", rootPrim.LocalID, - rootPrim.LocalID, rootPrim.BSBody.ptr.ToString("X"), - childPrim.LocalID, childPrim.BSBody.ptr.ToString("X"), + rootPrim.LocalID, rootPrim.PhysBody.ptr.ToString("X"), + childPrim.LocalID, childPrim.PhysBody.ptr.ToString("X"), 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( - PhysicsScene.World, rootPrim.BSBody, childPrim.BSBody, midPoint, true, true ); + 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. @@ -262,14 +248,14 @@ public sealed class BSLinksetConstraints : BSLinkset bool ret = false; DetailLog("{0},BSLinksetConstraint.PhysicallyUnlinkAChildFromRoot,taint,root={1},rBody={2},child={3},cBody={4}", rootPrim.LocalID, - rootPrim.LocalID, rootPrim.BSBody.ptr.ToString("X"), - childPrim.LocalID, childPrim.BSBody.ptr.ToString("X")); + rootPrim.LocalID, rootPrim.PhysBody.ptr.ToString("X"), + childPrim.LocalID, childPrim.PhysBody.ptr.ToString("X")); // Find the constraint for this link and get rid of it from the overall collection and from my list - if (PhysicsScene.Constraints.RemoveAndDestroyConstraint(rootPrim.BSBody, childPrim.BSBody)) + if (PhysicsScene.Constraints.RemoveAndDestroyConstraint(rootPrim.PhysBody, childPrim.PhysBody)) { // Make the child refresh its location - BulletSimAPI.PushUpdate2(childPrim.BSBody.ptr); + BulletSimAPI.PushUpdate2(childPrim.PhysBody.ptr); ret = true; } @@ -283,7 +269,7 @@ public sealed class BSLinksetConstraints : BSLinkset { DetailLog("{0},BSLinksetConstraint.PhysicallyUnlinkAllChildren,taint", rootPrim.LocalID); - return PhysicsScene.Constraints.RemoveAndDestroyConstraint(rootPrim.BSBody); + return PhysicsScene.Constraints.RemoveAndDestroyConstraint(rootPrim.PhysBody); } // Call each of the constraints that make up this linkset and recompute the @@ -300,7 +286,7 @@ public sealed class BSLinksetConstraints : BSLinkset // BulletSimAPI.SetCollisionFilterMask2(LinksetRoot.BSBody.ptr, // (uint)CollisionFilterGroups.LinksetFilter, (uint)CollisionFilterGroups.LinksetMask); DetailLog("{0},BSLinksetConstraint.RecomputeLinksetConstraints,set,rBody={1},linksetMass={2}", - LinksetRoot.LocalID, LinksetRoot.BSBody.ptr.ToString("X"), linksetMass); + LinksetRoot.LocalID, LinksetRoot.PhysBody.ptr.ToString("X"), linksetMass); foreach (BSPhysObject child in m_children) { @@ -310,7 +296,7 @@ public sealed class BSLinksetConstraints : BSLinkset child.UpdatePhysicalMassProperties(linksetMass); BSConstraint constrain; - if (!PhysicsScene.Constraints.TryGetConstraint(LinksetRoot.BSBody, child.BSBody, out constrain)) + if (!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 be8d64b..6220b21 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -68,9 +68,9 @@ public abstract class BSPhysObject : PhysicsActor public abstract void UpdatePhysicalMassProperties(float mass); // Reference to the physical body (btCollisionObject) of this object - public BulletBody BSBody; + public BulletBody PhysBody; // Reference to the physical shape (btCollisionShape) of this object - public BulletShape BSShape; + public BulletShape PhysShape; // 'true' if the mesh's underlying asset failed to build. // This will keep us from looping after the first time the build failed. @@ -206,7 +206,7 @@ public abstract class BSPhysObject : PhysicsActor PhysicsScene.TaintedObject(TypeName+".SubscribeEvents", delegate() { - CurrentCollisionFlags = BulletSimAPI.AddToCollisionFlags2(BSBody.ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); + CurrentCollisionFlags = BulletSimAPI.AddToCollisionFlags2(PhysBody.ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); }); } else @@ -220,7 +220,7 @@ public abstract class BSPhysObject : PhysicsActor SubscribedEventsMs = 0; PhysicsScene.TaintedObject(TypeName+".UnSubscribeEvents", delegate() { - CurrentCollisionFlags = BulletSimAPI.RemoveFromCollisionFlags2(BSBody.ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); + CurrentCollisionFlags = BulletSimAPI.RemoveFromCollisionFlags2(PhysBody.ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); }); } // Return 'true' if the simulator wants collision events diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 9ced61fa..8dd48ca 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -111,8 +111,8 @@ public sealed class BSPrim : BSPhysObject _mass = CalculateMass(); // No body or shape yet - BSBody = new BulletBody(LocalID, IntPtr.Zero); - BSShape = new BulletShape(IntPtr.Zero); + PhysBody = new BulletBody(LocalID, IntPtr.Zero); + PhysShape = new BulletShape(IntPtr.Zero); DetailLog("{0},BSPrim.constructor,call", LocalID); // do the actual object creation at taint time @@ -120,7 +120,7 @@ public sealed class BSPrim : BSPhysObject { CreateGeomAndObject(true); - CurrentCollisionFlags = BulletSimAPI.GetCollisionFlags2(BSBody.ptr); + CurrentCollisionFlags = BulletSimAPI.GetCollisionFlags2(PhysBody.ptr); }); } @@ -145,8 +145,8 @@ public sealed class BSPrim : BSPhysObject { DetailLog("{0},BSPrim.Destroy,taint,", LocalID); // If there are physical body and shape, release my use of same. - PhysicsScene.Shapes.DereferenceBody(BSBody, true, null); - PhysicsScene.Shapes.DereferenceShape(BSShape, true, null); + PhysicsScene.Shapes.DereferenceBody(PhysBody, true, null); + PhysicsScene.Shapes.DereferenceShape(PhysShape, true, null); }); } @@ -243,7 +243,7 @@ public sealed class BSPrim : BSPhysObject _rotationalVelocity = OMV.Vector3.Zero; // Zero some other properties in the physics engine - BulletSimAPI.ClearAllForces2(BSBody.ptr); + BulletSimAPI.ClearAllForces2(PhysBody.ptr); } public override void LockAngularMotion(OMV.Vector3 axis) @@ -256,7 +256,7 @@ public sealed class BSPrim : BSPhysObject get { if (!Linkset.IsRoot(this)) // child prims move around based on their parent. Need to get the latest location - _position = BulletSimAPI.GetPosition2(BSBody.ptr); + _position = BulletSimAPI.GetPosition2(PhysBody.ptr); // don't do the GetObjectPosition for root elements because this function is called a zillion times // _position = BulletSimAPI.GetObjectPosition2(PhysicsScene.World.ptr, BSBody.ptr); @@ -274,20 +274,20 @@ public sealed class BSPrim : BSPhysObject PhysicsScene.TaintedObject("BSPrim.setPosition", delegate() { // DetailLog("{0},BSPrim.SetPosition,taint,pos={1},orient={2}", LocalID, _position, _orientation); - BulletSimAPI.SetTranslation2(BSBody.ptr, _position, _orientation); + BulletSimAPI.SetTranslation2(PhysBody.ptr, _position, _orientation); ActivateIfPhysical(false); }); } } public override OMV.Vector3 ForcePosition { get { - _position = BulletSimAPI.GetPosition2(BSBody.ptr); + _position = BulletSimAPI.GetPosition2(PhysBody.ptr); return _position; } set { _position = value; PositionSanityCheck(); - BulletSimAPI.SetTranslation2(BSBody.ptr, _position, _orientation); + BulletSimAPI.SetTranslation2(PhysBody.ptr, _position, _orientation); ActivateIfPhysical(false); } } @@ -371,15 +371,15 @@ public sealed class BSPrim : BSPhysObject { if (IsStatic) { - BulletSimAPI.SetMassProps2(BSBody.ptr, 0f, OMV.Vector3.Zero); - BulletSimAPI.UpdateInertiaTensor2(BSBody.ptr); + BulletSimAPI.SetMassProps2(PhysBody.ptr, 0f, OMV.Vector3.Zero); + BulletSimAPI.UpdateInertiaTensor2(PhysBody.ptr); } else { - OMV.Vector3 localInertia = BulletSimAPI.CalculateLocalInertia2(BSShape.ptr, physMass); - BulletSimAPI.SetMassProps2(BSBody.ptr, physMass, localInertia); + OMV.Vector3 localInertia = BulletSimAPI.CalculateLocalInertia2(PhysShape.ptr, physMass); + BulletSimAPI.SetMassProps2(PhysBody.ptr, physMass, localInertia); // center of mass is at the zero of the object - BulletSimAPI.SetCenterOfMassByPosRot2(BSBody.ptr, ForcePosition, ForceOrientation); + BulletSimAPI.SetCenterOfMassByPosRot2(PhysBody.ptr, ForcePosition, ForceOrientation); // BulletSimAPI.UpdateInertiaTensor2(BSBody.ptr); DetailLog("{0},BSPrim.UpdateMassProperties,mass={1},localInertia={2}", LocalID, physMass, localInertia); } @@ -404,7 +404,7 @@ public sealed class BSPrim : BSPhysObject PhysicsScene.TaintedObject("BSPrim.setForce", delegate() { // DetailLog("{0},BSPrim.setForce,taint,force={1}", LocalID, _force); - BulletSimAPI.SetObjectForce2(BSBody.ptr, _force); + BulletSimAPI.SetObjectForce2(PhysBody.ptr, _force); }); } } @@ -498,7 +498,7 @@ public sealed class BSPrim : BSPhysObject PhysicsScene.TaintedObject("BSPrim.setVelocity", delegate() { // DetailLog("{0},BSPrim.SetVelocity,taint,vel={1}", LocalID, _velocity); - BulletSimAPI.SetLinearVelocity2(BSBody.ptr, _velocity); + BulletSimAPI.SetLinearVelocity2(PhysBody.ptr, _velocity); }); } } @@ -506,7 +506,7 @@ public sealed class BSPrim : BSPhysObject get { return _velocity; } set { _velocity = value; - BulletSimAPI.SetLinearVelocity2(BSBody.ptr, _velocity); + BulletSimAPI.SetLinearVelocity2(PhysBody.ptr, _velocity); } } public override OMV.Vector3 Torque { @@ -531,7 +531,7 @@ public sealed class BSPrim : BSPhysObject if (!Linkset.IsRoot(this)) { // Children move around because tied to parent. Get a fresh value. - _orientation = BulletSimAPI.GetOrientation2(BSBody.ptr); + _orientation = BulletSimAPI.GetOrientation2(PhysBody.ptr); } return _orientation; } @@ -544,7 +544,7 @@ public sealed class BSPrim : BSPhysObject { // _position = BulletSimAPI.GetObjectPosition2(PhysicsScene.World.ptr, BSBody.ptr); // DetailLog("{0},BSPrim.setOrientation,taint,pos={1},orient={2}", LocalID, _position, _orientation); - BulletSimAPI.SetTranslation2(BSBody.ptr, _position, _orientation); + BulletSimAPI.SetTranslation2(PhysBody.ptr, _position, _orientation); }); } } @@ -553,13 +553,13 @@ public sealed class BSPrim : BSPhysObject { get { - _orientation = BulletSimAPI.GetOrientation2(BSBody.ptr); + _orientation = BulletSimAPI.GetOrientation2(PhysBody.ptr); return _orientation; } set { _orientation = value; - BulletSimAPI.SetTranslation2(BSBody.ptr, _position, _orientation); + BulletSimAPI.SetTranslation2(PhysBody.ptr, _position, _orientation); } } public override int PhysicsActorType { @@ -615,7 +615,7 @@ public sealed 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). - BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.ptr, BSBody.ptr); + BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.ptr, PhysBody.ptr); // Set up the object physicalness (does gravity and collisions move this object) MakeDynamic(IsStatic); @@ -629,15 +629,15 @@ public sealed class BSPrim : BSPhysObject // Make solid or not (do things bounce off or pass through this object). MakeSolid(IsSolid); - BulletSimAPI.AddObjectToWorld2(PhysicsScene.World.ptr, BSBody.ptr); + BulletSimAPI.AddObjectToWorld2(PhysicsScene.World.ptr, PhysBody.ptr); // Rebuild its shape - BulletSimAPI.UpdateSingleAabb2(PhysicsScene.World.ptr, BSBody.ptr); + BulletSimAPI.UpdateSingleAabb2(PhysicsScene.World.ptr, PhysBody.ptr); // Collision filter can be set only when the object is in the world - if (BSBody.collisionFilter != 0 || BSBody.collisionMask != 0) + if (PhysBody.collisionFilter != 0 || PhysBody.collisionMask != 0) { - BulletSimAPI.SetCollisionFilterMask2(BSBody.ptr, (uint)BSBody.collisionFilter, (uint)BSBody.collisionMask); + BulletSimAPI.SetCollisionFilterMask2(PhysBody.ptr, (uint)PhysBody.collisionFilter, (uint)PhysBody.collisionMask); } // Recompute any linkset parameters. @@ -646,7 +646,7 @@ public sealed class BSPrim : BSPhysObject Linkset.Refresh(this); DetailLog("{0},BSPrim.UpdatePhysicalParameters,taintExit,static={1},solid={2},mass={3},collide={4},cf={5:X},body={6},shape={7}", - LocalID, IsStatic, IsSolid, _mass, SubscribedEvents(), CurrentCollisionFlags, BSBody, BSShape); + LocalID, IsStatic, IsSolid, _mass, SubscribedEvents(), CurrentCollisionFlags, PhysBody, PhysShape); } // "Making dynamic" means changing to and from static. @@ -659,44 +659,44 @@ public sealed class BSPrim : BSPhysObject if (makeStatic) { // Become a Bullet 'static' object type - CurrentCollisionFlags = BulletSimAPI.AddToCollisionFlags2(BSBody.ptr, CollisionFlags.CF_STATIC_OBJECT); + CurrentCollisionFlags = BulletSimAPI.AddToCollisionFlags2(PhysBody.ptr, CollisionFlags.CF_STATIC_OBJECT); // Stop all movement ZeroMotion(); // Center of mass is at the center of the object - BulletSimAPI.SetCenterOfMassByPosRot2(Linkset.LinksetRoot.BSBody.ptr, _position, _orientation); + BulletSimAPI.SetCenterOfMassByPosRot2(Linkset.LinksetRoot.PhysBody.ptr, _position, _orientation); // Mass is zero which disables a bunch of physics stuff in Bullet UpdatePhysicalMassProperties(0f); // Set collision detection parameters if (PhysicsScene.Params.ccdMotionThreshold > 0f) { - BulletSimAPI.SetCcdMotionThreshold2(BSBody.ptr, PhysicsScene.Params.ccdMotionThreshold); - BulletSimAPI.SetCcdSweptSphereRadius2(BSBody.ptr, PhysicsScene.Params.ccdSweptSphereRadius); + BulletSimAPI.SetCcdMotionThreshold2(PhysBody.ptr, PhysicsScene.Params.ccdMotionThreshold); + BulletSimAPI.SetCcdSweptSphereRadius2(PhysBody.ptr, PhysicsScene.Params.ccdSweptSphereRadius); } // There can be special things needed for implementing linksets Linkset.MakeStatic(this); // The activation state is 'disabled' so Bullet will not try to act on it. - BulletSimAPI.ForceActivationState2(BSBody.ptr, ActivationState.DISABLE_SIMULATION); + BulletSimAPI.ForceActivationState2(PhysBody.ptr, ActivationState.DISABLE_SIMULATION); // Start it out sleeping and physical actions could wake it up. // BulletSimAPI.ForceActivationState2(BSBody.ptr, ActivationState.ISLAND_SLEEPING); - BSBody.collisionFilter = CollisionFilterGroups.StaticObjectFilter; - BSBody.collisionMask = CollisionFilterGroups.StaticObjectMask; + PhysBody.collisionFilter = CollisionFilterGroups.StaticObjectFilter; + PhysBody.collisionMask = CollisionFilterGroups.StaticObjectMask; } else { // Not a Bullet static object - CurrentCollisionFlags = BulletSimAPI.RemoveFromCollisionFlags2(BSBody.ptr, CollisionFlags.CF_STATIC_OBJECT); + CurrentCollisionFlags = BulletSimAPI.RemoveFromCollisionFlags2(PhysBody.ptr, CollisionFlags.CF_STATIC_OBJECT); // Set various physical properties so internal dynamic properties will get computed correctly as they are set - BulletSimAPI.SetFriction2(BSBody.ptr, PhysicsScene.Params.defaultFriction); - BulletSimAPI.SetRestitution2(BSBody.ptr, PhysicsScene.Params.defaultRestitution); + BulletSimAPI.SetFriction2(PhysBody.ptr, PhysicsScene.Params.defaultFriction); + BulletSimAPI.SetRestitution2(PhysBody.ptr, PhysicsScene.Params.defaultRestitution); // per http://www.bulletphysics.org/Bullet/phpBB3/viewtopic.php?t=3382 // Since this can be called multiple times, only zero forces when becoming physical // BulletSimAPI.ClearAllForces2(BSBody.ptr); // For good measure, make sure the transform is set through to the motion state - BulletSimAPI.SetTranslation2(BSBody.ptr, _position, _orientation); + BulletSimAPI.SetTranslation2(PhysBody.ptr, _position, _orientation); // A dynamic object has mass UpdatePhysicalMassProperties(MassRaw); @@ -704,26 +704,26 @@ public sealed class BSPrim : BSPhysObject // Set collision detection parameters if (PhysicsScene.Params.ccdMotionThreshold > 0f) { - BulletSimAPI.SetCcdMotionThreshold2(BSBody.ptr, PhysicsScene.Params.ccdMotionThreshold); - BulletSimAPI.SetCcdSweptSphereRadius2(BSBody.ptr, PhysicsScene.Params.ccdSweptSphereRadius); + BulletSimAPI.SetCcdMotionThreshold2(PhysBody.ptr, PhysicsScene.Params.ccdMotionThreshold); + BulletSimAPI.SetCcdSweptSphereRadius2(PhysBody.ptr, PhysicsScene.Params.ccdSweptSphereRadius); } // Various values for simulation limits - BulletSimAPI.SetDamping2(BSBody.ptr, PhysicsScene.Params.linearDamping, PhysicsScene.Params.angularDamping); - BulletSimAPI.SetDeactivationTime2(BSBody.ptr, PhysicsScene.Params.deactivationTime); - BulletSimAPI.SetSleepingThresholds2(BSBody.ptr, PhysicsScene.Params.linearSleepingThreshold, PhysicsScene.Params.angularSleepingThreshold); - BulletSimAPI.SetContactProcessingThreshold2(BSBody.ptr, PhysicsScene.Params.contactProcessingThreshold); + BulletSimAPI.SetDamping2(PhysBody.ptr, PhysicsScene.Params.linearDamping, PhysicsScene.Params.angularDamping); + BulletSimAPI.SetDeactivationTime2(PhysBody.ptr, PhysicsScene.Params.deactivationTime); + BulletSimAPI.SetSleepingThresholds2(PhysBody.ptr, PhysicsScene.Params.linearSleepingThreshold, PhysicsScene.Params.angularSleepingThreshold); + BulletSimAPI.SetContactProcessingThreshold2(PhysBody.ptr, PhysicsScene.Params.contactProcessingThreshold); // There might be special things needed for implementing linksets. Linkset.MakeDynamic(this); // Force activation of the object so Bullet will act on it. // Must do the ForceActivationState2() to overcome the DISABLE_SIMULATION from static objects. - BulletSimAPI.ForceActivationState2(BSBody.ptr, ActivationState.ACTIVE_TAG); + BulletSimAPI.ForceActivationState2(PhysBody.ptr, ActivationState.ACTIVE_TAG); // BulletSimAPI.Activate2(BSBody.ptr, true); - BSBody.collisionFilter = CollisionFilterGroups.ObjectFilter; - BSBody.collisionMask = CollisionFilterGroups.ObjectMask; + PhysBody.collisionFilter = CollisionFilterGroups.ObjectFilter; + PhysBody.collisionMask = CollisionFilterGroups.ObjectMask; } } @@ -733,7 +733,7 @@ public sealed 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)BulletSimAPI.GetBodyType2(BSBody.ptr); + CollisionObjectTypes bodyType = (CollisionObjectTypes)BulletSimAPI.GetBodyType2(PhysBody.ptr); if (makeSolid) { // Verify the previous code created the correct shape for this type of thing. @@ -741,7 +741,7 @@ public sealed class BSPrim : BSPhysObject { m_log.ErrorFormat("{0} MakeSolid: physical body of wrong type for solidity. id={1}, type={2}", LogHeader, LocalID, bodyType); } - CurrentCollisionFlags = BulletSimAPI.RemoveFromCollisionFlags2(BSBody.ptr, CollisionFlags.CF_NO_CONTACT_RESPONSE); + CurrentCollisionFlags = BulletSimAPI.RemoveFromCollisionFlags2(PhysBody.ptr, CollisionFlags.CF_NO_CONTACT_RESPONSE); } else { @@ -749,9 +749,9 @@ public sealed class BSPrim : BSPhysObject { m_log.ErrorFormat("{0} MakeSolid: physical body of wrong type for non-solidness. id={1}, type={2}", LogHeader, LocalID, bodyType); } - CurrentCollisionFlags = BulletSimAPI.AddToCollisionFlags2(BSBody.ptr, CollisionFlags.CF_NO_CONTACT_RESPONSE); - BSBody.collisionFilter = CollisionFilterGroups.VolumeDetectFilter; - BSBody.collisionMask = CollisionFilterGroups.VolumeDetectMask; + CurrentCollisionFlags = BulletSimAPI.AddToCollisionFlags2(PhysBody.ptr, CollisionFlags.CF_NO_CONTACT_RESPONSE); + PhysBody.collisionFilter = CollisionFilterGroups.VolumeDetectFilter; + PhysBody.collisionMask = CollisionFilterGroups.VolumeDetectMask; } } @@ -761,7 +761,7 @@ public sealed class BSPrim : BSPhysObject private void ActivateIfPhysical(bool forceIt) { if (IsPhysical) - BulletSimAPI.Activate2(BSBody.ptr, forceIt); + BulletSimAPI.Activate2(PhysBody.ptr, forceIt); } // Turn on or off the flag controlling whether collision events are returned to the simulator. @@ -769,11 +769,11 @@ public sealed class BSPrim : BSPhysObject { if (wantsCollisionEvents) { - CurrentCollisionFlags = BulletSimAPI.AddToCollisionFlags2(BSBody.ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); + CurrentCollisionFlags = BulletSimAPI.AddToCollisionFlags2(PhysBody.ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); } else { - CurrentCollisionFlags = BulletSimAPI.RemoveFromCollisionFlags2(BSBody.ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); + CurrentCollisionFlags = BulletSimAPI.RemoveFromCollisionFlags2(PhysBody.ptr, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS); } } @@ -818,9 +818,9 @@ public sealed class BSPrim : BSPhysObject PhysicsScene.TaintedObject("BSPrim.setFloatOnWater", delegate() { if (_floatOnWater) - CurrentCollisionFlags = BulletSimAPI.AddToCollisionFlags2(BSBody.ptr, CollisionFlags.BS_FLOATS_ON_WATER); + CurrentCollisionFlags = BulletSimAPI.AddToCollisionFlags2(PhysBody.ptr, CollisionFlags.BS_FLOATS_ON_WATER); else - CurrentCollisionFlags = BulletSimAPI.RemoveFromCollisionFlags2(BSBody.ptr, CollisionFlags.BS_FLOATS_ON_WATER); + CurrentCollisionFlags = BulletSimAPI.RemoveFromCollisionFlags2(PhysBody.ptr, CollisionFlags.BS_FLOATS_ON_WATER); }); } } @@ -843,7 +843,7 @@ public sealed class BSPrim : BSPhysObject PhysicsScene.TaintedObject("BSPrim.setRotationalVelocity", delegate() { DetailLog("{0},BSPrim.SetRotationalVel,taint,rotvel={1}", LocalID, _rotationalVelocity); - BulletSimAPI.SetAngularVelocity2(BSBody.ptr, _rotationalVelocity); + BulletSimAPI.SetAngularVelocity2(PhysBody.ptr, _rotationalVelocity); }); } } @@ -853,7 +853,7 @@ public sealed class BSPrim : BSPhysObject } set { _rotationalVelocity = value; - BulletSimAPI.SetAngularVelocity2(BSBody.ptr, _rotationalVelocity); + BulletSimAPI.SetAngularVelocity2(PhysBody.ptr, _rotationalVelocity); } } public override bool Kinematic { @@ -879,7 +879,7 @@ public sealed class BSPrim : BSPhysObject // DetailLog("{0},BSPrim.setForceBuoyancy,taint,buoy={1}", LocalID, _buoyancy); // Buoyancy is faked by changing the gravity applied to the object float grav = PhysicsScene.Params.gravity * (1f - _buoyancy); - BulletSimAPI.SetGravity2(BSBody.ptr, new OMV.Vector3(0f, 0f, grav)); + BulletSimAPI.SetGravity2(PhysBody.ptr, new OMV.Vector3(0f, 0f, grav)); } } @@ -946,7 +946,7 @@ public sealed class BSPrim : BSPhysObject } DetailLog("{0},BSPrim.AddForce,taint,force={1}", LocalID, fSum); if (fSum != OMV.Vector3.Zero) - BulletSimAPI.ApplyCentralForce2(BSBody.ptr, fSum); + BulletSimAPI.ApplyCentralForce2(PhysBody.ptr, fSum); }; if (inTaintTime) addForceOperation(); @@ -986,7 +986,7 @@ public sealed class BSPrim : BSPhysObject DetailLog("{0},BSPrim.AddAngularForce,taint,aForce={1}", LocalID, fSum); if (fSum != OMV.Vector3.Zero) { - BulletSimAPI.ApplyTorque2(BSBody.ptr, fSum); + BulletSimAPI.ApplyTorque2(PhysBody.ptr, fSum); _torque = fSum; } }; @@ -1002,7 +1002,7 @@ public sealed class BSPrim : BSPhysObject BSScene.TaintCallback applyTorqueImpulseOperation = delegate() { DetailLog("{0},BSPrim.ApplyTorqueImpulse,taint,tImpulse={1}", LocalID, applyImpulse); - BulletSimAPI.ApplyTorqueImpulse2(BSBody.ptr, applyImpulse); + BulletSimAPI.ApplyTorqueImpulse2(PhysBody.ptr, applyImpulse); }; if (inTaintTime) applyTorqueImpulseOperation(); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index c27b5f0..cc5dbb2 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -1067,49 +1067,49 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters (s,cf,p,v) => { s.m_params[0].linearDamping = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].linearDamping; }, (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].linearDamping, p, l, v); }, - (s,o,v) => { BulletSimAPI.SetDamping2(o.BSBody.ptr, v, v); } ), + (s,o,v) => { BulletSimAPI.SetDamping2(o.PhysBody.ptr, v, v); } ), new ParameterDefn("AngularDamping", "Factor to damp angular movement per second (0.0 - 1.0)", 0f, (s,cf,p,v) => { s.m_params[0].angularDamping = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].angularDamping; }, (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].angularDamping, p, l, v); }, - (s,o,v) => { BulletSimAPI.SetDamping2(o.BSBody.ptr, v, v); } ), + (s,o,v) => { BulletSimAPI.SetDamping2(o.PhysBody.ptr, v, v); } ), new ParameterDefn("DeactivationTime", "Seconds before considering an object potentially static", 0.2f, (s,cf,p,v) => { s.m_params[0].deactivationTime = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].deactivationTime; }, (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].deactivationTime, p, l, v); }, - (s,o,v) => { BulletSimAPI.SetDeactivationTime2(o.BSBody.ptr, v); } ), + (s,o,v) => { BulletSimAPI.SetDeactivationTime2(o.PhysBody.ptr, v); } ), new ParameterDefn("LinearSleepingThreshold", "Seconds to measure linear movement before considering static", 0.8f, (s,cf,p,v) => { s.m_params[0].linearSleepingThreshold = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].linearSleepingThreshold; }, (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].linearSleepingThreshold, p, l, v); }, - (s,o,v) => { BulletSimAPI.SetSleepingThresholds2(o.BSBody.ptr, v, v); } ), + (s,o,v) => { BulletSimAPI.SetSleepingThresholds2(o.PhysBody.ptr, v, v); } ), new ParameterDefn("AngularSleepingThreshold", "Seconds to measure angular movement before considering static", 1.0f, (s,cf,p,v) => { s.m_params[0].angularSleepingThreshold = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].angularSleepingThreshold; }, (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].angularSleepingThreshold, p, l, v); }, - (s,o,v) => { BulletSimAPI.SetSleepingThresholds2(o.BSBody.ptr, v, v); } ), + (s,o,v) => { BulletSimAPI.SetSleepingThresholds2(o.PhysBody.ptr, v, v); } ), new ParameterDefn("CcdMotionThreshold", "Continuious collision detection threshold (0 means no CCD)" , 0f, // set to zero to disable (s,cf,p,v) => { s.m_params[0].ccdMotionThreshold = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].ccdMotionThreshold; }, (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].ccdMotionThreshold, p, l, v); }, - (s,o,v) => { BulletSimAPI.SetCcdMotionThreshold2(o.BSBody.ptr, v); } ), + (s,o,v) => { BulletSimAPI.SetCcdMotionThreshold2(o.PhysBody.ptr, v); } ), new ParameterDefn("CcdSweptSphereRadius", "Continuious collision detection test radius" , 0f, (s,cf,p,v) => { s.m_params[0].ccdSweptSphereRadius = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].ccdSweptSphereRadius; }, (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].ccdSweptSphereRadius, p, l, v); }, - (s,o,v) => { BulletSimAPI.SetCcdSweptSphereRadius2(o.BSBody.ptr, v); } ), + (s,o,v) => { BulletSimAPI.SetCcdSweptSphereRadius2(o.PhysBody.ptr, v); } ), new ParameterDefn("ContactProcessingThreshold", "Distance between contacts before doing collision check" , 0.1f, (s,cf,p,v) => { s.m_params[0].contactProcessingThreshold = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].contactProcessingThreshold; }, (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].contactProcessingThreshold, p, l, v); }, - (s,o,v) => { BulletSimAPI.SetContactProcessingThreshold2(o.BSBody.ptr, v); } ), + (s,o,v) => { BulletSimAPI.SetContactProcessingThreshold2(o.PhysBody.ptr, v); } ), new ParameterDefn("TerrainFriction", "Factor to reduce movement against terrain surface" , 0.5f, @@ -1428,8 +1428,8 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters { foreach (BSPrim prim in m_vehicles) { - BulletSimAPI.DumpRigidBody2(World.ptr, prim.BSBody.ptr); - BulletSimAPI.DumpCollisionShape2(World.ptr, prim.BSShape.ptr); + BulletSimAPI.DumpRigidBody2(World.ptr, prim.PhysBody.ptr); + BulletSimAPI.DumpCollisionShape2(World.ptr, prim.PhysShape.ptr); } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index 1219fc0..a38e650 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -106,11 +106,11 @@ public sealed class BSShapeCollection : IDisposable // rebuild the body around it. // Updates prim.BSBody with information/pointers to requested body bool newBody = CreateBody((newGeom || forceRebuild), prim, PhysicsScene.World, - prim.BSShape, shapeData, bodyCallback); + prim.PhysShape, shapeData, bodyCallback); ret = newGeom || newBody; } DetailLog("{0},BSShapeCollection.GetBodyAndShape,taintExit,force={1},ret={2},body={3},shape={4}", - prim.LocalID, forceRebuild, ret, prim.BSBody, prim.BSShape); + prim.LocalID, forceRebuild, ret, prim.PhysBody, prim.PhysShape); return ret; } @@ -337,7 +337,7 @@ public sealed class BSShapeCollection : IDisposable // an avatar capsule is close to a native shape (it is not shared) ret = GetReferenceToNativeShape(prim, shapeData, ShapeData.PhysicsShapeType.SHAPE_AVATAR, ShapeData.FixedShapeKey.KEY_CAPSULE, shapeCallback); - DetailLog("{0},BSShapeCollection.CreateGeom,avatarCapsule,shape={1}", prim.LocalID, prim.BSShape); + DetailLog("{0},BSShapeCollection.CreateGeom,avatarCapsule,shape={1}", prim.LocalID, prim.PhysShape); ret = true; haveShape = true; } @@ -360,13 +360,13 @@ public sealed class BSShapeCollection : IDisposable haveShape = true; if (forceRebuild || prim.Scale != shapeData.Size - || prim.BSShape.type != ShapeData.PhysicsShapeType.SHAPE_SPHERE + || prim.PhysShape.type != ShapeData.PhysicsShapeType.SHAPE_SPHERE ) { ret = GetReferenceToNativeShape(prim, shapeData, ShapeData.PhysicsShapeType.SHAPE_SPHERE, ShapeData.FixedShapeKey.KEY_SPHERE, shapeCallback); DetailLog("{0},BSShapeCollection.CreateGeom,sphere,force={1},shape={2}", - prim.LocalID, forceRebuild, prim.BSShape); + prim.LocalID, forceRebuild, prim.PhysShape); } } if (pbs.ProfileShape == ProfileShape.Square && pbs.PathCurve == (byte)Extrusion.Straight) @@ -374,13 +374,13 @@ public sealed class BSShapeCollection : IDisposable haveShape = true; if (forceRebuild || prim.Scale != shapeData.Size - || prim.BSShape.type != ShapeData.PhysicsShapeType.SHAPE_BOX + || prim.PhysShape.type != ShapeData.PhysicsShapeType.SHAPE_BOX ) { ret = GetReferenceToNativeShape( prim, shapeData, ShapeData.PhysicsShapeType.SHAPE_BOX, ShapeData.FixedShapeKey.KEY_BOX, shapeCallback); DetailLog("{0},BSShapeCollection.CreateGeom,box,force={1},shape={2}", - prim.LocalID, forceRebuild, prim.BSShape); + prim.LocalID, forceRebuild, prim.PhysShape); } } } @@ -394,13 +394,13 @@ public sealed class BSShapeCollection : IDisposable // Update prim.BSShape to reference a hull of this shape. ret = GetReferenceToHull(prim, shapeData, pbs, shapeCallback); DetailLog("{0},BSShapeCollection.CreateGeom,hull,shape={1},key={2}", - shapeData.ID, prim.BSShape, prim.BSShape.shapeKey.ToString("X")); + shapeData.ID, prim.PhysShape, prim.PhysShape.shapeKey.ToString("X")); } else { ret = GetReferenceToMesh(prim, shapeData, pbs, shapeCallback); DetailLog("{0},BSShapeCollection.CreateGeom,mesh,shape={1},key={2}", - shapeData.ID, prim.BSShape, prim.BSShape.shapeKey.ToString("X")); + shapeData.ID, prim.PhysShape, prim.PhysShape.shapeKey.ToString("X")); } } return ret; @@ -413,7 +413,7 @@ public sealed class BSShapeCollection : IDisposable ShapeDestructionCallback shapeCallback) { // release any previous shape - DereferenceShape(prim.BSShape, true, shapeCallback); + DereferenceShape(prim.PhysShape, true, shapeCallback); shapeData.Type = shapeType; // Bullet native objects are scaled by the Bullet engine so pass the size in @@ -426,7 +426,7 @@ public sealed class BSShapeCollection : IDisposable DetailLog("{0},BSShapeCollection.AddNativeShapeToPrim,create,newshape={1},scale={2}", shapeData.ID, newShape, shapeData.Scale); - prim.BSShape = newShape; + prim.PhysShape = newShape; return true; } @@ -475,14 +475,14 @@ public sealed class BSShapeCollection : IDisposable System.UInt64 newMeshKey = ComputeShapeKey(shapeData, pbs, out lod); // if this new shape is the same as last time, don't recreate the mesh - if (newMeshKey == prim.BSShape.shapeKey && prim.BSShape.type == ShapeData.PhysicsShapeType.SHAPE_MESH) + if (newMeshKey == prim.PhysShape.shapeKey && prim.PhysShape.type == ShapeData.PhysicsShapeType.SHAPE_MESH) return false; DetailLog("{0},BSShapeCollection.CreateGeomMesh,create,oldKey={1},newKey={2}", - prim.LocalID, prim.BSShape.shapeKey.ToString("X"), newMeshKey.ToString("X")); + prim.LocalID, prim.PhysShape.shapeKey.ToString("X"), newMeshKey.ToString("X")); // Since we're recreating new, get rid of the reference to the previous shape - DereferenceShape(prim.BSShape, true, shapeCallback); + DereferenceShape(prim.PhysShape, true, shapeCallback); newShape = CreatePhysicalMesh(prim.PhysObjectName, newMeshKey, pbs, shapeData.Size, lod); // Take evasive action if the mesh was not constructed. @@ -492,7 +492,7 @@ public sealed class BSShapeCollection : IDisposable // meshes are already scaled by the meshmerizer prim.Scale = new OMV.Vector3(1f, 1f, 1f); - prim.BSShape = newShape; + prim.PhysShape = newShape; return true; // 'true' means a new shape has been added to this prim } @@ -550,14 +550,14 @@ public sealed class BSShapeCollection : IDisposable System.UInt64 newHullKey = ComputeShapeKey(shapeData, pbs, out lod); // if the hull hasn't changed, don't rebuild it - if (newHullKey == prim.BSShape.shapeKey && prim.BSShape.type == ShapeData.PhysicsShapeType.SHAPE_HULL) + if (newHullKey == prim.PhysShape.shapeKey && prim.PhysShape.type == ShapeData.PhysicsShapeType.SHAPE_HULL) return false; DetailLog("{0},BSShapeCollection.CreateGeomHull,create,oldKey={1},newKey={2}", - prim.LocalID, prim.BSShape.shapeKey.ToString("X"), newHullKey.ToString("X")); + prim.LocalID, prim.PhysShape.shapeKey.ToString("X"), newHullKey.ToString("X")); // Remove usage of the previous shape. - DereferenceShape(prim.BSShape, true, shapeCallback); + DereferenceShape(prim.PhysShape, true, shapeCallback); newShape = CreatePhysicalHull(prim.PhysObjectName, newHullKey, pbs, shapeData.Size, lod); newShape = VerifyMeshCreated(newShape, prim, shapeData, pbs); @@ -566,7 +566,7 @@ public sealed class BSShapeCollection : IDisposable // hulls are already scaled by the meshmerizer prim.Scale = new OMV.Vector3(1f, 1f, 1f); - prim.BSShape = newShape; + prim.PhysShape = newShape; return true; // 'true' means a new shape has been added to this prim } @@ -778,13 +778,13 @@ public sealed class BSShapeCollection : IDisposable bool ret = false; // the mesh, hull or native shape must have already been created in Bullet - bool mustRebuild = (prim.BSBody.ptr == IntPtr.Zero); + bool mustRebuild = (prim.PhysBody.ptr == IntPtr.Zero); // If there is an existing body, verify it's of an acceptable type. // If not a solid object, body is a GhostObject. Otherwise a RigidBody. if (!mustRebuild) { - CollisionObjectTypes bodyType = (CollisionObjectTypes)BulletSimAPI.GetBodyType2(prim.BSBody.ptr); + CollisionObjectTypes bodyType = (CollisionObjectTypes)BulletSimAPI.GetBodyType2(prim.PhysBody.ptr); if (prim.IsSolid && bodyType != CollisionObjectTypes.CO_RIGID_BODY || !prim.IsSolid && bodyType != CollisionObjectTypes.CO_GHOST_OBJECT) { @@ -796,7 +796,7 @@ public sealed class BSShapeCollection : IDisposable if (mustRebuild || forceRebuild) { // Free any old body - DereferenceBody(prim.BSBody, true, bodyCallback); + DereferenceBody(prim.PhysBody, true, bodyCallback); BulletBody aBody; IntPtr bodyPtr = IntPtr.Zero; @@ -816,7 +816,7 @@ public sealed class BSShapeCollection : IDisposable ReferenceBody(aBody, true); - prim.BSBody = aBody; + prim.PhysBody = aBody; ret = true; } -- cgit v1.1 From 39c02dcc8c537d5989238ec97c876e033895a8a9 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Thu, 1 Nov 2012 10:23:37 -0700 Subject: BulletSim: Remove use of shapeData in ShapeCollection and rely on the available BSPhysObject varaiables. Fix line endings in BSLinksetCompound. --- .../Region/Physics/BulletSPlugin/BSCharacter.cs | 19 +- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 5 + .../Physics/BulletSPlugin/BSLinksetCompound.cs | 347 +++++++++++---------- .../Region/Physics/BulletSPlugin/BSPhysObject.cs | 4 + OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 30 +- .../Physics/BulletSPlugin/BSShapeCollection.cs | 116 +++---- .../Region/Physics/BulletSPlugin/BulletSimAPI.cs | 1 + 7 files changed, 256 insertions(+), 266 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index 8c7061d..2a634b9 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -99,26 +99,12 @@ public sealed class BSCharacter : BSPhysObject DetailLog("{0},BSCharacter.create,call,size={1},scale={2},density={3},volume={4},mass={5}", LocalID, _size, Scale, _avatarDensity, _avatarVolume, MassRaw); - ShapeData shapeData = new ShapeData(); - shapeData.ID = LocalID; - shapeData.Type = ShapeData.PhysicsShapeType.SHAPE_AVATAR; - shapeData.Position = _position; - shapeData.Rotation = _orientation; - shapeData.Velocity = _velocity; - shapeData.Size = Scale; // capsule is a native shape but scale is not just <1,1,1> - shapeData.Scale = Scale; - shapeData.Mass = _mass; - shapeData.Buoyancy = _buoyancy; - shapeData.Static = ShapeData.numericFalse; - shapeData.Friction = PhysicsScene.Params.avatarStandingFriction; - shapeData.Restitution = PhysicsScene.Params.avatarRestitution; - // do actual create at taint time PhysicsScene.TaintedObject("BSCharacter.create", delegate() { DetailLog("{0},BSCharacter.create,taint", LocalID); // New body and shape into BSBody and BSShape - PhysicsScene.Shapes.GetBodyAndShape(true, PhysicsScene.World, this, shapeData, null, null, null); + PhysicsScene.Shapes.GetBodyAndShape(true, PhysicsScene.World, this, null, null); SetPhysicalProperties(); }); @@ -212,6 +198,9 @@ public sealed class BSCharacter : BSPhysObject { set { BaseShape = value; } } + // I want the physics engine to make an avatar capsule + public override ShapeData.PhysicsShapeType PreferredPhysicalShape + { get { return ShapeData.PhysicsShapeType.SHAPE_AVATAR; } } public override bool Grabbed { set { _grabbed = value; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index 525ec28..f56851f 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -68,6 +68,11 @@ 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. + public virtual ShapeData.PhysicsShapeType PreferredPhysicalShape + { get { return ShapeData.PhysicsShapeType.SHAPE_UNKNOWN; } } + // We keep the prim's mass in the linkset structure since it could be dependent on other prims protected float m_mass; public float LinksetMass diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs index 1c569b5..638fae1 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs @@ -1,173 +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.Text; - -using OMV = OpenMetaverse; - -namespace OpenSim.Region.Physics.BulletSPlugin -{ -public sealed class BSLinksetCompound : BSLinkset -{ - // private static string LogHeader = "[BULLETSIM LINKSET CONSTRAINTS]"; - - public BSLinksetCompound(BSScene scene, BSPhysObject parent) - { - base.Initialize(scene, parent); - } - - // When physical properties are changed the linkset needs to recalculate - // its internal properties. - // This is queued in the 'post taint' queue so the - // refresh will happen once after all the other taints are applied. - public override void Refresh(BSPhysObject requestor) - { - // Queue to happen after all the other taint processing - PhysicsScene.PostTaintObject("BSLinksetcompound.Refresh", requestor.LocalID, delegate() - { - if (HasAnyChildren && IsRoot(requestor)) - RecomputeLinksetCompound(); - }); - } - - // The object is going dynamic (physical). Do any setup necessary - // for a dynamic linkset. - // Only the state of the passed object can be modified. The rest of the linkset - // has not yet been fully constructed. - // Return 'true' if any properties updated on the passed object. - // Called at taint-time! - public override bool MakeDynamic(BSPhysObject child) - { - // 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. - // Return 'true' if any properties updated on the passed object. - // This doesn't normally happen -- OpenSim removes the objects from the physical - // world if it is a static linkset. - // Called at taint-time! - public override bool MakeStatic(BSPhysObject child) - { - // What is done for each object in BSPrim is what we want. - return false; - } - - // Called at taint-time!! - public override void UpdateProperties(BSPhysObject updated) - { - // Nothing to do for constraints on property updates - } - - // Routine called when rebuilding the body of some member of the linkset. - // Destroy all the constraints have have been made to root and set - // 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(BSPrim child) - { - bool ret = false; - - DetailLog("{0},BSLinksetcompound.RemoveBodyDependencies,removeChildrenForRoot,rID={1},rBody={2}", - child.LocalID, LinksetRoot.LocalID, LinksetRoot.PhysBody.ptr.ToString("X")); - - // Cause the current shape to be freed and the new one to be built. - Refresh(LinksetRoot); - - return ret; - } - - // Companion to RemoveBodyDependencies(). If RemoveBodyDependencies() returns 'true', - // this routine will restore the removed constraints. - // Called at taint-time!! - public override void RestoreBodyDependencies(BSPrim child) - { - // The Refresh operation queued by RemoveBodyDependencies() will build any missing constraints. - } - - // ================================================================ - - // Add a new child to the linkset. - // Called while LinkActivity is locked. - protected override void AddChildToLinkset(BSPhysObject child) - { - if (!HasChild(child)) - { - m_children.Add(child); - - DetailLog("{0},BSLinksetCompound.AddChildToLinkset,call,child={1}", LinksetRoot.LocalID, child.LocalID); - - // Cause constraints and assorted properties to be recomputed before the next simulation step. - Refresh(LinksetRoot); - } - return; - } - - // Remove the specified child from the linkset. - // Safe to call even if the child is not really in my linkset. - protected override void RemoveChildFromLinkset(BSPhysObject child) - { - if (m_children.Remove(child)) - { - DetailLog("{0},BSLinksetCompound.RemoveChildFromLinkset,call,rID={1},rBody={2},cID={3},cBody={4}", - child.LocalID, - LinksetRoot.LocalID, LinksetRoot.PhysBody.ptr.ToString("X"), - child.LocalID, child.PhysBody.ptr.ToString("X")); - - // See that the linkset parameters are recomputed at the end of the taint time. - Refresh(LinksetRoot); - } - else - { - // Non-fatal occurance. - // PhysicsScene.Logger.ErrorFormat("{0}: Asked to remove child from linkset that was not in linkset", LogHeader); - } - return; - } - - - // Call each of the constraints that make up this linkset and recompute the - // various transforms and variables. Create constraints of not created yet. - // Called before the simulation step to make sure the constraint based linkset - // is all initialized. - // Called at taint time!! - private void RecomputeLinksetCompound() - { - float linksetMass = LinksetMass; - LinksetRoot.UpdatePhysicalMassProperties(linksetMass); - - // DEBUG: see of inter-linkset collisions are causing problems - // BulletSimAPI.SetCollisionFilterMask2(LinksetRoot.BSBody.ptr, - // (uint)CollisionFilterGroups.LinksetFilter, (uint)CollisionFilterGroups.LinksetMask); - DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,set,rBody={1},linksetMass={2}", - LinksetRoot.LocalID, LinksetRoot.PhysBody.ptr.ToString("X"), linksetMass); - - - } -} +/* + * 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 OMV = OpenMetaverse; + +namespace OpenSim.Region.Physics.BulletSPlugin +{ +public sealed class BSLinksetCompound : BSLinkset +{ + // private static string LogHeader = "[BULLETSIM LINKSET CONSTRAINTS]"; + + public BSLinksetCompound(BSScene scene, BSPhysObject parent) + { + base.Initialize(scene, parent); + } + + // When physical properties are changed the linkset needs to recalculate + // its internal properties. + // This is queued in the 'post taint' queue so the + // refresh will happen once after all the other taints are applied. + public override void Refresh(BSPhysObject requestor) + { + // Queue to happen after all the other taint processing + PhysicsScene.PostTaintObject("BSLinksetcompound.Refresh", requestor.LocalID, delegate() + { + if (HasAnyChildren && IsRoot(requestor)) + RecomputeLinksetCompound(); + }); + } + + // The object is going dynamic (physical). Do any setup necessary + // for a dynamic linkset. + // Only the state of the passed object can be modified. The rest of the linkset + // has not yet been fully constructed. + // Return 'true' if any properties updated on the passed object. + // Called at taint-time! + public override bool MakeDynamic(BSPhysObject child) + { + // 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. + // Return 'true' if any properties updated on the passed object. + // This doesn't normally happen -- OpenSim removes the objects from the physical + // world if it is a static linkset. + // Called at taint-time! + public override bool MakeStatic(BSPhysObject child) + { + // What is done for each object in BSPrim is what we want. + return false; + } + + // Called at taint-time!! + public override void UpdateProperties(BSPhysObject updated) + { + // Nothing to do for constraints on property updates + } + + // Routine called when rebuilding the body of some member of the linkset. + // Destroy all the constraints have have been made to root and set + // 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(BSPrim child) + { + bool ret = false; + + DetailLog("{0},BSLinksetcompound.RemoveBodyDependencies,removeChildrenForRoot,rID={1},rBody={2}", + child.LocalID, LinksetRoot.LocalID, LinksetRoot.PhysBody.ptr.ToString("X")); + + // Cause the current shape to be freed and the new one to be built. + Refresh(LinksetRoot); + + return ret; + } + + // Companion to RemoveBodyDependencies(). If RemoveBodyDependencies() returns 'true', + // this routine will restore the removed constraints. + // Called at taint-time!! + public override void RestoreBodyDependencies(BSPrim child) + { + // The Refresh operation queued by RemoveBodyDependencies() will build any missing constraints. + } + + // ================================================================ + + // Add a new child to the linkset. + // Called while LinkActivity is locked. + protected override void AddChildToLinkset(BSPhysObject child) + { + if (!HasChild(child)) + { + m_children.Add(child); + + DetailLog("{0},BSLinksetCompound.AddChildToLinkset,call,child={1}", LinksetRoot.LocalID, child.LocalID); + + // Cause constraints and assorted properties to be recomputed before the next simulation step. + Refresh(LinksetRoot); + } + return; + } + + // Remove the specified child from the linkset. + // Safe to call even if the child is not really in my linkset. + protected override void RemoveChildFromLinkset(BSPhysObject child) + { + if (m_children.Remove(child)) + { + DetailLog("{0},BSLinksetCompound.RemoveChildFromLinkset,call,rID={1},rBody={2},cID={3},cBody={4}", + child.LocalID, + LinksetRoot.LocalID, LinksetRoot.PhysBody.ptr.ToString("X"), + child.LocalID, child.PhysBody.ptr.ToString("X")); + + // See that the linkset parameters are recomputed at the end of the taint time. + Refresh(LinksetRoot); + } + else + { + // Non-fatal occurance. + // PhysicsScene.Logger.ErrorFormat("{0}: Asked to remove child from linkset that was not in linkset", LogHeader); + } + return; + } + + + // Call each of the constraints that make up this linkset and recompute the + // various transforms and variables. Create constraints of not created yet. + // Called before the simulation step to make sure the constraint based linkset + // is all initialized. + // Called at taint time!! + private void RecomputeLinksetCompound() + { + // Release the existing shape + PhysicsScene.Shapes.DereferenceShape(LinksetRoot.PhysShape, true, null); + + float linksetMass = LinksetMass; + LinksetRoot.UpdatePhysicalMassProperties(linksetMass); + + // DEBUG: see of inter-linkset collisions are causing problems + // BulletSimAPI.SetCollisionFilterMask2(LinksetRoot.BSBody.ptr, + // (uint)CollisionFilterGroups.LinksetFilter, (uint)CollisionFilterGroups.LinksetMask); + DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,set,rBody={1},linksetMass={2}", + LinksetRoot.LocalID, LinksetRoot.PhysBody.ptr.ToString("X"), linksetMass); + + + } +} } \ No newline at end of file diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index 6220b21..7d91468 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -78,6 +78,10 @@ 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 ShapeData.PhysicsShapeType PreferredPhysicalShape + { get { return ShapeData.PhysicsShapeType.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 diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 8dd48ca..8ce960d 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -171,6 +171,10 @@ public sealed class BSPrim : BSPhysObject ForceBodyShapeRebuild(false); } } + // Whatever the linkset wants is what I want. + public override ShapeData.PhysicsShapeType PreferredPhysicalShape + { get { return Linkset.PreferredPhysicalShape; } } + public override bool ForceBodyShapeRebuild(bool inTaintTime) { LastAssetBuildFailed = false; @@ -1310,34 +1314,11 @@ public sealed class BSPrim : BSPhysObject }// end CalculateMass #endregion Mass Calculation - // Copy prim's info into the BulletSim shape description structure - public void FillShapeInfo(out ShapeData shape) - { - shape.ID = LocalID; - shape.Type = ShapeData.PhysicsShapeType.SHAPE_UNKNOWN; - shape.Position = _position; - shape.Rotation = _orientation; - shape.Velocity = _velocity; - shape.Size = _size; - shape.Scale = Scale; - shape.Mass = _isPhysical ? _mass : 0f; - shape.Buoyancy = _buoyancy; - shape.HullKey = 0; - shape.MeshKey = 0; - shape.Friction = _friction; - shape.Restitution = _restitution; - shape.Collidable = (!IsPhantom) ? ShapeData.numericTrue : ShapeData.numericFalse; - shape.Static = _isPhysical ? ShapeData.numericFalse : ShapeData.numericTrue; - shape.Solid = IsSolid ? ShapeData.numericFalse : ShapeData.numericTrue; - } // Rebuild the geometry and object. // This is called when the shape changes so we need to recreate the mesh/hull. // Called at taint-time!!! private void CreateGeomAndObject(bool forceRebuild) { - ShapeData shapeData; - FillShapeInfo(out shapeData); - // If this prim is part of a linkset, we must remove and restore the physical // links if the body is rebuilt. bool needToRestoreLinkset = false; @@ -1346,8 +1327,7 @@ public sealed class BSPrim : BSPhysObject // Updates BSBody and BSShape with the new information. // Ignore 'forceRebuild'. This routine makes the right choices and changes of necessary. // Returns 'true' if either the body or the shape was changed. - PhysicsScene.Shapes.GetBodyAndShape(false, PhysicsScene.World, this, shapeData, BaseShape, - null, delegate(BulletBody dBody) + PhysicsScene.Shapes.GetBodyAndShape(false, PhysicsScene.World, this, null, delegate(BulletBody dBody) { // 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/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index a38e650..478924a 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -90,7 +90,6 @@ public sealed class BSShapeCollection : IDisposable // remove the physical constraints before the body is destroyed. // Called at taint-time!! public bool GetBodyAndShape(bool forceRebuild, BulletSim sim, BSPhysObject prim, - ShapeData shapeData, PrimitiveBaseShape pbs, ShapeDestructionCallback shapeCallback, BodyDestructionCallback bodyCallback) { bool ret = false; @@ -101,12 +100,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. // CreateGeom returns 'true' of BSShape as changed to a new shape. - bool newGeom = CreateGeom(forceRebuild, prim, shapeData, pbs, shapeCallback); + bool newGeom = CreateGeom(forceRebuild, prim, shapeCallback); // 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 bool newBody = CreateBody((newGeom || forceRebuild), prim, PhysicsScene.World, - prim.PhysShape, shapeData, bodyCallback); + prim.PhysShape, bodyCallback); ret = newGeom || newBody; } DetailLog("{0},BSShapeCollection.GetBodyAndShape,taintExit,force={1},ret={2},body={3},shape={4}", @@ -261,6 +260,9 @@ public sealed class BSShapeCollection : IDisposable case ShapeData.PhysicsShapeType.SHAPE_MESH: DereferenceMesh(shape, shapeCallback); break; + case ShapeData.PhysicsShapeType.SHAPE_COMPOUND: + DereferenceCompound(shape, shapeCallback); + break; case ShapeData.PhysicsShapeType.SHAPE_UNKNOWN: break; default: @@ -317,6 +319,13 @@ public sealed class BSShapeCollection : IDisposable } } + // Remove a reference to a compound shape. + // Called at taint-time. + private void DereferenceCompound(BulletShape shape, ShapeDestructionCallback shapeCallback) + { + // Compound shape is made of a bunch of meshes and natives. + } + // Create the geometry information in Bullet for later use. // The objects needs a hull if it's physical otherwise a mesh is enough. // if 'forceRebuild' is true, the geometry is unconditionally rebuilt. For meshes and hulls, @@ -325,17 +334,17 @@ 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, ShapeData shapeData, - PrimitiveBaseShape pbs, ShapeDestructionCallback shapeCallback) + private bool CreateGeom(bool forceRebuild, BSPhysObject prim, ShapeDestructionCallback shapeCallback) { bool ret = false; bool haveShape = false; bool nativeShapePossible = true; + PrimitiveBaseShape pbs = prim.BaseShape; - if (shapeData.Type == ShapeData.PhysicsShapeType.SHAPE_AVATAR) + if (prim.PreferredPhysicalShape == ShapeData.PhysicsShapeType.SHAPE_AVATAR) { // an avatar capsule is close to a native shape (it is not shared) - ret = GetReferenceToNativeShape(prim, shapeData, ShapeData.PhysicsShapeType.SHAPE_AVATAR, + ret = GetReferenceToNativeShape(prim, ShapeData.PhysicsShapeType.SHAPE_AVATAR, ShapeData.FixedShapeKey.KEY_CAPSULE, shapeCallback); DetailLog("{0},BSShapeCollection.CreateGeom,avatarCapsule,shape={1}", prim.LocalID, prim.PhysShape); ret = true; @@ -359,11 +368,11 @@ public sealed class BSShapeCollection : IDisposable { haveShape = true; if (forceRebuild - || prim.Scale != shapeData.Size + || prim.Scale != prim.Size || prim.PhysShape.type != ShapeData.PhysicsShapeType.SHAPE_SPHERE ) { - ret = GetReferenceToNativeShape(prim, shapeData, ShapeData.PhysicsShapeType.SHAPE_SPHERE, + ret = GetReferenceToNativeShape(prim, ShapeData.PhysicsShapeType.SHAPE_SPHERE, ShapeData.FixedShapeKey.KEY_SPHERE, shapeCallback); DetailLog("{0},BSShapeCollection.CreateGeom,sphere,force={1},shape={2}", prim.LocalID, forceRebuild, prim.PhysShape); @@ -373,11 +382,11 @@ public sealed class BSShapeCollection : IDisposable { haveShape = true; if (forceRebuild - || prim.Scale != shapeData.Size + || prim.Scale != prim.Size || prim.PhysShape.type != ShapeData.PhysicsShapeType.SHAPE_BOX ) { - ret = GetReferenceToNativeShape( prim, shapeData, ShapeData.PhysicsShapeType.SHAPE_BOX, + ret = GetReferenceToNativeShape( prim, ShapeData.PhysicsShapeType.SHAPE_BOX, ShapeData.FixedShapeKey.KEY_BOX, shapeCallback); DetailLog("{0},BSShapeCollection.CreateGeom,box,force={1},shape={2}", prim.LocalID, forceRebuild, prim.PhysShape); @@ -392,15 +401,15 @@ public sealed class BSShapeCollection : IDisposable if (prim.IsPhysical && PhysicsScene.ShouldUseHullsForPhysicalObjects) { // Update prim.BSShape to reference a hull of this shape. - ret = GetReferenceToHull(prim, shapeData, pbs, shapeCallback); + ret = GetReferenceToHull(prim,shapeCallback); DetailLog("{0},BSShapeCollection.CreateGeom,hull,shape={1},key={2}", - shapeData.ID, prim.PhysShape, prim.PhysShape.shapeKey.ToString("X")); + prim.LocalID, prim.PhysShape, prim.PhysShape.shapeKey.ToString("X")); } else { - ret = GetReferenceToMesh(prim, shapeData, pbs, shapeCallback); + ret = GetReferenceToMesh(prim, shapeCallback); DetailLog("{0},BSShapeCollection.CreateGeom,mesh,shape={1},key={2}", - shapeData.ID, prim.PhysShape, prim.PhysShape.shapeKey.ToString("X")); + prim.LocalID, prim.PhysShape, prim.PhysShape.shapeKey.ToString("X")); } } return ret; @@ -408,44 +417,45 @@ public sealed class BSShapeCollection : IDisposable // 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, ShapeData shapeData, + private bool GetReferenceToNativeShape(BSPhysObject prim, ShapeData.PhysicsShapeType shapeType, ShapeData.FixedShapeKey shapeKey, ShapeDestructionCallback shapeCallback) { // release any previous shape DereferenceShape(prim.PhysShape, true, shapeCallback); - shapeData.Type = shapeType; // Bullet native objects are scaled by the Bullet engine so pass the size in - prim.Scale = shapeData.Size; - shapeData.Scale = shapeData.Size; + prim.Scale = prim.Size; - BulletShape newShape = BuildPhysicalNativeShape(shapeType, shapeData, shapeKey); + BulletShape newShape = BuildPhysicalNativeShape(prim, shapeType, shapeKey); // Don't need to do a 'ReferenceShape()' here because native shapes are not shared. DetailLog("{0},BSShapeCollection.AddNativeShapeToPrim,create,newshape={1},scale={2}", - shapeData.ID, newShape, shapeData.Scale); + prim.LocalID, newShape, prim.Scale); prim.PhysShape = newShape; return true; } - private BulletShape BuildPhysicalNativeShape(ShapeData.PhysicsShapeType shapeType, - ShapeData shapeData, ShapeData.FixedShapeKey shapeKey) + private BulletShape BuildPhysicalNativeShape(BSPhysObject prim, ShapeData.PhysicsShapeType shapeType, + ShapeData.FixedShapeKey shapeKey) { BulletShape newShape; // Need to make sure the passed shape information is for the native type. - ShapeData nativeShapeData = shapeData; + ShapeData nativeShapeData = new ShapeData(); nativeShapeData.Type = shapeType; + nativeShapeData.ID = prim.LocalID; + nativeShapeData.Scale = prim.Scale; + nativeShapeData.Size = prim.Scale; nativeShapeData.MeshKey = (ulong)shapeKey; nativeShapeData.HullKey = (ulong)shapeKey; if (shapeType == ShapeData.PhysicsShapeType.SHAPE_AVATAR) { newShape = new BulletShape( - BulletSimAPI.BuildCapsuleShape2(PhysicsScene.World.ptr, 1f, 1f, nativeShapeData.Scale) + BulletSimAPI.BuildCapsuleShape2(PhysicsScene.World.ptr, 1f, 1f, prim.Scale) , shapeType); - DetailLog("{0},BSShapeCollection.BuiletPhysicalNativeShape,capsule,scale={1}", nativeShapeData.ID, nativeShapeData.Scale); + DetailLog("{0},BSShapeCollection.BuiletPhysicalNativeShape,capsule,scale={1}", prim.LocalID, prim.Scale); } else { @@ -454,7 +464,7 @@ public sealed class BSShapeCollection : IDisposable if (newShape.ptr == IntPtr.Zero) { PhysicsScene.Logger.ErrorFormat("{0} BuildPhysicalNativeShape failed. ID={1}, shape={2}", - LogHeader, nativeShapeData.ID, nativeShapeData.Type); + LogHeader, prim.LocalID, shapeType); } newShape.shapeKey = (System.UInt64)shapeKey; newShape.isNativeShape = true; @@ -466,13 +476,12 @@ public sealed class BSShapeCollection : IDisposable // 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, ShapeData shapeData, PrimitiveBaseShape pbs, - ShapeDestructionCallback shapeCallback) + private bool GetReferenceToMesh(BSPhysObject prim, ShapeDestructionCallback shapeCallback) { BulletShape newShape = new BulletShape(IntPtr.Zero); float lod; - System.UInt64 newMeshKey = ComputeShapeKey(shapeData, pbs, out 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 == ShapeData.PhysicsShapeType.SHAPE_MESH) @@ -484,9 +493,9 @@ public sealed class BSShapeCollection : IDisposable // Since we're recreating new, get rid of the reference to the previous shape DereferenceShape(prim.PhysShape, true, shapeCallback); - newShape = CreatePhysicalMesh(prim.PhysObjectName, newMeshKey, pbs, shapeData.Size, lod); + newShape = CreatePhysicalMesh(prim.PhysObjectName, newMeshKey, prim.BaseShape, prim.Size, lod); // Take evasive action if the mesh was not constructed. - newShape = VerifyMeshCreated(newShape, prim, shapeData, pbs); + newShape = VerifyMeshCreated(newShape, prim); ReferenceShape(newShape); @@ -541,13 +550,12 @@ public sealed class BSShapeCollection : IDisposable // See that hull shape exists in the physical world and update prim.BSShape. // We could be creating the hull because scale changed or whatever. - private bool GetReferenceToHull(BSPhysObject prim, ShapeData shapeData, PrimitiveBaseShape pbs, - ShapeDestructionCallback shapeCallback) + private bool GetReferenceToHull(BSPhysObject prim, ShapeDestructionCallback shapeCallback) { BulletShape newShape; float lod; - System.UInt64 newHullKey = ComputeShapeKey(shapeData, pbs, out 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 == ShapeData.PhysicsShapeType.SHAPE_HULL) @@ -559,8 +567,8 @@ public sealed class BSShapeCollection : IDisposable // Remove usage of the previous shape. DereferenceShape(prim.PhysShape, true, shapeCallback); - newShape = CreatePhysicalHull(prim.PhysObjectName, newHullKey, pbs, shapeData.Size, lod); - newShape = VerifyMeshCreated(newShape, prim, shapeData, pbs); + newShape = CreatePhysicalHull(prim.PhysObjectName, newHullKey, prim.BaseShape, prim.Size, lod); + newShape = VerifyMeshCreated(newShape, prim); ReferenceShape(newShape); @@ -687,7 +695,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(ShapeData shapeData, PrimitiveBaseShape pbs, out float retLod) + private System.UInt64 ComputeShapeKey(OMV.Vector3 size, PrimitiveBaseShape pbs, out float retLod) { // level of detail based on size and type of the object float lod = PhysicsScene.MeshLOD; @@ -695,40 +703,40 @@ public sealed class BSShapeCollection : IDisposable lod = PhysicsScene.SculptLOD; // Mega prims usually get more detail because one can interact with shape approximations at this size. - float maxAxis = Math.Max(shapeData.Size.X, Math.Max(shapeData.Size.Y, shapeData.Size.Z)); + float maxAxis = Math.Max(size.X, Math.Max(size.Y, size.Z)); if (maxAxis > PhysicsScene.MeshMegaPrimThreshold) lod = PhysicsScene.MeshMegaPrimLOD; retLod = lod; - return pbs.GetMeshKey(shapeData.Size, lod); + return pbs.GetMeshKey(size, lod); } // For those who don't want the LOD - private System.UInt64 ComputeShapeKey(ShapeData shapeData, PrimitiveBaseShape pbs) + private System.UInt64 ComputeShapeKey(OMV.Vector3 size, PrimitiveBaseShape pbs) { float lod; - return ComputeShapeKey(shapeData, pbs, out 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 decompressing JPEG2000s). - // The first case causes the asset to be fetched. The second case just requires + // 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. - private BulletShape VerifyMeshCreated(BulletShape newShape, BSPhysObject prim, ShapeData shapeData, PrimitiveBaseShape pbs) + private BulletShape VerifyMeshCreated(BulletShape newShape, BSPhysObject prim) { // If the shape was successfully created, nothing more to do if (newShape.ptr != IntPtr.Zero) return newShape; // If this mesh has an underlying asset and we have not failed getting it before, fetch the asset - if (pbs.SculptEntry && !prim.LastAssetBuildFailed && pbs.SculptTexture != OMV.UUID.Zero) + if (prim.BaseShape.SculptEntry && !prim.LastAssetBuildFailed && prim.BaseShape.SculptTexture != OMV.UUID.Zero) { prim.LastAssetBuildFailed = true; BSPhysObject xprim = prim; DetailLog("{0},BSShapeCollection.VerifyMeshCreated,fetchAsset,lID={1},lastFailed={2}", - LogHeader, shapeData.ID.ToString("X"), prim.LastAssetBuildFailed); + LogHeader, prim.LocalID, prim.LastAssetBuildFailed); Util.FireAndForget(delegate { RequestAssetDelegate assetProvider = PhysicsScene.RequestAssetMethod; @@ -745,7 +753,7 @@ public sealed class BSShapeCollection : IDisposable 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 native sphere setting since the rebuild is at taint time. + // No race condition with the normal shape setting since the rebuild is at taint time. yprim.ForceBodyShapeRebuild(false); }); @@ -757,13 +765,13 @@ public sealed class BSShapeCollection : IDisposable if (prim.LastAssetBuildFailed) { PhysicsScene.Logger.ErrorFormat("{0} Mesh failed to fetch asset. lID={1}, texture={2}", - LogHeader, shapeData.ID, pbs.SculptTexture); + LogHeader, prim.LocalID, prim.BaseShape.SculptTexture); } } // While we figure out the real problem, stick a simple native shape on the object. BulletShape fillinShape = - BuildPhysicalNativeShape(ShapeData.PhysicsShapeType.SHAPE_BOX, shapeData, ShapeData.FixedShapeKey.KEY_BOX); + BuildPhysicalNativeShape(prim, ShapeData.PhysicsShapeType.SHAPE_BOX, ShapeData.FixedShapeKey.KEY_BOX); return fillinShape; } @@ -773,7 +781,7 @@ public sealed class BSShapeCollection : IDisposable // Returns 'true' if an object was actually created. // Called at taint-time. private bool CreateBody(bool forceRebuild, BSPhysObject prim, BulletSim sim, BulletShape shape, - ShapeData shapeData, BodyDestructionCallback bodyCallback) + BodyDestructionCallback bodyCallback) { bool ret = false; @@ -803,16 +811,16 @@ public sealed class BSShapeCollection : IDisposable if (prim.IsSolid) { bodyPtr = BulletSimAPI.CreateBodyFromShape2(sim.ptr, shape.ptr, - shapeData.ID, shapeData.Position, shapeData.Rotation); + prim.LocalID, prim.ForcePosition, prim.ForceOrientation); DetailLog("{0},BSShapeCollection.CreateBody,mesh,ptr={1}", prim.LocalID, bodyPtr.ToString("X")); } else { bodyPtr = BulletSimAPI.CreateGhostFromShape2(sim.ptr, shape.ptr, - shapeData.ID, shapeData.Position, shapeData.Rotation); + prim.LocalID, prim.ForcePosition, prim.ForceOrientation); DetailLog("{0},BSShapeCollection.CreateBody,ghost,ptr={1}", prim.LocalID, bodyPtr.ToString("X")); } - aBody = new BulletBody(shapeData.ID, bodyPtr); + aBody = new BulletBody(prim.LocalID, bodyPtr); ReferenceBody(aBody, true); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs index 9b7ba03..3b6355c 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs @@ -194,6 +194,7 @@ public struct ShapeData // following defined by BulletSim SHAPE_GROUNDPLANE = 20, SHAPE_TERRAIN = 21, + SHAPE_COMPOUND = 22, }; public uint ID; public PhysicsShapeType Type; -- cgit v1.1 From f53b4e7a21f62a84e237c4ce8d2806124c3a76d2 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Thu, 1 Nov 2012 10:53:55 -0700 Subject: BulletSim: Add RawPosition and RawOrientation to BSPhysObject and rename MassRaw to RawMass. Fix BSShapeCollection to use Raw* for creating the body to eliminate exception from referencing the physical body before it has been created. --- OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs | 20 +++++++++++++++----- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 16 ++++++++-------- OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs | 4 +++- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 14 ++++++++++++-- .../Physics/BulletSPlugin/BSShapeCollection.cs | 2 +- 5 files changed, 39 insertions(+), 17 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index 2a634b9..9e1206a 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -97,7 +97,7 @@ public sealed class BSCharacter : BSPhysObject // set _avatarVolume and _mass based on capsule size, _density and Scale ComputeAvatarVolumeAndMass(); DetailLog("{0},BSCharacter.create,call,size={1},scale={2},density={3},volume={4},mass={5}", - LocalID, _size, Scale, _avatarDensity, _avatarVolume, MassRaw); + LocalID, _size, Scale, _avatarDensity, _avatarVolume, RawMass); // do actual create at taint time PhysicsScene.TaintedObject("BSCharacter.create", delegate() @@ -141,7 +141,7 @@ public sealed class BSCharacter : BSPhysObject BulletSimAPI.SetCcdSweptSphereRadius2(PhysBody.ptr, PhysicsScene.Params.ccdSweptSphereRadius); } - UpdatePhysicalMassProperties(MassRaw); + UpdatePhysicalMassProperties(RawMass); // Make so capsule does not fall over BulletSimAPI.SetAngularFactorV2(PhysBody.ptr, OMV.Vector3.Zero); @@ -181,12 +181,12 @@ public sealed class BSCharacter : BSPhysObject ComputeAvatarScale(_size); ComputeAvatarVolumeAndMass(); DetailLog("{0},BSCharacter.setSize,call,scale={1},density={2},volume={3},mass={4}", - LocalID, Scale, _avatarDensity, _avatarVolume, MassRaw); + LocalID, Scale, _avatarDensity, _avatarVolume, RawMass); PhysicsScene.TaintedObject("BSCharacter.setSize", delegate() { BulletSimAPI.SetLocalScaling2(PhysShape.ptr, Scale); - UpdatePhysicalMassProperties(MassRaw); + UpdatePhysicalMassProperties(RawMass); }); } @@ -231,6 +231,11 @@ 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 { // _position = BulletSimAPI.GetObjectPosition2(Scene.World.ptr, LocalID); @@ -316,7 +321,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 MassRaw { + public override float RawMass { get {return _mass; } } public override void UpdatePhysicalMassProperties(float physMass) @@ -405,6 +410,11 @@ 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; } set { diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index f56851f..9e0f499 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -106,7 +106,7 @@ public abstract class BSLinkset PhysicsScene = scene; LinksetRoot = parent; m_children = new HashSet(); - m_mass = parent.MassRaw; + m_mass = parent.RawMass; } // Link to a linkset where the child knows the parent. @@ -242,14 +242,14 @@ public abstract class BSLinkset // ================================================================ protected virtual float ComputeLinksetMass() { - float mass = LinksetRoot.MassRaw; + float mass = LinksetRoot.RawMass; if (HasAnyChildren) { lock (m_linksetActivityLock) { foreach (BSPhysObject bp in m_children) { - mass += bp.MassRaw; + mass += bp.RawMass; } } } @@ -261,13 +261,13 @@ public abstract class BSLinkset OMV.Vector3 com; lock (m_linksetActivityLock) { - com = LinksetRoot.Position * LinksetRoot.MassRaw; - float totalMass = LinksetRoot.MassRaw; + com = LinksetRoot.Position * LinksetRoot.RawMass; + float totalMass = LinksetRoot.RawMass; foreach (BSPhysObject bp in m_children) { - com += bp.Position * bp.MassRaw; - totalMass += bp.MassRaw; + com += bp.Position * bp.RawMass; + totalMass += bp.RawMass; } if (totalMass != 0f) com /= totalMass; @@ -285,7 +285,7 @@ public abstract class BSLinkset foreach (BSPhysObject bp in m_children) { - com += bp.Position * bp.MassRaw; + com += bp.Position * bp.RawMass; } com /= (m_children.Count + 1); } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index 7d91468..65d7f34 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -63,7 +63,7 @@ public abstract class BSPhysObject : PhysicsActor public BSLinkset Linkset { get; set; } // Return the object mass without calculating it or having side effects - public abstract float MassRaw { get; } + public abstract float RawMass { get; } // Set the raw mass but also update physical mass properties (inertia, ...) public abstract void UpdatePhysicalMassProperties(float mass); @@ -105,8 +105,10 @@ public abstract class BSPhysObject : PhysicsActor // Tell the object to clean up. public abstract void Destroy(); + public abstract OMV.Vector3 RawPosition { get; set; } public abstract OMV.Vector3 ForcePosition { get; set; } + public abstract OMV.Quaternion RawOrientation { get; set; } public abstract OMV.Quaternion ForceOrientation { get; set; } public abstract OMV.Vector3 ForceVelocity { get; set; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 8ce960d..1754be6 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -256,6 +256,11 @@ public sealed class BSPrim : BSPhysObject return; } + public override OMV.Vector3 RawPosition + { + get { return _position; } + set { _position = value; } + } public override OMV.Vector3 Position { get { if (!Linkset.IsRoot(this)) @@ -366,7 +371,7 @@ public sealed class BSPrim : BSPhysObject } // used when we only want this prim's mass and not the linkset thing - public override float MassRaw { + public override float RawMass { get { return _mass; } } // Set the physical mass to the passed mass. @@ -530,6 +535,11 @@ public sealed 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 { if (!Linkset.IsRoot(this)) @@ -703,7 +713,7 @@ public sealed class BSPrim : BSPhysObject BulletSimAPI.SetTranslation2(PhysBody.ptr, _position, _orientation); // A dynamic object has mass - UpdatePhysicalMassProperties(MassRaw); + UpdatePhysicalMassProperties(RawMass); // Set collision detection parameters if (PhysicsScene.Params.ccdMotionThreshold > 0f) diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index 478924a..e131919 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -811,7 +811,7 @@ public sealed class BSShapeCollection : IDisposable if (prim.IsSolid) { bodyPtr = BulletSimAPI.CreateBodyFromShape2(sim.ptr, shape.ptr, - prim.LocalID, prim.ForcePosition, prim.ForceOrientation); + prim.LocalID, prim.RawPosition, prim.RawOrientation); DetailLog("{0},BSShapeCollection.CreateBody,mesh,ptr={1}", prim.LocalID, bodyPtr.ToString("X")); } else -- cgit v1.1 From b0eccd5044b1a20b995a62d6fb76fdd73b712f9a Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Fri, 2 Nov 2012 09:53:41 -0700 Subject: BulletSim: debugging of compound shape implementation of linksets. Add compound shape creation and freeing in shape manager. Add optional taint-time execution method and update code to use it. Add API2 linkage for more compound shape methods (get num, get/remove by index, ...) Modify perferred shape return so linkset children can have differet shapes than root. Add Position and Orientation calls to linksets so children can be moved around by the linkset by its own calculation. Allows for very general linkset implementations. --- .../Region/Physics/BulletSPlugin/BSCharacter.cs | 13 +- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 19 ++- .../Physics/BulletSPlugin/BSLinksetCompound.cs | 106 ++++++++++---- .../Physics/BulletSPlugin/BSLinksetConstraints.cs | 12 ++ .../Region/Physics/BulletSPlugin/BSPhysObject.cs | 4 +- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 52 +++---- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 12 +- .../Physics/BulletSPlugin/BSShapeCollection.cs | 152 ++++++++++++++++----- .../Physics/BulletSPlugin/BSTerrainManager.cs | 21 +-- .../Region/Physics/BulletSPlugin/BulletSimAPI.cs | 15 +- 10 files changed, 274 insertions(+), 132 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index 9e1206a..2a5397e 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -200,7 +200,9 @@ public sealed class BSCharacter : BSPhysObject } // I want the physics engine to make an avatar capsule public override ShapeData.PhysicsShapeType PreferredPhysicalShape - { get { return ShapeData.PhysicsShapeType.SHAPE_AVATAR; } } + { + get {return ShapeData.PhysicsShapeType.SHAPE_AVATAR; } + } public override bool Grabbed { set { _grabbed = value; } @@ -238,6 +240,7 @@ public sealed class BSCharacter : BSPhysObject } public override OMV.Vector3 Position { get { + // Don't refetch the position because this function is called a zillion times // _position = BulletSimAPI.GetObjectPosition2(Scene.World.ptr, LocalID); return _position; } @@ -304,15 +307,11 @@ 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. - BSScene.TaintCallback sanityOperation = delegate() + PhysicsScene.TaintedObject(inTaintTime, "BSCharacter.PositionSanityCheck", delegate() { DetailLog("{0},BSCharacter.PositionSanityCheck,taint,pos={1},orient={2}", LocalID, _position, _orientation); BulletSimAPI.SetTranslation2(PhysBody.ptr, _position, _orientation); - }; - if (inTaintTime) - sanityOperation(); - else - PhysicsScene.TaintedObject("BSCharacter.PositionSanityCheck", sanityOperation); + }); ret = true; } return ret; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index 9e0f499..8f973f4 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -48,7 +48,8 @@ public abstract class BSLinkset */ // at the moment, there is only one - ret = new BSLinksetConstraints(physScene, parent); + // ret = new BSLinksetConstraints(physScene, parent); + ret = new BSLinksetCompound(physScene, parent); return ret; } @@ -69,10 +70,19 @@ public abstract class BSLinkset protected object m_linksetActivityLock = new Object(); // Some linksets have a preferred physical shape. - // Returns SHAPE_UNKNOWN if there is no preference. - public virtual ShapeData.PhysicsShapeType PreferredPhysicalShape - { get { return ShapeData.PhysicsShapeType.SHAPE_UNKNOWN; } } + // Returns SHAPE_UNKNOWN if there is no preference. Causes the correct shape to be selected. + public virtual ShapeData.PhysicsShapeType PreferredPhysicalShape(BSPhysObject requestor) + { + return ShapeData.PhysicsShapeType.SHAPE_UNKNOWN; + } + // Linksets move around the children so the linkset might need to compute the child position + public virtual OMV.Vector3 Position(BSPhysObject member) + { return member.RawPosition; } + public virtual OMV.Quaternion Orientation(BSPhysObject member) + { return member.RawOrientation; } + // TODO: does this need to be done for Velocity and RotationalVelocityy? + // We keep the prim's mass in the linkset structure since it could be dependent on other prims protected float m_mass; public float LinksetMass @@ -177,7 +187,6 @@ public abstract class BSLinkset } // Perform an action on each member of the linkset including root prim. - // The action is performed only on the objects that are physically in the linkset. // Depends on the action on whether this should be done at taint time. public delegate bool ForEachMemberAction(BSPhysObject obj); public virtual bool ForEachMember(ForEachMemberAction action) diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs index 638fae1..8b97ebb 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs @@ -41,18 +41,31 @@ public sealed class BSLinksetCompound : BSLinkset base.Initialize(scene, parent); } + // For compound implimented linksets, if there are children, use compound shape for the root. + public override ShapeData.PhysicsShapeType PreferredPhysicalShape(BSPhysObject requestor) + { + ShapeData.PhysicsShapeType ret = ShapeData.PhysicsShapeType.SHAPE_UNKNOWN; + if (IsRoot(requestor) && HasAnyChildren) + { + ret = ShapeData.PhysicsShapeType.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. // This is queued in the 'post taint' queue so the // refresh will happen once after all the other taints are applied. public override void Refresh(BSPhysObject requestor) { + DetailLog("{0},BSLinksetCompound.Refresh,schedulingRefresh,requestor={1}", LinksetRoot.LocalID, requestor.LocalID); // Queue to happen after all the other taint processing - PhysicsScene.PostTaintObject("BSLinksetcompound.Refresh", requestor.LocalID, delegate() - { - if (HasAnyChildren && IsRoot(requestor)) - RecomputeLinksetCompound(); - }); + PhysicsScene.PostTaintObject("BSLinksetCompound.Refresh", requestor.LocalID, delegate() + { + if (IsRoot(requestor) && HasAnyChildren) + RecomputeLinksetCompound(); + }); } // The object is going dynamic (physical). Do any setup necessary @@ -63,8 +76,17 @@ public sealed class BSLinksetCompound : BSLinkset // Called at taint-time! public override bool MakeDynamic(BSPhysObject child) { - // What is done for each object in BSPrim is what we want. - return false; + bool ret = false; + DetailLog("{0},BSLinksetCompound.MakeDynamic,call,isChild={1}", child.LocalID, HasChild(child)); + if (HasChild(child)) + { + // Physical children are removed from the world as the shape ofthe root compound + // shape takes over. + BulletSimAPI.AddToCollisionFlags2(child.PhysBody.ptr, CollisionFlags.CF_NO_CONTACT_RESPONSE); + BulletSimAPI.ForceActivationState2(child.PhysBody.ptr, ActivationState.DISABLE_SIMULATION); + ret = true; + } + return ret; } // The object is going static (non-physical). Do any setup necessary for a static linkset. @@ -74,8 +96,17 @@ public sealed class BSLinksetCompound : BSLinkset // Called at taint-time! public override bool MakeStatic(BSPhysObject child) { - // What is done for each object in BSPrim is what we want. - return false; + bool ret = false; + DetailLog("{0},BSLinksetCompound.MakeStatic,call,hasChild={1}", child.LocalID, HasChild(child)); + if (HasChild(child)) + { + // The non-physical children can come back to life. + BulletSimAPI.RemoveFromCollisionFlags2(child.PhysBody.ptr, CollisionFlags.CF_NO_CONTACT_RESPONSE); + // Don't force activation so setting of DISABLE_SIMULATION can stay. + BulletSimAPI.Activate2(child.PhysBody.ptr, false); + ret = true; + } + return ret; } // Called at taint-time!! @@ -84,20 +115,35 @@ public sealed class BSLinksetCompound : BSLinkset // Nothing to do for constraints on property updates } + // The children move around in relationship to the root. + // Just grab the current values of wherever it is right now. + public override OMV.Vector3 Position(BSPhysObject member) + { + return BulletSimAPI.GetPosition2(member.PhysBody.ptr); + } + + public override OMV.Quaternion Orientation(BSPhysObject member) + { + return BulletSimAPI.GetOrientation2(member.PhysBody.ptr); + } + // Routine called when rebuilding the body of some member of the linkset. - // Destroy all the constraints have have been made to root and set - // up to rebuild the constraints before the next simulation step. + // Since we don't keep in-physical 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(BSPrim child) { bool ret = false; - DetailLog("{0},BSLinksetcompound.RemoveBodyDependencies,removeChildrenForRoot,rID={1},rBody={2}", - child.LocalID, LinksetRoot.LocalID, LinksetRoot.PhysBody.ptr.ToString("X")); + DetailLog("{0},BSLinksetCompound.RemoveBodyDependencies,removeChildrenForRoot,rID={1},rBody={2},isRoot={3}", + child.LocalID, LinksetRoot.LocalID, LinksetRoot.PhysBody.ptr.ToString("X"), IsRoot(child)); - // Cause the current shape to be freed and the new one to be built. - Refresh(LinksetRoot); + if (!IsRoot(child)) + { + // Cause the current shape to be freed and the new one to be built. + Refresh(LinksetRoot); + ret = true; + } return ret; } @@ -139,13 +185,19 @@ public sealed class BSLinksetCompound : BSLinkset LinksetRoot.LocalID, LinksetRoot.PhysBody.ptr.ToString("X"), child.LocalID, child.PhysBody.ptr.ToString("X")); - // See that the linkset parameters are recomputed at the end of the taint time. - Refresh(LinksetRoot); - } - else - { - // Non-fatal occurance. - // PhysicsScene.Logger.ErrorFormat("{0}: Asked to remove child from linkset that was not in linkset", LogHeader); + // Cause the child's body to be rebuilt and thus restored to normal operation + child.ForceBodyShapeRebuild(false); + + if (!HasAnyChildren) + { + // The linkset is now empty. The root needs rebuilding. + LinksetRoot.ForceBodyShapeRebuild(false); + } + else + { + // Schedule a rebuild of the linkset before the next simulation tick. + Refresh(LinksetRoot); + } } return; } @@ -158,16 +210,18 @@ public sealed class BSLinksetCompound : BSLinkset // Called at taint time!! private void RecomputeLinksetCompound() { - // Release the existing shape - PhysicsScene.Shapes.DereferenceShape(LinksetRoot.PhysShape, true, null); - + DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,start,rBody={1},numChildren={2}", + LinksetRoot.LocalID, LinksetRoot.PhysBody.ptr.ToString("X"), NumberOfChildren); + + LinksetRoot.ForceBodyShapeRebuild(true); + float linksetMass = LinksetMass; LinksetRoot.UpdatePhysicalMassProperties(linksetMass); // DEBUG: see of inter-linkset collisions are causing problems // BulletSimAPI.SetCollisionFilterMask2(LinksetRoot.BSBody.ptr, // (uint)CollisionFilterGroups.LinksetFilter, (uint)CollisionFilterGroups.LinksetMask); - DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,set,rBody={1},linksetMass={2}", + DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,end,rBody={1},linksetMass={2}", LinksetRoot.LocalID, LinksetRoot.PhysBody.ptr.ToString("X"), linksetMass); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs index 65aed77..67a59ef 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs @@ -84,6 +84,18 @@ public sealed class BSLinksetConstraints : BSLinkset // Nothing to do for constraints on property updates } + // The children of the linkset are moved around by the constraints. + // Just grab the current values of wherever it is right now. + public override OMV.Vector3 Position(BSPhysObject member) + { + return BulletSimAPI.GetPosition2(member.PhysBody.ptr); + } + + public override OMV.Quaternion Orientation(BSPhysObject member) + { + return BulletSimAPI.GetOrientation2(member.PhysBody.ptr); + } + // Routine called when rebuilding the body of some member of the linkset. // Destroy all the constraints have have been made to root and set // up to rebuild the constraints before the next simulation step. diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index 65d7f34..7127aaf 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -81,7 +81,9 @@ public abstract class BSPhysObject : PhysicsActor // Some types of objects have preferred physical representations. // Returns SHAPE_UNKNOWN if there is no preference. public virtual ShapeData.PhysicsShapeType PreferredPhysicalShape - { get { return ShapeData.PhysicsShapeType.SHAPE_UNKNOWN; } } + { + get { return ShapeData.PhysicsShapeType.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 diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 1754be6..af403aa 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -173,20 +173,16 @@ public sealed class BSPrim : BSPhysObject } // Whatever the linkset wants is what I want. public override ShapeData.PhysicsShapeType PreferredPhysicalShape - { get { return Linkset.PreferredPhysicalShape; } } + { get { return Linkset.PreferredPhysicalShape(this); } } public override bool ForceBodyShapeRebuild(bool inTaintTime) { LastAssetBuildFailed = false; - BSScene.TaintCallback rebuildOperation = delegate() + PhysicsScene.TaintedObject(inTaintTime, "BSPrim.ForceBodyShapeRebuild", delegate() { _mass = CalculateMass(); // changing the shape changes the mass CreateGeomAndObject(true); - }; - if (inTaintTime) - rebuildOperation(); - else - PhysicsScene.TaintedObject("BSPrim.ForceBodyShapeRebuild", rebuildOperation); + }); return true; } public override bool Grabbed { @@ -263,9 +259,9 @@ public sealed class BSPrim : BSPhysObject } public override OMV.Vector3 Position { get { + // child prims move around based on their parent. Need to get the latest location if (!Linkset.IsRoot(this)) - // child prims move around based on their parent. Need to get the latest location - _position = BulletSimAPI.GetPosition2(PhysBody.ptr); + _position = Linkset.Position(this); // don't do the GetObjectPosition for root elements because this function is called a zillion times // _position = BulletSimAPI.GetObjectPosition2(PhysicsScene.World.ptr, BSBody.ptr); @@ -344,16 +340,11 @@ public sealed class BSPrim : 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. - BSScene.TaintCallback sanityOperation = delegate() + PhysicsScene.TaintedObject(inTaintTime, "BSPrim.PositionSanityCheck", delegate() { DetailLog("{0},BSPrim.PositionSanityCheck,taint,pos={1},orient={2}", LocalID, _position, _orientation); ForcePosition = _position; - }; - if (inTaintTime) - sanityOperation(); - else - PhysicsScene.TaintedObject("BSPrim.PositionSanityCheck", sanityOperation); - + }); ret = true; } return ret; @@ -542,10 +533,10 @@ public sealed class BSPrim : BSPhysObject } public override OMV.Quaternion Orientation { get { + // Children move around because tied to parent. Get a fresh value. if (!Linkset.IsRoot(this)) { - // Children move around because tied to parent. Get a fresh value. - _orientation = BulletSimAPI.GetOrientation2(PhysBody.ptr); + _orientation = Linkset.Orientation(this); } return _orientation; } @@ -946,7 +937,7 @@ public sealed class BSPrim : BSPhysObject m_log.WarnFormat("{0}: Got a NaN force applied to a prim. LocalID={1}", LogHeader, LocalID); return; } - BSScene.TaintCallback addForceOperation = delegate() + PhysicsScene.TaintedObject(inTaintTime, "BSPrim.AddForce", delegate() { OMV.Vector3 fSum = OMV.Vector3.Zero; lock (m_accumulatedForces) @@ -961,11 +952,7 @@ public sealed class BSPrim : BSPhysObject DetailLog("{0},BSPrim.AddForce,taint,force={1}", LocalID, fSum); if (fSum != OMV.Vector3.Zero) BulletSimAPI.ApplyCentralForce2(PhysBody.ptr, fSum); - }; - if (inTaintTime) - addForceOperation(); - else - PhysicsScene.TaintedObject("BSPrim.AddForce", addForceOperation); + }); } private List m_accumulatedAngularForces = new List(); @@ -985,7 +972,7 @@ public sealed class BSPrim : BSPhysObject m_log.WarnFormat("{0}: Got a NaN force applied to a prim. LocalID={1}", LogHeader, LocalID); return; } - BSScene.TaintCallback addAngularForceOperation = delegate() + PhysicsScene.TaintedObject(inTaintTime, "BSPrim.AddAngularForce", delegate() { OMV.Vector3 fSum = OMV.Vector3.Zero; lock (m_accumulatedAngularForces) @@ -1003,26 +990,19 @@ public sealed class BSPrim : BSPhysObject BulletSimAPI.ApplyTorque2(PhysBody.ptr, fSum); _torque = fSum; } - }; - if (inTaintTime) - addAngularForceOperation(); - else - PhysicsScene.TaintedObject("BSPrim.AddAngularForce", addAngularForceOperation); + }); } // A torque impulse. public void ApplyTorqueImpulse(OMV.Vector3 impulse, bool inTaintTime) { OMV.Vector3 applyImpulse = impulse; - BSScene.TaintCallback applyTorqueImpulseOperation = delegate() + PhysicsScene.TaintedObject(inTaintTime, "BSPrim.ApplyTorqueImpulse", delegate() { DetailLog("{0},BSPrim.ApplyTorqueImpulse,taint,tImpulse={1}", LocalID, applyImpulse); BulletSimAPI.ApplyTorqueImpulse2(PhysBody.ptr, applyImpulse); - }; - if (inTaintTime) - applyTorqueImpulseOperation(); - else - PhysicsScene.TaintedObject("BSPrim.ApplyTorqueImpulse", applyTorqueImpulseOperation); + }); } + public override void SetMomentum(OMV.Vector3 momentum) { // DetailLog("{0},BSPrim.SetMomentum,call,mom={1}", LocalID, momentum); } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index cc5dbb2..dcfcb83 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -692,6 +692,16 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters return; } + // 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) + { + if (inTaintTime) + callback(); + else + TaintedObject(ident, callback); + } + // When someone tries to change a property on a BSPrim or BSCharacter, the object queues // a callback into itself to do the actual property change. That callback is called // here just before the physics engine is called to step the simulation. @@ -1438,7 +1448,7 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters { PhysicsLogging.Write(msg, args); // Add the Flush() if debugging crashes to get all the messages written out. - // PhysicsLogging.Flush(); + 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"; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index e131919..107befe 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -122,18 +122,14 @@ public sealed class BSShapeCollection : IDisposable lock (m_collectionActivityLock) { DetailLog("{0},BSShapeCollection.ReferenceBody,newBody", body.ID, body); - BSScene.TaintCallback createOperation = delegate() + PhysicsScene.TaintedObject(inTaintTime, "BSShapeCollection.ReferenceBody", delegate() { if (!BulletSimAPI.IsInWorld2(body.ptr)) { BulletSimAPI.AddObjectToWorld2(PhysicsScene.World.ptr, body.ptr); DetailLog("{0},BSShapeCollection.ReferenceBody,addedToWorld,ref={1}", body.ID, body); } - }; - if (inTaintTime) - createOperation(); - else - PhysicsScene.TaintedObject("BSShapeCollection.ReferenceBody", createOperation); + }); } } @@ -146,7 +142,7 @@ public sealed class BSShapeCollection : IDisposable lock (m_collectionActivityLock) { - BSScene.TaintCallback removeOperation = delegate() + PhysicsScene.TaintedObject(inTaintTime, "BSShapeCollection.DereferenceBody", delegate() { DetailLog("{0},BSShapeCollection.DereferenceBody,DestroyingBody. ptr={1}, inTaintTime={2}", body.ID, body.ptr.ToString("X"), inTaintTime); @@ -159,12 +155,7 @@ public sealed class BSShapeCollection : IDisposable // Zero any reference to the shape so it is not freed when the body is deleted. BulletSimAPI.SetCollisionShape2(PhysicsScene.World.ptr, body.ptr, IntPtr.Zero); BulletSimAPI.DestroyObject2(PhysicsScene.World.ptr, body.ptr); - }; - // If already in taint-time, do the operations now. Otherwise queue for later. - if (inTaintTime) - removeOperation(); - else - PhysicsScene.TaintedObject("BSShapeCollection.DereferenceBody", removeOperation); + }); } } @@ -238,7 +229,7 @@ public sealed class BSShapeCollection : IDisposable if (shape.ptr == IntPtr.Zero) return; - BSScene.TaintCallback dereferenceOperation = delegate() + PhysicsScene.TaintedObject(inTaintTime, "BSShapeCollection.DereferenceShape", delegate() { if (shape.ptr != IntPtr.Zero) { @@ -270,18 +261,7 @@ public sealed class BSShapeCollection : IDisposable } } } - }; - if (inTaintTime) - { - lock (m_collectionActivityLock) - { - dereferenceOperation(); - } - } - else - { - PhysicsScene.TaintedObject("BSShapeCollection.DereferenceShape", dereferenceOperation); - } + }); } // Count down the reference count for a mesh shape @@ -311,7 +291,10 @@ public sealed class BSShapeCollection : IDisposable { 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; DetailLog("{0},BSShapeCollection.DereferenceHull,key={1},refCnt={2}", @@ -320,10 +303,48 @@ public sealed class BSShapeCollection : IDisposable } // Remove a reference to a compound shape. + // Taking a compound shape apart is a little tricky because if you just delete the + // physical object, 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) { - // Compound shape is made of a bunch of meshes and natives. + if (!BulletSimAPI.IsCompound2(shape.ptr)) + { + // 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.ptr.ToString("X")); + DetailLog("{0},BSShapeCollection.DereferenceCompound,notACompoundShape,type={1},ptr={2}", + BSScene.DetailLogZero, shape.type, shape.ptr.ToString("X")); + return; + } + int numChildren = BulletSimAPI.GetNumberOfCompoundChildren2(shape.ptr); + for (int ii = 0; ii < numChildren; ii++) + { + IntPtr childShape = BulletSimAPI.RemoveChildShapeFromCompoundShapeIndex2(shape.ptr, ii); + DereferenceAnonCollisionShape(childShape); + } + BulletSimAPI.DeleteCollisionShape2(PhysicsScene.World.ptr, shape.ptr); + } + + // 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. + // This is coming from a compound shape that we created so we know it is either native or mesh. + // Called at taint-time. + private void DereferenceAnonCollisionShape(IntPtr cShape) + { + BulletShape shapeInfo = new BulletShape(cShape, ShapeData.PhysicsShapeType.SHAPE_MESH); + if (BulletSimAPI.IsCompound2(cShape)) + shapeInfo.type = ShapeData.PhysicsShapeType.SHAPE_COMPOUND; + + if (BulletSimAPI.IsNativeShape2(cShape)) + { + shapeInfo.isNativeShape = true; + shapeInfo.type = ShapeData.PhysicsShapeType.SHAPE_BOX; // (technically, type doesn't matter) + } + + DereferenceShape(shapeInfo, true, null); } // Create the geometry information in Bullet for later use. @@ -338,10 +359,8 @@ public sealed class BSShapeCollection : IDisposable { bool ret = false; bool haveShape = false; - bool nativeShapePossible = true; - PrimitiveBaseShape pbs = prim.BaseShape; - if (prim.PreferredPhysicalShape == ShapeData.PhysicsShapeType.SHAPE_AVATAR) + if (!haveShape && prim.PreferredPhysicalShape == ShapeData.PhysicsShapeType.SHAPE_AVATAR) { // an avatar capsule is close to a native shape (it is not shared) ret = GetReferenceToNativeShape(prim, ShapeData.PhysicsShapeType.SHAPE_AVATAR, @@ -350,6 +369,31 @@ public sealed class BSShapeCollection : IDisposable 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 already been created. + if (!haveShape && prim.PreferredPhysicalShape == ShapeData.PhysicsShapeType.SHAPE_COMPOUND) + { + ret = GetReferenceToCompoundShape(prim, shapeCallback); + DetailLog("{0},BSShapeCollection.CreateGeom,compoundShape,shape={1}", prim.LocalID, prim.PhysShape); + haveShape = true; + } + + if (!haveShape) + { + ret = CreateGeomNonSpecial(forceRebuild, prim, shapeCallback); + } + + return ret; + } + + private bool CreateGeomNonSpecial(bool forceRebuild, BSPhysObject prim, ShapeDestructionCallback shapeCallback) + { + bool ret = false; + bool haveShape = false; + bool nativeShapePossible = true; + PrimitiveBaseShape pbs = prim.BaseShape; + // If the prim attributes are simple, this could be a simple Bullet native shape if (!haveShape && pbs != null @@ -363,6 +407,7 @@ public sealed class BSShapeCollection : IDisposable && pbs.PathScaleX == 100 && pbs.PathScaleY == 100 && pbs.PathShearX == 0 && pbs.PathShearY == 0) ) ) { + // It doesn't look like Bullet scales spheres so make sure the scales are all equal if ((pbs.ProfileShape == ProfileShape.HalfCircle && pbs.PathCurve == (byte)Extrusion.Curve1) && pbs.Scale.X == pbs.Scale.Y && pbs.Scale.Y == pbs.Scale.Z) { @@ -378,7 +423,7 @@ public sealed class BSShapeCollection : IDisposable prim.LocalID, forceRebuild, prim.PhysShape); } } - if (pbs.ProfileShape == ProfileShape.Square && pbs.PathCurve == (byte)Extrusion.Straight) + if (!haveShape && pbs.ProfileShape == ProfileShape.Square && pbs.PathCurve == (byte)Extrusion.Straight) { haveShape = true; if (forceRebuild @@ -393,9 +438,10 @@ public sealed class BSShapeCollection : IDisposable } } } + // If a simple shape is not happening, create a mesh and possibly a hull. // Note that if it's a native shape, the check for physical/non-physical is not - // made. Native shapes are best used in either case. + // made. Native shapes work in either case. if (!haveShape && pbs != null) { if (prim.IsPhysical && PhysicsScene.ShouldUseHullsForPhysicalObjects) @@ -487,7 +533,7 @@ public sealed class BSShapeCollection : IDisposable if (newMeshKey == prim.PhysShape.shapeKey && prim.PhysShape.type == ShapeData.PhysicsShapeType.SHAPE_MESH) return false; - DetailLog("{0},BSShapeCollection.CreateGeomMesh,create,oldKey={1},newKey={2}", + DetailLog("{0},BSShapeCollection.GetReferenceToMesh,create,oldKey={1},newKey={2}", prim.LocalID, prim.PhysShape.shapeKey.ToString("X"), newMeshKey.ToString("X")); // Since we're recreating new, get rid of the reference to the previous shape @@ -535,7 +581,7 @@ public sealed class BSShapeCollection : IDisposable verticesAsFloats[vi++] = vv.Z; } - // m_log.DebugFormat("{0}: CreateGeomMesh: calling CreateMesh. lid={1}, key={2}, indices={3}, vertices={4}", + // m_log.DebugFormat("{0}: BSShapeCollection.CreatePhysicalMesh: calling CreateMesh. lid={1}, key={2}, indices={3}, vertices={4}", // LogHeader, prim.LocalID, newMeshKey, indices.Length, vertices.Count); meshPtr = BulletSimAPI.CreateMeshShape2(PhysicsScene.World.ptr, @@ -561,7 +607,7 @@ public sealed class BSShapeCollection : IDisposable if (newHullKey == prim.PhysShape.shapeKey && prim.PhysShape.type == ShapeData.PhysicsShapeType.SHAPE_HULL) return false; - DetailLog("{0},BSShapeCollection.CreateGeomHull,create,oldKey={1},newKey={2}", + 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. @@ -693,6 +739,42 @@ public sealed class BSShapeCollection : IDisposable 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) + { + BulletShape cShape = new BulletShape( + BulletSimAPI.CreateCompoundShape2(PhysicsScene.World.ptr), ShapeData.PhysicsShapeType.SHAPE_COMPOUND); + + // The prim's linkset is the source of the children. + // TODO: there is too much knowledge here about the internals of linksets and too much + // dependency on the relationship of compound shapes and linksets (what if we want to use + // compound shapes for something else?). Think through this and clean up so the + // appropriate knowledge is used at the correct software levels. + + // Recreate the geometry of the root prim (might have been a linkset root in the past) + CreateGeomNonSpecial(true, prim, null); + + BSPhysObject rootPrim = prim.Linkset.LinksetRoot; + + prim.Linkset.ForEachMember(delegate(BSPhysObject cPrim) + { + OMV.Quaternion invRootOrientation = OMV.Quaternion.Inverse(rootPrim.RawOrientation); + OMV.Vector3 displacementPos = (cPrim.RawPosition - rootPrim.RawPosition) * invRootOrientation; + OMV.Quaternion displacementRot = cPrim.RawOrientation * invRootOrientation; + + DetailLog("{0},BSShapeCollection.GetReferenceToCompoundShape,addMemberToShape,mID={1},mShape={2},dispPos={3},dispRot={4}", + prim.LocalID, cPrim.LocalID, cPrim.PhysShape.ptr.ToString("X"), displacementPos, displacementRot); + + BulletSimAPI.AddChildShapeToCompoundShape2(cShape.ptr, cPrim.PhysShape.ptr, displacementPos, displacementRot); + return false; + }); + + prim.PhysShape = cShape; + + return true; + } + // 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) diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs index 11298fe..7c34af2 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs @@ -238,7 +238,7 @@ public sealed class BSTerrainManager DetailLog("{0},UpdateOrCreateTerrain:UpdateExisting,call,terrainBase={1},minC={2}, maxC={3}, szX={4}, szY={5}", BSScene.DetailLogZero, terrainRegionBase, mapInfo.minCoords, mapInfo.maxCoords, mapInfo.sizeX, mapInfo.sizeY); - BSScene.TaintCallback rebuildOperation = delegate() + PhysicsScene.TaintedObject(inTaintTime, "BSScene.UpdateOrCreateTerrain:UpdateExisting", delegate() { if (MegaRegionParentPhysicsScene != null) { @@ -337,14 +337,7 @@ public sealed class BSTerrainManager BulletSimAPI.ForceActivationState2(mapInfo.terrainBody.ptr, ActivationState.DISABLE_SIMULATION); m_terrainModified = true; - }; - - // There is the option to do the changes now (we're already in 'taint time'), or - // to do the Bullet operations later. - if (inTaintTime) - rebuildOperation(); - else - PhysicsScene.TaintedObject("BSScene.UpdateOrCreateTerrain:UpdateExisting", rebuildOperation); + }); } else { @@ -364,7 +357,7 @@ public sealed class BSTerrainManager BSScene.DetailLogZero, newTerrainID, minCoords, minCoords); // Code that must happen at taint-time - BSScene.TaintCallback createOperation = delegate() + PhysicsScene.TaintedObject(inTaintTime, "BSScene.UpdateOrCreateTerrain:NewTerrain", delegate() { DetailLog("{0},UpdateOrCreateTerrain:NewTerrain,taint,baseX={1},baseY={2}", BSScene.DetailLogZero, minCoords.X, minCoords.Y); // Create a new mapInfo that will be filled with the new info @@ -377,13 +370,7 @@ public sealed class BSTerrainManager UpdateOrCreateTerrain(newTerrainID, heightMap, minCoords, maxCoords, true); m_terrainModified = true; - }; - - // If already in taint-time, just call Bullet. Otherwise queue the operations for the safe time. - if (inTaintTime) - createOperation(); - else - PhysicsScene.TaintedObject("BSScene.UpdateOrCreateTerrain:NewTerrain", createOperation); + }); } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs index 3b6355c..143b8be 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs @@ -399,8 +399,6 @@ public enum CollisionFilterGroups : uint }; - - // CFM controls the 'hardness' of the constraint. 0=fixed, 0..1=violatable. Default=0 // ERP controls amount of correction per tick. Usable range=0.1..0.8. Default=0.2. public enum ConstraintParams : int @@ -618,10 +616,19 @@ public static extern IntPtr BuildCapsuleShape2(IntPtr world, float radius, float public static extern IntPtr CreateCompoundShape2(IntPtr sim); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern void AddChildToCompoundShape2(IntPtr cShape, IntPtr addShape, Vector3 pos, Quaternion rot); +public static extern int GetNumberOfCompoundChildren2(IntPtr cShape); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void AddChildShapeToCompoundShape2(IntPtr cShape, IntPtr addShape, Vector3 pos, Quaternion rot); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern IntPtr GetChildShapeFromCompoundShapeIndex2(IntPtr cShape, int indx); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern IntPtr RemoveChildShapeFromCompoundShapeIndex2(IntPtr cShape, int indx); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern void RemoveChildFromCompoundShape2(IntPtr cShape, IntPtr removeShape); +public static extern void RemoveChildShapeFromCompoundShape2(IntPtr cShape, IntPtr removeShape); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern IntPtr DuplicateCollisionShape2(IntPtr sim, IntPtr srcShape, uint id); -- cgit v1.1 From 1dc23b2b9713f4099534ae0d08c2caf5c8b036b4 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Fri, 2 Nov 2012 10:35:12 -0700 Subject: BulletSim: parameterize selection of linkset implementation --- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 28 ++++++++++++++-------- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 5 ++++ .../Region/Physics/BulletSPlugin/BulletSimAPI.cs | 1 + 3 files changed, 24 insertions(+), 10 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index 8f973f4..3a92f93 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -36,21 +36,29 @@ public abstract class BSLinkset { // private static string LogHeader = "[BULLETSIM LINKSET]"; + public enum LinksetImplementation + { + Constraint = 0, // linkset tied together with constraints + Compound = 1, // linkset tied together as a compound object + Manual = 2 // linkset tied together manually (code moves all the pieces) + } // Create the correct type of linkset for this child public static BSLinkset Factory(BSScene physScene, BSPhysObject parent) { BSLinkset ret = null; - /* - if (parent.IsPhysical) - ret = new BSLinksetConstraints(physScene, parent); - else - ret = new BSLinksetManual(physScene, parent); - */ - - // at the moment, there is only one - // ret = new BSLinksetConstraints(physScene, parent); - ret = new BSLinksetCompound(physScene, parent); + switch ((int)physScene.Params.linksetImplementation) + { + case (int)LinksetImplementation.Compound: + ret = new BSLinksetCompound(physScene, parent); + break; + case (int)LinksetImplementation.Manual: + // ret = new BSLinksetManual(physScene, parent); + break; + default: + ret = new BSLinksetConstraints(physScene, parent); + break; + } return ret; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index dcfcb83..13aa860 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -1214,6 +1214,11 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters (s) => { return s.m_params[0].numberOfSolverIterations; }, (s,p,l,v) => { s.m_params[0].numberOfSolverIterations = v; } ), + new ParameterDefn("LinksetImplementation", "Type of linkset implementation (0=Constraint, 1=Compound)", + (float)BSLinkset.LinksetImplementation.Constraint, + (s,cf,p,v) => { s.m_params[0].linksetImplementation = cf.GetFloat(p,v); }, + (s) => { return s.m_params[0].linksetImplementation; }, + (s,p,l,v) => { s.m_params[0].linksetImplementation = v; } ), new ParameterDefn("LinkConstraintUseFrameOffset", "For linksets built with constraints, enable frame offsetFor linksets built with constraints, enable frame offset.", ConfigurationParameters.numericFalse, (s,cf,p,v) => { s.m_params[0].linkConstraintUseFrameOffset = s.NumericBool(cf.GetBoolean(p, s.BoolNumeric(v))); }, diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs index 143b8be..ac6d2b2 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs @@ -300,6 +300,7 @@ public struct ConfigurationParameters public float shouldEnableFrictionCaching; public float numberOfSolverIterations; + public float linksetImplementation; public float linkConstraintUseFrameOffset; public float linkConstraintEnableTransMotor; public float linkConstraintTransMotorMaxVel; -- cgit v1.1 From 498ea76e637961d8b4e3d39b758f7f2dea2fe998 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Fri, 2 Nov 2012 17:22:34 -0700 Subject: BulletSim: Move construction of compound linkset from ShapeCollection into LinksetCompound where it should be. Create meshes for native shapes when part of a compound linkset because scale is currently per object and not per collision shape. Don't schedule a LinksetCompound refresh if just changing properties. --- .../Physics/BulletSPlugin/BSLinksetCompound.cs | 72 ++++++++++++++---- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 24 +++++- .../Physics/BulletSPlugin/BSShapeCollection.cs | 85 +++++++++++----------- 3 files changed, 120 insertions(+), 61 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs index 8b97ebb..adf4aff 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs @@ -34,7 +34,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin { public sealed class BSLinksetCompound : BSLinkset { - // private static string LogHeader = "[BULLETSIM LINKSET CONSTRAINTS]"; + private static string LogHeader = "[BULLETSIM LINKSET COMPOUND]"; public BSLinksetCompound(BSScene scene, BSPhysObject parent) { @@ -59,6 +59,12 @@ public sealed class BSLinksetCompound : BSLinkset // refresh will happen once after all the other taints are applied. public override void Refresh(BSPhysObject requestor) { + // External request for Refresh (from BSPrim) is not necessary + // InternalRefresh(requestor); + } + + private void InternalRefresh(BSPhysObject requestor) + { DetailLog("{0},BSLinksetCompound.Refresh,schedulingRefresh,requestor={1}", LinksetRoot.LocalID, requestor.LocalID); // Queue to happen after all the other taint processing PhysicsScene.PostTaintObject("BSLinksetCompound.Refresh", requestor.LocalID, delegate() @@ -135,13 +141,13 @@ public sealed class BSLinksetCompound : BSLinkset { bool ret = false; - DetailLog("{0},BSLinksetCompound.RemoveBodyDependencies,removeChildrenForRoot,rID={1},rBody={2},isRoot={3}", - child.LocalID, LinksetRoot.LocalID, LinksetRoot.PhysBody.ptr.ToString("X"), IsRoot(child)); + DetailLog("{0},BSLinksetCompound.RemoveBodyDependencies,refreshIfChild,rID={1},rBody={2},isRoot={3}", + child.LocalID, LinksetRoot.LocalID, LinksetRoot.PhysBody.ptr.ToString("X"), IsRoot(child)); if (!IsRoot(child)) { // Cause the current shape to be freed and the new one to be built. - Refresh(LinksetRoot); + InternalRefresh(LinksetRoot); ret = true; } @@ -169,7 +175,7 @@ public sealed class BSLinksetCompound : BSLinkset DetailLog("{0},BSLinksetCompound.AddChildToLinkset,call,child={1}", LinksetRoot.LocalID, child.LocalID); // Cause constraints and assorted properties to be recomputed before the next simulation step. - Refresh(LinksetRoot); + InternalRefresh(LinksetRoot); } return; } @@ -196,34 +202,68 @@ public sealed class BSLinksetCompound : BSLinkset else { // Schedule a rebuild of the linkset before the next simulation tick. - Refresh(LinksetRoot); + InternalRefresh(LinksetRoot); } } return; } - - // Call each of the constraints that make up this linkset and recompute the - // various transforms and variables. Create constraints of not created yet. - // Called before the simulation step to make sure the constraint based linkset + // Called before the simulation step to make sure the compound based linkset // is all initialized. + // 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 void RecomputeLinksetCompound() { - DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,start,rBody={1},numChildren={2}", - LinksetRoot.LocalID, LinksetRoot.PhysBody.ptr.ToString("X"), NumberOfChildren); - + // Cause the root shape to be rebuilt as a compound object with just the root in it LinksetRoot.ForceBodyShapeRebuild(true); + DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,start,rBody={1},rShape={2},numChildren={3}", + LinksetRoot.LocalID, LinksetRoot.PhysBody, LinksetRoot.PhysShape, NumberOfChildren); + + ForEachMember(delegate(BSPhysObject cPrim) + { + if (!IsRoot(cPrim)) + { + OMV.Quaternion invRootOrientation = OMV.Quaternion.Inverse(LinksetRoot.RawOrientation); + OMV.Vector3 displacementPos = (cPrim.RawPosition - LinksetRoot.RawPosition) * invRootOrientation; + OMV.Quaternion displacementRot = cPrim.RawOrientation * invRootOrientation; + + DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,addMemberToShape,mID={1},mShape={2},dispPos={3},dispRot={4}", + LinksetRoot.LocalID, cPrim.LocalID, cPrim.PhysShape, displacementPos, displacementRot); + + if (cPrim.PhysShape.isNativeShape) + { + // Native shapes are not shared so we need to create a new one. + // A mesh or hull is created because scale is not available on a native shape. + // (TODO: Bullet does have a btScaledCollisionShape. Can that be used?) + BulletShape saveShape = cPrim.PhysShape; + PhysicsScene.Shapes.CreateGeomMeshOrHull(cPrim, null); + BulletShape newShape = cPrim.PhysShape; + cPrim.PhysShape = saveShape; + BulletSimAPI.AddChildShapeToCompoundShape2(LinksetRoot.PhysShape.ptr, newShape.ptr, displacementPos, displacementRot); + } + else + { + // For the shared shapes (meshes and hulls) just use the shape in the child + 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); + } + BulletSimAPI.AddChildShapeToCompoundShape2(LinksetRoot.PhysShape.ptr, cPrim.PhysShape.ptr, displacementPos, displacementRot); + } + } + return false; + }); + + float linksetMass = LinksetMass; LinksetRoot.UpdatePhysicalMassProperties(linksetMass); // DEBUG: see of inter-linkset collisions are causing problems // BulletSimAPI.SetCollisionFilterMask2(LinksetRoot.BSBody.ptr, // (uint)CollisionFilterGroups.LinksetFilter, (uint)CollisionFilterGroups.LinksetMask); - DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,end,rBody={1},linksetMass={2}", - LinksetRoot.LocalID, LinksetRoot.PhysBody.ptr.ToString("X"), linksetMass); - } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index 13aa860..de35359 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -116,6 +116,10 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters // True if initialized and ready to do simulation steps private bool m_initialized = false; + // Flag which is true when processing taints. + // Not guaranteed to be correct all the time (don't depend on this) but good for debugging. + public bool InTaintTime { get; private set; } + // Pinned memory used to pass step information between managed and unmanaged private int m_maxCollisionsPerFrame; private CollisionDesc[] m_collisionArray; @@ -270,6 +274,9 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters TerrainManager = new BSTerrainManager(this); TerrainManager.CreateInitialGroundPlaneAndTerrain(); + m_log.WarnFormat("{0} Linksets implemented with {1}", LogHeader, (BSLinkset.LinksetImplementation)Params.linksetImplementation); + + InTaintTime = false; m_initialized = true; } @@ -707,8 +714,10 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters // here just before the physics engine is called to step the simulation. public void ProcessTaints() { + InTaintTime = true; ProcessRegularTaints(); ProcessPostTaintTaints(); + InTaintTime = false; } private void ProcessRegularTaints() @@ -851,6 +860,17 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters } } + public bool AssertInTaintTime(string whereFrom) + { + if (!InTaintTime) + { + DetailLog("{0},BSScene.AssertInTaintTime,NOT IN TAINT TIME,Region={1},Where={2}", DetailLogZero, RegionName, whereFrom); + m_log.ErrorFormat("{0} NOT IN TAINT TIME!! Region={1}, Where={2}", LogHeader, RegionName, whereFrom); + Util.PrintCallStack(); + } + return InTaintTime; + } + #endregion // Taints #region Vehicles @@ -1214,8 +1234,8 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters (s) => { return s.m_params[0].numberOfSolverIterations; }, (s,p,l,v) => { s.m_params[0].numberOfSolverIterations = v; } ), - new ParameterDefn("LinksetImplementation", "Type of linkset implementation (0=Constraint, 1=Compound)", - (float)BSLinkset.LinksetImplementation.Constraint, + new ParameterDefn("LinksetImplementation", "Type of linkset implementation (0=Constraint, 1=Compound, 2=Manual)", + (float)BSLinkset.LinksetImplementation.Compound, (s,cf,p,v) => { s.m_params[0].linksetImplementation = cf.GetFloat(p,v); }, (s) => { return s.m_params[0].linksetImplementation; }, (s,p,l,v) => { s.m_params[0].linksetImplementation = v; } ), diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index 107befe..662b19d 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -92,6 +92,8 @@ public sealed class BSShapeCollection : IDisposable public bool GetBodyAndShape(bool forceRebuild, BulletSim sim, BSPhysObject prim, ShapeDestructionCallback shapeCallback, BodyDestructionCallback bodyCallback) { + PhysicsScene.AssertInTaintTime("BSShapeCollection.GetBodyAndShape"); + bool ret = false; // This lock could probably be pushed down lower but building shouldn't take long @@ -121,7 +123,7 @@ public sealed class BSShapeCollection : IDisposable { lock (m_collectionActivityLock) { - DetailLog("{0},BSShapeCollection.ReferenceBody,newBody", body.ID, body); + DetailLog("{0},BSShapeCollection.ReferenceBody,newBody,body={1}", body.ID, body); PhysicsScene.TaintedObject(inTaintTime, "BSShapeCollection.ReferenceBody", delegate() { if (!BulletSimAPI.IsInWorld2(body.ptr)) @@ -165,7 +167,7 @@ public sealed class BSShapeCollection : IDisposable // 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. - private bool ReferenceShape(BulletShape shape) + public bool ReferenceShape(BulletShape shape) { bool ret = false; switch (shape.type) @@ -276,8 +278,8 @@ public sealed class BSShapeCollection : IDisposable if (shapeCallback != null) shapeCallback(shape); meshDesc.lastReferenced = System.DateTime.Now; Meshes[shape.shapeKey] = meshDesc; - DetailLog("{0},BSShapeCollection.DereferenceMesh,key={1},refCnt={2}", - BSScene.DetailLogZero, shape.shapeKey.ToString("X"), meshDesc.referenceCount); + DetailLog("{0},BSShapeCollection.DereferenceMesh,shape={1},refCnt={2}", + BSScene.DetailLogZero, shape, meshDesc.referenceCount); } } @@ -297,8 +299,8 @@ public sealed class BSShapeCollection : IDisposable hullDesc.lastReferenced = System.DateTime.Now; Hulls[shape.shapeKey] = hullDesc; - DetailLog("{0},BSShapeCollection.DereferenceHull,key={1},refCnt={2}", - BSScene.DetailLogZero, shape.shapeKey.ToString("X"), hullDesc.referenceCount); + DetailLog("{0},BSShapeCollection.DereferenceHull,shape={1},refCnt={2}", + BSScene.DetailLogZero, shape, hullDesc.referenceCount); } } @@ -319,8 +321,11 @@ public sealed class BSShapeCollection : IDisposable BSScene.DetailLogZero, shape.type, shape.ptr.ToString("X")); return; } + int numChildren = BulletSimAPI.GetNumberOfCompoundChildren2(shape.ptr); - for (int ii = 0; ii < numChildren; ii++) + DetailLog("{0},BSShapeCollection.DereferenceCompound,shape={1},children={2}", BSScene.DetailLogZero, shape, numChildren); + + for (int ii = numChildren - 1; ii >= 0; ii--) { IntPtr childShape = BulletSimAPI.RemoveChildShapeFromCompoundShapeIndex2(shape.ptr, ii); DereferenceAnonCollisionShape(childShape); @@ -343,6 +348,7 @@ public sealed class BSShapeCollection : IDisposable shapeInfo.isNativeShape = true; shapeInfo.type = ShapeData.PhysicsShapeType.SHAPE_BOX; // (technically, type doesn't matter) } + DetailLog("{0},BSShapeCollection.DereferenceAnonCollisionShape,shape={1}", BSScene.DetailLogZero, shapeInfo); DereferenceShape(shapeInfo, true, null); } @@ -440,23 +446,32 @@ public sealed class BSShapeCollection : IDisposable } // If a simple shape is not happening, create a mesh and possibly a hull. + if (!haveShape && pbs != null) + { + ret = CreateGeomMeshOrHull(prim, shapeCallback); + } + + return ret; + } + + public bool CreateGeomMeshOrHull(BSPhysObject prim, ShapeDestructionCallback shapeCallback) + { + + bool ret = false; // Note that if it's a native shape, the check for physical/non-physical is not // made. Native shapes work in either case. - if (!haveShape && pbs != null) + if (prim.IsPhysical && PhysicsScene.ShouldUseHullsForPhysicalObjects) { - if (prim.IsPhysical && PhysicsScene.ShouldUseHullsForPhysicalObjects) - { - // Update prim.BSShape to reference a hull of this shape. - ret = GetReferenceToHull(prim,shapeCallback); - DetailLog("{0},BSShapeCollection.CreateGeom,hull,shape={1},key={2}", - prim.LocalID, prim.PhysShape, prim.PhysShape.shapeKey.ToString("X")); - } - else - { - ret = GetReferenceToMesh(prim, shapeCallback); - DetailLog("{0},BSShapeCollection.CreateGeom,mesh,shape={1},key={2}", - prim.LocalID, prim.PhysShape, prim.PhysShape.shapeKey.ToString("X")); - } + // Update prim.BSShape to reference a hull of this shape. + ret = GetReferenceToHull(prim,shapeCallback); + DetailLog("{0},BSShapeCollection.CreateGeom,hull,shape={1},key={2}", + prim.LocalID, prim.PhysShape, prim.PhysShape.shapeKey.ToString("X")); + } + else + { + ret = GetReferenceToMesh(prim, shapeCallback); + DetailLog("{0},BSShapeCollection.CreateGeom,mesh,shape={1},key={2}", + prim.LocalID, prim.PhysShape, prim.PhysShape.shapeKey.ToString("X")); } return ret; } @@ -743,32 +758,16 @@ public sealed class BSShapeCollection : IDisposable // 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 we create the new root shape below. + // DereferenceShape(prim.PhysShape, true, shapeCallback); + BulletShape cShape = new BulletShape( BulletSimAPI.CreateCompoundShape2(PhysicsScene.World.ptr), ShapeData.PhysicsShapeType.SHAPE_COMPOUND); - // The prim's linkset is the source of the children. - // TODO: there is too much knowledge here about the internals of linksets and too much - // dependency on the relationship of compound shapes and linksets (what if we want to use - // compound shapes for something else?). Think through this and clean up so the - // appropriate knowledge is used at the correct software levels. - - // Recreate the geometry of the root prim (might have been a linkset root in the past) + // Create the shape for the root prim and add it to the compound shape CreateGeomNonSpecial(true, prim, null); - - BSPhysObject rootPrim = prim.Linkset.LinksetRoot; - - prim.Linkset.ForEachMember(delegate(BSPhysObject cPrim) - { - OMV.Quaternion invRootOrientation = OMV.Quaternion.Inverse(rootPrim.RawOrientation); - OMV.Vector3 displacementPos = (cPrim.RawPosition - rootPrim.RawPosition) * invRootOrientation; - OMV.Quaternion displacementRot = cPrim.RawOrientation * invRootOrientation; - - DetailLog("{0},BSShapeCollection.GetReferenceToCompoundShape,addMemberToShape,mID={1},mShape={2},dispPos={3},dispRot={4}", - prim.LocalID, cPrim.LocalID, cPrim.PhysShape.ptr.ToString("X"), displacementPos, displacementRot); - - BulletSimAPI.AddChildShapeToCompoundShape2(cShape.ptr, cPrim.PhysShape.ptr, displacementPos, displacementRot); - return false; - }); + BulletSimAPI.AddChildShapeToCompoundShape2(cShape.ptr, prim.PhysShape.ptr, OMV.Vector3.Zero, OMV.Quaternion.Identity); prim.PhysShape = cShape; -- cgit v1.1 From 894bb4893b8bb269f8561737e4603a9b31183f2c Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Sat, 3 Nov 2012 18:26:00 -0700 Subject: BulletSim: search the mesh and hull lists to find shapes if type is not known. This makes sure the correct accounting is done for the particular shape. --- .../Physics/BulletSPlugin/BSLinksetCompound.cs | 10 +- .../Physics/BulletSPlugin/BSLinksetConstraints.cs | 2 +- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 2 +- .../Physics/BulletSPlugin/BSShapeCollection.cs | 102 ++++++++++++++++++--- 4 files changed, 96 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 adf4aff..6e68695 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs @@ -134,7 +134,7 @@ public sealed class BSLinksetCompound : BSLinkset } // Routine called when rebuilding the body of some member of the linkset. - // Since we don't keep in-physical world relationships, do nothing unless it's a child changing. + // 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(BSPrim child) @@ -221,10 +221,12 @@ public sealed class BSLinksetCompound : BSLinkset DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,start,rBody={1},rShape={2},numChildren={3}", LinksetRoot.LocalID, LinksetRoot.PhysBody, LinksetRoot.PhysShape, NumberOfChildren); + // Add a shape for each of the other children in the linkset ForEachMember(delegate(BSPhysObject cPrim) { if (!IsRoot(cPrim)) { + // Each child position and rotation is given relative to the root. OMV.Quaternion invRootOrientation = OMV.Quaternion.Inverse(LinksetRoot.RawOrientation); OMV.Vector3 displacementPos = (cPrim.RawPosition - LinksetRoot.RawPosition) * invRootOrientation; OMV.Quaternion displacementRot = cPrim.RawOrientation * invRootOrientation; @@ -245,7 +247,7 @@ public sealed class BSLinksetCompound : BSLinkset } else { - // For the shared shapes (meshes and hulls) just use the shape in the child + // For the shared shapes (meshes and hulls), just use the shape in the child. if (PhysicsScene.Shapes.ReferenceShape(cPrim.PhysShape)) { PhysicsScene.Logger.ErrorFormat("{0} Rebuilt sharable shape when building linkset! Region={1}, primID={2}, shape={3}", @@ -254,10 +256,10 @@ public sealed class BSLinksetCompound : BSLinkset BulletSimAPI.AddChildShapeToCompoundShape2(LinksetRoot.PhysShape.ptr, cPrim.PhysShape.ptr, displacementPos, displacementRot); } } - return false; + return false; // 'false' says to move onto the next child in the list }); - + // With all of the linkset packed into the root prim, it has the mass of everyone. float linksetMass = LinksetMass; LinksetRoot.UpdatePhysicalMassProperties(linksetMass); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs index 67a59ef..d2387fb 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs @@ -294,7 +294,7 @@ public sealed class BSLinksetConstraints : BSLinkset float linksetMass = LinksetMass; LinksetRoot.UpdatePhysicalMassProperties(linksetMass); - // DEBUG: see of inter-linkset collisions are causing problems + // DEBUG: see of inter-linkset collisions are causing problems // BulletSimAPI.SetCollisionFilterMask2(LinksetRoot.BSBody.ptr, // (uint)CollisionFilterGroups.LinksetFilter, (uint)CollisionFilterGroups.LinksetMask); DetailLog("{0},BSLinksetConstraint.RecomputeLinksetConstraints,set,rBody={1},linksetMass={2}", diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index de35359..c2e0ef1 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -1472,7 +1472,7 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters public void DetailLog(string msg, params Object[] args) { PhysicsLogging.Write(msg, args); - // Add the Flush() if debugging crashes to get all the messages written out. + // Add the Flush() if debugging crashes. Gets all the messages written out. PhysicsLogging.Flush(); } // Used to fill in the LocalID when there isn't one. It's the correct number of characters. diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index 662b19d..4a31c7d 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -48,6 +48,7 @@ public sealed class BSShapeCollection : IDisposable public IntPtr ptr; public int referenceCount; public DateTime lastReferenced; + public UInt64 shapeKey; } // Description of a hull. @@ -57,6 +58,7 @@ public sealed class BSShapeCollection : IDisposable public IntPtr ptr; public int referenceCount; public DateTime lastReferenced; + public UInt64 shapeKey; } // The sharable set of meshes and hulls. Indexed by their shape hash. @@ -116,7 +118,7 @@ public sealed class BSShapeCollection : IDisposable return ret; } - // Track another user of a body + // 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. public void ReferenceBody(BulletBody body, bool inTaintTime) @@ -146,13 +148,16 @@ public sealed class BSShapeCollection : IDisposable { PhysicsScene.TaintedObject(inTaintTime, "BSShapeCollection.DereferenceBody", delegate() { - DetailLog("{0},BSShapeCollection.DereferenceBody,DestroyingBody. ptr={1}, inTaintTime={2}", - body.ID, body.ptr.ToString("X"), inTaintTime); + DetailLog("{0},BSShapeCollection.DereferenceBody,DestroyingBody,body={1},inTaintTime={2}", + body.ID, body, inTaintTime); // If the caller needs to know the old body is going away, pass the event up. if (bodyCallback != null) bodyCallback(body); - // It may have already been removed from the world in which case the next is a NOOP. - BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.ptr, body.ptr); + if (BulletSimAPI.IsInWorld2(body.ptr)) + { + BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.ptr, body.ptr); + DetailLog("{0},BSShapeCollection.DereferenceBody,removingFromWorld. Body={1}", body.ID, body); + } // Zero any reference to the shape so it is not freed when the body is deleted. BulletSimAPI.SetCollisionShape2(PhysicsScene.World.ptr, body.ptr, IntPtr.Zero); @@ -185,6 +190,7 @@ public sealed class BSShapeCollection : IDisposable { // This is a new reference to a mesh meshDesc.ptr = shape.ptr; + meshDesc.shapeKey = shape.shapeKey; // We keep a reference to the underlying IMesh data so a hull can be built meshDesc.referenceCount = 1; DetailLog("{0},BSShapeCollection.ReferenceShape,newMesh,key={1},cnt={2}", @@ -207,6 +213,7 @@ public sealed class BSShapeCollection : IDisposable { // This is a new reference to a hull hullDesc.ptr = shape.ptr; + hullDesc.shapeKey = shape.shapeKey; hullDesc.referenceCount = 1; DetailLog("{0},BSShapeCollection.ReferenceShape,newHull,key={1},cnt={2}", BSScene.DetailLogZero, shape.shapeKey.ToString("X"), hullDesc.referenceCount); @@ -306,7 +313,7 @@ public sealed class BSShapeCollection : IDisposable // Remove a reference to a compound shape. // Taking a compound shape apart is a little tricky because if you just delete the - // physical object, it will free all the underlying children. We can't do that because + // 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. @@ -335,22 +342,53 @@ public sealed class BSShapeCollection : IDisposable // 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. - // This is coming from a compound shape that we created so we know it is either native or mesh. // Called at taint-time. private void DereferenceAnonCollisionShape(IntPtr cShape) { - BulletShape shapeInfo = new BulletShape(cShape, ShapeData.PhysicsShapeType.SHAPE_MESH); - if (BulletSimAPI.IsCompound2(cShape)) - shapeInfo.type = ShapeData.PhysicsShapeType.SHAPE_COMPOUND; + MeshDesc meshDesc; + HullDesc hullDesc; - if (BulletSimAPI.IsNativeShape2(cShape)) + BulletShape shapeInfo = new BulletShape(cShape); + if (TryGetMeshByPtr(cShape, out meshDesc)) + { + shapeInfo.type = ShapeData.PhysicsShapeType.SHAPE_MESH; + shapeInfo.shapeKey = meshDesc.shapeKey; + } + else { - shapeInfo.isNativeShape = true; - shapeInfo.type = ShapeData.PhysicsShapeType.SHAPE_BOX; // (technically, type doesn't matter) + if (TryGetHullByPtr(cShape, out hullDesc)) + { + shapeInfo.type = ShapeData.PhysicsShapeType.SHAPE_HULL; + shapeInfo.shapeKey = hullDesc.shapeKey; + } + else + { + if (BulletSimAPI.IsCompound2(cShape)) + { + shapeInfo.type = ShapeData.PhysicsShapeType.SHAPE_COMPOUND; + } + else + { + if (BulletSimAPI.IsNativeShape2(cShape)) + { + shapeInfo.isNativeShape = true; + shapeInfo.type = ShapeData.PhysicsShapeType.SHAPE_BOX; // (technically, type doesn't matter) + } + } + } } + DetailLog("{0},BSShapeCollection.DereferenceAnonCollisionShape,shape={1}", BSScene.DetailLogZero, shapeInfo); - DereferenceShape(shapeInfo, true, null); + if (shapeInfo.type != ShapeData.PhysicsShapeType.SHAPE_UNKNOWN) + { + DereferenceShape(shapeInfo, true, null); + } + else + { + PhysicsScene.Logger.ErrorFormat("{0} Could not decypher shape type. Region={1}, addr={2}", + LogHeader, PhysicsScene.RegionName, cShape.ToString("X")); + } } // Create the geometry information in Bullet for later use. @@ -913,6 +951,42 @@ public sealed class BSShapeCollection : IDisposable return ret; } + private bool TryGetMeshByPtr(IntPtr addr, out MeshDesc outDesc) + { + bool ret = false; + MeshDesc foundDesc = new MeshDesc(); + foreach (MeshDesc md in Meshes.Values) + { + if (md.ptr == addr) + { + foundDesc = md; + ret = true; + break; + } + + } + outDesc = foundDesc; + return ret; + } + + private bool TryGetHullByPtr(IntPtr addr, out HullDesc outDesc) + { + bool ret = false; + HullDesc foundDesc = new HullDesc(); + foreach (HullDesc hd in Hulls.Values) + { + if (hd.ptr == addr) + { + foundDesc = hd; + ret = true; + break; + } + + } + outDesc = foundDesc; + return ret; + } + private void DetailLog(string msg, params Object[] args) { if (PhysicsScene.PhysicsLogging.Enabled) -- cgit v1.1 From 79f7c466a116bf368423d4e18163f34fd8d66ce1 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Sat, 3 Nov 2012 21:08:39 -0700 Subject: BulletSim: fix compound linkset crash by not freeing shape of child prims. Remove all compilation warnings (mostly 'protected' in sealed classes.) Add the dynamicAabbEnable parameter to creation of compound shapes. --- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 6 +++--- .../Region/Physics/BulletSPlugin/BSLinksetCompound.cs | 11 ++++++----- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 3 +++ OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 4 ++-- .../Region/Physics/BulletSPlugin/BSShapeCollection.cs | 16 ++++++++++------ OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs | 2 +- 6 files changed, 25 insertions(+), 17 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index 38609e3..819635a 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -89,7 +89,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin //Angular properties private Vector3 m_angularMotorDirection = Vector3.Zero; // angular velocity requested by LSL motor - private int m_angularMotorApply = 0; // application frame counter + // private int m_angularMotorApply = 0; // application frame counter private Vector3 m_angularMotorVelocity = Vector3.Zero; // current angular motor velocity private float m_angularMotorTimescale = 0; // motor angular velocity ramp up rate private float m_angularMotorDecayTimescale = 0; // motor angular velocity decay rate @@ -199,7 +199,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin break; case Vehicle.ANGULAR_MOTOR_DIRECTION: m_angularMotorDirection = new Vector3(pValue, pValue, pValue); - m_angularMotorApply = 100; + // m_angularMotorApply = 100; break; case Vehicle.LINEAR_FRICTION_TIMESCALE: m_linearFrictionTimescale = new Vector3(pValue, pValue, pValue); @@ -229,7 +229,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin pValue.Y = Math.Max(-12.56f, Math.Min(pValue.Y, 12.56f)); pValue.Z = Math.Max(-12.56f, Math.Min(pValue.Z, 12.56f)); m_angularMotorDirection = new Vector3(pValue.X, pValue.Y, pValue.Z); - m_angularMotorApply = 100; + // m_angularMotorApply = 100; break; case Vehicle.LINEAR_FRICTION_TIMESCALE: m_linearFrictionTimescale = new Vector3(pValue.X, pValue.Y, pValue.Z); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs index 6e68695..12c6d7a 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs @@ -83,8 +83,8 @@ public sealed class BSLinksetCompound : BSLinkset public override bool MakeDynamic(BSPhysObject child) { bool ret = false; - DetailLog("{0},BSLinksetCompound.MakeDynamic,call,isChild={1}", child.LocalID, HasChild(child)); - if (HasChild(child)) + DetailLog("{0},BSLinksetCompound.MakeDynamic,call,IsRoot={1}", child.LocalID, IsRoot(child)); + if (!IsRoot(child)) { // Physical children are removed from the world as the shape ofthe root compound // shape takes over. @@ -103,8 +103,8 @@ public sealed class BSLinksetCompound : BSLinkset public override bool MakeStatic(BSPhysObject child) { bool ret = false; - DetailLog("{0},BSLinksetCompound.MakeStatic,call,hasChild={1}", child.LocalID, HasChild(child)); - if (HasChild(child)) + DetailLog("{0},BSLinksetCompound.MakeStatic,call,IsRoot={1}", child.LocalID, IsRoot(child)); + if (!IsRoot(child)) { // The non-physical children can come back to life. BulletSimAPI.RemoveFromCollisionFlags2(child.PhysBody.ptr, CollisionFlags.CF_NO_CONTACT_RESPONSE); @@ -240,6 +240,7 @@ public sealed class BSLinksetCompound : BSLinkset // A mesh or hull is created because scale is not available on a native shape. // (TODO: Bullet does have a btScaledCollisionShape. Can that be used?) BulletShape saveShape = cPrim.PhysShape; + cPrim.PhysShape.ptr = IntPtr.Zero; // Don't let the create free the child's shape PhysicsScene.Shapes.CreateGeomMeshOrHull(cPrim, null); BulletShape newShape = cPrim.PhysShape; cPrim.PhysShape = saveShape; @@ -263,7 +264,7 @@ public sealed class BSLinksetCompound : BSLinkset float linksetMass = LinksetMass; LinksetRoot.UpdatePhysicalMassProperties(linksetMass); - // DEBUG: see of inter-linkset collisions are causing problems + // DEBUG: see of inter-linkset collisions are causing problems for constraint linksets. // BulletSimAPI.SetCollisionFilterMask2(LinksetRoot.BSBody.ptr, // (uint)CollisionFilterGroups.LinksetFilter, (uint)CollisionFilterGroups.LinksetMask); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index af403aa..aaa0d93 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -703,6 +703,9 @@ public sealed class BSPrim : BSPhysObject // For good measure, make sure the transform is set through to the motion state BulletSimAPI.SetTranslation2(PhysBody.ptr, _position, _orientation); + // Center of mass is at the center of the object + BulletSimAPI.SetCenterOfMassByPosRot2(Linkset.LinksetRoot.PhysBody.ptr, _position, _orientation); + // A dynamic object has mass UpdatePhysicalMassProperties(RawMass); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index c2e0ef1..740f339 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -1391,7 +1391,7 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters // If the local ID is APPLY_TO_NONE, just change the default value // If the localID is APPLY_TO_ALL change the default value and apply the new value to all the lIDs // If the localID is a specific object, apply the parameter change to only that object - protected void UpdateParameterObject(ref float defaultLoc, string parm, uint localID, float val) + private void UpdateParameterObject(ref float defaultLoc, string parm, uint localID, float val) { List objectIDs = new List(); switch (localID) @@ -1416,7 +1416,7 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters } // schedule the actual updating of the paramter to when the phys engine is not busy - protected void TaintedUpdateParameter(string parm, List lIDs, float val) + private void TaintedUpdateParameter(string parm, List lIDs, float val) { float xval = val; List xlIDs = lIDs; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index 4a31c7d..29a23c0 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -38,7 +38,7 @@ public sealed class BSShapeCollection : IDisposable { private static string LogHeader = "[BULLETSIM SHAPE COLLECTION]"; - protected BSScene PhysicsScene { get; set; } + private BSScene PhysicsScene { get; set; } private Object m_collectionActivityLock = new Object(); @@ -103,11 +103,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. - // CreateGeom returns 'true' of BSShape as changed to a new shape. + // Returns 'true' of BSShape is changed to a new shape. bool newGeom = CreateGeom(forceRebuild, prim, shapeCallback); // 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, prim.PhysShape, bodyCallback); ret = newGeom || newBody; @@ -431,6 +432,7 @@ public sealed class BSShapeCollection : IDisposable return ret; } + // Create a mesh/hull shape or a native shape if 'nativeShapePossible' is 'true'. private bool CreateGeomNonSpecial(bool forceRebuild, BSPhysObject prim, ShapeDestructionCallback shapeCallback) { bool ret = false; @@ -797,15 +799,17 @@ public sealed class BSShapeCollection : IDisposable 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 we create the new root shape below. + // 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 = new BulletShape( - BulletSimAPI.CreateCompoundShape2(PhysicsScene.World.ptr), ShapeData.PhysicsShapeType.SHAPE_COMPOUND); + BulletSimAPI.CreateCompoundShape2(PhysicsScene.World.ptr, false), ShapeData.PhysicsShapeType.SHAPE_COMPOUND); - // Create the shape for the root prim and add it to the compound shape - CreateGeomNonSpecial(true, prim, null); + // Create the shape for the root prim and add it to the compound shape. Cannot be a native shape. + CreateGeomMeshOrHull(prim, shapeCallback); BulletSimAPI.AddChildShapeToCompoundShape2(cShape.ptr, prim.PhysShape.ptr, OMV.Vector3.Zero, OMV.Quaternion.Identity); + DetailLog("{0},BSShapeCollection.GetReferenceToCompoundShape,addRootPrim,compShape={1},rootShape={2}", + prim.LocalID, cShape, prim.PhysShape); prim.PhysShape = cShape; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs index ac6d2b2..702bd77 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs @@ -614,7 +614,7 @@ public static extern bool IsNativeShape2(IntPtr shape); public static extern IntPtr BuildCapsuleShape2(IntPtr world, float radius, float height, Vector3 scale); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern IntPtr CreateCompoundShape2(IntPtr sim); +public static extern IntPtr CreateCompoundShape2(IntPtr sim, bool enableDynamicAabbTree); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern int GetNumberOfCompoundChildren2(IntPtr cShape); -- cgit v1.1 From 36d77fe27c4a49127c5d5baa4ed4653a25f1726d Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 6 Nov 2012 12:04:55 -0800 Subject: BulletSim: Add separate linear and angular damping function calls. Add function for recalculating compound shape bounding box. --- OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs | 9 +++++++++ 1 file changed, 9 insertions(+) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs index 702bd77..07149d8 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs @@ -632,6 +632,9 @@ public static extern IntPtr RemoveChildShapeFromCompoundShapeIndex2(IntPtr cShap public static extern void RemoveChildShapeFromCompoundShape2(IntPtr cShape, IntPtr removeShape); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void RecalculateCompoundShapeLocalAabb2(IntPtr cShape); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern IntPtr DuplicateCollisionShape2(IntPtr sim, IntPtr srcShape, uint id); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] @@ -919,6 +922,12 @@ public static extern Vector3 GetGravity2(IntPtr obj); public static extern void SetDamping2(IntPtr obj, float lin_damping, float ang_damping); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void SetLinearDamping2(IntPtr obj, float lin_damping); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] +public static extern void SetAngularDamping2(IntPtr obj, float ang_damping); + +[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static extern float GetLinearDamping2(IntPtr obj); [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -- cgit v1.1 From 702fd1e09473cede1458eef7b2c50cd39149a9f3 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 6 Nov 2012 12:07:22 -0800 Subject: BulletSim: only compute linkset mass when membership changes rather than everytime someone asks for it. --- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 8 ++++++-- 1 file changed, 6 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 3a92f93..436e043 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -49,6 +49,9 @@ public abstract class BSLinkset switch ((int)physScene.Params.linksetImplementation) { + case (int)LinksetImplementation.Constraint: + ret = new BSLinksetConstraints(physScene, parent); + break; case (int)LinksetImplementation.Compound: ret = new BSLinksetCompound(physScene, parent); break; @@ -56,7 +59,7 @@ public abstract class BSLinkset // ret = new BSLinksetManual(physScene, parent); break; default: - ret = new BSLinksetConstraints(physScene, parent); + ret = new BSLinksetCompound(physScene, parent); break; } return ret; @@ -97,7 +100,6 @@ public abstract class BSLinkset { get { - m_mass = ComputeLinksetMass(); return m_mass; } } @@ -138,6 +140,7 @@ public abstract class BSLinkset // Don't add the root to its own linkset if (!IsRoot(child)) AddChildToLinkset(child); + m_mass = ComputeLinksetMass(); } return this; } @@ -156,6 +159,7 @@ public abstract class BSLinkset return this; } RemoveChildFromLinkset(child); + m_mass = ComputeLinksetMass(); } // The child is down to a linkset of just itself -- cgit v1.1 From f70a3099b539f046e4d206a3244a3170751060b1 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 6 Nov 2012 12:08:17 -0800 Subject: BulletSim: recalculate the compound shape bounding box when built. --- OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs | 2 ++ 1 file changed, 2 insertions(+) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs index 12c6d7a..3238c85 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs @@ -264,6 +264,8 @@ public sealed class BSLinksetCompound : BSLinkset float linksetMass = LinksetMass; LinksetRoot.UpdatePhysicalMassProperties(linksetMass); + BulletSimAPI.RecalculateCompoundShapeLocalAabb2(LinksetRoot.PhysShape.ptr); + // DEBUG: see of inter-linkset collisions are causing problems for constraint linksets. // BulletSimAPI.SetCollisionFilterMask2(LinksetRoot.BSBody.ptr, // (uint)CollisionFilterGroups.LinksetFilter, (uint)CollisionFilterGroups.LinksetMask); -- cgit v1.1 From e2130817e5c033ef671f0af512f568e422ec7887 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 6 Nov 2012 17:54:36 -0800 Subject: BulletSim: remove limit on taints that can happen before a step. Remove some debugging code (detail log flushing). --- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 28 ++++++++++++++----------- 1 file changed, 16 insertions(+), 12 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index 740f339..1cc607a 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -491,7 +491,6 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters // Some of the prims operate with special vehicle properties ProcessVehicles(timeStep); - numTaints += _taintOperations.Count; ProcessTaints(); // the vehicles might have added taints // step the physical world one interval @@ -500,7 +499,7 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters try { - // DumpVehicles(); // DEBUG + if (VehicleLoggingEnabled) DumpVehicles(); // DEBUG if (PhysicsLogging.Enabled) beforeTime = Util.EnvironmentTickCount(); numSubSteps = BulletSimAPI.PhysicsStep2(World.ptr, timeStep, m_maxSubSteps, m_fixedTimeStep, @@ -509,7 +508,7 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters if (PhysicsLogging.Enabled) simTime = Util.EnvironmentTickCountSubtract(beforeTime); DetailLog("{0},Simulate,call, frame={1}, nTaints={2}, simTime={3}, substeps={4}, updates={5}, colliders={6}", DetailLogZero, m_simulationStep, numTaints, simTime, numSubSteps, updatedEntityCount, collidersCount); - // DumpVehicles(); // DEBUG + if (VehicleLoggingEnabled) DumpVehicles(); // DEBUG } catch (Exception e) { @@ -521,7 +520,6 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters collidersCount = 0; } - // Don't have to use the pointers passed back since we know it is the same pinned memory we passed in // Get a value for 'now' so all the collision and update routines don't have to get their own @@ -724,6 +722,9 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters { if (_taintOperations.Count > 0) // save allocating new list if there is nothing to process { + /* + // Code to limit the number of taints processed per step. Meant to limit step time. + // Unsure if a good idea as code assumes that taints are done before the step. int taintCount = m_taintsToProcessPerStep; TaintCallbackEntry oneCallback = new TaintCallbackEntry(); while (_taintOperations.Count > 0 && taintCount-- > 0) @@ -752,13 +753,17 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters } } } - /* + if (_taintOperations.Count > 0) + { + DetailLog("{0},BSScene.ProcessTaints,leftTaintsOnList,numNotProcessed={1}", DetailLogZero, _taintOperations.Count); + } + */ // swizzle a new list into the list location so we can process what's there List oldList; lock (_taintLock) { - oldList = _taintedObjects; - _taintedObjects = new List(); + oldList = _taintOperations; + _taintOperations = new List(); } foreach (TaintCallbackEntry tcbe in oldList) @@ -774,7 +779,6 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters } } oldList.Clear(); - */ } } @@ -1043,7 +1047,7 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters (s) => { return (float)s.m_maxUpdatesPerFrame; }, (s,p,l,v) => { s.m_maxUpdatesPerFrame = (int)v; } ), new ParameterDefn("MaxTaintsToProcessPerStep", "Number of update taints to process before each simulation step", - 100f, + 500f, (s,cf,p,v) => { s.m_taintsToProcessPerStep = cf.GetInt(p, (int)v); }, (s) => { return (float)s.m_taintsToProcessPerStep; }, (s,p,l,v) => { s.m_taintsToProcessPerStep = (int)v; } ), @@ -1097,13 +1101,13 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters (s,cf,p,v) => { s.m_params[0].linearDamping = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].linearDamping; }, (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].linearDamping, p, l, v); }, - (s,o,v) => { BulletSimAPI.SetDamping2(o.PhysBody.ptr, v, v); } ), + (s,o,v) => { BulletSimAPI.SetDamping2(o.PhysBody.ptr, v, s.m_params[0].angularDamping); } ), new ParameterDefn("AngularDamping", "Factor to damp angular movement per second (0.0 - 1.0)", 0f, (s,cf,p,v) => { s.m_params[0].angularDamping = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].angularDamping; }, (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].angularDamping, p, l, v); }, - (s,o,v) => { BulletSimAPI.SetDamping2(o.PhysBody.ptr, v, v); } ), + (s,o,v) => { BulletSimAPI.SetDamping2(o.PhysBody.ptr, s.m_params[0].linearDamping, v); } ), new ParameterDefn("DeactivationTime", "Seconds before considering an object potentially static", 0.2f, (s,cf,p,v) => { s.m_params[0].deactivationTime = cf.GetFloat(p, v); }, @@ -1473,7 +1477,7 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters { PhysicsLogging.Write(msg, args); // Add the Flush() if debugging crashes. Gets all the messages written out. - PhysicsLogging.Flush(); + // 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 76cc3030314b3302da46bfe4078f076ba1b3d8a1 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 6 Nov 2012 17:58:55 -0800 Subject: BulletSim: Add ZeroAngularMotion method to physical objects. Add inTaint flag to ZeroMotion method. Update the references to those functions. --- .../Region/Physics/BulletSPlugin/BSCharacter.cs | 27 +++++++--- .../Physics/BulletSPlugin/BSLinksetConstraints.cs | 2 +- .../Region/Physics/BulletSPlugin/BSPhysObject.cs | 20 +++++-- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 61 ++++++++++++++++------ 4 files changed, 82 insertions(+), 28 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index 2a5397e..f33c124 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -103,7 +103,7 @@ public sealed class BSCharacter : BSPhysObject PhysicsScene.TaintedObject("BSCharacter.create", delegate() { DetailLog("{0},BSCharacter.create,taint", LocalID); - // New body and shape into BSBody and BSShape + // New body and shape into PhysBody and PhysShape PhysicsScene.Shapes.GetBodyAndShape(true, PhysicsScene.World, this, null, null); SetPhysicalProperties(); @@ -126,7 +126,7 @@ public sealed class BSCharacter : BSPhysObject { BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.ptr, PhysBody.ptr); - ZeroMotion(); + ZeroMotion(true); ForcePosition = _position; // Set the velocity and compute the proper friction ForceVelocity = _velocity; @@ -218,18 +218,31 @@ public sealed class BSCharacter : BSPhysObject // Do it to the properties so the values get set in the physics engine. // Push the setting of the values to the viewer. // Called at taint time! - public override void ZeroMotion() + public override void ZeroMotion(bool inTaintTime) { _velocity = OMV.Vector3.Zero; _acceleration = OMV.Vector3.Zero; _rotationalVelocity = OMV.Vector3.Zero; // Zero some other properties directly into the physics engine - BulletSimAPI.SetLinearVelocity2(PhysBody.ptr, OMV.Vector3.Zero); - BulletSimAPI.SetAngularVelocity2(PhysBody.ptr, OMV.Vector3.Zero); - BulletSimAPI.SetInterpolationVelocity2(PhysBody.ptr, OMV.Vector3.Zero, OMV.Vector3.Zero); - BulletSimAPI.ClearForces2(PhysBody.ptr); + PhysicsScene.TaintedObject(inTaintTime, "BSCharacter.ZeroMotion", delegate() + { + BulletSimAPI.ClearAllForces2(PhysBody.ptr); + }); } + public override void ZeroAngularMotion(bool inTaintTime) + { + _rotationalVelocity = OMV.Vector3.Zero; + + PhysicsScene.TaintedObject(inTaintTime, "BSCharacter.ZeroMotion", delegate() + { + BulletSimAPI.SetInterpolationAngularVelocity2(PhysBody.ptr, OMV.Vector3.Zero); + BulletSimAPI.SetAngularVelocity2(PhysBody.ptr, OMV.Vector3.Zero); + // The next also get rid of applied linear force but the linear velocity is untouched. + BulletSimAPI.ClearForces2(PhysBody.ptr); + }); + } + public override void LockAngularMotion(OMV.Vector3 axis) { return; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs index d2387fb..c855fda 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetConstraints.cs @@ -184,7 +184,7 @@ public sealed class BSLinksetConstraints : BSLinkset private BSConstraint BuildConstraint(BSPhysObject rootPrim, BSPhysObject childPrim) { // Zero motion for children so they don't interpolate - childPrim.ZeroMotion(); + childPrim.ZeroMotion(true); // Relative position normalized to the root prim // Essentually a vector pointing from center of rootPrim to center of childPrim diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index 7127aaf..e803072 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -34,9 +34,17 @@ using OpenSim.Region.Physics.Manager; 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. +/* + * 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 + * 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. + */ public abstract class BSPhysObject : PhysicsActor { protected void BaseInitialize(BSScene parentScene, uint localID, string name, string typeName) @@ -67,6 +75,9 @@ public abstract class BSPhysObject : PhysicsActor // Set the raw mass but also update physical mass properties (inertia, ...) public abstract void UpdatePhysicalMassProperties(float mass); + // The last value calculated for the prim's inertia + public OMV.Vector3 Inertia { get; set; } + // Reference to the physical body (btCollisionObject) of this object public BulletBody PhysBody; // Reference to the physical shape (btCollisionShape) of this object @@ -96,7 +107,8 @@ public abstract class BSPhysObject : PhysicsActor public abstract bool IsStatic { get; } // Stop all physical motion. - public abstract void ZeroMotion(); + public abstract void ZeroMotion(bool inTaintTime); + public abstract void ZeroAngularMotion(bool inTaintTime); // Step the vehicle simulation for this object. A NOOP if the vehicle was not configured. public virtual void StepVehicle(float timeStep) { } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index aaa0d93..14eb505 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -25,8 +25,6 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -// Uncomment this it enable code to do all shape an body memory management -// in the C# code. using System; using System.Reflection; using System.Collections.Generic; @@ -236,14 +234,27 @@ public sealed class BSPrim : BSPhysObject // Do it to the properties so the values get set in the physics engine. // Push the setting of the values to the viewer. // Called at taint time! - public override void ZeroMotion() + public override void ZeroMotion(bool inTaintTime) { _velocity = OMV.Vector3.Zero; _acceleration = OMV.Vector3.Zero; _rotationalVelocity = OMV.Vector3.Zero; // Zero some other properties in the physics engine - BulletSimAPI.ClearAllForces2(PhysBody.ptr); + PhysicsScene.TaintedObject(inTaintTime, "BSPrim.ZeroMotion", delegate() + { + BulletSimAPI.ClearAllForces2(PhysBody.ptr); + }); + } + public override void ZeroAngularMotion(bool inTaintTime) + { + _rotationalVelocity = OMV.Vector3.Zero; + // Zero some other properties in the physics engine + PhysicsScene.TaintedObject(inTaintTime, "BSPrim.ZeroMotion", delegate() + { + BulletSimAPI.SetInterpolationAngularVelocity2(PhysBody.ptr, OMV.Vector3.Zero); + BulletSimAPI.SetAngularVelocity2(PhysBody.ptr, OMV.Vector3.Zero); + }); } public override void LockAngularMotion(OMV.Vector3 axis) @@ -371,17 +382,18 @@ public sealed class BSPrim : BSPhysObject { if (IsStatic) { - BulletSimAPI.SetMassProps2(PhysBody.ptr, 0f, OMV.Vector3.Zero); + Inertia = OMV.Vector3.Zero; + BulletSimAPI.SetMassProps2(PhysBody.ptr, 0f, Inertia); BulletSimAPI.UpdateInertiaTensor2(PhysBody.ptr); } else { - OMV.Vector3 localInertia = BulletSimAPI.CalculateLocalInertia2(PhysShape.ptr, physMass); - BulletSimAPI.SetMassProps2(PhysBody.ptr, physMass, localInertia); + Inertia = BulletSimAPI.CalculateLocalInertia2(PhysShape.ptr, physMass); + BulletSimAPI.SetMassProps2(PhysBody.ptr, physMass, Inertia); + BulletSimAPI.UpdateInertiaTensor2(PhysBody.ptr); // center of mass is at the zero of the object - BulletSimAPI.SetCenterOfMassByPosRot2(PhysBody.ptr, ForcePosition, ForceOrientation); - // BulletSimAPI.UpdateInertiaTensor2(BSBody.ptr); - DetailLog("{0},BSPrim.UpdateMassProperties,mass={1},localInertia={2}", LocalID, physMass, localInertia); + // DEBUG DEBUG BulletSimAPI.SetCenterOfMassByPosRot2(PhysBody.ptr, ForcePosition, ForceOrientation); + DetailLog("{0},BSPrim.UpdateMassProperties,mass={1},localInertia={2}", LocalID, physMass, Inertia); } } @@ -582,7 +594,7 @@ public sealed class BSPrim : BSPhysObject // DetailLog("{0},setIsPhysical,taint,isPhys={1}", LocalID, _isPhysical); SetObjectDynamic(true); // whether phys-to-static or static-to-phys, the object is not moving. - ZeroMotion(); + ZeroMotion(true); }); } } @@ -648,6 +660,7 @@ public sealed class BSPrim : BSPhysObject // Recompute any linkset parameters. // When going from non-physical to physical, this re-enables the constraints that // had been automatically disabled when the mass was set to zero. + // For compound based linksets, this enables and disables interactions of the children. Linkset.Refresh(this); DetailLog("{0},BSPrim.UpdatePhysicalParameters,taintExit,static={1},solid={2},mass={3},collide={4},cf={5:X},body={6},shape={7}", @@ -666,9 +679,9 @@ public sealed class BSPrim : BSPhysObject // Become a Bullet 'static' object type CurrentCollisionFlags = BulletSimAPI.AddToCollisionFlags2(PhysBody.ptr, CollisionFlags.CF_STATIC_OBJECT); // Stop all movement - ZeroMotion(); + ZeroMotion(true); // Center of mass is at the center of the object - BulletSimAPI.SetCenterOfMassByPosRot2(Linkset.LinksetRoot.PhysBody.ptr, _position, _orientation); + // DEBUG DEBUG BulletSimAPI.SetCenterOfMassByPosRot2(Linkset.LinksetRoot.PhysBody.ptr, _position, _orientation); // Mass is zero which disables a bunch of physics stuff in Bullet UpdatePhysicalMassProperties(0f); // Set collision detection parameters @@ -704,7 +717,7 @@ public sealed class BSPrim : BSPhysObject BulletSimAPI.SetTranslation2(PhysBody.ptr, _position, _orientation); // Center of mass is at the center of the object - BulletSimAPI.SetCenterOfMassByPosRot2(Linkset.LinksetRoot.PhysBody.ptr, _position, _orientation); + // DEBUG DEBUG BulletSimAPI.SetCenterOfMassByPosRot2(Linkset.LinksetRoot.PhysBody.ptr, _position, _orientation); // A dynamic object has mass UpdatePhysicalMassProperties(RawMass); @@ -958,6 +971,16 @@ public sealed class BSPrim : BSPhysObject }); } + public void ApplyForceImpulse(OMV.Vector3 impulse, bool inTaintTime) + { + OMV.Vector3 applyImpulse = impulse; + PhysicsScene.TaintedObject(inTaintTime, "BSPrim.ApplyForceImpulse", delegate() + { + DetailLog("{0},BSPrim.ApplyForceImpulse,taint,tImpulse={1}", LocalID, applyImpulse); + BulletSimAPI.ApplyCentralImpulse2(PhysBody.ptr, applyImpulse); + }); + } + private List m_accumulatedAngularForces = new List(); public override void AddAngularForce(OMV.Vector3 force, bool pushforce) { AddAngularForce(force, pushforce, false); @@ -1001,7 +1024,6 @@ public sealed class BSPrim : BSPhysObject OMV.Vector3 applyImpulse = impulse; PhysicsScene.TaintedObject(inTaintTime, "BSPrim.ApplyTorqueImpulse", delegate() { - DetailLog("{0},BSPrim.ApplyTorqueImpulse,taint,tImpulse={1}", LocalID, applyImpulse); BulletSimAPI.ApplyTorqueImpulse2(PhysBody.ptr, applyImpulse); }); } @@ -1315,9 +1337,10 @@ public sealed class BSPrim : BSPhysObject // If this prim is part of a linkset, we must remove and restore the physical // links if the body is rebuilt. bool needToRestoreLinkset = false; + bool needToRestoreVehicle = false; // Create the correct physical representation for this type of object. - // Updates BSBody and BSShape with the new information. + // Updates PhysBody and PhysShape with the new information. // Ignore 'forceRebuild'. This routine makes the right choices and changes of necessary. // Returns 'true' if either the body or the shape was changed. PhysicsScene.Shapes.GetBodyAndShape(false, PhysicsScene.World, this, null, delegate(BulletBody dBody) @@ -1326,6 +1349,7 @@ public sealed class BSPrim : BSPhysObject // Remove all the physical dependencies on the old body. // (Maybe someday make the changing of BSShape an event handled by BSLinkset.) needToRestoreLinkset = Linkset.RemoveBodyDependencies(this); + needToRestoreVehicle = _vehicle.RemoveBodyDependencies(this); }); if (needToRestoreLinkset) @@ -1333,6 +1357,11 @@ public sealed class BSPrim : BSPhysObject // If physical body dependencies were removed, restore them Linkset.RestoreBodyDependencies(this); } + if (needToRestoreVehicle) + { + // If physical body dependencies were removed, restore them + _vehicle.RestoreBodyDependencies(this); + } // Make sure the properties are set on the new object UpdatePhysicalParameters(); -- cgit v1.1 From ee00c5c8851dd364acef858f3fd9f5164797fc1e Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 6 Nov 2012 18:10:06 -0800 Subject: BulletSim: many changes to tune vehicles for BulletSim. The problem left is that the vehicle sitting on something needs to press down for gravity and what its sitting on pushes up so the vehicle does not penetrate. The effect is Bullet calculates a lot of random angular motion for the vehicle. Various schemes of damping and zeroing has not resolved the problem. --- OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs | 224 +++++++++++++++------ 1 file changed, 161 insertions(+), 63 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs index 819635a..dbc9039 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSDynamics.cs @@ -54,10 +54,15 @@ namespace OpenSim.Region.Physics.BulletSPlugin { public sealed class BSDynamics { + private static string LogHeader = "[BULLETSIM VEHICLE]"; + private BSScene PhysicsScene { get; set; } // the prim this dynamic controller belongs to private BSPrim Prim { get; set; } + // mass of the vehicle fetched each time we're calles + private float m_vehicleMass; + // Vehicle properties public Vehicle Type { get; set; } @@ -516,7 +521,29 @@ namespace OpenSim.Region.Physics.BulletSPlugin // Friction effects are handled by this vehicle code BulletSimAPI.SetFriction2(Prim.PhysBody.ptr, 0f); BulletSimAPI.SetHitFraction2(Prim.PhysBody.ptr, 0f); + + // BulletSimAPI.SetAngularDamping2(Prim.PhysBody.ptr, 0.8f); + + VDetailLog("{0},BSDynamics.Refresh,zeroingFriction and adding damping", Prim.LocalID); + } + } + + public bool RemoveBodyDependencies(BSPhysObject prim) + { + // If active, we need to add our properties back when the body is rebuilt. + return IsActive; + } + + public void RestoreBodyDependencies(BSPhysObject prim) + { + if (Prim.LocalID != prim.LocalID) + { + // The call should be on us by our prim. Error if not. + PhysicsScene.Logger.ErrorFormat("{0} RestoreBodyDependencies: called by not my prim. passedLocalID={1}, vehiclePrimLocalID={2}", + LogHeader, prim.LocalID, Prim.LocalID); + return; } + Refresh(); } // One step of the vehicle properties for the next 'pTimestep' seconds. @@ -533,16 +560,26 @@ namespace OpenSim.Region.Physics.BulletSPlugin // m_lastLinearVelocityVector = Prim.ForceVelocity * Quaternion.Inverse(Prim.ForceOrientation); // DEBUG: // END DEBUG + m_vehicleMass = Prim.Linkset.LinksetMass; + MoveLinear(pTimestep); + // Commented out for debug MoveAngular(pTimestep); - LimitRotation(pTimestep); + // Prim.ApplyTorqueImpulse(-Prim.RotationalVelocity * m_vehicleMass, false); // DEBUG DEBUG + // Prim.ForceRotationalVelocity = -Prim.RotationalVelocity; // DEBUG DEBUG - // DEBUG: Trying to figure out why Bullet goes crazy when the root prim is moved. - // BulletSimAPI.SetInterpolationVelocity2(Prim.BSBody.ptr, m_newVelocity, m_lastAngularVelocity); // DEBUG DEBUG DEBUG + LimitRotation(pTimestep); // remember the position so next step we can limit absolute movement effects m_lastPositionVector = Prim.ForcePosition; + VDetailLog("{0},BSDynamics.Step,frict={1},grav={2},inertia={3},mass={4}", // DEBUG DEBUG + Prim.LocalID, + BulletSimAPI.GetFriction2(Prim.PhysBody.ptr), + BulletSimAPI.GetGravity2(Prim.PhysBody.ptr), + Prim.Inertia, + m_vehicleMass + ); VDetailLog("{0},BSDynamics.Step,done,pos={1},force={2},velocity={3},angvel={4}", Prim.LocalID, Prim.ForcePosition, Prim.Force, Prim.ForceVelocity, Prim.RotationalVelocity); }// end Step @@ -555,25 +592,26 @@ namespace OpenSim.Region.Physics.BulletSPlugin // m_lastLinearVelocityVector is the current speed we are moving in that direction if (m_linearMotorDirection.LengthSquared() > 0.001f) { - Vector3 origDir = m_linearMotorDirection; - Vector3 origVel = m_lastLinearVelocityVector; + Vector3 origDir = m_linearMotorDirection; // DEBUG + Vector3 origVel = m_lastLinearVelocityVector; // DEBUG + // DEBUG: the vehicle velocity rotated to be relative to vehicle coordinates for comparison Vector3 vehicleVelocity = Prim.ForceVelocity * Quaternion.Inverse(Prim.ForceOrientation); // DEBUG - // add drive to body + // Add (desiredVelocity - lastAppliedVelocity) / howLongItShouldTakeToComplete Vector3 addAmount = (m_linearMotorDirection - m_lastLinearVelocityVector)/(m_linearMotorTimescale) * pTimestep; - // lastLinearVelocityVector is the current body velocity vector m_lastLinearVelocityVector += addAmount; float decayFactor = (1.0f / m_linearMotorDecayTimescale) * pTimestep; m_linearMotorDirection *= (1f - decayFactor); - Vector3 frictionFactor = (Vector3.One / m_linearFrictionTimescale) * pTimestep; - m_lastLinearVelocityVector *= (Vector3.One - frictionFactor); - // Rotate new object velocity from vehicle relative to world coordinates m_newVelocity = m_lastLinearVelocityVector * Prim.ForceOrientation; - VDetailLog("{0},MoveLinear,nonZero,origdir={1},origvel={2},vehVel={3},add={4},decay={5},frict={6},lmDir={7},lmVel={8},newVel={9}", + // Apply friction for next time + Vector3 frictionFactor = (Vector3.One / m_linearFrictionTimescale) * pTimestep; + m_lastLinearVelocityVector *= (Vector3.One - frictionFactor); + + VDetailLog("{0},MoveLinear,nonZero,origlmDir={1},origlvVel={2},vehVel={3},add={4},decay={5},frict={6},lmDir={7},lvVec={8},newVel={9}", Prim.LocalID, origDir, origVel, vehicleVelocity, addAmount, decayFactor, frictionFactor, m_linearMotorDirection, m_lastLinearVelocityVector, m_newVelocity); } @@ -607,7 +645,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin // If below the terrain, move us above the ground a little. float terrainHeight = Prim.PhysicsScene.TerrainManager.GetTerrainHeightAtXYZ(pos); // Taking the rotated size doesn't work here because m_prim.Size is the size of the root prim and not the linkset. - // Need to add a m_prim.LinkSet.Size similar to m_prim.LinkSet.Mass. + // TODO: Add a m_prim.LinkSet.Size similar to m_prim.LinkSet.Mass. // Vector3 rotatedSize = m_prim.Size * m_prim.ForceOrientation; // if (rotatedSize.Z < terrainHeight) if (pos.Z < terrainHeight) @@ -638,13 +676,15 @@ namespace OpenSim.Region.Physics.BulletSPlugin if ((m_flags & VehicleFlag.HOVER_UP_ONLY) != 0) { - // If body is aready heigher, use its height as target height - if (pos.Z > m_VhoverTargetHeight) m_VhoverTargetHeight = pos.Z; + // If body is already heigher, use its height as target height + if (pos.Z > m_VhoverTargetHeight) + m_VhoverTargetHeight = pos.Z; } if ((m_flags & VehicleFlag.LOCK_HOVER_HEIGHT) != 0) { - if ((pos.Z - m_VhoverTargetHeight) > .2 || (pos.Z - m_VhoverTargetHeight) < -.2) + if (Math.Abs(pos.Z - m_VhoverTargetHeight) > 0.2f) { + pos.Z = m_VhoverTargetHeight; Prim.ForcePosition = pos; } } @@ -709,25 +749,28 @@ namespace OpenSim.Region.Physics.BulletSPlugin } } - // Limit absolute vertical change - float Zchange = Math.Abs(posChange.Z); + #region downForce + Vector3 downForce = Vector3.Zero; + if ((m_flags & (VehicleFlag.LIMIT_MOTOR_UP)) != 0) { - if (Zchange > .3) - grav.Z = (float)(grav.Z * 3); - if (Zchange > .15) - grav.Z = (float)(grav.Z * 2); - if (Zchange > .75) - grav.Z = (float)(grav.Z * 1.5); - if (Zchange > .05) - grav.Z = (float)(grav.Z * 1.25); - if (Zchange > .025) - grav.Z = (float)(grav.Z * 1.125); - float postemp = (pos.Z - terrainHeight); - if (postemp > 2.5f) - grav.Z = (float)(grav.Z * 1.037125); - VDetailLog("{0},MoveLinear,limitMotorUp,grav={1}", Prim.LocalID, grav); + // If the vehicle is motoring into the sky, get it going back down. + // Is this an angular force or both linear and angular?? + float distanceAboveGround = pos.Z - terrainHeight; + if (distanceAboveGround > 2f) + { + // downForce = new Vector3(0, 0, (-distanceAboveGround / m_bankingTimescale) * pTimestep); + // downForce = new Vector3(0, 0, -distanceAboveGround / m_bankingTimescale); + downForce = new Vector3(0, 0, -distanceAboveGround); + } + // TODO: this calculation is all wrong. From the description at + // (http://wiki.secondlife.com/wiki/Category:LSL_Vehicle), the downForce + // has a decay factor. This says this force should + // be computed with a motor. + VDetailLog("{0},MoveLinear,limitMotorUp,distAbove={1},downForce={2}", + Prim.LocalID, distanceAboveGround, downForce); } + #endregion // downForce // If not changing some axis, reduce out velocity if ((m_flags & (VehicleFlag.NO_X)) != 0) @@ -737,13 +780,28 @@ namespace OpenSim.Region.Physics.BulletSPlugin if ((m_flags & (VehicleFlag.NO_Z)) != 0) m_newVelocity.Z = 0; - // Apply velocity + // Clamp REALLY high or low velocities + if (m_newVelocity.LengthSquared() > 1e6f) + { + m_newVelocity /= m_newVelocity.Length(); + m_newVelocity *= 1000f; + } + else if (m_newVelocity.LengthSquared() < 1e-6f) + m_newVelocity = Vector3.Zero; + + // Stuff new linear velocity into the vehicle Prim.ForceVelocity = m_newVelocity; - // Prim.AddForce(m_newVelocity * Prim.Linkset.LinksetMass, false); - Prim.AddForce(grav * Prim.Linkset.LinksetMass, false); + // Prim.ApplyForceImpulse((m_newVelocity - Prim.Velocity) * m_vehicleMass, false); // DEBUG DEBUG - VDetailLog("{0},MoveLinear,done,lmDir={1},lmVel={2},newVel={3},grav={4}", - Prim.LocalID, m_linearMotorDirection, m_lastLinearVelocityVector, m_newVelocity, grav); + Vector3 totalDownForce = downForce + grav; + if (totalDownForce != Vector3.Zero) + { + Prim.AddForce(totalDownForce * m_vehicleMass, false); + // Prim.ApplyForceImpulse(totalDownForce * m_vehicleMass, false); + } + + VDetailLog("{0},MoveLinear,done,lmDir={1},lmVel={2},newVel={3},primVel={4},totalDown={5}", + Prim.LocalID, m_linearMotorDirection, m_lastLinearVelocityVector, m_newVelocity, Prim.Velocity, totalDownForce); } // end MoveLinear() @@ -765,7 +823,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin Vector3 origDir = m_angularMotorDirection; // new velocity += error / ( time to get there / step interval) - // requested speed - last motor speed + // requested direction - current vehicle direction m_angularMotorVelocity += (m_angularMotorDirection - m_angularMotorVelocity) / (m_angularMotorTimescale / pTimestep); // decay requested direction m_angularMotorDirection *= (1.0f - (pTimestep * 1.0f/m_angularMotorDecayTimescale)); @@ -784,10 +842,11 @@ namespace OpenSim.Region.Physics.BulletSPlugin Vector3 deflection = Vector3.Zero; Vector3 banking = Vector3.Zero; + // If vertical attaction timescale is reasonable and we applied an angular force last time... if (m_verticalAttractionTimescale < 300 && m_lastAngularVelocity != Vector3.Zero) { float VAservo = pTimestep * 0.2f / m_verticalAttractionTimescale; - if (Prim.Linkset.LinksetIsColliding) + if (Prim.IsColliding) VAservo = pTimestep * 0.05f / (m_verticalAttractionTimescale); VAservo *= (m_verticalAttractionEfficiency * m_verticalAttractionEfficiency); @@ -806,7 +865,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin verticalError.X = 2.0f - verticalError.X; verticalError.Y = 2.0f - verticalError.Y; } - // scale it by VAservo + // scale it by VAservo (timestep and timescale) verticalError = verticalError * VAservo; // As the body rotates around the X axis, then verticalError.Y increases; Rotated around Y @@ -822,25 +881,30 @@ namespace OpenSim.Region.Physics.BulletSPlugin vertattr.X += bounce * angularVelocity.X; vertattr.Y += bounce * angularVelocity.Y; - VDetailLog("{0},MoveAngular,verticalAttraction,verticalError={1},bounce={2},vertattr={3}", - Prim.LocalID, verticalError, bounce, vertattr); + VDetailLog("{0},MoveAngular,verticalAttraction,VAservo={1},effic={2},verticalError={3},bounce={4},vertattr={5}", + Prim.LocalID, VAservo, m_verticalAttractionEfficiency, verticalError, bounce, vertattr); } #endregion // Vertical attactor #region Deflection - //Forward is the prefered direction, but if the reference frame has changed, we need to take this into account as well if (m_angularDeflectionEfficiency != 0) { - Vector3 preferredAxisOfMotion = + // Compute a scaled vector that points in the preferred axis (X direction) + Vector3 scaledDefaultDirection = new Vector3((pTimestep * 10 * (m_angularDeflectionEfficiency / m_angularDeflectionTimescale)), 0, 0); - preferredAxisOfMotion *= Quaternion.Add(Prim.ForceOrientation, m_referenceFrame); + // Adding the current vehicle orientation and reference frame displaces the orientation to the frame. + // Rotate the scaled default axix relative to the actual vehicle direction giving where it should point. + Vector3 preferredAxisOfMotion = scaledDefaultDirection * Quaternion.Add(Prim.ForceOrientation, m_referenceFrame); + // Scale by efficiency and timescale deflection = (preferredAxisOfMotion * (m_angularDeflectionEfficiency) / m_angularDeflectionTimescale) * pTimestep; VDetailLog("{0},MoveAngular,Deflection,perfAxis={1},deflection={2}", Prim.LocalID, preferredAxisOfMotion, deflection); + // This deflection computation is not correct. + deflection = Vector3.Zero; } #endregion @@ -875,7 +939,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin } else banking.Z += (effSquared*(mult*mix))*(m_angularMotorVelocity.X) * 4; - if (!Prim.Linkset.LinksetIsColliding && Math.Abs(m_angularMotorVelocity.X) > mix) + if (!Prim.IsColliding && Math.Abs(m_angularMotorVelocity.X) > mix) //If they are colliding, we probably shouldn't shove the prim around... probably { float angVelZ = m_angularMotorVelocity.X*-1; @@ -904,6 +968,40 @@ namespace OpenSim.Region.Physics.BulletSPlugin // Sum velocities m_lastAngularVelocity = m_angularMotorVelocity + vertattr + banking + deflection; + #region Linear Motor Offset + + //Offset section + if (m_linearMotorOffset != Vector3.Zero) + { + //Offset of linear velocity doesn't change the linear velocity, + // but causes a torque to be applied, for example... + // + // IIIII >>> IIIII + // IIIII >>> IIIII + // IIIII >>> IIIII + // ^ + // | Applying a force at the arrow will cause the object to move forward, but also rotate + // + // + // The torque created is the linear velocity crossed with the offset + + // NOTE: this computation does should be in the linear section + // because there we know the impulse being applied. + Vector3 torqueFromOffset = Vector3.Zero; + // torqueFromOffset = Vector3.Cross(m_linearMotorOffset, appliedImpulse); + if (float.IsNaN(torqueFromOffset.X)) + torqueFromOffset.X = 0; + if (float.IsNaN(torqueFromOffset.Y)) + torqueFromOffset.Y = 0; + if (float.IsNaN(torqueFromOffset.Z)) + torqueFromOffset.Z = 0; + torqueFromOffset *= m_vehicleMass; + Prim.ApplyTorqueImpulse(torqueFromOffset, true); + VDetailLog("{0},BSDynamic.MoveAngular,motorOffset,applyTorqueImpulse={1}", Prim.LocalID, torqueFromOffset); + } + + #endregion + if ((m_flags & (VehicleFlag.NO_DEFLECTION_UP)) != 0) { m_lastAngularVelocity.X = 0; @@ -914,25 +1012,25 @@ namespace OpenSim.Region.Physics.BulletSPlugin if (m_lastAngularVelocity.ApproxEquals(Vector3.Zero, 0.01f)) { m_lastAngularVelocity = Vector3.Zero; // Reduce small value to zero. - VDetailLog("{0},MoveAngular,zeroSmallValues,lastAngular={1}", Prim.LocalID, m_lastAngularVelocity); + Prim.ZeroAngularMotion(true); + VDetailLog("{0},MoveAngular,zeroAngularMotion,lastAngular={1}", Prim.LocalID, m_lastAngularVelocity); + } + else + { + // Apply to the body. + // The above calculates the absolute angular velocity needed. Angular velocity is massless. + // Since we are stuffing the angular velocity directly into the object, the computed + // velocity needs to be scaled by the timestep. + Vector3 applyAngularForce = ((m_lastAngularVelocity * pTimestep) - Prim.ForceRotationalVelocity); + Prim.ForceRotationalVelocity = applyAngularForce; + + // Decay the angular movement for next time + Vector3 decayamount = (Vector3.One / m_angularFrictionTimescale) * pTimestep; + m_lastAngularVelocity *= Vector3.One - decayamount; + + VDetailLog("{0},MoveAngular,done,newRotVel={1},decay={2},lastAngular={3}", + Prim.LocalID, applyAngularForce, decayamount, m_lastAngularVelocity); } - - // Apply to the body - // The above calculates the absolute angular velocity needed - // Prim.ForceRotationalVelocity = m_lastAngularVelocity; - - // Apply a force to overcome current angular velocity - Vector3 applyAngularForce = (m_lastAngularVelocity - Prim.ForceRotationalVelocity) * Prim.Linkset.LinksetMass; - // Vector3 applyAngularForce = (m_lastAngularVelocity - Prim.ForceRotationalVelocity); - // Prim.AddAngularForce(applyAngularForce, false); - Prim.ApplyTorqueImpulse(applyAngularForce, false); - - // Apply friction for next time - Vector3 decayamount = (Vector3.One / m_angularFrictionTimescale) * pTimestep; - m_lastAngularVelocity *= Vector3.One - decayamount; - - VDetailLog("{0},MoveAngular,done,applyAForce={1},decay={2},lastAngular={3}", - Prim.LocalID, applyAngularForce, decayamount, m_lastAngularVelocity); } //end MoveAngular internal void LimitRotation(float timestep) -- cgit v1.1 From 67d5dbbb49fa44e433bc6f5448f1b3e16c242524 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Wed, 7 Nov 2012 15:28:06 -0800 Subject: BulletSim: add classes for physics motors. Eventually these will replace the manual code for vehicles and add PID functionality to avatar movement. --- OpenSim/Region/Physics/BulletSPlugin/BSMotors.cs | 104 +++++++++++++++++++++++ 1 file changed, 104 insertions(+) create mode 100755 OpenSim/Region/Physics/BulletSPlugin/BSMotors.cs (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSMotors.cs b/OpenSim/Region/Physics/BulletSPlugin/BSMotors.cs new file mode 100755 index 0000000..bc6e4c4 --- /dev/null +++ b/OpenSim/Region/Physics/BulletSPlugin/BSMotors.cs @@ -0,0 +1,104 @@ +using System; +using System.Collections.Generic; +using System.Text; +using OpenMetaverse; + +namespace OpenSim.Region.Physics.BulletSPlugin +{ +public abstract class BSMotor +{ + public virtual void Reset() { } + public virtual void Zero() { } +} +// Can all the incremental stepping be replaced with motor classes? +public class BSVMotor : BSMotor +{ + public Vector3 FrameOfReference { get; set; } + public Vector3 Offset { get; set; } + + public float TimeScale { get; set; } + public float TargetValueDecayTimeScale { get; set; } + public Vector3 CurrentValueReductionTimescale { get; set; } + public float Efficiency { get; set; } + + public Vector3 TargetValue { get; private set; } + public Vector3 CurrentValue { get; private set; } + + + + BSVMotor(float timeScale, float decayTimeScale, Vector3 frictionTimeScale, float efficiency) + { + TimeScale = timeScale; + TargetValueDecayTimeScale = decayTimeScale; + CurrentValueReductionTimescale = frictionTimeScale; + Efficiency = efficiency; + } + public void SetCurrent(Vector3 current) + { + CurrentValue = current; + } + public void SetTarget(Vector3 target) + { + TargetValue = target; + } + public Vector3 Step(float timeStep) + { + if (CurrentValue.LengthSquared() > 0.001f) + { + // Vector3 origDir = Target; // DEBUG + // Vector3 origVel = CurrentValue; // DEBUG + + // Add (desiredVelocity - currentAppliedVelocity) / howLongItShouldTakeToComplete + Vector3 addAmount = (TargetValue - CurrentValue)/(TargetValue) * timeStep; + CurrentValue += addAmount; + + float decayFactor = (1.0f / TargetValueDecayTimeScale) * timeStep; + TargetValue *= (1f - decayFactor); + + Vector3 frictionFactor = (Vector3.One / CurrentValueReductionTimescale) * timeStep; + CurrentValue *= (Vector3.One - frictionFactor); + } + else + { + // if what remains of direction is very small, zero it. + TargetValue = Vector3.Zero; + CurrentValue = Vector3.Zero; + + // VDetailLog("{0},MoveLinear,zeroed", Prim.LocalID); + } + return CurrentValue; + } +} + +public class BSFMotor : BSMotor +{ + public float TimeScale { get; set; } + public float DecayTimeScale { get; set; } + public float Friction { get; set; } + public float Efficiency { get; set; } + + public float Target { get; private set; } + public float CurrentValue { get; private set; } + + BSFMotor(float timeScale, float decayTimescale, float friction, float efficiency) + { + } + public void SetCurrent(float target) + { + } + public void SetTarget(float target) + { + } + public float Step(float timeStep) + { + return 0f; + } +} +public class BSPIDMotor : BSMotor +{ + // TODO: write and use this one + BSPIDMotor() + { + } +} +} -- cgit v1.1 From 366651831952558b03b8f6ec442a0867b257b808 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Wed, 7 Nov 2012 15:29:51 -0800 Subject: BulletSim: add skeleton classes for shape objectification. This will eventually replace all the if's and switches in ShapeCollection with polymorphism. --- OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs | 213 +++++++++++++++++++++++ 1 file changed, 213 insertions(+) create mode 100755 OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs new file mode 100755 index 0000000..5e2c4a8 --- /dev/null +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs @@ -0,0 +1,213 @@ +/* + * 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; + +namespace OpenSim.Region.Physics.BulletSPlugin +{ +public abstract class BSShape +{ + public IntPtr ptr { get; set; } + public ShapeData.PhysicsShapeType type { get; set; } + public System.UInt64 key { get; set; } + public int referenceCount { get; set; } + public DateTime lastReferenced { get; set; } + + protected void Initialize() + { + ptr = IntPtr.Zero; + type = ShapeData.PhysicsShapeType.SHAPE_UNKNOWN; + key = 0; + referenceCount = 0; + lastReferenced = DateTime.Now; + } + + // 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 == ShapeData.PhysicsShapeType.SHAPE_AVATAR) + { + // an avatar capsule is close to a native shape (it is not shared) + ret = BSShapeNative.GetReference(physicsScene, prim, ShapeData.PhysicsShapeType.SHAPE_AVATAR, + ShapeData.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 already been created. + if (ret == null && prim.PreferredPhysicalShape == ShapeData.PhysicsShapeType.SHAPE_COMPOUND) + { + // Getting a reference to a compound shape gets you the compound shape with the root prim shape added + ret = BSShapeCompound.GetReference(prim); + physicsScene.DetailLog("{0},BSShapeCollection.CreateGeom,compoundShape,shape={1}", prim.LocalID, ret); + } + + if (ret == null) + ret = GetShapeReferenceNonSpecial(physicsScene, forceRebuild, prim); + + return ret; + } + public static BSShape GetShapeReferenceNonSpecial(BSScene physicsScene, bool forceRebuild, BSPhysObject prim) + { + return null; + } + public static BSShape GetShapeReferenceNonNative(BSScene physicsScene, bool forceRebuild, BSPhysObject prim) + { + return null; + } + + // 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(); + + public override string ToString() + { + StringBuilder buff = new StringBuilder(); + buff.Append(""); + return buff.ToString(); + } +} + +public class BSShapeNull : BSShape +{ + public BSShapeNull() + { + base.Initialize(); + } + public static BSShape GetReference() { return new BSShapeNull(); } + 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.Initialize(); + } + public static BSShape GetReference(BSScene physicsScene, BSPhysObject prim, + ShapeData.PhysicsShapeType shapeType, ShapeData.FixedShapeKey shapeKey) + { + // Native shapes are not shared and are always built anew. + return new BSShapeNative(physicsScene, prim, shapeType, shapeKey); + } + + private BSShapeNative(BSScene physicsScene, BSPhysObject prim, + ShapeData.PhysicsShapeType shapeType, ShapeData.FixedShapeKey shapeKey) + { + ShapeData nativeShapeData = new ShapeData(); + nativeShapeData.Type = shapeType; + nativeShapeData.ID = prim.LocalID; + nativeShapeData.Scale = prim.Scale; + nativeShapeData.Size = prim.Scale; + nativeShapeData.MeshKey = (ulong)shapeKey; + nativeShapeData.HullKey = (ulong)shapeKey; + + + if (shapeType == ShapeData.PhysicsShapeType.SHAPE_AVATAR) + { + ptr = BulletSimAPI.BuildCapsuleShape2(physicsScene.World.ptr, 1f, 1f, prim.Scale); + physicsScene.DetailLog("{0},BSShapeCollection.BuiletPhysicalNativeShape,capsule,scale={1}", prim.LocalID, prim.Scale); + } + else + { + ptr = BulletSimAPI.BuildNativeShape2(physicsScene.World.ptr, nativeShapeData); + } + if (ptr == IntPtr.Zero) + { + 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); + BulletSimAPI.DeleteCollisionShape2(physicsScene.World.ptr, ptr); + ptr = IntPtr.Zero; + // Garbage collection will free up this instance. + } +} + +public class BSShapeMesh : BSShape +{ + private static string LogHeader = "[BULLETSIM SHAPE MESH]"; + private static Dictionary Meshes = new Dictionary(); + + public BSShapeMesh() + { + base.Initialize(); + } + public static BSShape GetReference() { return new BSShapeNull(); } + public override void Dereference(BSScene physicsScene) { } +} + +public class BSShapeHull : BSShape +{ + private static string LogHeader = "[BULLETSIM SHAPE HULL]"; + private static Dictionary Hulls = new Dictionary(); + + public BSShapeHull() + { + base.Initialize(); + } + public static BSShape GetReference() { return new BSShapeNull(); } + public override void Dereference(BSScene physicsScene) { } +} + +public class BSShapeCompound : BSShape +{ + private static string LogHeader = "[BULLETSIM SHAPE COMPOUND]"; + public BSShapeCompound() + { + base.Initialize(); + } + public static BSShape GetReference(BSPhysObject prim) + { + return new BSShapeNull(); + } + public override void Dereference(BSScene physicsScene) { } +} +} -- cgit v1.1 From 9bc0419679ac8b05cd9b6a5cf340f1e6b8d5d288 Mon Sep 17 00:00:00 2001 From: Dan Lake Date: Thu, 8 Nov 2012 01:18:25 -0800 Subject: ODECharacter overrides TargetVelocity. No change to existing behavior --- OpenSim/Region/Physics/OdePlugin/ODECharacter.cs | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/OdePlugin/ODECharacter.cs b/OpenSim/Region/Physics/OdePlugin/ODECharacter.cs index c736557..319f6ab 100644 --- a/OpenSim/Region/Physics/OdePlugin/ODECharacter.cs +++ b/OpenSim/Region/Physics/OdePlugin/ODECharacter.cs @@ -661,6 +661,20 @@ namespace OpenSim.Region.Physics.OdePlugin set { return; } } + public override Vector3 TargetVelocity + { + get + { + return m_taintTargetVelocity; + } + + set + { + Velocity = value; + } + } + + public override Vector3 Velocity { get @@ -1394,4 +1408,4 @@ namespace OpenSim.Region.Physics.OdePlugin m_eventsubscription += p; } } -} \ No newline at end of file +} -- cgit v1.1 From e4cb7af98a122773e84baf9be38b8b34f02e89a4 Mon Sep 17 00:00:00 2001 From: Diva Canto Date: Tue, 13 Nov 2012 19:26:43 -0800 Subject: Updated all existing AssemblyVersions's to 0.7.5.*. Many DLLs still don't have an AssemblyInfo file. --- OpenSim/Region/Physics/BasicPhysicsPlugin/AssemblyInfo.cs | 2 +- .../Region/Physics/ConvexDecompositionDotNet/Properties/AssemblyInfo.cs | 2 +- OpenSim/Region/Physics/Manager/AssemblyInfo.cs | 2 +- OpenSim/Region/Physics/OdePlugin/AssemblyInfo.cs | 2 +- OpenSim/Region/Physics/POSPlugin/AssemblyInfo.cs | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BasicPhysicsPlugin/AssemblyInfo.cs b/OpenSim/Region/Physics/BasicPhysicsPlugin/AssemblyInfo.cs index 063eb54..0d7cf38 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.6.5.*")] +[assembly : AssemblyVersion("0.7.5.*")] diff --git a/OpenSim/Region/Physics/ConvexDecompositionDotNet/Properties/AssemblyInfo.cs b/OpenSim/Region/Physics/ConvexDecompositionDotNet/Properties/AssemblyInfo.cs index 4285e8c..5ff945d 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("1.0.0.0")] +[assembly: AssemblyVersion("0.7.5.*")] [assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/OpenSim/Region/Physics/Manager/AssemblyInfo.cs b/OpenSim/Region/Physics/Manager/AssemblyInfo.cs index 1f9bf03..099aac1 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.6.5.*")] +[assembly : AssemblyVersion("0.7.5.*")] diff --git a/OpenSim/Region/Physics/OdePlugin/AssemblyInfo.cs b/OpenSim/Region/Physics/OdePlugin/AssemblyInfo.cs index d65929a..142318e 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.6.5.*")] +[assembly : AssemblyVersion("0.7.5.*")] diff --git a/OpenSim/Region/Physics/POSPlugin/AssemblyInfo.cs b/OpenSim/Region/Physics/POSPlugin/AssemblyInfo.cs index af24567..e446d6c 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.6.5.*")] +[assembly : AssemblyVersion("0.7.5.*")] -- cgit v1.1 From aeeaa3a0a9b965dfe5d1111b178234c94de9ba9d Mon Sep 17 00:00:00 2001 From: Diva Canto Date: Wed, 14 Nov 2012 11:09:43 -0800 Subject: Added AssemblyInfos to every dll in the OpenSim.Region namespace. --- .../Physics/BasicPhysicsPlugin/AssemblyInfo.cs | 2 +- .../BulletSPlugin/Properties/AssemblyInfo.cs | 33 ++++++++++++++++++++++ OpenSim/Region/Physics/Manager/AssemblyInfo.cs | 2 +- .../Physics/Meshing/Properties/AssemblyInfo.cs | 33 ++++++++++++++++++++++ OpenSim/Region/Physics/OdePlugin/AssemblyInfo.cs | 2 +- OpenSim/Region/Physics/POSPlugin/AssemblyInfo.cs | 2 +- 6 files changed, 70 insertions(+), 4 deletions(-) create mode 100644 OpenSim/Region/Physics/BulletSPlugin/Properties/AssemblyInfo.cs create mode 100644 OpenSim/Region/Physics/Meshing/Properties/AssemblyInfo.cs (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BasicPhysicsPlugin/AssemblyInfo.cs b/OpenSim/Region/Physics/BasicPhysicsPlugin/AssemblyInfo.cs index 0d7cf38..fb9cb66 100644 --- a/OpenSim/Region/Physics/BasicPhysicsPlugin/AssemblyInfo.cs +++ b/OpenSim/Region/Physics/BasicPhysicsPlugin/AssemblyInfo.cs @@ -39,7 +39,7 @@ using System.Runtime.InteropServices; [assembly : AssemblyConfiguration("")] [assembly : AssemblyCompany("http://opensimulator.org")] [assembly : AssemblyProduct("BasicPhysicsPlugin")] -[assembly : AssemblyCopyright("Copyright (c) OpenSimulator.org Developers 2007-2009")] +[assembly : AssemblyCopyright("Copyright (c) OpenSimulator.org Developers")] [assembly : AssemblyTrademark("")] [assembly : AssemblyCulture("")] diff --git a/OpenSim/Region/Physics/BulletSPlugin/Properties/AssemblyInfo.cs b/OpenSim/Region/Physics/BulletSPlugin/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..0d1db3b --- /dev/null +++ b/OpenSim/Region/Physics/BulletSPlugin/Properties/AssemblyInfo.cs @@ -0,0 +1,33 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("OpenSim.Region.Physics.BulletSPlugin")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("http://opensimulator.org")] +[assembly: AssemblyProduct("OpenSim")] +[assembly: AssemblyCopyright("OpenSimulator developers")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("520ea11b-20cb-449d-ba05-c01015fed841")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +[assembly: AssemblyVersion("0.7.5.*")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/OpenSim/Region/Physics/Manager/AssemblyInfo.cs b/OpenSim/Region/Physics/Manager/AssemblyInfo.cs index 099aac1..36b4235 100644 --- a/OpenSim/Region/Physics/Manager/AssemblyInfo.cs +++ b/OpenSim/Region/Physics/Manager/AssemblyInfo.cs @@ -39,7 +39,7 @@ using System.Runtime.InteropServices; [assembly : AssemblyConfiguration("")] [assembly : AssemblyCompany("http://opensimulator.org")] [assembly : AssemblyProduct("PhysicsManager")] -[assembly : AssemblyCopyright("Copyright (c) OpenSimulator.org Developers 2007-2009")] +[assembly : AssemblyCopyright("Copyright (c) OpenSimulator.org Developers")] [assembly : AssemblyTrademark("")] [assembly : AssemblyCulture("")] diff --git a/OpenSim/Region/Physics/Meshing/Properties/AssemblyInfo.cs b/OpenSim/Region/Physics/Meshing/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..4cc1731 --- /dev/null +++ b/OpenSim/Region/Physics/Meshing/Properties/AssemblyInfo.cs @@ -0,0 +1,33 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("OpenSim.Region.Physics.Meshing")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("http://opensimulator.org")] +[assembly: AssemblyProduct("OpenSim")] +[assembly: AssemblyCopyright("OpenSimulator developers")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("4b7e35c2-a9dd-4b10-b778-eb417f4f6884")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +[assembly: AssemblyVersion("0.7.5.*")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/OpenSim/Region/Physics/OdePlugin/AssemblyInfo.cs b/OpenSim/Region/Physics/OdePlugin/AssemblyInfo.cs index 142318e..3c4f06a 100644 --- a/OpenSim/Region/Physics/OdePlugin/AssemblyInfo.cs +++ b/OpenSim/Region/Physics/OdePlugin/AssemblyInfo.cs @@ -39,7 +39,7 @@ using System.Runtime.InteropServices; [assembly : AssemblyConfiguration("")] [assembly : AssemblyCompany("http://opensimulator.org")] [assembly : AssemblyProduct("OdePlugin")] -[assembly : AssemblyCopyright("Copyright (c) OpenSimulator.org Developers 2007-2009")] +[assembly : AssemblyCopyright("Copyright (c) OpenSimulator.org Developers")] [assembly : AssemblyTrademark("")] [assembly : AssemblyCulture("")] diff --git a/OpenSim/Region/Physics/POSPlugin/AssemblyInfo.cs b/OpenSim/Region/Physics/POSPlugin/AssemblyInfo.cs index e446d6c..d07df02 100644 --- a/OpenSim/Region/Physics/POSPlugin/AssemblyInfo.cs +++ b/OpenSim/Region/Physics/POSPlugin/AssemblyInfo.cs @@ -39,7 +39,7 @@ using System.Runtime.InteropServices; [assembly : AssemblyConfiguration("")] [assembly : AssemblyCompany("http://opensimulator.org")] [assembly : AssemblyProduct("POSPlugin")] -[assembly : AssemblyCopyright("Copyright (c) OpenSimulator.org Developers 2007-2009")] +[assembly : AssemblyCopyright("Copyright (c) OpenSimulator.org Developers")] [assembly : AssemblyTrademark("")] [assembly : AssemblyCulture("")] -- cgit v1.1 From 079a1e704fcaa9fddc9bb3de0a205969cba058bc Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Sun, 18 Nov 2012 18:17:30 -0800 Subject: BulletSim: remove the obsolete interface to the Bullet code. Update BulletSim libraries with code stripped of the obsolete code. --- .../Region/Physics/BulletSPlugin/BulletSimAPI.cs | 134 --------------------- 1 file changed, 134 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs index 07149d8..28fae13 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs @@ -429,140 +429,6 @@ static class BulletSimAPI { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void DebugLogCallback([MarshalAs(UnmanagedType.LPStr)]string msg); -[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -[return: MarshalAs(UnmanagedType.LPStr)] -public static extern string GetVersion(); - -/* Remove the linkage to the old api methods -[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern uint Initialize(Vector3 maxPosition, IntPtr parms, - int maxCollisions, IntPtr collisionArray, - int maxUpdates, IntPtr updateArray, - DebugLogCallback logRoutine); - -[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern void CreateInitialGroundPlaneAndTerrain(uint worldID); - -[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern void SetHeightmap(uint worldID, [MarshalAs(UnmanagedType.LPArray)] float[] heightMap); - -[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern void Shutdown(uint worldID); - -[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool UpdateParameter(uint worldID, uint localID, - [MarshalAs(UnmanagedType.LPStr)]string paramCode, float value); - -// =============================================================================== -[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern int PhysicsStep(uint worldID, float timeStep, int maxSubSteps, float fixedTimeStep, - out int updatedEntityCount, - out IntPtr updatedEntitiesPtr, - out int collidersCount, - out IntPtr collidersPtr); - -[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool CreateHull(uint worldID, System.UInt64 meshKey, - int hullCount, [MarshalAs(UnmanagedType.LPArray)] float[] hulls - ); - -[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool CreateMesh(uint worldID, System.UInt64 meshKey, - int indexCount, [MarshalAs(UnmanagedType.LPArray)] int[] indices, - int verticesCount, [MarshalAs(UnmanagedType.LPArray)] float[] vertices - ); - -[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool DestroyHull(uint worldID, System.UInt64 meshKey); - -[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool DestroyMesh(uint worldID, System.UInt64 meshKey); - -[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool CreateObject(uint worldID, ShapeData shapeData); - -[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern Vector3 GetObjectPosition(uint WorldID, uint id); - -[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern Quaternion GetObjectOrientation(uint WorldID, uint id); - -[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool SetObjectTranslation(uint worldID, uint id, Vector3 position, Quaternion rotation); - -[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool SetObjectVelocity(uint worldID, uint id, Vector3 velocity); - -[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool SetObjectAngularVelocity(uint worldID, uint id, Vector3 angularVelocity); - -// Set the current force acting on the object -[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool SetObjectForce(uint worldID, uint id, Vector3 force); - -[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool SetObjectScaleMass(uint worldID, uint id, Vector3 scale, float mass, bool isDynamic); - -[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool SetObjectCollidable(uint worldID, uint id, bool phantom); - -[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool SetObjectDynamic(uint worldID, uint id, bool isDynamic, float mass); - -[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool SetObjectGhost(uint worldID, uint id, bool ghostly); - -[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool SetObjectProperties(uint worldID, uint id, bool isStatic, bool isSolid, bool genCollisions, float mass); - -[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool SetObjectBuoyancy(uint worldID, uint id, float buoyancy); - -[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool HasObject(uint worldID, uint id); - -[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern bool DestroyObject(uint worldID, uint id); - -// =============================================================================== -[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern SweepHit ConvexSweepTest(uint worldID, uint id, Vector3 to, float extraMargin); - -[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern RaycastHit RayTest(uint worldID, uint id, Vector3 from, Vector3 to); - -[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern Vector3 RecoverFromPenetration(uint worldID, uint id); - -// =============================================================================== -[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern void DumpBulletStatistics(); -*/ -// Log a debug message -[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern void SetDebugLogCallback(DebugLogCallback callback); - -// =============================================================================== -// =============================================================================== -// =============================================================================== -// A new version of the API that enables moving all the logic out of the C++ code and into -// the C# code. This will make modifications easier for the next person. -// This interface passes the actual pointers to the objects in the unmanaged -// address space. All the management (calls for creation/destruction/lookup) -// is done in the C# code. -// The names have a "2" tacked on. This will be removed as the C# code gets rebuilt -// and the old code is removed. - -// Functions use while converting from API1 to API2. Can be removed when totally converted. -[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern IntPtr GetSimHandle2(uint worldID); - -[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern IntPtr GetBodyHandleWorldID2(uint worldID, uint id); - -[DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -public static extern IntPtr GetBodyHandle2(IntPtr world, uint id); - // =============================================================================== // Initialization and simulation [DllImport("BulletSim", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] -- cgit v1.1 From 22be36be69bbf571b26753307b9c2c5456a34d73 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Sun, 18 Nov 2012 22:57:26 -0800 Subject: BulletSim: fix the problem with flying being disabled when crossing region boundries. --- OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs | 8 ++++++-- 1 file changed, 6 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 f33c124..3c48dcc 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -78,8 +78,8 @@ public sealed class BSCharacter : BSPhysObject 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") { - base.BaseInitialize(parent_scene, localID, avName, "BSCharacter"); _physicsActorType = (int)ActorTypes.Agent; _position = pos; _size = size; @@ -131,6 +131,10 @@ public sealed class BSCharacter : BSPhysObject // Set the velocity and compute the proper friction ForceVelocity = _velocity; + // 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. + Flying = _flying; + BulletSimAPI.SetRestitution2(PhysBody.ptr, PhysicsScene.Params.avatarRestitution); BulletSimAPI.SetMargin2(PhysShape.ptr, PhysicsScene.Params.collisionMargin); BulletSimAPI.SetLocalScaling2(PhysShape.ptr, Scale); @@ -615,7 +619,7 @@ public sealed class BSCharacter : BSPhysObject newScale.Y = PhysicsScene.Params.avatarCapsuleRadius; // From the total height, remove the capsule half spheres that are at each end - newScale.Z = size.Z- (newScale.X + newScale.Y); + newScale.Z = size.Z - (newScale.X + newScale.Y); Scale = newScale; } -- cgit v1.1 From 6c961d8addf5c6aad81165042e684e45429b3b21 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Sun, 18 Nov 2012 22:58:36 -0800 Subject: BulletSim: Use base class constructors for initialization of BSShape and other classes. --- .../Region/Physics/BulletSPlugin/BSPhysObject.cs | 5 +- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 2 +- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 2 +- OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs | 421 ++++++++++----------- 4 files changed, 214 insertions(+), 216 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index e803072..991e5b1 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -47,7 +47,10 @@ namespace OpenSim.Region.Physics.BulletSPlugin */ public abstract class BSPhysObject : PhysicsActor { - protected void BaseInitialize(BSScene parentScene, uint localID, string name, string typeName) + protected BSPhysObject() + { + } + protected BSPhysObject(BSScene parentScene, uint localID, string name, string typeName) { PhysicsScene = parentScene; LocalID = localID; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 14eb505..500c84a 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -88,9 +88,9 @@ public sealed class BSPrim : BSPhysObject public BSPrim(uint localID, String primName, BSScene parent_scene, OMV.Vector3 pos, OMV.Vector3 size, OMV.Quaternion rotation, PrimitiveBaseShape pbs, bool pisPhysical) + : base(parent_scene, localID, primName, "BSPrim") { // m_log.DebugFormat("{0}: BSPrim creation of {1}, id={2}", LogHeader, primName, localID); - base.BaseInitialize(parent_scene, localID, primName, "BSPrim"); _physicsActorType = (int)ActorTypes.Prim; _position = pos; _size = size; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index 1cc607a..2fee95e 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -683,7 +683,7 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters #region Taints // Calls to the PhysicsActors can't directly call into the physics engine - // because it might be busy. We delay changes to a known time. + // 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) { diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs index 5e2c4a8..d59a486 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs @@ -1,213 +1,208 @@ -/* - * 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; - -namespace OpenSim.Region.Physics.BulletSPlugin -{ -public abstract class BSShape -{ - public IntPtr ptr { get; set; } - public ShapeData.PhysicsShapeType type { get; set; } - public System.UInt64 key { get; set; } - public int referenceCount { get; set; } - public DateTime lastReferenced { get; set; } - - protected void Initialize() - { - ptr = IntPtr.Zero; - type = ShapeData.PhysicsShapeType.SHAPE_UNKNOWN; - key = 0; - referenceCount = 0; - lastReferenced = DateTime.Now; - } - - // 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 == ShapeData.PhysicsShapeType.SHAPE_AVATAR) - { - // an avatar capsule is close to a native shape (it is not shared) - ret = BSShapeNative.GetReference(physicsScene, prim, ShapeData.PhysicsShapeType.SHAPE_AVATAR, - ShapeData.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 already been created. - if (ret == null && prim.PreferredPhysicalShape == ShapeData.PhysicsShapeType.SHAPE_COMPOUND) - { - // Getting a reference to a compound shape gets you the compound shape with the root prim shape added - ret = BSShapeCompound.GetReference(prim); - physicsScene.DetailLog("{0},BSShapeCollection.CreateGeom,compoundShape,shape={1}", prim.LocalID, ret); - } - - if (ret == null) - ret = GetShapeReferenceNonSpecial(physicsScene, forceRebuild, prim); - - return ret; - } - public static BSShape GetShapeReferenceNonSpecial(BSScene physicsScene, bool forceRebuild, BSPhysObject prim) - { - return null; - } - public static BSShape GetShapeReferenceNonNative(BSScene physicsScene, bool forceRebuild, BSPhysObject prim) - { - return null; - } - - // 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(); - - public override string ToString() - { - StringBuilder buff = new StringBuilder(); - buff.Append(""); - return buff.ToString(); - } -} - -public class BSShapeNull : BSShape -{ - public BSShapeNull() - { - base.Initialize(); - } - public static BSShape GetReference() { return new BSShapeNull(); } - 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.Initialize(); - } - public static BSShape GetReference(BSScene physicsScene, BSPhysObject prim, - ShapeData.PhysicsShapeType shapeType, ShapeData.FixedShapeKey shapeKey) - { - // Native shapes are not shared and are always built anew. - return new BSShapeNative(physicsScene, prim, shapeType, shapeKey); - } - - private BSShapeNative(BSScene physicsScene, BSPhysObject prim, - ShapeData.PhysicsShapeType shapeType, ShapeData.FixedShapeKey shapeKey) - { - ShapeData nativeShapeData = new ShapeData(); - nativeShapeData.Type = shapeType; - nativeShapeData.ID = prim.LocalID; - nativeShapeData.Scale = prim.Scale; - nativeShapeData.Size = prim.Scale; - nativeShapeData.MeshKey = (ulong)shapeKey; - nativeShapeData.HullKey = (ulong)shapeKey; - - - if (shapeType == ShapeData.PhysicsShapeType.SHAPE_AVATAR) - { - ptr = BulletSimAPI.BuildCapsuleShape2(physicsScene.World.ptr, 1f, 1f, prim.Scale); - physicsScene.DetailLog("{0},BSShapeCollection.BuiletPhysicalNativeShape,capsule,scale={1}", prim.LocalID, prim.Scale); - } - else - { - ptr = BulletSimAPI.BuildNativeShape2(physicsScene.World.ptr, nativeShapeData); - } - if (ptr == IntPtr.Zero) - { - 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); - BulletSimAPI.DeleteCollisionShape2(physicsScene.World.ptr, ptr); - ptr = IntPtr.Zero; - // Garbage collection will free up this instance. - } -} - -public class BSShapeMesh : BSShape -{ - private static string LogHeader = "[BULLETSIM SHAPE MESH]"; - private static Dictionary Meshes = new Dictionary(); - - public BSShapeMesh() - { - base.Initialize(); - } - public static BSShape GetReference() { return new BSShapeNull(); } - public override void Dereference(BSScene physicsScene) { } -} - -public class BSShapeHull : BSShape -{ - private static string LogHeader = "[BULLETSIM SHAPE HULL]"; - private static Dictionary Hulls = new Dictionary(); - - public BSShapeHull() - { - base.Initialize(); - } - public static BSShape GetReference() { return new BSShapeNull(); } - public override void Dereference(BSScene physicsScene) { } -} - -public class BSShapeCompound : BSShape -{ - private static string LogHeader = "[BULLETSIM SHAPE COMPOUND]"; - public BSShapeCompound() - { - base.Initialize(); - } - public static BSShape GetReference(BSPhysObject prim) - { - return new BSShapeNull(); - } - public override void Dereference(BSScene physicsScene) { } -} -} +/* + * 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; + +namespace OpenSim.Region.Physics.BulletSPlugin +{ +public abstract class BSShape +{ + public IntPtr ptr { get; set; } + public ShapeData.PhysicsShapeType type { get; set; } + public System.UInt64 key { get; set; } + public int referenceCount { get; set; } + public DateTime lastReferenced { get; set; } + + public BSShape() + { + ptr = IntPtr.Zero; + type = ShapeData.PhysicsShapeType.SHAPE_UNKNOWN; + key = 0; + referenceCount = 0; + lastReferenced = DateTime.Now; + } + + // 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 == ShapeData.PhysicsShapeType.SHAPE_AVATAR) + { + // an avatar capsule is close to a native shape (it is not shared) + ret = BSShapeNative.GetReference(physicsScene, prim, ShapeData.PhysicsShapeType.SHAPE_AVATAR, + ShapeData.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 already been created. + if (ret == null && prim.PreferredPhysicalShape == ShapeData.PhysicsShapeType.SHAPE_COMPOUND) + { + // Getting a reference to a compound shape gets you the compound shape with the root prim shape added + ret = BSShapeCompound.GetReference(prim); + physicsScene.DetailLog("{0},BSShapeCollection.CreateGeom,compoundShape,shape={1}", prim.LocalID, ret); + } + + if (ret == null) + ret = GetShapeReferenceNonSpecial(physicsScene, forceRebuild, prim); + + return ret; + } + public static BSShape GetShapeReferenceNonSpecial(BSScene physicsScene, bool forceRebuild, BSPhysObject prim) + { + return null; + } + public static BSShape GetShapeReferenceNonNative(BSScene physicsScene, bool forceRebuild, BSPhysObject prim) + { + return null; + } + + // 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(); + + public override string ToString() + { + StringBuilder buff = new StringBuilder(); + buff.Append(""); + return buff.ToString(); + } +} + +public class BSShapeNull : BSShape +{ + public BSShapeNull() : base() + { + } + public static BSShape GetReference() { return new BSShapeNull(); } + 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 static BSShape GetReference(BSScene physicsScene, BSPhysObject prim, + ShapeData.PhysicsShapeType shapeType, ShapeData.FixedShapeKey shapeKey) + { + // Native shapes are not shared and are always built anew. + return new BSShapeNative(physicsScene, prim, shapeType, shapeKey); + } + + private BSShapeNative(BSScene physicsScene, BSPhysObject prim, + ShapeData.PhysicsShapeType shapeType, ShapeData.FixedShapeKey shapeKey) + { + ShapeData nativeShapeData = new ShapeData(); + nativeShapeData.Type = shapeType; + nativeShapeData.ID = prim.LocalID; + nativeShapeData.Scale = prim.Scale; + nativeShapeData.Size = prim.Scale; + nativeShapeData.MeshKey = (ulong)shapeKey; + nativeShapeData.HullKey = (ulong)shapeKey; + + + if (shapeType == ShapeData.PhysicsShapeType.SHAPE_AVATAR) + { + ptr = BulletSimAPI.BuildCapsuleShape2(physicsScene.World.ptr, 1f, 1f, prim.Scale); + physicsScene.DetailLog("{0},BSShapeCollection.BuiletPhysicalNativeShape,capsule,scale={1}", prim.LocalID, prim.Scale); + } + else + { + ptr = BulletSimAPI.BuildNativeShape2(physicsScene.World.ptr, nativeShapeData); + } + if (ptr == IntPtr.Zero) + { + 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); + BulletSimAPI.DeleteCollisionShape2(physicsScene.World.ptr, ptr); + ptr = IntPtr.Zero; + // Garbage collection will free up this instance. + } +} + +public class BSShapeMesh : BSShape +{ + private static string LogHeader = "[BULLETSIM SHAPE MESH]"; + private static Dictionary Meshes = new Dictionary(); + + public BSShapeMesh() : base() + { + } + public static BSShape GetReference() { return new BSShapeNull(); } + public override void Dereference(BSScene physicsScene) { } +} + +public class BSShapeHull : BSShape +{ + private static string LogHeader = "[BULLETSIM SHAPE HULL]"; + private static Dictionary Hulls = new Dictionary(); + + public BSShapeHull() : base() + { + } + public static BSShape GetReference() { return new BSShapeNull(); } + public override void Dereference(BSScene physicsScene) { } +} + +public class BSShapeCompound : BSShape +{ + private static string LogHeader = "[BULLETSIM SHAPE COMPOUND]"; + public BSShapeCompound() : base() + { + } + public static BSShape GetReference(BSPhysObject prim) + { + return new BSShapeNull(); + } + public override void Dereference(BSScene physicsScene) { } +} +} -- cgit v1.1 From 2f5fe4b88e8eb0388cc2138c48a941b1317ed560 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 20 Nov 2012 08:34:18 -0800 Subject: BulletSim: tweek avatar capsule parameters so avatar feet don't go below ground. This solves the bouncing, short avatar problem (Mantis 6403). --- OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs | 7 ++++--- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 11 ++++++----- 2 files changed, 10 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 3c48dcc..fa1a23f 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -184,8 +184,8 @@ public sealed class BSCharacter : BSPhysObject _size = value; ComputeAvatarScale(_size); ComputeAvatarVolumeAndMass(); - DetailLog("{0},BSCharacter.setSize,call,scale={1},density={2},volume={3},mass={4}", - LocalID, Scale, _avatarDensity, _avatarVolume, RawMass); + DetailLog("{0},BSCharacter.setSize,call,size={1},scale={2},density={3},volume={4},mass={5}", + LocalID, _size, Scale, _avatarDensity, _avatarVolume, RawMass); PhysicsScene.TaintedObject("BSCharacter.setSize", delegate() { @@ -619,7 +619,8 @@ public sealed class BSCharacter : BSPhysObject newScale.Y = PhysicsScene.Params.avatarCapsuleRadius; // From the total height, remove the capsule half spheres that are at each end - newScale.Z = size.Z - (newScale.X + newScale.Y); + // The 1.15f came from ODE. Not sure what this factors in. + newScale.Z = (size.Z * 1.15f) - (newScale.X + newScale.Y); Scale = newScale; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index 2fee95e..58dccea 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -712,7 +712,7 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters // here just before the physics engine is called to step the simulation. public void ProcessTaints() { - InTaintTime = true; + InTaintTime = true; // Only used for debugging so locking is not necessary. ProcessRegularTaints(); ProcessPostTaintTaints(); InTaintTime = false; @@ -758,6 +758,7 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters DetailLog("{0},BSScene.ProcessTaints,leftTaintsOnList,numNotProcessed={1}", DetailLogZero, _taintOperations.Count); } */ + // swizzle a new list into the list location so we can process what's there List oldList; lock (_taintLock) @@ -787,8 +788,6 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters // will replace any previous operation by the same object. public void PostTaintObject(String ident, uint ID, TaintCallback callback) { - if (!m_initialized) return; - string uniqueIdent = ident + "-" + ID.ToString(); lock (_taintLock) { @@ -864,13 +863,14 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters } } + // Only used for debugging. Does not change state of anything so locking is not necessary. public bool AssertInTaintTime(string whereFrom) { if (!InTaintTime) { DetailLog("{0},BSScene.AssertInTaintTime,NOT IN TAINT TIME,Region={1},Where={2}", DetailLogZero, RegionName, whereFrom); m_log.ErrorFormat("{0} NOT IN TAINT TIME!! Region={1}, Where={2}", LogHeader, RegionName, whereFrom); - Util.PrintCallStack(); + Util.PrintCallStack(); // Prints the stack into the DEBUG log file. } return InTaintTime; } @@ -1186,7 +1186,8 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters (s) => { return s.m_params[0].avatarCapsuleRadius; }, (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].avatarCapsuleRadius, p, l, v); } ), new ParameterDefn("AvatarCapsuleHeight", "Default height of space around avatar", - 1.5f, + // 1.5f, + 2.140599f, (s,cf,p,v) => { s.m_params[0].avatarCapsuleHeight = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].avatarCapsuleHeight; }, (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].avatarCapsuleHeight, p, l, v); } ), -- cgit v1.1 From 4d29488216f3619455cda72aaf2d6ccf8f3e2402 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 20 Nov 2012 08:43:43 -0800 Subject: BulletSim: change PositionSanityCheck to apply a force to correct position corrections (below ground and floating). --- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 61 ++++++++++------------ .../Physics/BulletSPlugin/BSShapeCollection.cs | 2 +- 2 files changed, 30 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 500c84a..b1b5846 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -47,7 +47,6 @@ public sealed class BSPrim : BSPhysObject // _size is what the user passed. Scale is what we pass to the physics engine with the mesh. // Often Scale is unity because the meshmerizer will apply _size when creating the mesh. private OMV.Vector3 _size; // the multiplier for each mesh dimension as passed by the user - // private OMV.Vector3 _scale; // the multiplier for each mesh dimension for the mesh as created by the meshmerizer private bool _grabbed; private bool _isSelected; @@ -274,19 +273,19 @@ public sealed class BSPrim : BSPhysObject if (!Linkset.IsRoot(this)) _position = Linkset.Position(this); - // don't do the GetObjectPosition for root elements because this function is called a zillion times + // don't do the GetObjectPosition for root elements because this function is called a zillion times. // _position = BulletSimAPI.GetObjectPosition2(PhysicsScene.World.ptr, BSBody.ptr); return _position; } set { - // If you must push the position into the physics engine, use ForcePosition. + // If the position must be forced into the physics engine, use ForcePosition. if (_position == value) { return; } _position = value; // TODO: what does it mean to set the position of a child prim?? Rebuild the constraint? - PositionSanityCheck(); + PositionSanityCheck(false); PhysicsScene.TaintedObject("BSPrim.setPosition", delegate() { // DetailLog("{0},BSPrim.SetPosition,taint,pos={1},orient={2}", LocalID, _position, _orientation); @@ -302,7 +301,7 @@ public sealed class BSPrim : BSPhysObject } set { _position = value; - PositionSanityCheck(); + // PositionSanityCheck(); // Don't do this! Causes a loop and caller should know better. BulletSimAPI.SetTranslation2(PhysBody.ptr, _position, _orientation); ActivateIfPhysical(false); } @@ -311,52 +310,43 @@ public sealed class BSPrim : BSPhysObject // Check that the current position is sane and, if not, modify the position to make it so. // Check for being below terrain and being out of bounds. // Returns 'true' of the position was made sane by some action. - private bool PositionSanityCheck() + private bool PositionSanityCheck(bool inTaintTime) { bool ret = false; - // If totally below the ground, move the prim up - // TODO: figure out the right solution for this... only for dynamic objects? - /* float terrainHeight = PhysicsScene.TerrainManager.GetTerrainHeightAtXYZ(_position); + OMV.Vector3 upForce = OMV.Vector3.Zero; if (Position.Z < terrainHeight) { DetailLog("{0},BSPrim.PositionAdjustUnderGround,call,pos={1},terrain={2}", LocalID, _position, terrainHeight); - _position.Z = terrainHeight + 2.0f; + float targetHeight = terrainHeight + (Size.Z / 2f); + // Upforce proportional to the distance away from the terrain. Correct the error in 1 sec. + upForce.Z = (terrainHeight - Position.Z) * 1f; ret = true; } - */ + if ((CurrentCollisionFlags & CollisionFlags.BS_FLOATS_ON_WATER) != 0) { float waterHeight = PhysicsScene.GetWaterLevelAtXYZ(_position); // TODO: a floating motor so object will bob in the water - if (Position.Z < waterHeight) + if (Math.Abs(Position.Z - waterHeight) > 0.1f) { - _position.Z = waterHeight; + // Upforce proportional to the distance away from the water. Correct the error in 1 sec. + upForce.Z = (waterHeight - Position.Z) * 1f; ret = true; } } // TODO: check for out of bounds - return ret; - } - // A version of the sanity check that also makes sure a new position value is - // pushed to the physics engine. This routine would be used by anyone - // who is not already pushing the value. - private bool PositionSanityCheck(bool inTaintTime) - { - bool ret = false; - if (PositionSanityCheck()) + // The above code computes a force to apply to correct any out-of-bounds problems. Apply same. + if (ret) { - // 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, "BSPrim.PositionSanityCheck", delegate() + PhysicsScene.TaintedObject(inTaintTime, "BSPrim.PositionSanityCheck:belowTerrain", delegate() { - DetailLog("{0},BSPrim.PositionSanityCheck,taint,pos={1},orient={2}", LocalID, _position, _orientation); - ForcePosition = _position; + // Apply upforce and overcome gravity. + ForceVelocity = ForceVelocity + upForce - PhysicsScene.DefaultGravity; }); - ret = true; } return ret; } @@ -940,6 +930,7 @@ public sealed class BSPrim : BSPhysObject public override void AddForce(OMV.Vector3 force, bool pushforce) { AddForce(force, pushforce, false); } + // Applying a force just adds this to the total force on the object. public void AddForce(OMV.Vector3 force, bool pushforce, bool inTaintTime) { // for an object, doesn't matter if force is a pushforce or not if (force.IsFinite()) @@ -971,6 +962,7 @@ public sealed class BSPrim : BSPhysObject }); } + // An impulse force is scaled by the mass of the object. public void ApplyForceImpulse(OMV.Vector3 impulse, bool inTaintTime) { OMV.Vector3 applyImpulse = impulse; @@ -1423,7 +1415,7 @@ public sealed class BSPrim : BSPhysObject if (changed != 0) { // Only update the position of single objects and linkset roots - if (this._parentPrim == null) + if (Linkset.IsRoot(this)) { base.RequestPhysicsterseUpdate(); } @@ -1435,19 +1427,24 @@ public sealed class BSPrim : BSPhysObject // Updates only for individual prims and for the root object of a linkset. if (Linkset.IsRoot(this)) { - // Assign to the local variables so the normal set action does not happen + // Assign directly to the local variables so the normal set action does not happen _position = entprop.Position; _orientation = entprop.Rotation; _velocity = entprop.Velocity; _acceleration = entprop.Acceleration; _rotationalVelocity = entprop.RotationalVelocity; + // The sanity check can change the velocity and/or position. + if (PositionSanityCheck(true)) + { + entprop.Position = _position; + entprop.Velocity = _velocity; + } + // remember the current and last set values LastEntityProperties = CurrentEntityProperties; CurrentEntityProperties = entprop; - PositionSanityCheck(true); - OMV.Vector3 direction = OMV.Vector3.UnitX * _orientation; DetailLog("{0},BSPrim.UpdateProperties,call,pos={1},orient={2},dir={3},vel={4},rotVel={5}", LocalID, _position, _orientation, direction, _velocity, _rotationalVelocity); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index 29a23c0..7ef6429 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -940,7 +940,7 @@ public sealed class BSShapeCollection : IDisposable else { bodyPtr = BulletSimAPI.CreateGhostFromShape2(sim.ptr, shape.ptr, - prim.LocalID, prim.ForcePosition, prim.ForceOrientation); + prim.LocalID, prim.RawPosition, prim.RawOrientation); DetailLog("{0},BSShapeCollection.CreateBody,ghost,ptr={1}", prim.LocalID, bodyPtr.ToString("X")); } aBody = new BulletBody(prim.LocalID, bodyPtr); -- cgit v1.1 From d6db0d5740dae03174f65846556f2f06d573b5c4 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 20 Nov 2012 11:24:25 -0800 Subject: BulletSim: uplevel PhysicsShapeType out of ShapeData structure (since it is getting simplified out of existance someday) and update all the references to that enum. --- .../Region/Physics/BulletSPlugin/BSCharacter.cs | 4 +- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 4 +- .../Physics/BulletSPlugin/BSLinksetCompound.cs | 6 +-- .../Region/Physics/BulletSPlugin/BSPhysObject.cs | 4 +- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 2 +- .../Physics/BulletSPlugin/BSShapeCollection.cs | 56 +++++++++++----------- OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs | 16 +++---- .../Physics/BulletSPlugin/BSTerrainManager.cs | 4 +- .../Region/Physics/BulletSPlugin/BulletSimAPI.cs | 37 +++++++------- 9 files changed, 67 insertions(+), 66 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index fa1a23f..92ff804 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -203,9 +203,9 @@ public sealed class BSCharacter : BSPhysObject set { BaseShape = value; } } // I want the physics engine to make an avatar capsule - public override ShapeData.PhysicsShapeType PreferredPhysicalShape + public override PhysicsShapeType PreferredPhysicalShape { - get {return ShapeData.PhysicsShapeType.SHAPE_AVATAR; } + get {return PhysicsShapeType.SHAPE_AVATAR; } } public override bool Grabbed { diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index 436e043..4ee047b 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -82,9 +82,9 @@ public abstract class BSLinkset // Some linksets have a preferred physical shape. // Returns SHAPE_UNKNOWN if there is no preference. Causes the correct shape to be selected. - public virtual ShapeData.PhysicsShapeType PreferredPhysicalShape(BSPhysObject requestor) + public virtual PhysicsShapeType PreferredPhysicalShape(BSPhysObject requestor) { - return ShapeData.PhysicsShapeType.SHAPE_UNKNOWN; + return PhysicsShapeType.SHAPE_UNKNOWN; } // Linksets move around the children so the linkset might need to compute the child position diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs index 3238c85..cb37840 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs @@ -42,12 +42,12 @@ public sealed class BSLinksetCompound : BSLinkset } // For compound implimented linksets, if there are children, use compound shape for the root. - public override ShapeData.PhysicsShapeType PreferredPhysicalShape(BSPhysObject requestor) + public override PhysicsShapeType PreferredPhysicalShape(BSPhysObject requestor) { - ShapeData.PhysicsShapeType ret = ShapeData.PhysicsShapeType.SHAPE_UNKNOWN; + PhysicsShapeType ret = PhysicsShapeType.SHAPE_UNKNOWN; if (IsRoot(requestor) && HasAnyChildren) { - ret = ShapeData.PhysicsShapeType.SHAPE_COMPOUND; + ret = PhysicsShapeType.SHAPE_COMPOUND; } // DetailLog("{0},BSLinksetCompound.PreferredPhysicalShape,call,shape={1}", LinksetRoot.LocalID, ret); return ret; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index 991e5b1..e68b167 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -94,9 +94,9 @@ public abstract class BSPhysObject : PhysicsActor public PrimitiveBaseShape BaseShape { get; protected set; } // Some types of objects have preferred physical representations. // Returns SHAPE_UNKNOWN if there is no preference. - public virtual ShapeData.PhysicsShapeType PreferredPhysicalShape + public virtual PhysicsShapeType PreferredPhysicalShape { - get { return ShapeData.PhysicsShapeType.SHAPE_UNKNOWN; } + get { return PhysicsShapeType.SHAPE_UNKNOWN; } } // When the physical properties are updated, an EntityProperty holds the update values. diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index b1b5846..2657e4b 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -169,7 +169,7 @@ public sealed class BSPrim : BSPhysObject } } // Whatever the linkset wants is what I want. - public override ShapeData.PhysicsShapeType PreferredPhysicalShape + public override PhysicsShapeType PreferredPhysicalShape { get { return Linkset.PreferredPhysicalShape(this); } } public override bool ForceBodyShapeRebuild(bool inTaintTime) diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index 7ef6429..746a52e 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -178,7 +178,7 @@ public sealed class BSShapeCollection : IDisposable bool ret = false; switch (shape.type) { - case ShapeData.PhysicsShapeType.SHAPE_MESH: + case PhysicsShapeType.SHAPE_MESH: MeshDesc meshDesc; if (Meshes.TryGetValue(shape.shapeKey, out meshDesc)) { @@ -201,7 +201,7 @@ public sealed class BSShapeCollection : IDisposable meshDesc.lastReferenced = System.DateTime.Now; Meshes[shape.shapeKey] = meshDesc; break; - case ShapeData.PhysicsShapeType.SHAPE_HULL: + case PhysicsShapeType.SHAPE_HULL: HullDesc hullDesc; if (Hulls.TryGetValue(shape.shapeKey, out hullDesc)) { @@ -224,7 +224,7 @@ public sealed class BSShapeCollection : IDisposable hullDesc.lastReferenced = System.DateTime.Now; Hulls[shape.shapeKey] = hullDesc; break; - case ShapeData.PhysicsShapeType.SHAPE_UNKNOWN: + case PhysicsShapeType.SHAPE_UNKNOWN: break; default: // Native shapes are not tracked and they don't go into any list @@ -255,16 +255,16 @@ public sealed class BSShapeCollection : IDisposable { switch (shape.type) { - case ShapeData.PhysicsShapeType.SHAPE_HULL: + case PhysicsShapeType.SHAPE_HULL: DereferenceHull(shape, shapeCallback); break; - case ShapeData.PhysicsShapeType.SHAPE_MESH: + case PhysicsShapeType.SHAPE_MESH: DereferenceMesh(shape, shapeCallback); break; - case ShapeData.PhysicsShapeType.SHAPE_COMPOUND: + case PhysicsShapeType.SHAPE_COMPOUND: DereferenceCompound(shape, shapeCallback); break; - case ShapeData.PhysicsShapeType.SHAPE_UNKNOWN: + case PhysicsShapeType.SHAPE_UNKNOWN: break; default: break; @@ -352,28 +352,28 @@ public sealed class BSShapeCollection : IDisposable BulletShape shapeInfo = new BulletShape(cShape); if (TryGetMeshByPtr(cShape, out meshDesc)) { - shapeInfo.type = ShapeData.PhysicsShapeType.SHAPE_MESH; + shapeInfo.type = PhysicsShapeType.SHAPE_MESH; shapeInfo.shapeKey = meshDesc.shapeKey; } else { if (TryGetHullByPtr(cShape, out hullDesc)) { - shapeInfo.type = ShapeData.PhysicsShapeType.SHAPE_HULL; + shapeInfo.type = PhysicsShapeType.SHAPE_HULL; shapeInfo.shapeKey = hullDesc.shapeKey; } else { if (BulletSimAPI.IsCompound2(cShape)) { - shapeInfo.type = ShapeData.PhysicsShapeType.SHAPE_COMPOUND; + shapeInfo.type = PhysicsShapeType.SHAPE_COMPOUND; } else { if (BulletSimAPI.IsNativeShape2(cShape)) { shapeInfo.isNativeShape = true; - shapeInfo.type = ShapeData.PhysicsShapeType.SHAPE_BOX; // (technically, type doesn't matter) + shapeInfo.type = PhysicsShapeType.SHAPE_BOX; // (technically, type doesn't matter) } } } @@ -381,7 +381,7 @@ public sealed class BSShapeCollection : IDisposable DetailLog("{0},BSShapeCollection.DereferenceAnonCollisionShape,shape={1}", BSScene.DetailLogZero, shapeInfo); - if (shapeInfo.type != ShapeData.PhysicsShapeType.SHAPE_UNKNOWN) + if (shapeInfo.type != PhysicsShapeType.SHAPE_UNKNOWN) { DereferenceShape(shapeInfo, true, null); } @@ -405,10 +405,10 @@ public sealed class BSShapeCollection : IDisposable bool ret = false; bool haveShape = false; - if (!haveShape && prim.PreferredPhysicalShape == ShapeData.PhysicsShapeType.SHAPE_AVATAR) + if (!haveShape && prim.PreferredPhysicalShape == PhysicsShapeType.SHAPE_AVATAR) { // an avatar capsule is close to a native shape (it is not shared) - ret = GetReferenceToNativeShape(prim, ShapeData.PhysicsShapeType.SHAPE_AVATAR, + ret = GetReferenceToNativeShape(prim, PhysicsShapeType.SHAPE_AVATAR, ShapeData.FixedShapeKey.KEY_CAPSULE, shapeCallback); DetailLog("{0},BSShapeCollection.CreateGeom,avatarCapsule,shape={1}", prim.LocalID, prim.PhysShape); ret = true; @@ -417,7 +417,7 @@ public sealed class BSShapeCollection : IDisposable // 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 already been created. - if (!haveShape && prim.PreferredPhysicalShape == ShapeData.PhysicsShapeType.SHAPE_COMPOUND) + if (!haveShape && prim.PreferredPhysicalShape == PhysicsShapeType.SHAPE_COMPOUND) { ret = GetReferenceToCompoundShape(prim, shapeCallback); DetailLog("{0},BSShapeCollection.CreateGeom,compoundShape,shape={1}", prim.LocalID, prim.PhysShape); @@ -460,10 +460,10 @@ public sealed class BSShapeCollection : IDisposable haveShape = true; if (forceRebuild || prim.Scale != prim.Size - || prim.PhysShape.type != ShapeData.PhysicsShapeType.SHAPE_SPHERE + || prim.PhysShape.type != PhysicsShapeType.SHAPE_SPHERE ) { - ret = GetReferenceToNativeShape(prim, ShapeData.PhysicsShapeType.SHAPE_SPHERE, + ret = GetReferenceToNativeShape(prim, PhysicsShapeType.SHAPE_SPHERE, ShapeData.FixedShapeKey.KEY_SPHERE, shapeCallback); DetailLog("{0},BSShapeCollection.CreateGeom,sphere,force={1},shape={2}", prim.LocalID, forceRebuild, prim.PhysShape); @@ -474,10 +474,10 @@ public sealed class BSShapeCollection : IDisposable haveShape = true; if (forceRebuild || prim.Scale != prim.Size - || prim.PhysShape.type != ShapeData.PhysicsShapeType.SHAPE_BOX + || prim.PhysShape.type != PhysicsShapeType.SHAPE_BOX ) { - ret = GetReferenceToNativeShape( prim, ShapeData.PhysicsShapeType.SHAPE_BOX, + ret = GetReferenceToNativeShape( prim, PhysicsShapeType.SHAPE_BOX, ShapeData.FixedShapeKey.KEY_BOX, shapeCallback); DetailLog("{0},BSShapeCollection.CreateGeom,box,force={1},shape={2}", prim.LocalID, forceRebuild, prim.PhysShape); @@ -519,7 +519,7 @@ public sealed class BSShapeCollection : IDisposable // 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, - ShapeData.PhysicsShapeType shapeType, ShapeData.FixedShapeKey shapeKey, + PhysicsShapeType shapeType, ShapeData.FixedShapeKey shapeKey, ShapeDestructionCallback shapeCallback) { // release any previous shape @@ -538,7 +538,7 @@ public sealed class BSShapeCollection : IDisposable return true; } - private BulletShape BuildPhysicalNativeShape(BSPhysObject prim, ShapeData.PhysicsShapeType shapeType, + private BulletShape BuildPhysicalNativeShape(BSPhysObject prim, PhysicsShapeType shapeType, ShapeData.FixedShapeKey shapeKey) { BulletShape newShape; @@ -551,7 +551,7 @@ public sealed class BSShapeCollection : IDisposable nativeShapeData.MeshKey = (ulong)shapeKey; nativeShapeData.HullKey = (ulong)shapeKey; - if (shapeType == ShapeData.PhysicsShapeType.SHAPE_AVATAR) + if (shapeType == PhysicsShapeType.SHAPE_AVATAR) { newShape = new BulletShape( BulletSimAPI.BuildCapsuleShape2(PhysicsScene.World.ptr, 1f, 1f, prim.Scale) @@ -585,7 +585,7 @@ public sealed class BSShapeCollection : IDisposable 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 == ShapeData.PhysicsShapeType.SHAPE_MESH) + if (newMeshKey == prim.PhysShape.shapeKey && prim.PhysShape.type == PhysicsShapeType.SHAPE_MESH) return false; DetailLog("{0},BSShapeCollection.GetReferenceToMesh,create,oldKey={1},newKey={2}", @@ -643,7 +643,7 @@ public sealed class BSShapeCollection : IDisposable indices.GetLength(0), indices, vertices.Count, verticesAsFloats); } } - BulletShape newShape = new BulletShape(meshPtr, ShapeData.PhysicsShapeType.SHAPE_MESH); + BulletShape newShape = new BulletShape(meshPtr, PhysicsShapeType.SHAPE_MESH); newShape.shapeKey = newMeshKey; return newShape; @@ -659,7 +659,7 @@ public sealed class BSShapeCollection : IDisposable 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 == ShapeData.PhysicsShapeType.SHAPE_HULL) + if (newHullKey == prim.PhysShape.shapeKey && prim.PhysShape.type == PhysicsShapeType.SHAPE_HULL) return false; DetailLog("{0},BSShapeCollection.GetReferenceToHull,create,oldKey={1},newKey={2}", @@ -780,7 +780,7 @@ public sealed class BSShapeCollection : IDisposable } } - BulletShape newShape = new BulletShape(hullPtr, ShapeData.PhysicsShapeType.SHAPE_HULL); + BulletShape newShape = new BulletShape(hullPtr, PhysicsShapeType.SHAPE_HULL); newShape.shapeKey = newHullKey; return newShape; // 'true' means a new shape has been added to this prim @@ -803,7 +803,7 @@ public sealed class BSShapeCollection : IDisposable // DereferenceShape(prim.PhysShape, true, shapeCallback); BulletShape cShape = new BulletShape( - BulletSimAPI.CreateCompoundShape2(PhysicsScene.World.ptr, false), ShapeData.PhysicsShapeType.SHAPE_COMPOUND); + BulletSimAPI.CreateCompoundShape2(PhysicsScene.World.ptr, false), PhysicsShapeType.SHAPE_COMPOUND); // Create the shape for the root prim and add it to the compound shape. Cannot be a native shape. CreateGeomMeshOrHull(prim, shapeCallback); @@ -894,7 +894,7 @@ public sealed class BSShapeCollection : IDisposable // While we figure out the real problem, stick a simple native shape on the object. BulletShape fillinShape = - BuildPhysicalNativeShape(prim, ShapeData.PhysicsShapeType.SHAPE_BOX, ShapeData.FixedShapeKey.KEY_BOX); + BuildPhysicalNativeShape(prim, PhysicsShapeType.SHAPE_BOX, ShapeData.FixedShapeKey.KEY_BOX); return fillinShape; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs index d59a486..2896805 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs @@ -35,7 +35,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin public abstract class BSShape { public IntPtr ptr { get; set; } - public ShapeData.PhysicsShapeType type { get; set; } + public PhysicsShapeType type { get; set; } public System.UInt64 key { get; set; } public int referenceCount { get; set; } public DateTime lastReferenced { get; set; } @@ -43,7 +43,7 @@ public abstract class BSShape public BSShape() { ptr = IntPtr.Zero; - type = ShapeData.PhysicsShapeType.SHAPE_UNKNOWN; + type = PhysicsShapeType.SHAPE_UNKNOWN; key = 0; referenceCount = 0; lastReferenced = DateTime.Now; @@ -54,17 +54,17 @@ public abstract class BSShape { BSShape ret = null; - if (prim.PreferredPhysicalShape == ShapeData.PhysicsShapeType.SHAPE_AVATAR) + if (prim.PreferredPhysicalShape == PhysicsShapeType.SHAPE_AVATAR) { // an avatar capsule is close to a native shape (it is not shared) - ret = BSShapeNative.GetReference(physicsScene, prim, ShapeData.PhysicsShapeType.SHAPE_AVATAR, + ret = BSShapeNative.GetReference(physicsScene, prim, PhysicsShapeType.SHAPE_AVATAR, ShapeData.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 already been created. - if (ret == null && prim.PreferredPhysicalShape == ShapeData.PhysicsShapeType.SHAPE_COMPOUND) + if (ret == null && prim.PreferredPhysicalShape == PhysicsShapeType.SHAPE_COMPOUND) { // Getting a reference to a compound shape gets you the compound shape with the root prim shape added ret = BSShapeCompound.GetReference(prim); @@ -123,14 +123,14 @@ public class BSShapeNative : BSShape { } public static BSShape GetReference(BSScene physicsScene, BSPhysObject prim, - ShapeData.PhysicsShapeType shapeType, ShapeData.FixedShapeKey shapeKey) + PhysicsShapeType shapeType, ShapeData.FixedShapeKey shapeKey) { // Native shapes are not shared and are always built anew. return new BSShapeNative(physicsScene, prim, shapeType, shapeKey); } private BSShapeNative(BSScene physicsScene, BSPhysObject prim, - ShapeData.PhysicsShapeType shapeType, ShapeData.FixedShapeKey shapeKey) + PhysicsShapeType shapeType, ShapeData.FixedShapeKey shapeKey) { ShapeData nativeShapeData = new ShapeData(); nativeShapeData.Type = shapeType; @@ -141,7 +141,7 @@ public class BSShapeNative : BSShape nativeShapeData.HullKey = (ulong)shapeKey; - if (shapeType == ShapeData.PhysicsShapeType.SHAPE_AVATAR) + if (shapeType == PhysicsShapeType.SHAPE_AVATAR) { ptr = BulletSimAPI.BuildCapsuleShape2(physicsScene.World.ptr, 1f, 1f, prim.Scale); physicsScene.DetailLog("{0},BSShapeCollection.BuiletPhysicalNativeShape,capsule,scale={1}", prim.LocalID, prim.Scale); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs index 7c34af2..cc28e4d 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs @@ -109,7 +109,7 @@ public sealed class BSTerrainManager // The ground plane is here to catch things that are trying to drop to negative infinity BulletShape groundPlaneShape = new BulletShape( BulletSimAPI.CreateGroundPlaneShape2(BSScene.GROUNDPLANE_ID, 1f, TERRAIN_COLLISION_MARGIN), - ShapeData.PhysicsShapeType.SHAPE_GROUNDPLANE); + PhysicsShapeType.SHAPE_GROUNDPLANE); m_groundPlane = new BulletBody(BSScene.GROUNDPLANE_ID, BulletSimAPI.CreateBodyWithDefaultMotionState2(groundPlaneShape.ptr, BSScene.GROUNDPLANE_ID, Vector3.Zero, Quaternion.Identity)); @@ -299,7 +299,7 @@ public sealed class BSTerrainManager // Create the terrain shape from the mapInfo mapInfo.terrainShape = new BulletShape(BulletSimAPI.CreateTerrainShape2(mapInfo.Ptr), - ShapeData.PhysicsShapeType.SHAPE_TERRAIN); + PhysicsShapeType.SHAPE_TERRAIN); // The terrain object initial position is at the center of the object Vector3 centerPos; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs index 28fae13..bb63b0a 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs @@ -88,11 +88,11 @@ public struct BulletShape public BulletShape(IntPtr xx) { ptr = xx; - type=ShapeData.PhysicsShapeType.SHAPE_UNKNOWN; + type=PhysicsShapeType.SHAPE_UNKNOWN; shapeKey = 0; isNativeShape = false; } - public BulletShape(IntPtr xx, ShapeData.PhysicsShapeType typ) + public BulletShape(IntPtr xx, PhysicsShapeType typ) { ptr = xx; type = typ; @@ -100,7 +100,7 @@ public struct BulletShape isNativeShape = false; } public IntPtr ptr; - public ShapeData.PhysicsShapeType type; + public PhysicsShapeType type; public System.UInt64 shapeKey; public bool isNativeShape; public override string ToString() @@ -178,24 +178,25 @@ public struct ConvexHull int VertexCount; Vector3[] Vertices; } +public enum PhysicsShapeType +{ + SHAPE_UNKNOWN = 0, + SHAPE_AVATAR = 1, + SHAPE_BOX = 2, + SHAPE_CONE = 3, + SHAPE_CYLINDER = 4, + SHAPE_SPHERE = 5, + SHAPE_MESH = 6, + SHAPE_HULL = 7, + // following defined by BulletSim + SHAPE_GROUNDPLANE = 20, + SHAPE_TERRAIN = 21, + SHAPE_COMPOUND = 22, + SHAPE_HEIGHTMAP = 23, +}; [StructLayout(LayoutKind.Sequential)] public struct ShapeData { - public enum PhysicsShapeType - { - SHAPE_UNKNOWN = 0, - SHAPE_AVATAR = 1, - SHAPE_BOX = 2, - SHAPE_CONE = 3, - SHAPE_CYLINDER = 4, - SHAPE_SPHERE = 5, - SHAPE_MESH = 6, - SHAPE_HULL = 7, - // following defined by BulletSim - SHAPE_GROUNDPLANE = 20, - SHAPE_TERRAIN = 21, - SHAPE_COMPOUND = 22, - }; public uint ID; public PhysicsShapeType Type; public Vector3 Position; -- cgit v1.1 From 65e55ada87e110b65f3d69eb0a4f2402fb1f3ece Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 20 Nov 2012 11:30:22 -0800 Subject: BulletSim: uplevel FixedShapeKey out of ShapeData structure (since it is getting simplified out of existance someday) and update all the references to same. --- .../Physics/BulletSPlugin/BSShapeCollection.cs | 12 +++++------ OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs | 6 +++--- .../Region/Physics/BulletSPlugin/BulletSimAPI.cs | 24 ++++++++++++---------- 3 files changed, 22 insertions(+), 20 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index 746a52e..0232618 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -409,7 +409,7 @@ public sealed class BSShapeCollection : IDisposable { // an avatar capsule is close to a native shape (it is not shared) ret = GetReferenceToNativeShape(prim, PhysicsShapeType.SHAPE_AVATAR, - ShapeData.FixedShapeKey.KEY_CAPSULE, shapeCallback); + FixedShapeKey.KEY_CAPSULE, shapeCallback); DetailLog("{0},BSShapeCollection.CreateGeom,avatarCapsule,shape={1}", prim.LocalID, prim.PhysShape); ret = true; haveShape = true; @@ -464,7 +464,7 @@ public sealed class BSShapeCollection : IDisposable ) { ret = GetReferenceToNativeShape(prim, PhysicsShapeType.SHAPE_SPHERE, - ShapeData.FixedShapeKey.KEY_SPHERE, shapeCallback); + FixedShapeKey.KEY_SPHERE, shapeCallback); DetailLog("{0},BSShapeCollection.CreateGeom,sphere,force={1},shape={2}", prim.LocalID, forceRebuild, prim.PhysShape); } @@ -478,7 +478,7 @@ public sealed class BSShapeCollection : IDisposable ) { ret = GetReferenceToNativeShape( prim, PhysicsShapeType.SHAPE_BOX, - ShapeData.FixedShapeKey.KEY_BOX, shapeCallback); + FixedShapeKey.KEY_BOX, shapeCallback); DetailLog("{0},BSShapeCollection.CreateGeom,box,force={1},shape={2}", prim.LocalID, forceRebuild, prim.PhysShape); } @@ -519,7 +519,7 @@ public sealed class BSShapeCollection : IDisposable // 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, - PhysicsShapeType shapeType, ShapeData.FixedShapeKey shapeKey, + PhysicsShapeType shapeType, FixedShapeKey shapeKey, ShapeDestructionCallback shapeCallback) { // release any previous shape @@ -539,7 +539,7 @@ public sealed class BSShapeCollection : IDisposable } private BulletShape BuildPhysicalNativeShape(BSPhysObject prim, PhysicsShapeType shapeType, - ShapeData.FixedShapeKey shapeKey) + FixedShapeKey shapeKey) { BulletShape newShape; // Need to make sure the passed shape information is for the native type. @@ -894,7 +894,7 @@ public sealed class BSShapeCollection : IDisposable // While we figure out the real problem, stick a simple native shape on the object. BulletShape fillinShape = - BuildPhysicalNativeShape(prim, PhysicsShapeType.SHAPE_BOX, ShapeData.FixedShapeKey.KEY_BOX); + BuildPhysicalNativeShape(prim, PhysicsShapeType.SHAPE_BOX, FixedShapeKey.KEY_BOX); return fillinShape; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs index 2896805..71b5074 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs @@ -58,7 +58,7 @@ public abstract class BSShape { // an avatar capsule is close to a native shape (it is not shared) ret = BSShapeNative.GetReference(physicsScene, prim, PhysicsShapeType.SHAPE_AVATAR, - ShapeData.FixedShapeKey.KEY_CAPSULE); + FixedShapeKey.KEY_CAPSULE); physicsScene.DetailLog("{0},BSShape.GetShapeReference,avatarCapsule,shape={1}", prim.LocalID, ret); } @@ -123,14 +123,14 @@ public class BSShapeNative : BSShape { } public static BSShape GetReference(BSScene physicsScene, BSPhysObject prim, - PhysicsShapeType shapeType, ShapeData.FixedShapeKey shapeKey) + PhysicsShapeType shapeType, FixedShapeKey shapeKey) { // Native shapes are not shared and are always built anew. return new BSShapeNative(physicsScene, prim, shapeType, shapeKey); } private BSShapeNative(BSScene physicsScene, BSPhysObject prim, - PhysicsShapeType shapeType, ShapeData.FixedShapeKey shapeKey) + PhysicsShapeType shapeType, FixedShapeKey shapeKey) { ShapeData nativeShapeData = new ShapeData(); nativeShapeData.Type = shapeType; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs index bb63b0a..75e7f99 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs @@ -89,7 +89,7 @@ public struct BulletShape { ptr = xx; type=PhysicsShapeType.SHAPE_UNKNOWN; - shapeKey = 0; + shapeKey = (System.UInt64)FixedShapeKey.KEY_NONE; isNativeShape = false; } public BulletShape(IntPtr xx, PhysicsShapeType typ) @@ -194,6 +194,18 @@ public enum PhysicsShapeType SHAPE_COMPOUND = 22, SHAPE_HEIGHTMAP = 23, }; + +// The native shapes have predefined shape hash keys +public enum FixedShapeKey : ulong +{ + KEY_NONE = 0, + KEY_BOX = 1, + KEY_SPHERE = 2, + KEY_CONE = 3, + KEY_CYLINDER = 4, + KEY_CAPSULE = 5, +} + [StructLayout(LayoutKind.Sequential)] public struct ShapeData { @@ -217,16 +229,6 @@ public struct ShapeData // note that bools are passed as floats since bool size changes by language and architecture public const float numericTrue = 1f; public const float numericFalse = 0f; - - // The native shapes have predefined shape hash keys - public enum FixedShapeKey : ulong - { - KEY_BOX = 1, - KEY_SPHERE = 2, - KEY_CONE = 3, - KEY_CYLINDER = 4, - KEY_CAPSULE = 5, - } } [StructLayout(LayoutKind.Sequential)] public struct SweepHit -- cgit v1.1 From 8dd5813889b17cc213d20491b41dbf8142b3ccb9 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 20 Nov 2012 11:33:42 -0800 Subject: BulletSim: rename SHAPE_AVATAR to SHAPE_CAPSULE with the eye to eventually having mesh avatars. --- OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs | 2 +- OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs | 6 +++--- OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs | 6 +++--- OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs | 2 +- 4 files changed, 8 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 92ff804..799211e 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -205,7 +205,7 @@ public sealed class BSCharacter : BSPhysObject // I want the physics engine to make an avatar capsule public override PhysicsShapeType PreferredPhysicalShape { - get {return PhysicsShapeType.SHAPE_AVATAR; } + get {return PhysicsShapeType.SHAPE_CAPSULE; } } public override bool Grabbed { diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index 0232618..a53ad6e 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -405,10 +405,10 @@ public sealed class BSShapeCollection : IDisposable bool ret = false; bool haveShape = false; - if (!haveShape && prim.PreferredPhysicalShape == PhysicsShapeType.SHAPE_AVATAR) + if (!haveShape && prim.PreferredPhysicalShape == PhysicsShapeType.SHAPE_CAPSULE) { // an avatar capsule is close to a native shape (it is not shared) - ret = GetReferenceToNativeShape(prim, PhysicsShapeType.SHAPE_AVATAR, + ret = GetReferenceToNativeShape(prim, PhysicsShapeType.SHAPE_CAPSULE, FixedShapeKey.KEY_CAPSULE, shapeCallback); DetailLog("{0},BSShapeCollection.CreateGeom,avatarCapsule,shape={1}", prim.LocalID, prim.PhysShape); ret = true; @@ -551,7 +551,7 @@ public sealed class BSShapeCollection : IDisposable nativeShapeData.MeshKey = (ulong)shapeKey; nativeShapeData.HullKey = (ulong)shapeKey; - if (shapeType == PhysicsShapeType.SHAPE_AVATAR) + if (shapeType == PhysicsShapeType.SHAPE_CAPSULE) { newShape = new BulletShape( BulletSimAPI.BuildCapsuleShape2(PhysicsScene.World.ptr, 1f, 1f, prim.Scale) diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs index 71b5074..f2e62d9 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs @@ -54,10 +54,10 @@ public abstract class BSShape { BSShape ret = null; - if (prim.PreferredPhysicalShape == PhysicsShapeType.SHAPE_AVATAR) + if (prim.PreferredPhysicalShape == PhysicsShapeType.SHAPE_CAPSULE) { // an avatar capsule is close to a native shape (it is not shared) - ret = BSShapeNative.GetReference(physicsScene, prim, PhysicsShapeType.SHAPE_AVATAR, + ret = BSShapeNative.GetReference(physicsScene, prim, PhysicsShapeType.SHAPE_CAPSULE, FixedShapeKey.KEY_CAPSULE); physicsScene.DetailLog("{0},BSShape.GetShapeReference,avatarCapsule,shape={1}", prim.LocalID, ret); } @@ -141,7 +141,7 @@ public class BSShapeNative : BSShape nativeShapeData.HullKey = (ulong)shapeKey; - if (shapeType == PhysicsShapeType.SHAPE_AVATAR) + if (shapeType == PhysicsShapeType.SHAPE_CAPSULE) { ptr = BulletSimAPI.BuildCapsuleShape2(physicsScene.World.ptr, 1f, 1f, prim.Scale); physicsScene.DetailLog("{0},BSShapeCollection.BuiletPhysicalNativeShape,capsule,scale={1}", prim.LocalID, prim.Scale); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs index 75e7f99..407d6d7 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs @@ -181,7 +181,7 @@ public struct ConvexHull public enum PhysicsShapeType { SHAPE_UNKNOWN = 0, - SHAPE_AVATAR = 1, + SHAPE_CAPSULE = 1, SHAPE_BOX = 2, SHAPE_CONE = 3, SHAPE_CYLINDER = 4, -- cgit v1.1 From 71b9640dfa67e830769aad64ef208d767e102c92 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 20 Nov 2012 14:51:50 -0800 Subject: BulletSim: pull heightmap implementation out of the terrain manager so a mesh terrain can be implemented. --- .../Physics/BulletSPlugin/BSTerrainHeightmap.cs | 174 ++++++++++++++ .../Physics/BulletSPlugin/BSTerrainManager.cs | 257 +++++++-------------- .../Region/Physics/BulletSPlugin/BSTerrainMesh.cs | 73 ++++++ .../Region/Physics/BulletSPlugin/BulletSimAPI.cs | 4 +- 4 files changed, 327 insertions(+), 181 deletions(-) create mode 100755 OpenSim/Region/Physics/BulletSPlugin/BSTerrainHeightmap.cs create mode 100755 OpenSim/Region/Physics/BulletSPlugin/BSTerrainMesh.cs (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainHeightmap.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainHeightmap.cs new file mode 100755 index 0000000..3bb63cd --- /dev/null +++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainHeightmap.cs @@ -0,0 +1,174 @@ +/* + * 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 OpenSim.Framework; +using OpenSim.Region.Framework; +using OpenSim.Region.CoreModules; +using OpenSim.Region.Physics.Manager; + +using Nini.Config; +using log4net; + +using OpenMetaverse; + +namespace OpenSim.Region.Physics.BulletSPlugin +{ +public sealed class BSTerrainHeightmap : BSTerrainPhys +{ + static string LogHeader = "[BULLETSIM TERRAIN HEIGHTMAP]"; + + BulletHeightMapInfo m_mapInfo; + + public BSTerrainHeightmap(BSScene physicsScene, uint id, Vector3 regionSize) + : base(physicsScene) + { + Vector3 minTerrainCoords = new Vector3(0f, 0f, BSTerrainManager.HEIGHT_INITIALIZATION - BSTerrainManager.HEIGHT_EQUAL_FUDGE); + Vector3 maxTerrainCoords = new Vector3(regionSize.X, regionSize.Y, BSTerrainManager.HEIGHT_INITIALIZATION); + int totalHeights = (int)maxTerrainCoords.X * (int)maxTerrainCoords.Y; + float[] initialMap = new float[totalHeights]; + for (int ii = 0; ii < totalHeights; ii++) + { + initialMap[ii] = BSTerrainManager.HEIGHT_INITIALIZATION; + } + m_mapInfo = new BulletHeightMapInfo(id, initialMap, IntPtr.Zero); + m_mapInfo.minCoords = minTerrainCoords; + m_mapInfo.maxCoords = maxTerrainCoords; + // Don't have to free any previous since we just got here. + BuildHeightmapTerrain(); + } + + // 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, uint id, float[] initialMap, + Vector3 minCoords, Vector3 maxCoords) + : base(physicsScene) + { + m_mapInfo = new BulletHeightMapInfo(id, initialMap, IntPtr.Zero); + m_mapInfo.minCoords = minCoords; + m_mapInfo.maxCoords = maxCoords; + m_mapInfo.minZ = minCoords.Z; + m_mapInfo.maxZ = maxCoords.Z; + + // Don't have to free any previous since we just got here. + BuildHeightmapTerrain(); + } + + public override void Dispose() + { + ReleaseHeightMapTerrain(); + } + + // Using the information in m_mapInfo, create the physical representation of the heightmap. + private void BuildHeightmapTerrain() + { + m_mapInfo.Ptr = BulletSimAPI.CreateHeightMapInfo2(PhysicsScene.World.ptr, m_mapInfo.ID, + m_mapInfo.minCoords, m_mapInfo.maxCoords, + m_mapInfo.heightMap, BSTerrainManager.TERRAIN_COLLISION_MARGIN); + + // Create the terrain shape from the mapInfo + m_mapInfo.terrainShape = new BulletShape(BulletSimAPI.CreateTerrainShape2(m_mapInfo.Ptr), + PhysicsShapeType.SHAPE_TERRAIN); + + // The terrain object initial position is at the center of the object + Vector3 centerPos; + centerPos.X = m_mapInfo.minCoords.X + (m_mapInfo.sizeX / 2f); + 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 = new BulletBody(m_mapInfo.ID, + BulletSimAPI.CreateBodyWithDefaultMotionState2(m_mapInfo.terrainShape.ptr, + m_mapInfo.ID, centerPos, Quaternion.Identity)); + + // Set current terrain attributes + BulletSimAPI.SetFriction2(m_mapInfo.terrainBody.ptr, PhysicsScene.Params.terrainFriction); + BulletSimAPI.SetHitFraction2(m_mapInfo.terrainBody.ptr, PhysicsScene.Params.terrainHitFraction); + BulletSimAPI.SetRestitution2(m_mapInfo.terrainBody.ptr, PhysicsScene.Params.terrainRestitution); + BulletSimAPI.SetCollisionFlags2(m_mapInfo.terrainBody.ptr, CollisionFlags.CF_STATIC_OBJECT); + + // Return the new terrain to the world of physical objects + BulletSimAPI.AddObjectToWorld2(PhysicsScene.World.ptr, m_mapInfo.terrainBody.ptr); + + // redo its bounding box now that it is in the world + BulletSimAPI.UpdateSingleAabb2(PhysicsScene.World.ptr, m_mapInfo.terrainBody.ptr); + + BulletSimAPI.SetCollisionFilterMask2(m_mapInfo.terrainBody.ptr, + (uint)CollisionFilterGroups.TerrainFilter, + (uint)CollisionFilterGroups.TerrainMask); + + // Make it so the terrain will not move or be considered for movement. + BulletSimAPI.ForceActivationState2(m_mapInfo.terrainBody.ptr, ActivationState.DISABLE_SIMULATION); + + return; + } + + // If there is information in m_mapInfo pointing to physical structures, release same. + private void ReleaseHeightMapTerrain() + { + if (m_mapInfo != null) + { + if (m_mapInfo.terrainBody.ptr != IntPtr.Zero) + { + if (BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.ptr, m_mapInfo.terrainBody.ptr)) + { + // Frees both the body and the shape. + BulletSimAPI.DestroyObject2(PhysicsScene.World.ptr, m_mapInfo.terrainBody.ptr); + BulletSimAPI.ReleaseHeightMapInfo2(m_mapInfo.Ptr); + } + } + } + m_mapInfo = null; + } + + // The passed position is relative to the base of the region. + public override float GetHeightAtXYZ(Vector3 pos) + { + float ret = BSTerrainManager.HEIGHT_GETHEIGHT_RET; + + int mapIndex = (int)pos.Y * (int)m_mapInfo.sizeY + (int)pos.X; + try + { + ret = m_mapInfo.heightMap[mapIndex]; + } + 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}", + LogHeader, m_mapInfo.terrainRegionBase, pos); + ret = BSTerrainManager.HEIGHT_GETHEIGHT_RET; + } + return ret; + } + + public override Vector3 TerrainBase + { + get { return m_mapInfo.terrainRegionBase; } + } +} +} diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs index cc28e4d..db04299 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs @@ -40,6 +40,22 @@ using OpenMetaverse; namespace OpenSim.Region.Physics.BulletSPlugin { + +// The physical implementation of the terrain is wrapped in this class. +public abstract class BSTerrainPhys : IDisposable +{ + public BSScene PhysicsScene { get; private set; } + + public BSTerrainPhys(BSScene physicsScene) + { + PhysicsScene = physicsScene; + } + public abstract void Dispose(); + public abstract float GetHeightAtXYZ(Vector3 pos); + public abstract Vector3 TerrainBase { get; } +} + +// ========================================================================================== public sealed class BSTerrainManager { static string LogHeader = "[BULLETSIM TERRAIN MANAGER]"; @@ -67,11 +83,10 @@ public sealed class BSTerrainManager // If doing mega-regions, if we're region zero we will be managing multiple // region terrains since region zero does the physics for the whole mega-region. - private Dictionary m_heightMaps; + private Dictionary m_terrains; - // True of the terrain has been modified. - // Used to force recalculation of terrain height after terrain has been modified - private bool m_terrainModified; + // Flags used to know when to recalculate the height. + private bool m_terrainModified = false; // If we are doing mega-regions, terrains are added from TERRAIN_ID to m_terrainCount. // This is incremented before assigning to new region so it is the last ID allocated. @@ -89,8 +104,7 @@ public sealed class BSTerrainManager public BSTerrainManager(BSScene physicsScene) { PhysicsScene = physicsScene; - m_heightMaps = new Dictionary(); - m_terrainModified = false; + m_terrains = new Dictionary(); // Assume one region of default size m_worldOffset = Vector3.Zero; @@ -99,9 +113,6 @@ public sealed class BSTerrainManager } // Create the initial instance of terrain and the underlying ground plane. - // The objects are allocated in the unmanaged space and the pointers are tracked - // by the managed code. - // The terrains and the groundPlane are not added to the list of PhysObjects. // This is called from the initialization routine so we presume it is // safe to call Bullet in real time. We hope no one is moving prims around yet. public void CreateInitialGroundPlaneAndTerrain() @@ -121,15 +132,9 @@ public sealed class BSTerrainManager BulletSimAPI.SetCollisionFilterMask2(m_groundPlane.ptr, (uint)CollisionFilterGroups.GroundPlaneFilter, (uint)CollisionFilterGroups.GroundPlaneMask); - Vector3 minTerrainCoords = new Vector3(0f, 0f, HEIGHT_INITIALIZATION - HEIGHT_EQUAL_FUDGE); - Vector3 maxTerrainCoords = new Vector3(DefaultRegionSize.X, DefaultRegionSize.Y, HEIGHT_INITIALIZATION); - int totalHeights = (int)maxTerrainCoords.X * (int)maxTerrainCoords.Y; - float[] initialMap = new float[totalHeights]; - for (int ii = 0; ii < totalHeights; ii++) - { - initialMap[ii] = HEIGHT_INITIALIZATION; - } - UpdateOrCreateTerrain(BSScene.TERRAIN_ID, initialMap, minTerrainCoords, maxTerrainCoords, true); + // Build an initial terrain and put it in the world. This quickly gets replaced by the real region terrain. + BSTerrainPhys initialTerrain = new BSTerrainHeightmap(PhysicsScene, BSScene.TERRAIN_ID, DefaultRegionSize); + m_terrains.Add(Vector3.Zero, initialTerrain); } // Release all the terrain structures we might have allocated @@ -150,15 +155,11 @@ public sealed class BSTerrainManager // Release all the terrain we have allocated public void ReleaseTerrain() { - foreach (KeyValuePair kvp in m_heightMaps) + foreach (KeyValuePair kvp in m_terrains) { - if (BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.ptr, kvp.Value.terrainBody.ptr)) - { - BulletSimAPI.DestroyObject2(PhysicsScene.World.ptr, kvp.Value.terrainBody.ptr); - BulletSimAPI.ReleaseHeightMapInfo2(kvp.Value.Ptr); - } + kvp.Value.Dispose(); } - m_heightMaps.Clear(); + m_terrains.Clear(); } // The simulator wants to set a new heightmap for the terrain. @@ -176,8 +177,9 @@ public sealed class BSTerrainManager { DetailLog("{0},SetTerrain.ToParent,offset={1},worldMax={2}", BSScene.DetailLogZero, m_worldOffset, m_worldMax); - ((BSScene)MegaRegionParentPhysicsScene).TerrainManager.UpdateOrCreateTerrain(BSScene.CHILDTERRAIN_ID, - localHeightMap, m_worldOffset, m_worldOffset + DefaultRegionSize, true); + ((BSScene)MegaRegionParentPhysicsScene).TerrainManager.UpdateTerrain( + BSScene.CHILDTERRAIN_ID, localHeightMap, + m_worldOffset, m_worldOffset + DefaultRegionSize, true); } } else @@ -185,7 +187,7 @@ public sealed class BSTerrainManager // If not doing the mega-prim thing, just change the terrain DetailLog("{0},SetTerrain.Existing", BSScene.DetailLogZero); - UpdateOrCreateTerrain(BSScene.TERRAIN_ID, localHeightMap, + UpdateTerrain(BSScene.TERRAIN_ID, localHeightMap, m_worldOffset, m_worldOffset + DefaultRegionSize, true); } }); @@ -195,56 +197,60 @@ public sealed class BSTerrainManager // based on the passed information. The 'id' should be either the terrain id or // BSScene.CHILDTERRAIN_ID. If the latter, a new child terrain ID will be allocated and used. // The latter feature is for creating child terrains for mega-regions. - // If called with a mapInfo in m_heightMaps but the terrain has no body yet (mapInfo.terrainBody.Ptr == 0) - // then a new body and shape is created and the mapInfo is filled. - // This call is used for doing the initial terrain creation. // If called with a mapInfo in m_heightMaps and there is an existing terrain body, a new // terrain shape is created and added to the body. // This call is most often used to update the heightMap and parameters of the terrain. // (The above does suggest that some simplification/refactoring is in order.) - private void UpdateOrCreateTerrain(uint id, float[] heightMap, Vector3 minCoords, Vector3 maxCoords, bool inTaintTime) + private void UpdateTerrain(uint id, float[] heightMap, + Vector3 minCoords, Vector3 maxCoords, bool inTaintTime) { - DetailLog("{0},BSTerrainManager.UpdateOrCreateTerrain,call,minC={1},maxC={2},inTaintTime={3}", + DetailLog("{0},BSTerrainManager.UpdateTerrain,call,minC={1},maxC={2},inTaintTime={3}", BSScene.DetailLogZero, minCoords, maxCoords, inTaintTime); + // Find high and low points of passed heightmap. + // The min and max passed in are usually the region objects can exist in (maximum + // object height, for instance). The terrain wants the bounding box for the + // terrain so we replace passed min and max Z with the actual terrain min/max Z. + // limit, for float minZ = float.MaxValue; float maxZ = float.MinValue; - Vector2 terrainRegionBase = new Vector2(minCoords.X, minCoords.Y); - - int heightMapSize = heightMap.Length; - for (int ii = 0; ii < heightMapSize; ii++) + foreach (float height in heightMap) { - float height = heightMap[ii]; if (height < minZ) minZ = height; if (height > maxZ) maxZ = height; } - - // The shape of the terrain is from its base to its extents. minCoords.Z = minZ; maxCoords.Z = maxZ; - BulletHeightMapInfo mapInfo; - if (m_heightMaps.TryGetValue(terrainRegionBase, out mapInfo)) + Vector3 terrainRegionBase = new Vector3(minCoords.X, minCoords.Y, 0f); + + BSTerrainPhys terrainPhys; + if (m_terrains.TryGetValue(terrainRegionBase, out terrainPhys)) { // If this is terrain we know about, it's easy to update - mapInfo.heightMap = heightMap; - mapInfo.minCoords = minCoords; - mapInfo.maxCoords = maxCoords; - mapInfo.minZ = minZ; - mapInfo.maxZ = maxZ; - mapInfo.sizeX = maxCoords.X - minCoords.X; - mapInfo.sizeY = maxCoords.Y - minCoords.Y; - DetailLog("{0},UpdateOrCreateTerrain:UpdateExisting,call,terrainBase={1},minC={2}, maxC={3}, szX={4}, szY={5}", - BSScene.DetailLogZero, terrainRegionBase, mapInfo.minCoords, mapInfo.maxCoords, mapInfo.sizeX, mapInfo.sizeY); - - PhysicsScene.TaintedObject(inTaintTime, "BSScene.UpdateOrCreateTerrain:UpdateExisting", delegate() + DetailLog("{0},UpdateTerrain:UpdateExisting,call,terrainBase={1}", BSScene.DetailLogZero, terrainRegionBase); + + PhysicsScene.TaintedObject(inTaintTime, "BSScene.UpdateTerrain:UpdateExisting", delegate() { - if (MegaRegionParentPhysicsScene != null) + // Remove old terrain from the collection + m_terrains.Remove(terrainPhys.TerrainBase); + // Release any physical memory it may be using. + terrainPhys.Dispose(); + + if (MegaRegionParentPhysicsScene == null) + { + BSTerrainPhys newTerrainPhys = new BSTerrainHeightmap(PhysicsScene, id, + heightMap, minCoords, maxCoords); + m_terrains.Add(terrainRegionBase, newTerrainPhys); + + m_terrainModified = true; + } + else { // It's possible that Combine() was called after this code was queued. // If we are a child of combined regions, we don't create any terrain for us. - DetailLog("{0},UpdateOrCreateTerrain:AmACombineChild,taint", BSScene.DetailLogZero); + DetailLog("{0},BSTerrainManager.UpdateTerrain:AmACombineChild,taint", BSScene.DetailLogZero); // Get rid of any terrain that may have been allocated for us. ReleaseGroundPlaneAndTerrain(); @@ -252,91 +258,6 @@ public sealed class BSTerrainManager // I hate doing this, but just bail return; } - - if (mapInfo.terrainBody.ptr != IntPtr.Zero) - { - // Updating an existing terrain. - DetailLog("{0},UpdateOrCreateTerrain:UpdateExisting,taint,terrainBase={1},minC={2}, maxC={3}, szX={4}, szY={5}", - BSScene.DetailLogZero, terrainRegionBase, mapInfo.minCoords, mapInfo.maxCoords, mapInfo.sizeX, mapInfo.sizeY); - - // Remove from the dynamics world because we're going to mangle this object - BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.ptr, mapInfo.terrainBody.ptr); - - // Get rid of the old terrain - BulletSimAPI.DestroyObject2(PhysicsScene.World.ptr, mapInfo.terrainBody.ptr); - BulletSimAPI.ReleaseHeightMapInfo2(mapInfo.Ptr); - mapInfo.Ptr = IntPtr.Zero; - - /* - // NOTE: This routine is half here because I can't get the terrain shape replacement - // to work. In the short term, the above three lines completely delete the old - // terrain and the code below recreates one from scratch. - // Hopefully the Bullet community will help me out on this one. - - // First, release the old collision shape (there is only one terrain) - BulletSimAPI.DeleteCollisionShape2(m_physicsScene.World.Ptr, mapInfo.terrainShape.Ptr); - - // Fill the existing height map info with the new location and size information - BulletSimAPI.FillHeightMapInfo2(m_physicsScene.World.Ptr, mapInfo.Ptr, mapInfo.ID, - mapInfo.minCoords, mapInfo.maxCoords, mapInfo.heightMap, TERRAIN_COLLISION_MARGIN); - - // Create a terrain shape based on the new info - mapInfo.terrainShape = new BulletShape(BulletSimAPI.CreateTerrainShape2(mapInfo.Ptr)); - - // Stuff the shape into the existing terrain body - BulletSimAPI.SetBodyShape2(m_physicsScene.World.Ptr, mapInfo.terrainBody.Ptr, mapInfo.terrainShape.Ptr); - */ - } - // else - { - // Creating a new terrain. - DetailLog("{0},UpdateOrCreateTerrain:CreateNewTerrain,taint,baseX={1},baseY={2},minZ={3},maxZ={4}", - BSScene.DetailLogZero, mapInfo.minCoords.X, mapInfo.minCoords.Y, minZ, maxZ); - - mapInfo.ID = id; - mapInfo.Ptr = BulletSimAPI.CreateHeightMapInfo2(PhysicsScene.World.ptr, mapInfo.ID, - mapInfo.minCoords, mapInfo.maxCoords, mapInfo.heightMap, TERRAIN_COLLISION_MARGIN); - - // Create the terrain shape from the mapInfo - mapInfo.terrainShape = new BulletShape(BulletSimAPI.CreateTerrainShape2(mapInfo.Ptr), - PhysicsShapeType.SHAPE_TERRAIN); - - // The terrain object initial position is at the center of the object - Vector3 centerPos; - centerPos.X = minCoords.X + (mapInfo.sizeX / 2f); - centerPos.Y = minCoords.Y + (mapInfo.sizeY / 2f); - centerPos.Z = minZ + ((maxZ - minZ) / 2f); - - mapInfo.terrainBody = new BulletBody(mapInfo.ID, - BulletSimAPI.CreateBodyWithDefaultMotionState2(mapInfo.terrainShape.ptr, - id, centerPos, Quaternion.Identity)); - } - - // Make sure the entry is in the heightmap table - m_heightMaps[terrainRegionBase] = mapInfo; - - // Set current terrain attributes - BulletSimAPI.SetFriction2(mapInfo.terrainBody.ptr, PhysicsScene.Params.terrainFriction); - BulletSimAPI.SetHitFraction2(mapInfo.terrainBody.ptr, PhysicsScene.Params.terrainHitFraction); - BulletSimAPI.SetRestitution2(mapInfo.terrainBody.ptr, PhysicsScene.Params.terrainRestitution); - BulletSimAPI.SetCollisionFlags2(mapInfo.terrainBody.ptr, CollisionFlags.CF_STATIC_OBJECT); - - // Return the new terrain to the world of physical objects - BulletSimAPI.AddObjectToWorld2(PhysicsScene.World.ptr, mapInfo.terrainBody.ptr); - - // redo its bounding box now that it is in the world - BulletSimAPI.UpdateSingleAabb2(PhysicsScene.World.ptr, mapInfo.terrainBody.ptr); - - BulletSimAPI.SetCollisionFilterMask2(mapInfo.terrainBody.ptr, - (uint)CollisionFilterGroups.TerrainFilter, - (uint)CollisionFilterGroups.TerrainMask); - - // Make sure the new shape is processed. - // BulletSimAPI.Activate2(mapInfo.terrainBody.ptr, true); - // BulletSimAPI.ForceActivationState2(mapInfo.terrainBody.ptr, ActivationState.ISLAND_SLEEPING); - BulletSimAPI.ForceActivationState2(mapInfo.terrainBody.ptr, ActivationState.DISABLE_SIMULATION); - - m_terrainModified = true; }); } else @@ -353,34 +274,23 @@ public sealed class BSTerrainManager Vector3 minCoordsX = minCoords; Vector3 maxCoordsX = maxCoords; - DetailLog("{0},UpdateOrCreateTerrain:NewTerrain,call,id={1}, minC={2}, maxC={3}", + DetailLog("{0},UpdateTerrain:NewTerrain,call,id={1}, minC={2}, maxC={3}", BSScene.DetailLogZero, newTerrainID, minCoords, minCoords); // Code that must happen at taint-time - PhysicsScene.TaintedObject(inTaintTime, "BSScene.UpdateOrCreateTerrain:NewTerrain", delegate() + PhysicsScene.TaintedObject(inTaintTime, "BSScene.UpdateTerrain:NewTerrain", delegate() { - DetailLog("{0},UpdateOrCreateTerrain:NewTerrain,taint,baseX={1},baseY={2}", BSScene.DetailLogZero, minCoords.X, minCoords.Y); - // Create a new mapInfo that will be filled with the new info - mapInfo = new BulletHeightMapInfo(id, heightMapX, - BulletSimAPI.CreateHeightMapInfo2(PhysicsScene.World.ptr, newTerrainID, - minCoordsX, maxCoordsX, heightMapX, TERRAIN_COLLISION_MARGIN)); - // Put the unfilled heightmap info into the collection of same - m_heightMaps.Add(terrainRegionBase, mapInfo); - // Build the terrain - UpdateOrCreateTerrain(newTerrainID, heightMap, minCoords, maxCoords, true); + DetailLog("{0},UpdateTerrain:NewTerrain,taint,baseX={1},baseY={2}", + BSScene.DetailLogZero, minCoordsX.X, minCoordsX.Y); + BSTerrainPhys newTerrainPhys = new BSTerrainHeightmap(PhysicsScene, newTerrainID, + heightMapX, minCoordsX, maxCoordsX); + m_terrains.Add(terrainRegionBase, newTerrainPhys); m_terrainModified = true; }); } } - // Someday we will have complex terrain with caves and tunnels - public float GetTerrainHeightAtXYZ(Vector3 loc) - { - // For the moment, it's flat and convex - return GetTerrainHeightAtXY(loc.X, loc.Y); - } - // Given an X and Y, find the height of the terrain. // Since we could be handling multiple terrains for a mega-region, // the base of the region is calcuated assuming all regions are @@ -390,8 +300,10 @@ public sealed class BSTerrainManager private float lastHeightTX = 999999f; private float lastHeightTY = 999999f; private float lastHeight = HEIGHT_INITIAL_LASTHEIGHT; - private float GetTerrainHeightAtXY(float tX, float tY) + public float GetTerrainHeightAtXYZ(Vector3 loc) { + float tX = loc.X; + float tY = loc.Y; // You'd be surprized at the number of times this routine is called // with the same parameters as last time. if (!m_terrainModified && lastHeightTX == tX && lastHeightTY == tY) @@ -403,27 +315,14 @@ public sealed class BSTerrainManager int offsetX = ((int)(tX / (int)DefaultRegionSize.X)) * (int)DefaultRegionSize.X; int offsetY = ((int)(tY / (int)DefaultRegionSize.Y)) * (int)DefaultRegionSize.Y; - Vector2 terrainBaseXY = new Vector2(offsetX, offsetY); + Vector3 terrainBaseXYZ = new Vector3(offsetX, offsetY, 0f); - BulletHeightMapInfo mapInfo; - if (m_heightMaps.TryGetValue(terrainBaseXY, out mapInfo)) + BSTerrainPhys physTerrain; + if (m_terrains.TryGetValue(terrainBaseXYZ, out physTerrain)) { - float regionX = tX - offsetX; - float regionY = tY - offsetY; - int mapIndex = (int)regionY * (int)mapInfo.sizeY + (int)regionX; - try - { - ret = mapInfo.heightMap[mapIndex]; - } - 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}, x={2}, y={3}", - LogHeader, terrainBaseXY, regionX, regionY); - ret = HEIGHT_GETHEIGHT_RET; - } - // DetailLog("{0},BSTerrainManager.GetTerrainHeightAtXY,bX={1},baseY={2},szX={3},szY={4},regX={5},regY={6},index={7},ht={8}", - // BSScene.DetailLogZero, offsetX, offsetY, mapInfo.sizeX, mapInfo.sizeY, regionX, regionY, mapIndex, ret); + ret = physTerrain.GetHeightAtXYZ(loc - terrainBaseXYZ); + DetailLog("{0},BSTerrainManager.GetTerrainHeightAtXYZ,loc={1},base={2},height={3}", + BSScene.DetailLogZero, loc, terrainBaseXYZ, ret); } else { @@ -466,7 +365,7 @@ public sealed class BSTerrainManager // Unhook all the combining that I know about. public void UnCombine(PhysicsScene pScene) { - // Just like ODE, for the moment a NOP + // Just like ODE, we don't do anything yet. DetailLog("{0},BSTerrainManager.UnCombine", BSScene.DetailLogZero); } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainMesh.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainMesh.cs new file mode 100755 index 0000000..387c78b --- /dev/null +++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainMesh.cs @@ -0,0 +1,73 @@ +/* + * 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 OpenSim.Framework; +using OpenSim.Region.Framework; +using OpenSim.Region.CoreModules; +using OpenSim.Region.Physics.Manager; + +using Nini.Config; +using log4net; + +using OpenMetaverse; + +namespace OpenSim.Region.Physics.BulletSPlugin +{ +public sealed class BSTerrainMesh : BSTerrainPhys +{ + static string LogHeader = "[BULLETSIM TERRAIN MESH]"; + + public BSTerrainMesh(BSScene physicsScene, uint id, Vector3 regionSize) + : base(physicsScene) + { + } + + public BSTerrainMesh(BSScene physicsScene /* parameters for making mesh */) + : base(physicsScene) + { + } + + public override void Dispose() + { + return; + } + + public override float GetHeightAtXYZ(Vector3 pos) + { + return 12345f; + } + + public override Vector3 TerrainBase + { + get { return Vector3.Zero; } + } + +} +} diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs index 407d6d7..bab3b3d 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs @@ -152,7 +152,7 @@ public class BulletHeightMapInfo ID = id; Ptr = xx; heightMap = hm; - terrainRegionBase = new Vector2(0f, 0f); + terrainRegionBase = Vector3.Zero; minCoords = new Vector3(100f, 100f, 25f); maxCoords = new Vector3(101f, 101f, 26f); minZ = maxZ = 0f; @@ -161,7 +161,7 @@ public class BulletHeightMapInfo public uint ID; public IntPtr Ptr; public float[] heightMap; - public Vector2 terrainRegionBase; + public Vector3 terrainRegionBase; public Vector3 minCoords; public Vector3 maxCoords; public float sizeX, sizeY; -- cgit v1.1 From 34cbc738a84b7946a87e8bfd3bb04869519b3dee Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 20 Nov 2012 20:36:49 -0800 Subject: BulletSim: enablement and debugging of mesh terrain. --- .../Physics/BulletSPlugin/BSTerrainHeightmap.cs | 28 ++- .../Physics/BulletSPlugin/BSTerrainManager.cs | 26 ++- .../Region/Physics/BulletSPlugin/BSTerrainMesh.cs | 229 ++++++++++++++++++++- .../Region/Physics/BulletSPlugin/BulletSimAPI.cs | 6 +- 4 files changed, 253 insertions(+), 36 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainHeightmap.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainHeightmap.cs index 3bb63cd..e9fd0cb 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainHeightmap.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainHeightmap.cs @@ -44,10 +44,11 @@ public sealed class BSTerrainHeightmap : BSTerrainPhys { static string LogHeader = "[BULLETSIM TERRAIN HEIGHTMAP]"; - BulletHeightMapInfo m_mapInfo; + BulletHeightMapInfo m_mapInfo = null; - public BSTerrainHeightmap(BSScene physicsScene, uint id, Vector3 regionSize) - : base(physicsScene) + // Constructor to build a default, flat heightmap terrain. + public BSTerrainHeightmap(BSScene physicsScene, Vector3 regionBase, uint id, Vector3 regionSize) + : base(physicsScene, regionBase, id) { Vector3 minTerrainCoords = new Vector3(0f, 0f, BSTerrainManager.HEIGHT_INITIALIZATION - BSTerrainManager.HEIGHT_EQUAL_FUDGE); Vector3 maxTerrainCoords = new Vector3(regionSize.X, regionSize.Y, BSTerrainManager.HEIGHT_INITIALIZATION); @@ -60,21 +61,23 @@ public sealed class BSTerrainHeightmap : BSTerrainPhys m_mapInfo = new BulletHeightMapInfo(id, initialMap, IntPtr.Zero); m_mapInfo.minCoords = minTerrainCoords; m_mapInfo.maxCoords = maxTerrainCoords; + m_mapInfo.terrainRegionBase = TerrainBase; // Don't have to free any previous since we just got here. BuildHeightmapTerrain(); } // 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, uint id, float[] initialMap, + public BSTerrainHeightmap(BSScene physicsScene, Vector3 regionBase, uint id, float[] initialMap, Vector3 minCoords, Vector3 maxCoords) - : base(physicsScene) + : base(physicsScene, regionBase, id) { m_mapInfo = new BulletHeightMapInfo(id, initialMap, IntPtr.Zero); m_mapInfo.minCoords = minCoords; m_mapInfo.maxCoords = maxCoords; m_mapInfo.minZ = minCoords.Z; m_mapInfo.maxZ = maxCoords.Z; + m_mapInfo.terrainRegionBase = TerrainBase; // Don't have to free any previous since we just got here. BuildHeightmapTerrain(); @@ -135,12 +138,10 @@ public sealed class BSTerrainHeightmap : BSTerrainPhys { if (m_mapInfo.terrainBody.ptr != IntPtr.Zero) { - if (BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.ptr, m_mapInfo.terrainBody.ptr)) - { - // Frees both the body and the shape. - BulletSimAPI.DestroyObject2(PhysicsScene.World.ptr, m_mapInfo.terrainBody.ptr); - BulletSimAPI.ReleaseHeightMapInfo2(m_mapInfo.Ptr); - } + BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.ptr, m_mapInfo.terrainBody.ptr); + // Frees both the body and the shape. + BulletSimAPI.DestroyObject2(PhysicsScene.World.ptr, m_mapInfo.terrainBody.ptr); + BulletSimAPI.ReleaseHeightMapInfo2(m_mapInfo.Ptr); } } m_mapInfo = null; @@ -165,10 +166,5 @@ public sealed class BSTerrainHeightmap : BSTerrainPhys } return ret; } - - public override Vector3 TerrainBase - { - get { return m_mapInfo.terrainRegionBase; } - } } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs index db04299..ed0dfa8 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs @@ -45,14 +45,18 @@ namespace OpenSim.Region.Physics.BulletSPlugin public abstract class BSTerrainPhys : IDisposable { public BSScene 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) + public BSTerrainPhys(BSScene physicsScene, Vector3 regionBase, uint id) { PhysicsScene = physicsScene; + TerrainBase = regionBase; + ID = id; } public abstract void Dispose(); public abstract float GetHeightAtXYZ(Vector3 pos); - public abstract Vector3 TerrainBase { get; } } // ========================================================================================== @@ -133,7 +137,7 @@ public sealed class BSTerrainManager (uint)CollisionFilterGroups.GroundPlaneFilter, (uint)CollisionFilterGroups.GroundPlaneMask); // Build an initial terrain and put it in the world. This quickly gets replaced by the real region terrain. - BSTerrainPhys initialTerrain = new BSTerrainHeightmap(PhysicsScene, BSScene.TERRAIN_ID, DefaultRegionSize); + BSTerrainPhys initialTerrain = new BSTerrainHeightmap(PhysicsScene, Vector3.Zero, BSScene.TERRAIN_ID, DefaultRegionSize); m_terrains.Add(Vector3.Zero, initialTerrain); } @@ -208,10 +212,9 @@ public sealed class BSTerrainManager BSScene.DetailLogZero, minCoords, maxCoords, inTaintTime); // Find high and low points of passed heightmap. - // The min and max passed in are usually the region objects can exist in (maximum + // The min and max passed in is usually the area objects can be in (maximum // object height, for instance). The terrain wants the bounding box for the // terrain so we replace passed min and max Z with the actual terrain min/max Z. - // limit, for float minZ = float.MaxValue; float maxZ = float.MinValue; foreach (float height in heightMap) @@ -219,6 +222,11 @@ public sealed class BSTerrainManager if (height < minZ) minZ = height; if (height > maxZ) maxZ = height; } + if (minZ == maxZ) + { + // If min and max are the same, reduce min a little bit so a good bounding box is created. + minZ -= BSTerrainManager.HEIGHT_EQUAL_FUDGE; + } minCoords.Z = minZ; maxCoords.Z = maxZ; @@ -240,7 +248,9 @@ public sealed class BSTerrainManager if (MegaRegionParentPhysicsScene == null) { - BSTerrainPhys newTerrainPhys = new BSTerrainHeightmap(PhysicsScene, id, + // BSTerrainPhys newTerrainPhys = new BSTerrainHeightmap(PhysicsScene, terrainRegionBase, id, + // heightMap, minCoords, maxCoords); + BSTerrainPhys newTerrainPhys = new BSTerrainMesh(PhysicsScene, terrainRegionBase, id, heightMap, minCoords, maxCoords); m_terrains.Add(terrainRegionBase, newTerrainPhys); @@ -282,8 +292,8 @@ public sealed class BSTerrainManager { DetailLog("{0},UpdateTerrain:NewTerrain,taint,baseX={1},baseY={2}", BSScene.DetailLogZero, minCoordsX.X, minCoordsX.Y); - BSTerrainPhys newTerrainPhys = new BSTerrainHeightmap(PhysicsScene, newTerrainID, - heightMapX, minCoordsX, maxCoordsX); + BSTerrainPhys newTerrainPhys = new BSTerrainHeightmap(PhysicsScene, terrainRegionBase, + newTerrainID, heightMapX, minCoordsX, maxCoordsX); m_terrains.Add(terrainRegionBase, newTerrainPhys); m_terrainModified = true; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainMesh.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainMesh.cs index 387c78b..bbb014a 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainMesh.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainMesh.cs @@ -44,30 +44,241 @@ public sealed class BSTerrainMesh : BSTerrainPhys { static string LogHeader = "[BULLETSIM TERRAIN MESH]"; - public BSTerrainMesh(BSScene physicsScene, uint id, Vector3 regionSize) - : base(physicsScene) + private float[] m_savedHeightMap; + int m_sizeX; + int m_sizeY; + + BulletShape m_terrainShape; + BulletBody m_terrainBody; + + public BSTerrainMesh(BSScene physicsScene, Vector3 regionBase, uint id, Vector3 regionSize) + : base(physicsScene, regionBase, id) { } - public BSTerrainMesh(BSScene physicsScene /* parameters for making mesh */) - : base(physicsScene) + public BSTerrainMesh(BSScene physicsScene, Vector3 regionBase, uint id /* parameters for making mesh */) + : base(physicsScene, regionBase, id) { } + // Create terrain mesh from a heightmap. + public BSTerrainMesh(BSScene physicsScene, Vector3 regionBase, uint id, float[] initialMap, + Vector3 minCoords, Vector3 maxCoords) + : base(physicsScene, regionBase, id) + { + int indicesCount; + int[] indices; + int verticesCount; + float[] vertices; + + m_savedHeightMap = initialMap; + + m_sizeX = (int)(maxCoords.X - minCoords.X); + m_sizeY = (int)(maxCoords.Y - minCoords.Y); + + if (!BSTerrainMesh.ConvertHeightmapToMesh(PhysicsScene, initialMap, m_sizeX, m_sizeY, + (float)m_sizeX, (float)m_sizeY, + Vector3.Zero, 1.0f, + out indicesCount, out indices, out verticesCount, out vertices)) + { + // DISASTER!! + PhysicsScene.DetailLog("{0},BSTerrainMesh.create,failedConversionOfHeightmap", ID); + 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,afterConvertHeightmapToMesh,ver={1},ind={2}", + ID, verticesCount, indicesCount); + + m_terrainShape = new BulletShape(BulletSimAPI.CreateMeshShape2(PhysicsScene.World.ptr, + indicesCount, indices, verticesCount, vertices), + PhysicsShapeType.SHAPE_MESH); + if (m_terrainShape.ptr == IntPtr.Zero) + { + // DISASTER!! + PhysicsScene.DetailLog("{0},BSTerrainMesh.create,failedCreationOfShape", ID); + 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; + } + PhysicsScene.DetailLog("{0},BSTerrainMesh.create,afterCreateShape,shape={1}", ID, m_terrainShape); + + // The terrain object initial position is at the center of the object + Vector3 centerPos; + centerPos.X = minCoords.X + (m_sizeX / 2f); + centerPos.Y = minCoords.Y + (m_sizeY / 2f); + centerPos.Z = minCoords.Z + ((maxCoords.Z - minCoords.Z) / 2f); + Quaternion rot = Quaternion.Identity; + + PhysicsScene.DetailLog("{0},BSTerrainMesh.create,creatingBody,centerPos={1},rot={2}", ID, centerPos, rot); + m_terrainBody = new BulletBody(id, BulletSimAPI.CreateBodyWithDefaultMotionState2( + m_terrainShape.ptr, ID, centerPos, rot)); + if (m_terrainBody.ptr == IntPtr.Zero) + { + // DISASTER!! + 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.DetailLog("{0},BSTerrainMesh.create,afterCreateBody,body={1}", ID, m_terrainBody); + + // Set current terrain attributes + BulletSimAPI.SetFriction2(m_terrainBody.ptr, PhysicsScene.Params.terrainFriction); + BulletSimAPI.SetHitFraction2(m_terrainBody.ptr, PhysicsScene.Params.terrainHitFraction); + BulletSimAPI.SetRestitution2(m_terrainBody.ptr, PhysicsScene.Params.terrainRestitution); + BulletSimAPI.SetCollisionFlags2(m_terrainBody.ptr, CollisionFlags.CF_STATIC_OBJECT); + + // Static objects are not very massive. + BulletSimAPI.SetMassProps2(m_terrainBody.ptr, 0f, Vector3.Zero); + + // Return the new terrain to the world of physical objects + BulletSimAPI.AddObjectToWorld2(PhysicsScene.World.ptr, m_terrainBody.ptr); + + // redo its bounding box now that it is in the world + BulletSimAPI.UpdateSingleAabb2(PhysicsScene.World.ptr, m_terrainBody.ptr); + + BulletSimAPI.SetCollisionFilterMask2(m_terrainBody.ptr, + (uint)CollisionFilterGroups.TerrainFilter, + (uint)CollisionFilterGroups.TerrainMask); + + // Make it so the terrain will not move or be considered for movement. + BulletSimAPI.ForceActivationState2(m_terrainBody.ptr, ActivationState.DISABLE_SIMULATION); + } + public override void Dispose() { - return; + if (m_terrainBody.ptr != IntPtr.Zero) + { + BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.ptr, m_terrainBody.ptr); + // Frees both the body and the shape. + BulletSimAPI.DestroyObject2(PhysicsScene.World.ptr, m_terrainBody.ptr); + } } public override float GetHeightAtXYZ(Vector3 pos) { - return 12345f; + // For the moment use the saved heightmap to get the terrain height. + // TODO: raycast downward to find the true terrain below the position. + float ret = BSTerrainManager.HEIGHT_GETHEIGHT_RET; + + int mapIndex = (int)pos.Y * m_sizeY + (int)pos.X; + try + { + ret = m_savedHeightMap[mapIndex]; + } + 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}", + LogHeader, TerrainBase, pos); + ret = BSTerrainManager.HEIGHT_GETHEIGHT_RET; + } + return ret; } - public override Vector3 TerrainBase + // Convert the passed heightmap to mesh information suitable for CreateMeshShape2(). + // Return 'true' if successfully created. + public static bool ConvertHeightmapToMesh( + BSScene physicsScene, + float[] heightMap, int sizeX, int sizeY, // parameters of incoming heightmap + float extentX, float extentY, // zero based range for output vertices + Vector3 extentBase, // base to be added to all vertices + float magnification, // number of vertices to create between heightMap coords + out int indicesCountO, out int[] indicesO, + out int verticesCountO, out float[] verticesO) { - get { return Vector3.Zero; } - } + bool ret = false; + + int indicesCount = 0; + int verticesCount = 0; + int[] indices = new int[0]; + float[] vertices = new float[0]; + // Simple mesh creation which assumes magnification == 1, sizeX == extentX and sizeY == extentY. + // TODO: do a more general solution that scales, adds new vertices and smoothes the result. + + try + { + // One vertice per heightmap value plus the vertices off the top and bottom edge. + int totalVertices = (sizeX + 1) * (sizeY + 1); + vertices = new float[totalVertices * 3]; + int totalIndices = sizeX * sizeY * 6; + indices = new int[totalIndices]; + + physicsScene.DetailLog("{0},BSTerrainMesh.ConvertHeightMapToMesh,totVert={1},totInd={2}", + BSScene.DetailLogZero, totalVertices, totalIndices); + float magX = (float)sizeX / extentX; + float magY = (float)sizeY / extentY; + // Note that sizeX+1 vertices are created since there is land between this and the next region. + for (int yy = 0; yy <= sizeY; yy++) + { + for (int xx = 0; xx <= sizeX; xx++) // Hint: the "<=" means we got through sizeX + 1 times + { + int offset = yy * sizeX + xx; + // Extend the height from the height from the last row or column + if (yy == sizeY) offset -= sizeX; + if (xx == sizeX) offset -= 1; + float height = heightMap[offset]; + vertices[verticesCount + 0] = (float)xx * magX + extentBase.X; + vertices[verticesCount + 1] = (float)yy * magY + extentBase.Y; + vertices[verticesCount + 2] = height + extentBase.Z; + if (physicsScene.PhysicsLogging.Enabled && verticesCount < 900) // DEBUG DEBUG DEBUG + { + Vector3 genVertex = new Vector3( + vertices[verticesCount + 0], + vertices[verticesCount + 1], + vertices[verticesCount + 2]); + physicsScene.DetailLog("{0},BSTerrainMesh.ConvertHeightMapToMesh,ii={1},vertex={2}", + BSScene.DetailLogZero, verticesCount/3, genVertex); + } + verticesCount += 3; + } + } + verticesCount = verticesCount / 3; + physicsScene.DetailLog("{0},BSTerrainMesh.ConvertHeightMapToMesh,completeVerts,verCount={1}", + BSScene.DetailLogZero, verticesCount); + + for (int yy = 0; yy < sizeY; yy++) + { + for (int xx = 0; xx < sizeX; xx++) + { + int offset = yy * sizeX + xx; + // Each vertices is presumed to be the upper left corner of a box of two triangles + indices[indicesCount + 0] = offset; + indices[indicesCount + 1] = offset + 1; + indices[indicesCount + 2] = offset + sizeX + 1; // accounting for the extra column + indices[indicesCount + 3] = offset + 1; + indices[indicesCount + 4] = offset + sizeX + 2; + indices[indicesCount + 5] = offset + sizeX + 1; + if (indicesCount < (300 * 6)) // DEBUG DEBUG DEBUG + physicsScene.DetailLog("{0},BSTerrainMesh.ConvertHeightMapToMesh,i0={1},i1={2},i2={3},i3={4},i4={5},i5={6}", // DEEBUG DEBUG DEBUG + BSScene.DetailLogZero, + indices[indicesCount + 0], + indices[indicesCount + 1], + indices[indicesCount + 2], + indices[indicesCount + 3], + indices[indicesCount + 4], + indices[indicesCount + 5] + ); + indicesCount += 6; + } + } + physicsScene.DetailLog("{0},BSTerrainMesh.ConvertHeightMapToMesh,completeIndices,indCount={1}", // DEEBUG DEBUG DEBUG + LogHeader, indicesCount); // DEBUG + ret = true; + } + catch (Exception e) + { + physicsScene.Logger.ErrorFormat("{0} Failed conversion of heightmap to mesh. Base={1}, e={2}", + LogHeader, extentBase, e); + } + + indicesCountO = indicesCount; + indicesO = indices; + verticesCountO = verticesCount; + verticesO = vertices; + + return ret; + } } } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs index bab3b3d..a2271a9 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs @@ -391,13 +391,13 @@ public enum CollisionFilterGroups : uint ObjectFilter = BSolidFilter, ObjectMask = BAllFilter, StaticObjectFilter = BStaticFilter, - StaticObjectMask = BAllFilter, + StaticObjectMask = BAllFilter & ~BStaticFilter, // static objects don't collide with each other LinksetFilter = BLinksetFilter, - LinksetMask = BAllFilter & ~BLinksetFilter, + LinksetMask = BAllFilter & ~BLinksetFilter, // linkset objects don't collide with each other VolumeDetectFilter = BSensorTrigger, VolumeDetectMask = ~BSensorTrigger, TerrainFilter = BTerrainFilter, - TerrainMask = BAllFilter & ~BStaticFilter, + TerrainMask = BAllFilter & ~BStaticFilter, // static objects on the ground don't collide GroundPlaneFilter = BGroundPlaneFilter, GroundPlaneMask = BAllFilter -- cgit v1.1 From 2dc7e9d3fa091418814af90565244a8c1972feec Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Tue, 20 Nov 2012 20:38:51 -0800 Subject: BulletSim: fix line endings to be all Linux style (windows style keeps creeping in) --- .../Physics/BulletSPlugin/BSTerrainHeightmap.cs | 340 ++++++------ .../Region/Physics/BulletSPlugin/BSTerrainMesh.cs | 568 ++++++++++----------- 2 files changed, 454 insertions(+), 454 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainHeightmap.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainHeightmap.cs index e9fd0cb..8fc36d1 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainHeightmap.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainHeightmap.cs @@ -1,170 +1,170 @@ -/* - * 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 OpenSim.Framework; -using OpenSim.Region.Framework; -using OpenSim.Region.CoreModules; -using OpenSim.Region.Physics.Manager; - -using Nini.Config; -using log4net; - -using OpenMetaverse; - -namespace OpenSim.Region.Physics.BulletSPlugin -{ -public sealed class BSTerrainHeightmap : BSTerrainPhys -{ - static string LogHeader = "[BULLETSIM TERRAIN HEIGHTMAP]"; - - BulletHeightMapInfo m_mapInfo = null; - - // Constructor to build a default, flat heightmap terrain. - public BSTerrainHeightmap(BSScene physicsScene, Vector3 regionBase, uint id, Vector3 regionSize) - : base(physicsScene, regionBase, id) - { - Vector3 minTerrainCoords = new Vector3(0f, 0f, BSTerrainManager.HEIGHT_INITIALIZATION - BSTerrainManager.HEIGHT_EQUAL_FUDGE); - Vector3 maxTerrainCoords = new Vector3(regionSize.X, regionSize.Y, BSTerrainManager.HEIGHT_INITIALIZATION); - int totalHeights = (int)maxTerrainCoords.X * (int)maxTerrainCoords.Y; - float[] initialMap = new float[totalHeights]; - for (int ii = 0; ii < totalHeights; ii++) - { - initialMap[ii] = BSTerrainManager.HEIGHT_INITIALIZATION; - } - m_mapInfo = new BulletHeightMapInfo(id, initialMap, IntPtr.Zero); - m_mapInfo.minCoords = minTerrainCoords; - m_mapInfo.maxCoords = maxTerrainCoords; - m_mapInfo.terrainRegionBase = TerrainBase; - // Don't have to free any previous since we just got here. - BuildHeightmapTerrain(); - } - - // 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, - Vector3 minCoords, Vector3 maxCoords) - : base(physicsScene, regionBase, id) - { - m_mapInfo = new BulletHeightMapInfo(id, initialMap, IntPtr.Zero); - m_mapInfo.minCoords = minCoords; - m_mapInfo.maxCoords = maxCoords; - m_mapInfo.minZ = minCoords.Z; - m_mapInfo.maxZ = maxCoords.Z; - m_mapInfo.terrainRegionBase = TerrainBase; - - // Don't have to free any previous since we just got here. - BuildHeightmapTerrain(); - } - - public override void Dispose() - { - ReleaseHeightMapTerrain(); - } - - // Using the information in m_mapInfo, create the physical representation of the heightmap. - private void BuildHeightmapTerrain() - { - m_mapInfo.Ptr = BulletSimAPI.CreateHeightMapInfo2(PhysicsScene.World.ptr, m_mapInfo.ID, - m_mapInfo.minCoords, m_mapInfo.maxCoords, - m_mapInfo.heightMap, BSTerrainManager.TERRAIN_COLLISION_MARGIN); - - // Create the terrain shape from the mapInfo - m_mapInfo.terrainShape = new BulletShape(BulletSimAPI.CreateTerrainShape2(m_mapInfo.Ptr), - PhysicsShapeType.SHAPE_TERRAIN); - - // The terrain object initial position is at the center of the object - Vector3 centerPos; - centerPos.X = m_mapInfo.minCoords.X + (m_mapInfo.sizeX / 2f); - 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 = new BulletBody(m_mapInfo.ID, - BulletSimAPI.CreateBodyWithDefaultMotionState2(m_mapInfo.terrainShape.ptr, - m_mapInfo.ID, centerPos, Quaternion.Identity)); - - // Set current terrain attributes - BulletSimAPI.SetFriction2(m_mapInfo.terrainBody.ptr, PhysicsScene.Params.terrainFriction); - BulletSimAPI.SetHitFraction2(m_mapInfo.terrainBody.ptr, PhysicsScene.Params.terrainHitFraction); - BulletSimAPI.SetRestitution2(m_mapInfo.terrainBody.ptr, PhysicsScene.Params.terrainRestitution); - BulletSimAPI.SetCollisionFlags2(m_mapInfo.terrainBody.ptr, CollisionFlags.CF_STATIC_OBJECT); - - // Return the new terrain to the world of physical objects - BulletSimAPI.AddObjectToWorld2(PhysicsScene.World.ptr, m_mapInfo.terrainBody.ptr); - - // redo its bounding box now that it is in the world - BulletSimAPI.UpdateSingleAabb2(PhysicsScene.World.ptr, m_mapInfo.terrainBody.ptr); - - BulletSimAPI.SetCollisionFilterMask2(m_mapInfo.terrainBody.ptr, - (uint)CollisionFilterGroups.TerrainFilter, - (uint)CollisionFilterGroups.TerrainMask); - - // Make it so the terrain will not move or be considered for movement. - BulletSimAPI.ForceActivationState2(m_mapInfo.terrainBody.ptr, ActivationState.DISABLE_SIMULATION); - - return; - } - - // If there is information in m_mapInfo pointing to physical structures, release same. - private void ReleaseHeightMapTerrain() - { - if (m_mapInfo != null) - { - if (m_mapInfo.terrainBody.ptr != IntPtr.Zero) - { - BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.ptr, m_mapInfo.terrainBody.ptr); - // Frees both the body and the shape. - BulletSimAPI.DestroyObject2(PhysicsScene.World.ptr, m_mapInfo.terrainBody.ptr); - BulletSimAPI.ReleaseHeightMapInfo2(m_mapInfo.Ptr); - } - } - m_mapInfo = null; - } - - // The passed position is relative to the base of the region. - public override float GetHeightAtXYZ(Vector3 pos) - { - float ret = BSTerrainManager.HEIGHT_GETHEIGHT_RET; - - int mapIndex = (int)pos.Y * (int)m_mapInfo.sizeY + (int)pos.X; - try - { - ret = m_mapInfo.heightMap[mapIndex]; - } - 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}", - LogHeader, m_mapInfo.terrainRegionBase, pos); - ret = BSTerrainManager.HEIGHT_GETHEIGHT_RET; - } - return ret; - } -} -} +/* + * 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 OpenSim.Framework; +using OpenSim.Region.Framework; +using OpenSim.Region.CoreModules; +using OpenSim.Region.Physics.Manager; + +using Nini.Config; +using log4net; + +using OpenMetaverse; + +namespace OpenSim.Region.Physics.BulletSPlugin +{ +public sealed class BSTerrainHeightmap : BSTerrainPhys +{ + static string LogHeader = "[BULLETSIM TERRAIN HEIGHTMAP]"; + + BulletHeightMapInfo m_mapInfo = null; + + // Constructor to build a default, flat heightmap terrain. + public BSTerrainHeightmap(BSScene physicsScene, Vector3 regionBase, uint id, Vector3 regionSize) + : base(physicsScene, regionBase, id) + { + Vector3 minTerrainCoords = new Vector3(0f, 0f, BSTerrainManager.HEIGHT_INITIALIZATION - BSTerrainManager.HEIGHT_EQUAL_FUDGE); + Vector3 maxTerrainCoords = new Vector3(regionSize.X, regionSize.Y, BSTerrainManager.HEIGHT_INITIALIZATION); + int totalHeights = (int)maxTerrainCoords.X * (int)maxTerrainCoords.Y; + float[] initialMap = new float[totalHeights]; + for (int ii = 0; ii < totalHeights; ii++) + { + initialMap[ii] = BSTerrainManager.HEIGHT_INITIALIZATION; + } + m_mapInfo = new BulletHeightMapInfo(id, initialMap, IntPtr.Zero); + m_mapInfo.minCoords = minTerrainCoords; + m_mapInfo.maxCoords = maxTerrainCoords; + m_mapInfo.terrainRegionBase = TerrainBase; + // Don't have to free any previous since we just got here. + BuildHeightmapTerrain(); + } + + // 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, + Vector3 minCoords, Vector3 maxCoords) + : base(physicsScene, regionBase, id) + { + m_mapInfo = new BulletHeightMapInfo(id, initialMap, IntPtr.Zero); + m_mapInfo.minCoords = minCoords; + m_mapInfo.maxCoords = maxCoords; + m_mapInfo.minZ = minCoords.Z; + m_mapInfo.maxZ = maxCoords.Z; + m_mapInfo.terrainRegionBase = TerrainBase; + + // Don't have to free any previous since we just got here. + BuildHeightmapTerrain(); + } + + public override void Dispose() + { + ReleaseHeightMapTerrain(); + } + + // Using the information in m_mapInfo, create the physical representation of the heightmap. + private void BuildHeightmapTerrain() + { + m_mapInfo.Ptr = BulletSimAPI.CreateHeightMapInfo2(PhysicsScene.World.ptr, m_mapInfo.ID, + m_mapInfo.minCoords, m_mapInfo.maxCoords, + m_mapInfo.heightMap, BSTerrainManager.TERRAIN_COLLISION_MARGIN); + + // Create the terrain shape from the mapInfo + m_mapInfo.terrainShape = new BulletShape(BulletSimAPI.CreateTerrainShape2(m_mapInfo.Ptr), + PhysicsShapeType.SHAPE_TERRAIN); + + // The terrain object initial position is at the center of the object + Vector3 centerPos; + centerPos.X = m_mapInfo.minCoords.X + (m_mapInfo.sizeX / 2f); + 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 = new BulletBody(m_mapInfo.ID, + BulletSimAPI.CreateBodyWithDefaultMotionState2(m_mapInfo.terrainShape.ptr, + m_mapInfo.ID, centerPos, Quaternion.Identity)); + + // Set current terrain attributes + BulletSimAPI.SetFriction2(m_mapInfo.terrainBody.ptr, PhysicsScene.Params.terrainFriction); + BulletSimAPI.SetHitFraction2(m_mapInfo.terrainBody.ptr, PhysicsScene.Params.terrainHitFraction); + BulletSimAPI.SetRestitution2(m_mapInfo.terrainBody.ptr, PhysicsScene.Params.terrainRestitution); + BulletSimAPI.SetCollisionFlags2(m_mapInfo.terrainBody.ptr, CollisionFlags.CF_STATIC_OBJECT); + + // Return the new terrain to the world of physical objects + BulletSimAPI.AddObjectToWorld2(PhysicsScene.World.ptr, m_mapInfo.terrainBody.ptr); + + // redo its bounding box now that it is in the world + BulletSimAPI.UpdateSingleAabb2(PhysicsScene.World.ptr, m_mapInfo.terrainBody.ptr); + + BulletSimAPI.SetCollisionFilterMask2(m_mapInfo.terrainBody.ptr, + (uint)CollisionFilterGroups.TerrainFilter, + (uint)CollisionFilterGroups.TerrainMask); + + // Make it so the terrain will not move or be considered for movement. + BulletSimAPI.ForceActivationState2(m_mapInfo.terrainBody.ptr, ActivationState.DISABLE_SIMULATION); + + return; + } + + // If there is information in m_mapInfo pointing to physical structures, release same. + private void ReleaseHeightMapTerrain() + { + if (m_mapInfo != null) + { + if (m_mapInfo.terrainBody.ptr != IntPtr.Zero) + { + BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.ptr, m_mapInfo.terrainBody.ptr); + // Frees both the body and the shape. + BulletSimAPI.DestroyObject2(PhysicsScene.World.ptr, m_mapInfo.terrainBody.ptr); + BulletSimAPI.ReleaseHeightMapInfo2(m_mapInfo.Ptr); + } + } + m_mapInfo = null; + } + + // The passed position is relative to the base of the region. + public override float GetHeightAtXYZ(Vector3 pos) + { + float ret = BSTerrainManager.HEIGHT_GETHEIGHT_RET; + + int mapIndex = (int)pos.Y * (int)m_mapInfo.sizeY + (int)pos.X; + try + { + ret = m_mapInfo.heightMap[mapIndex]; + } + 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}", + LogHeader, m_mapInfo.terrainRegionBase, pos); + ret = BSTerrainManager.HEIGHT_GETHEIGHT_RET; + } + return ret; + } +} +} diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainMesh.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainMesh.cs index bbb014a..a199078 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainMesh.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainMesh.cs @@ -1,284 +1,284 @@ -/* - * 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 OpenSim.Framework; -using OpenSim.Region.Framework; -using OpenSim.Region.CoreModules; -using OpenSim.Region.Physics.Manager; - -using Nini.Config; -using log4net; - -using OpenMetaverse; - -namespace OpenSim.Region.Physics.BulletSPlugin -{ -public sealed class BSTerrainMesh : BSTerrainPhys -{ - static string LogHeader = "[BULLETSIM TERRAIN MESH]"; - - private float[] m_savedHeightMap; - int m_sizeX; - int m_sizeY; - - BulletShape m_terrainShape; - BulletBody m_terrainBody; - - public BSTerrainMesh(BSScene physicsScene, Vector3 regionBase, uint id, Vector3 regionSize) - : base(physicsScene, regionBase, id) - { - } - - public BSTerrainMesh(BSScene physicsScene, Vector3 regionBase, uint id /* parameters for making mesh */) - : base(physicsScene, regionBase, id) - { - } - - // Create terrain mesh from a heightmap. - public BSTerrainMesh(BSScene physicsScene, Vector3 regionBase, uint id, float[] initialMap, - Vector3 minCoords, Vector3 maxCoords) - : base(physicsScene, regionBase, id) - { - int indicesCount; - int[] indices; - int verticesCount; - float[] vertices; - - m_savedHeightMap = initialMap; - - m_sizeX = (int)(maxCoords.X - minCoords.X); - m_sizeY = (int)(maxCoords.Y - minCoords.Y); - - if (!BSTerrainMesh.ConvertHeightmapToMesh(PhysicsScene, initialMap, m_sizeX, m_sizeY, - (float)m_sizeX, (float)m_sizeY, - Vector3.Zero, 1.0f, - out indicesCount, out indices, out verticesCount, out vertices)) - { - // DISASTER!! - PhysicsScene.DetailLog("{0},BSTerrainMesh.create,failedConversionOfHeightmap", ID); - 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,afterConvertHeightmapToMesh,ver={1},ind={2}", - ID, verticesCount, indicesCount); - - m_terrainShape = new BulletShape(BulletSimAPI.CreateMeshShape2(PhysicsScene.World.ptr, - indicesCount, indices, verticesCount, vertices), - PhysicsShapeType.SHAPE_MESH); - if (m_terrainShape.ptr == IntPtr.Zero) - { - // DISASTER!! - PhysicsScene.DetailLog("{0},BSTerrainMesh.create,failedCreationOfShape", ID); - 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; - } - PhysicsScene.DetailLog("{0},BSTerrainMesh.create,afterCreateShape,shape={1}", ID, m_terrainShape); - - // The terrain object initial position is at the center of the object - Vector3 centerPos; - centerPos.X = minCoords.X + (m_sizeX / 2f); - centerPos.Y = minCoords.Y + (m_sizeY / 2f); - centerPos.Z = minCoords.Z + ((maxCoords.Z - minCoords.Z) / 2f); - Quaternion rot = Quaternion.Identity; - - PhysicsScene.DetailLog("{0},BSTerrainMesh.create,creatingBody,centerPos={1},rot={2}", ID, centerPos, rot); - m_terrainBody = new BulletBody(id, BulletSimAPI.CreateBodyWithDefaultMotionState2( - m_terrainShape.ptr, ID, centerPos, rot)); - if (m_terrainBody.ptr == IntPtr.Zero) - { - // DISASTER!! - 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.DetailLog("{0},BSTerrainMesh.create,afterCreateBody,body={1}", ID, m_terrainBody); - - // Set current terrain attributes - BulletSimAPI.SetFriction2(m_terrainBody.ptr, PhysicsScene.Params.terrainFriction); - BulletSimAPI.SetHitFraction2(m_terrainBody.ptr, PhysicsScene.Params.terrainHitFraction); - BulletSimAPI.SetRestitution2(m_terrainBody.ptr, PhysicsScene.Params.terrainRestitution); - BulletSimAPI.SetCollisionFlags2(m_terrainBody.ptr, CollisionFlags.CF_STATIC_OBJECT); - - // Static objects are not very massive. - BulletSimAPI.SetMassProps2(m_terrainBody.ptr, 0f, Vector3.Zero); - - // Return the new terrain to the world of physical objects - BulletSimAPI.AddObjectToWorld2(PhysicsScene.World.ptr, m_terrainBody.ptr); - - // redo its bounding box now that it is in the world - BulletSimAPI.UpdateSingleAabb2(PhysicsScene.World.ptr, m_terrainBody.ptr); - - BulletSimAPI.SetCollisionFilterMask2(m_terrainBody.ptr, - (uint)CollisionFilterGroups.TerrainFilter, - (uint)CollisionFilterGroups.TerrainMask); - - // Make it so the terrain will not move or be considered for movement. - BulletSimAPI.ForceActivationState2(m_terrainBody.ptr, ActivationState.DISABLE_SIMULATION); - } - - public override void Dispose() - { - if (m_terrainBody.ptr != IntPtr.Zero) - { - BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.ptr, m_terrainBody.ptr); - // Frees both the body and the shape. - BulletSimAPI.DestroyObject2(PhysicsScene.World.ptr, m_terrainBody.ptr); - } - } - - public override float GetHeightAtXYZ(Vector3 pos) - { - // For the moment use the saved heightmap to get the terrain height. - // TODO: raycast downward to find the true terrain below the position. - float ret = BSTerrainManager.HEIGHT_GETHEIGHT_RET; - - int mapIndex = (int)pos.Y * m_sizeY + (int)pos.X; - try - { - ret = m_savedHeightMap[mapIndex]; - } - 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}", - LogHeader, TerrainBase, pos); - ret = BSTerrainManager.HEIGHT_GETHEIGHT_RET; - } - return ret; - } - - // Convert the passed heightmap to mesh information suitable for CreateMeshShape2(). - // Return 'true' if successfully created. - public static bool ConvertHeightmapToMesh( - BSScene physicsScene, - float[] heightMap, int sizeX, int sizeY, // parameters of incoming heightmap - float extentX, float extentY, // zero based range for output vertices - Vector3 extentBase, // base to be added to all vertices - float magnification, // number of vertices to create between heightMap coords - out int indicesCountO, out int[] indicesO, - out int verticesCountO, out float[] verticesO) - { - bool ret = false; - - int indicesCount = 0; - int verticesCount = 0; - int[] indices = new int[0]; - float[] vertices = new float[0]; - - // Simple mesh creation which assumes magnification == 1, sizeX == extentX and sizeY == extentY. - // TODO: do a more general solution that scales, adds new vertices and smoothes the result. - - try - { - // One vertice per heightmap value plus the vertices off the top and bottom edge. - int totalVertices = (sizeX + 1) * (sizeY + 1); - vertices = new float[totalVertices * 3]; - int totalIndices = sizeX * sizeY * 6; - indices = new int[totalIndices]; - - physicsScene.DetailLog("{0},BSTerrainMesh.ConvertHeightMapToMesh,totVert={1},totInd={2}", - BSScene.DetailLogZero, totalVertices, totalIndices); - float magX = (float)sizeX / extentX; - float magY = (float)sizeY / extentY; - // Note that sizeX+1 vertices are created since there is land between this and the next region. - for (int yy = 0; yy <= sizeY; yy++) - { - for (int xx = 0; xx <= sizeX; xx++) // Hint: the "<=" means we got through sizeX + 1 times - { - int offset = yy * sizeX + xx; - // Extend the height from the height from the last row or column - if (yy == sizeY) offset -= sizeX; - if (xx == sizeX) offset -= 1; - float height = heightMap[offset]; - vertices[verticesCount + 0] = (float)xx * magX + extentBase.X; - vertices[verticesCount + 1] = (float)yy * magY + extentBase.Y; - vertices[verticesCount + 2] = height + extentBase.Z; - if (physicsScene.PhysicsLogging.Enabled && verticesCount < 900) // DEBUG DEBUG DEBUG - { - Vector3 genVertex = new Vector3( - vertices[verticesCount + 0], - vertices[verticesCount + 1], - vertices[verticesCount + 2]); - physicsScene.DetailLog("{0},BSTerrainMesh.ConvertHeightMapToMesh,ii={1},vertex={2}", - BSScene.DetailLogZero, verticesCount/3, genVertex); - } - verticesCount += 3; - } - } - verticesCount = verticesCount / 3; - physicsScene.DetailLog("{0},BSTerrainMesh.ConvertHeightMapToMesh,completeVerts,verCount={1}", - BSScene.DetailLogZero, verticesCount); - - for (int yy = 0; yy < sizeY; yy++) - { - for (int xx = 0; xx < sizeX; xx++) - { - int offset = yy * sizeX + xx; - // Each vertices is presumed to be the upper left corner of a box of two triangles - indices[indicesCount + 0] = offset; - indices[indicesCount + 1] = offset + 1; - indices[indicesCount + 2] = offset + sizeX + 1; // accounting for the extra column - indices[indicesCount + 3] = offset + 1; - indices[indicesCount + 4] = offset + sizeX + 2; - indices[indicesCount + 5] = offset + sizeX + 1; - if (indicesCount < (300 * 6)) // DEBUG DEBUG DEBUG - physicsScene.DetailLog("{0},BSTerrainMesh.ConvertHeightMapToMesh,i0={1},i1={2},i2={3},i3={4},i4={5},i5={6}", // DEEBUG DEBUG DEBUG - BSScene.DetailLogZero, - indices[indicesCount + 0], - indices[indicesCount + 1], - indices[indicesCount + 2], - indices[indicesCount + 3], - indices[indicesCount + 4], - indices[indicesCount + 5] - ); - indicesCount += 6; - } - } - physicsScene.DetailLog("{0},BSTerrainMesh.ConvertHeightMapToMesh,completeIndices,indCount={1}", // DEEBUG DEBUG DEBUG - LogHeader, indicesCount); // DEBUG - ret = true; - } - catch (Exception e) - { - physicsScene.Logger.ErrorFormat("{0} Failed conversion of heightmap to mesh. Base={1}, e={2}", - LogHeader, extentBase, e); - } - - indicesCountO = indicesCount; - indicesO = indices; - verticesCountO = verticesCount; - verticesO = vertices; - - return ret; - } -} -} +/* + * 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 OpenSim.Framework; +using OpenSim.Region.Framework; +using OpenSim.Region.CoreModules; +using OpenSim.Region.Physics.Manager; + +using Nini.Config; +using log4net; + +using OpenMetaverse; + +namespace OpenSim.Region.Physics.BulletSPlugin +{ +public sealed class BSTerrainMesh : BSTerrainPhys +{ + static string LogHeader = "[BULLETSIM TERRAIN MESH]"; + + private float[] m_savedHeightMap; + int m_sizeX; + int m_sizeY; + + BulletShape m_terrainShape; + BulletBody m_terrainBody; + + public BSTerrainMesh(BSScene physicsScene, Vector3 regionBase, uint id, Vector3 regionSize) + : base(physicsScene, regionBase, id) + { + } + + public BSTerrainMesh(BSScene physicsScene, Vector3 regionBase, uint id /* parameters for making mesh */) + : base(physicsScene, regionBase, id) + { + } + + // Create terrain mesh from a heightmap. + public BSTerrainMesh(BSScene physicsScene, Vector3 regionBase, uint id, float[] initialMap, + Vector3 minCoords, Vector3 maxCoords) + : base(physicsScene, regionBase, id) + { + int indicesCount; + int[] indices; + int verticesCount; + float[] vertices; + + m_savedHeightMap = initialMap; + + m_sizeX = (int)(maxCoords.X - minCoords.X); + m_sizeY = (int)(maxCoords.Y - minCoords.Y); + + if (!BSTerrainMesh.ConvertHeightmapToMesh(PhysicsScene, initialMap, m_sizeX, m_sizeY, + (float)m_sizeX, (float)m_sizeY, + Vector3.Zero, 1.0f, + out indicesCount, out indices, out verticesCount, out vertices)) + { + // DISASTER!! + PhysicsScene.DetailLog("{0},BSTerrainMesh.create,failedConversionOfHeightmap", ID); + 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,afterConvertHeightmapToMesh,ver={1},ind={2}", + ID, verticesCount, indicesCount); + + m_terrainShape = new BulletShape(BulletSimAPI.CreateMeshShape2(PhysicsScene.World.ptr, + indicesCount, indices, verticesCount, vertices), + PhysicsShapeType.SHAPE_MESH); + if (m_terrainShape.ptr == IntPtr.Zero) + { + // DISASTER!! + PhysicsScene.DetailLog("{0},BSTerrainMesh.create,failedCreationOfShape", ID); + 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; + } + PhysicsScene.DetailLog("{0},BSTerrainMesh.create,afterCreateShape,shape={1}", ID, m_terrainShape); + + // The terrain object initial position is at the center of the object + Vector3 centerPos; + centerPos.X = minCoords.X + (m_sizeX / 2f); + centerPos.Y = minCoords.Y + (m_sizeY / 2f); + centerPos.Z = minCoords.Z + ((maxCoords.Z - minCoords.Z) / 2f); + Quaternion rot = Quaternion.Identity; + + PhysicsScene.DetailLog("{0},BSTerrainMesh.create,creatingBody,centerPos={1},rot={2}", ID, centerPos, rot); + m_terrainBody = new BulletBody(id, BulletSimAPI.CreateBodyWithDefaultMotionState2( + m_terrainShape.ptr, ID, centerPos, rot)); + if (m_terrainBody.ptr == IntPtr.Zero) + { + // DISASTER!! + 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.DetailLog("{0},BSTerrainMesh.create,afterCreateBody,body={1}", ID, m_terrainBody); + + // Set current terrain attributes + BulletSimAPI.SetFriction2(m_terrainBody.ptr, PhysicsScene.Params.terrainFriction); + BulletSimAPI.SetHitFraction2(m_terrainBody.ptr, PhysicsScene.Params.terrainHitFraction); + BulletSimAPI.SetRestitution2(m_terrainBody.ptr, PhysicsScene.Params.terrainRestitution); + BulletSimAPI.SetCollisionFlags2(m_terrainBody.ptr, CollisionFlags.CF_STATIC_OBJECT); + + // Static objects are not very massive. + BulletSimAPI.SetMassProps2(m_terrainBody.ptr, 0f, Vector3.Zero); + + // Return the new terrain to the world of physical objects + BulletSimAPI.AddObjectToWorld2(PhysicsScene.World.ptr, m_terrainBody.ptr); + + // redo its bounding box now that it is in the world + BulletSimAPI.UpdateSingleAabb2(PhysicsScene.World.ptr, m_terrainBody.ptr); + + BulletSimAPI.SetCollisionFilterMask2(m_terrainBody.ptr, + (uint)CollisionFilterGroups.TerrainFilter, + (uint)CollisionFilterGroups.TerrainMask); + + // Make it so the terrain will not move or be considered for movement. + BulletSimAPI.ForceActivationState2(m_terrainBody.ptr, ActivationState.DISABLE_SIMULATION); + } + + public override void Dispose() + { + if (m_terrainBody.ptr != IntPtr.Zero) + { + BulletSimAPI.RemoveObjectFromWorld2(PhysicsScene.World.ptr, m_terrainBody.ptr); + // Frees both the body and the shape. + BulletSimAPI.DestroyObject2(PhysicsScene.World.ptr, m_terrainBody.ptr); + } + } + + public override float GetHeightAtXYZ(Vector3 pos) + { + // For the moment use the saved heightmap to get the terrain height. + // TODO: raycast downward to find the true terrain below the position. + float ret = BSTerrainManager.HEIGHT_GETHEIGHT_RET; + + int mapIndex = (int)pos.Y * m_sizeY + (int)pos.X; + try + { + ret = m_savedHeightMap[mapIndex]; + } + 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}", + LogHeader, TerrainBase, pos); + ret = BSTerrainManager.HEIGHT_GETHEIGHT_RET; + } + return ret; + } + + // Convert the passed heightmap to mesh information suitable for CreateMeshShape2(). + // Return 'true' if successfully created. + public static bool ConvertHeightmapToMesh( + BSScene physicsScene, + float[] heightMap, int sizeX, int sizeY, // parameters of incoming heightmap + float extentX, float extentY, // zero based range for output vertices + Vector3 extentBase, // base to be added to all vertices + float magnification, // number of vertices to create between heightMap coords + out int indicesCountO, out int[] indicesO, + out int verticesCountO, out float[] verticesO) + { + bool ret = false; + + int indicesCount = 0; + int verticesCount = 0; + int[] indices = new int[0]; + float[] vertices = new float[0]; + + // Simple mesh creation which assumes magnification == 1, sizeX == extentX and sizeY == extentY. + // TODO: do a more general solution that scales, adds new vertices and smoothes the result. + + try + { + // One vertice per heightmap value plus the vertices off the top and bottom edge. + int totalVertices = (sizeX + 1) * (sizeY + 1); + vertices = new float[totalVertices * 3]; + int totalIndices = sizeX * sizeY * 6; + indices = new int[totalIndices]; + + physicsScene.DetailLog("{0},BSTerrainMesh.ConvertHeightMapToMesh,totVert={1},totInd={2}", + BSScene.DetailLogZero, totalVertices, totalIndices); + float magX = (float)sizeX / extentX; + float magY = (float)sizeY / extentY; + // Note that sizeX+1 vertices are created since there is land between this and the next region. + for (int yy = 0; yy <= sizeY; yy++) + { + for (int xx = 0; xx <= sizeX; xx++) // Hint: the "<=" means we got through sizeX + 1 times + { + int offset = yy * sizeX + xx; + // Extend the height from the height from the last row or column + if (yy == sizeY) offset -= sizeX; + if (xx == sizeX) offset -= 1; + float height = heightMap[offset]; + vertices[verticesCount + 0] = (float)xx * magX + extentBase.X; + vertices[verticesCount + 1] = (float)yy * magY + extentBase.Y; + vertices[verticesCount + 2] = height + extentBase.Z; + if (physicsScene.PhysicsLogging.Enabled && verticesCount < 900) // DEBUG DEBUG DEBUG + { + Vector3 genVertex = new Vector3( + vertices[verticesCount + 0], + vertices[verticesCount + 1], + vertices[verticesCount + 2]); + physicsScene.DetailLog("{0},BSTerrainMesh.ConvertHeightMapToMesh,ii={1},vertex={2}", + BSScene.DetailLogZero, verticesCount/3, genVertex); + } + verticesCount += 3; + } + } + verticesCount = verticesCount / 3; + physicsScene.DetailLog("{0},BSTerrainMesh.ConvertHeightMapToMesh,completeVerts,verCount={1}", + BSScene.DetailLogZero, verticesCount); + + for (int yy = 0; yy < sizeY; yy++) + { + for (int xx = 0; xx < sizeX; xx++) + { + int offset = yy * sizeX + xx; + // Each vertices is presumed to be the upper left corner of a box of two triangles + indices[indicesCount + 0] = offset; + indices[indicesCount + 1] = offset + 1; + indices[indicesCount + 2] = offset + sizeX + 1; // accounting for the extra column + indices[indicesCount + 3] = offset + 1; + indices[indicesCount + 4] = offset + sizeX + 2; + indices[indicesCount + 5] = offset + sizeX + 1; + if (indicesCount < (300 * 6)) // DEBUG DEBUG DEBUG + physicsScene.DetailLog("{0},BSTerrainMesh.ConvertHeightMapToMesh,i0={1},i1={2},i2={3},i3={4},i4={5},i5={6}", // DEEBUG DEBUG DEBUG + BSScene.DetailLogZero, + indices[indicesCount + 0], + indices[indicesCount + 1], + indices[indicesCount + 2], + indices[indicesCount + 3], + indices[indicesCount + 4], + indices[indicesCount + 5] + ); + indicesCount += 6; + } + } + physicsScene.DetailLog("{0},BSTerrainMesh.ConvertHeightMapToMesh,completeIndices,indCount={1}", // DEEBUG DEBUG DEBUG + LogHeader, indicesCount); // DEBUG + ret = true; + } + catch (Exception e) + { + physicsScene.Logger.ErrorFormat("{0} Failed conversion of heightmap to mesh. Base={1}, e={2}", + LogHeader, extentBase, e); + } + + indicesCountO = indicesCount; + indicesO = indices; + verticesCountO = verticesCount; + verticesO = vertices; + + return ret; + } +} +} -- cgit v1.1 From a59368c4a1889ccd79da9e564ee84b213a7f6fbd Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Wed, 21 Nov 2012 10:37:40 -0800 Subject: BulletSim: add terrainImplementation parameter with default to Mesh. --- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 5 +++ .../Physics/BulletSPlugin/BSTerrainManager.cs | 45 +++++++++++++++++++--- .../Region/Physics/BulletSPlugin/BulletSimAPI.cs | 1 + 3 files changed, 46 insertions(+), 5 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index 58dccea..0e73d04 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -1145,6 +1145,11 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].contactProcessingThreshold, p, l, v); }, (s,o,v) => { BulletSimAPI.SetContactProcessingThreshold2(o.PhysBody.ptr, v); } ), + new ParameterDefn("TerrainImplementation", "Type of shape to use for terrain (0=heightmap, 1=mesh)", + (float)BSTerrainPhys.TerrainImplementation.Mesh, + (s,cf,p,v) => { s.m_params[0].terrainImplementation = cf.GetFloat(p,v); }, + (s) => { return s.m_params[0].terrainImplementation; }, + (s,p,l,v) => { s.m_params[0].terrainImplementation = v; } ), new ParameterDefn("TerrainFriction", "Factor to reduce movement against terrain surface" , 0.5f, (s,cf,p,v) => { s.m_params[0].terrainFriction = cf.GetFloat(p, v); }, diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs index ed0dfa8..b88f561 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs @@ -44,6 +44,12 @@ namespace OpenSim.Region.Physics.BulletSPlugin // The physical implementation of the terrain is wrapped in this class. public abstract class BSTerrainPhys : IDisposable { + public enum TerrainImplementation + { + Heightmap = 0, + Mesh = 1 + } + public BSScene 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; } @@ -246,12 +252,27 @@ public sealed class BSTerrainManager // Release any physical memory it may be using. terrainPhys.Dispose(); + BSTerrainPhys newTerrainPhys = null; ; if (MegaRegionParentPhysicsScene == null) { - // BSTerrainPhys newTerrainPhys = new BSTerrainHeightmap(PhysicsScene, terrainRegionBase, id, - // heightMap, minCoords, maxCoords); - BSTerrainPhys newTerrainPhys = new BSTerrainMesh(PhysicsScene, terrainRegionBase, id, + // TODO: redo terrain implementation selection to be centralized (there is another + // use below) and to accept an asset specification (for a mesh). + switch ((int)PhysicsScene.Params.terrainImplementation) + { + case (int)BSTerrainPhys.TerrainImplementation.Heightmap: + newTerrainPhys = new BSTerrainHeightmap(PhysicsScene, terrainRegionBase, id, + heightMap, minCoords, maxCoords); + break; + case (int)BSTerrainPhys.TerrainImplementation.Mesh: + newTerrainPhys = new BSTerrainMesh(PhysicsScene, terrainRegionBase, id, heightMap, minCoords, maxCoords); + break; + default: + PhysicsScene.Logger.ErrorFormat("{0} Bad terrain implementation specified. type={1}/{2}", + LogHeader, (int)PhysicsScene.Params.terrainImplementation, PhysicsScene.Params.terrainImplementation); + break; + } + m_terrains.Add(terrainRegionBase, newTerrainPhys); m_terrainModified = true; @@ -292,8 +313,22 @@ public sealed class BSTerrainManager { DetailLog("{0},UpdateTerrain:NewTerrain,taint,baseX={1},baseY={2}", BSScene.DetailLogZero, minCoordsX.X, minCoordsX.Y); - BSTerrainPhys newTerrainPhys = new BSTerrainHeightmap(PhysicsScene, terrainRegionBase, - newTerrainID, heightMapX, minCoordsX, maxCoordsX); + BSTerrainPhys newTerrainPhys = null; + switch ((int)PhysicsScene.Params.terrainImplementation) + { + case (int)BSTerrainPhys.TerrainImplementation.Heightmap: + newTerrainPhys = new BSTerrainHeightmap(PhysicsScene, terrainRegionBase, id, + heightMap, minCoords, maxCoords); + break; + case (int)BSTerrainPhys.TerrainImplementation.Mesh: + newTerrainPhys = new BSTerrainMesh(PhysicsScene, terrainRegionBase, id, + heightMap, minCoords, maxCoords); + break; + default: + PhysicsScene.Logger.ErrorFormat("{0} Bad terrain implementation specified. type={1}/{2}", + LogHeader, (int)PhysicsScene.Params.terrainImplementation, PhysicsScene.Params.terrainImplementation); + break; + } m_terrains.Add(terrainRegionBase, newTerrainPhys); m_terrainModified = true; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs index a2271a9..e218053 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs @@ -283,6 +283,7 @@ public struct ConfigurationParameters public float ccdSweptSphereRadius; public float contactProcessingThreshold; + public float terrainImplementation; public float terrainFriction; public float terrainHitFraction; public float terrainRestitution; -- cgit v1.1 From 4a0de0170412a939bade6cd149c94c7fd3ef020e Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Wed, 21 Nov 2012 13:44:02 -0800 Subject: BulletSim: Properly position mesh terrain on creation (fixes terrain not appearing to be working). Centralize terrain shape creation logic. Remove very chatty detail log messages. --- .../Physics/BulletSPlugin/BSTerrainManager.cs | 74 ++++++++++------------ .../Region/Physics/BulletSPlugin/BSTerrainMesh.cs | 46 +++----------- 2 files changed, 44 insertions(+), 76 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs index b88f561..097cd3e 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs @@ -241,38 +241,20 @@ public sealed class BSTerrainManager BSTerrainPhys terrainPhys; if (m_terrains.TryGetValue(terrainRegionBase, out terrainPhys)) { - // If this is terrain we know about, it's easy to update - - DetailLog("{0},UpdateTerrain:UpdateExisting,call,terrainBase={1}", BSScene.DetailLogZero, terrainRegionBase); + // There is already a terrain in this spot. Free the old and build the new. + DetailLog("{0},UpdateTerrain:UpdateExisting,call,id={1},base={2},minC={3},maxC={4}", + BSScene.DetailLogZero, id, terrainRegionBase, minCoords, minCoords); PhysicsScene.TaintedObject(inTaintTime, "BSScene.UpdateTerrain:UpdateExisting", delegate() { // Remove old terrain from the collection - m_terrains.Remove(terrainPhys.TerrainBase); + m_terrains.Remove(terrainRegionBase); // Release any physical memory it may be using. terrainPhys.Dispose(); - BSTerrainPhys newTerrainPhys = null; ; if (MegaRegionParentPhysicsScene == null) { - // TODO: redo terrain implementation selection to be centralized (there is another - // use below) and to accept an asset specification (for a mesh). - switch ((int)PhysicsScene.Params.terrainImplementation) - { - case (int)BSTerrainPhys.TerrainImplementation.Heightmap: - newTerrainPhys = new BSTerrainHeightmap(PhysicsScene, terrainRegionBase, id, - heightMap, minCoords, maxCoords); - break; - case (int)BSTerrainPhys.TerrainImplementation.Mesh: - newTerrainPhys = new BSTerrainMesh(PhysicsScene, terrainRegionBase, id, - heightMap, minCoords, maxCoords); - break; - default: - PhysicsScene.Logger.ErrorFormat("{0} Bad terrain implementation specified. type={1}/{2}", - LogHeader, (int)PhysicsScene.Params.terrainImplementation, PhysicsScene.Params.terrainImplementation); - break; - } - + BSTerrainPhys newTerrainPhys = BuildPhysicalTerrain(terrainRegionBase, id, heightMap, minCoords, maxCoords); m_terrains.Add(terrainRegionBase, newTerrainPhys); m_terrainModified = true; @@ -313,22 +295,7 @@ public sealed class BSTerrainManager { DetailLog("{0},UpdateTerrain:NewTerrain,taint,baseX={1},baseY={2}", BSScene.DetailLogZero, minCoordsX.X, minCoordsX.Y); - BSTerrainPhys newTerrainPhys = null; - switch ((int)PhysicsScene.Params.terrainImplementation) - { - case (int)BSTerrainPhys.TerrainImplementation.Heightmap: - newTerrainPhys = new BSTerrainHeightmap(PhysicsScene, terrainRegionBase, id, - heightMap, minCoords, maxCoords); - break; - case (int)BSTerrainPhys.TerrainImplementation.Mesh: - newTerrainPhys = new BSTerrainMesh(PhysicsScene, terrainRegionBase, id, - heightMap, minCoords, maxCoords); - break; - default: - PhysicsScene.Logger.ErrorFormat("{0} Bad terrain implementation specified. type={1}/{2}", - LogHeader, (int)PhysicsScene.Params.terrainImplementation, PhysicsScene.Params.terrainImplementation); - break; - } + BSTerrainPhys newTerrainPhys = BuildPhysicalTerrain(terrainRegionBase, id, heightMap, minCoords, maxCoords); m_terrains.Add(terrainRegionBase, newTerrainPhys); m_terrainModified = true; @@ -336,6 +303,35 @@ public sealed class BSTerrainManager } } + // 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, + PhysicsScene.Params.terrainImplementation); + BSTerrainPhys newTerrainPhys = null; + switch ((int)PhysicsScene.Params.terrainImplementation) + { + case (int)BSTerrainPhys.TerrainImplementation.Heightmap: + newTerrainPhys = new BSTerrainHeightmap(PhysicsScene, terrainRegionBase, id, + heightMap, minCoords, maxCoords); + break; + case (int)BSTerrainPhys.TerrainImplementation.Mesh: + newTerrainPhys = new BSTerrainMesh(PhysicsScene, terrainRegionBase, id, + heightMap, minCoords, maxCoords); + break; + default: + PhysicsScene.Logger.ErrorFormat("{0} Bad terrain implementation specified. Type={1}/{2},Region={3}/{4}", + LogHeader, + (int)PhysicsScene.Params.terrainImplementation, + PhysicsScene.Params.terrainImplementation, + PhysicsScene.RegionName, terrainRegionBase); + break; + } + return newTerrainPhys; + } + + // Given an X and Y, find the height of the terrain. // Since we could be handling multiple terrains for a mega-region, // the base of the region is calcuated assuming all regions are diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainMesh.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainMesh.cs index a199078..3279b6f 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainMesh.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainMesh.cs @@ -76,7 +76,8 @@ public sealed class BSTerrainMesh : BSTerrainPhys m_sizeX = (int)(maxCoords.X - minCoords.X); m_sizeY = (int)(maxCoords.Y - minCoords.Y); - if (!BSTerrainMesh.ConvertHeightmapToMesh(PhysicsScene, initialMap, m_sizeX, m_sizeY, + if (!BSTerrainMesh.ConvertHeightmapToMesh(PhysicsScene, initialMap, + m_sizeX, m_sizeY, (float)m_sizeX, (float)m_sizeY, Vector3.Zero, 1.0f, out indicesCount, out indices, out verticesCount, out vertices)) @@ -87,8 +88,6 @@ public sealed class BSTerrainMesh : BSTerrainPhys // Something is very messed up and a crash is in our future. return; } - PhysicsScene.DetailLog("{0},BSTerrainMesh.create,afterConvertHeightmapToMesh,ver={1},ind={2}", - ID, verticesCount, indicesCount); m_terrainShape = new BulletShape(BulletSimAPI.CreateMeshShape2(PhysicsScene.World.ptr, indicesCount, indices, verticesCount, vertices), @@ -101,18 +100,11 @@ public sealed class BSTerrainMesh : BSTerrainPhys // Something is very messed up and a crash is in our future. return; } - PhysicsScene.DetailLog("{0},BSTerrainMesh.create,afterCreateShape,shape={1}", ID, m_terrainShape); - // The terrain object initial position is at the center of the object - Vector3 centerPos; - centerPos.X = minCoords.X + (m_sizeX / 2f); - centerPos.Y = minCoords.Y + (m_sizeY / 2f); - centerPos.Z = minCoords.Z + ((maxCoords.Z - minCoords.Z) / 2f); + Vector3 pos = regionBase; Quaternion rot = Quaternion.Identity; - PhysicsScene.DetailLog("{0},BSTerrainMesh.create,creatingBody,centerPos={1},rot={2}", ID, centerPos, rot); - m_terrainBody = new BulletBody(id, BulletSimAPI.CreateBodyWithDefaultMotionState2( - m_terrainShape.ptr, ID, centerPos, rot)); + m_terrainBody = new BulletBody(id, BulletSimAPI.CreateBodyWithDefaultMotionState2( m_terrainShape.ptr, ID, pos, rot)); if (m_terrainBody.ptr == IntPtr.Zero) { // DISASTER!! @@ -120,7 +112,6 @@ public sealed class BSTerrainMesh : BSTerrainPhys // Something is very messed up and a crash is in our future. return; } - PhysicsScene.DetailLog("{0},BSTerrainMesh.create,afterCreateBody,body={1}", ID, m_terrainBody); // Set current terrain attributes BulletSimAPI.SetFriction2(m_terrainBody.ptr, PhysicsScene.Params.terrainFriction); @@ -194,7 +185,7 @@ public sealed class BSTerrainMesh : BSTerrainPhys int[] indices = new int[0]; float[] vertices = new float[0]; - // Simple mesh creation which assumes magnification == 1, sizeX == extentX and sizeY == extentY. + // Simple mesh creation which assumes magnification == 1. // TODO: do a more general solution that scales, adds new vertices and smoothes the result. try @@ -205,10 +196,10 @@ public sealed class BSTerrainMesh : BSTerrainPhys int totalIndices = sizeX * sizeY * 6; indices = new int[totalIndices]; - physicsScene.DetailLog("{0},BSTerrainMesh.ConvertHeightMapToMesh,totVert={1},totInd={2}", - BSScene.DetailLogZero, totalVertices, totalIndices); float magX = (float)sizeX / extentX; float magY = (float)sizeY / extentY; + physicsScene.DetailLog("{0},BSTerrainMesh.ConvertHeightMapToMesh,totVert={1},totInd={2},extentBase={3},magX={4},magY={5}", + BSScene.DetailLogZero, totalVertices, totalIndices, extentBase, magX, magY); // Note that sizeX+1 vertices are created since there is land between this and the next region. for (int yy = 0; yy <= sizeY; yy++) { @@ -222,15 +213,6 @@ public sealed class BSTerrainMesh : BSTerrainPhys vertices[verticesCount + 0] = (float)xx * magX + extentBase.X; vertices[verticesCount + 1] = (float)yy * magY + extentBase.Y; vertices[verticesCount + 2] = height + extentBase.Z; - if (physicsScene.PhysicsLogging.Enabled && verticesCount < 900) // DEBUG DEBUG DEBUG - { - Vector3 genVertex = new Vector3( - vertices[verticesCount + 0], - vertices[verticesCount + 1], - vertices[verticesCount + 2]); - physicsScene.DetailLog("{0},BSTerrainMesh.ConvertHeightMapToMesh,ii={1},vertex={2}", - BSScene.DetailLogZero, verticesCount/3, genVertex); - } verticesCount += 3; } } @@ -250,16 +232,6 @@ public sealed class BSTerrainMesh : BSTerrainPhys indices[indicesCount + 3] = offset + 1; indices[indicesCount + 4] = offset + sizeX + 2; indices[indicesCount + 5] = offset + sizeX + 1; - if (indicesCount < (300 * 6)) // DEBUG DEBUG DEBUG - physicsScene.DetailLog("{0},BSTerrainMesh.ConvertHeightMapToMesh,i0={1},i1={2},i2={3},i3={4},i4={5},i5={6}", // DEEBUG DEBUG DEBUG - BSScene.DetailLogZero, - indices[indicesCount + 0], - indices[indicesCount + 1], - indices[indicesCount + 2], - indices[indicesCount + 3], - indices[indicesCount + 4], - indices[indicesCount + 5] - ); indicesCount += 6; } } @@ -269,8 +241,8 @@ public sealed class BSTerrainMesh : BSTerrainPhys } catch (Exception e) { - physicsScene.Logger.ErrorFormat("{0} Failed conversion of heightmap to mesh. Base={1}, e={2}", - LogHeader, extentBase, e); + physicsScene.Logger.ErrorFormat("{0} Failed conversion of heightmap to mesh. For={1}/{2}, e={3}", + LogHeader, physicsScene.RegionName, extentBase, e); } indicesCountO = indicesCount; -- cgit v1.1 From cbc7e7bf85bfd9e916146b0ae4a605996c24720b Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Wed, 21 Nov 2012 16:31:23 -0800 Subject: BulletSim: Make avatar capsule so it is not circular. Simple attempt to make avatars better shaped. Replace parameter 'avatarCapsuleRadius' with 'avatarCapsuleWidth' and 'avatarCapsuleDepth'. More tweeking to avatar height calculation. A little better but short avatar's feet are above the terrain and tall avatar's feet are a little below the ground. --- .../Region/Physics/BulletSPlugin/BSCharacter.cs | 24 +++++++++++++++------- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 4 +++- OpenSim/Region/Physics/BulletSPlugin/BSScene.cs | 18 +++++++++------- .../Physics/BulletSPlugin/BSShapeCollection.cs | 9 ++++---- .../Physics/BulletSPlugin/BSTerrainManager.cs | 2 +- .../Region/Physics/BulletSPlugin/BulletSimAPI.cs | 3 ++- 6 files changed, 39 insertions(+), 21 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index 799211e..e2aa41e 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -82,7 +82,13 @@ public sealed class BSCharacter : BSPhysObject { _physicsActorType = (int)ActorTypes.Agent; _position = pos; + + // Old versions of ScenePresence passed only the height. If width and/or depth are zero, + // replace with the default values. _size = size; + if (_size.X == 0f) _size.X = PhysicsScene.Params.avatarCapsuleDepth; + if (_size.Y == 0f) _size.Y = PhysicsScene.Params.avatarCapsuleWidth; + _flying = isFlying; _orientation = OMV.Quaternion.Identity; _velocity = OMV.Vector3.Zero; @@ -175,8 +181,7 @@ public sealed class BSCharacter : BSPhysObject get { // Avatar capsule size is kept in the scale parameter. - // return _size; - return new OMV.Vector3(Scale.X * 2f, Scale.Y * 2f, Scale.Z); + return _size; } set { @@ -614,14 +619,19 @@ public sealed class BSCharacter : BSPhysObject // The 'size' given by the simulator is the mid-point of the avatar // and X and Y are unspecified. - OMV.Vector3 newScale = OMV.Vector3.Zero; - newScale.X = PhysicsScene.Params.avatarCapsuleRadius; - newScale.Y = PhysicsScene.Params.avatarCapsuleRadius; + OMV.Vector3 newScale = size; + // newScale.X = PhysicsScene.Params.avatarCapsuleWidth; + // newScale.Y = PhysicsScene.Params.avatarCapsuleDepth; // From the total height, remove the capsule half spheres that are at each end // The 1.15f came from ODE. Not sure what this factors in. - newScale.Z = (size.Z * 1.15f) - (newScale.X + newScale.Y); - Scale = newScale; + // newScale.Z = (size.Z * 1.15f) - (newScale.X + newScale.Y); + + // 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) * 2f); + + // Convert diameters to radii and height to half height -- the way Bullet expects it. + Scale = newScale / 2f; } // set _avatarVolume and _mass based on capsule size, _density and Scale diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 2657e4b..5d16bbf 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -93,7 +93,7 @@ public sealed class BSPrim : BSPhysObject _physicsActorType = (int)ActorTypes.Prim; _position = pos; _size = size; - Scale = new OMV.Vector3(1f, 1f, 1f); // the scale will be set by CreateGeom depending on object type + Scale = size; // the scale will be set by CreateGeom depending on object type _orientation = rotation; _buoyancy = 1f; _velocity = OMV.Vector3.Zero; @@ -154,6 +154,8 @@ public sealed class BSPrim : BSPhysObject public override OMV.Vector3 Size { get { return _size; } set { + // We presume the scale and size are the same. If scale must be changed for + // the physical shape, that is done when the geometry is built. _size = value; ForceBodyShapeRebuild(false); } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs index 0e73d04..27a78d1 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSScene.cs @@ -1185,14 +1185,18 @@ public sealed class BSScene : PhysicsScene, IPhysicsParameters (s,cf,p,v) => { s.m_params[0].avatarRestitution = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].avatarRestitution; }, (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].avatarRestitution, p, l, v); } ), - new ParameterDefn("AvatarCapsuleRadius", "Radius of space around an avatar", - 0.37f, - (s,cf,p,v) => { s.m_params[0].avatarCapsuleRadius = cf.GetFloat(p, v); }, - (s) => { return s.m_params[0].avatarCapsuleRadius; }, - (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].avatarCapsuleRadius, p, l, v); } ), + new ParameterDefn("AvatarCapsuleWidth", "The distance between the sides of the avatar capsule", + 0.6f, + (s,cf,p,v) => { s.m_params[0].avatarCapsuleWidth = cf.GetFloat(p, v); }, + (s) => { return s.m_params[0].avatarCapsuleWidth; }, + (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].avatarCapsuleWidth, p, l, v); } ), + new ParameterDefn("AvatarCapsuleDepth", "The distance between the front and back of the avatar capsule", + 0.45f, + (s,cf,p,v) => { s.m_params[0].avatarCapsuleDepth = cf.GetFloat(p, v); }, + (s) => { return s.m_params[0].avatarCapsuleDepth; }, + (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].avatarCapsuleDepth, p, l, v); } ), new ParameterDefn("AvatarCapsuleHeight", "Default height of space around avatar", - // 1.5f, - 2.140599f, + 1.5f, (s,cf,p,v) => { s.m_params[0].avatarCapsuleHeight = cf.GetFloat(p, v); }, (s) => { return s.m_params[0].avatarCapsuleHeight; }, (s,p,l,v) => { s.UpdateParameterObject(ref s.m_params[0].avatarCapsuleHeight, p, l, v); } ), diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index a53ad6e..869735c 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -525,9 +525,6 @@ public sealed class BSShapeCollection : IDisposable // release any previous shape DereferenceShape(prim.PhysShape, true, shapeCallback); - // Bullet native objects are scaled by the Bullet engine so pass the size in - prim.Scale = prim.Size; - BulletShape newShape = BuildPhysicalNativeShape(prim, shapeType, shapeKey); // Don't need to do a 'ReferenceShape()' here because native shapes are not shared. @@ -547,12 +544,13 @@ public sealed class BSShapeCollection : IDisposable nativeShapeData.Type = shapeType; nativeShapeData.ID = prim.LocalID; nativeShapeData.Scale = prim.Scale; - nativeShapeData.Size = prim.Scale; + nativeShapeData.Size = prim.Scale; // unneeded, I think. nativeShapeData.MeshKey = (ulong)shapeKey; nativeShapeData.HullKey = (ulong)shapeKey; if (shapeType == PhysicsShapeType.SHAPE_CAPSULE) { + // The proper scale has been calculated in the prim. newShape = new BulletShape( BulletSimAPI.BuildCapsuleShape2(PhysicsScene.World.ptr, 1f, 1f, prim.Scale) , shapeType); @@ -560,6 +558,9 @@ public sealed class BSShapeCollection : IDisposable } else { + // Native shapes are scaled in Bullet so set the scaling to the size + prim.Scale = prim.Size; + nativeShapeData.Scale = prim.Scale; newShape = new BulletShape(BulletSimAPI.BuildNativeShape2(PhysicsScene.World.ptr, nativeShapeData), shapeType); } if (newShape.ptr == IntPtr.Zero) diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs index 097cd3e..71fca33 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs @@ -308,7 +308,7 @@ public sealed class BSTerrainManager { PhysicsScene.Logger.DebugFormat("{0} Terrain for {1}/{2} created with {3}", LogHeader, PhysicsScene.RegionName, terrainRegionBase, - PhysicsScene.Params.terrainImplementation); + (BSTerrainPhys.TerrainImplementation)PhysicsScene.Params.terrainImplementation); BSTerrainPhys newTerrainPhys = null; switch ((int)PhysicsScene.Params.terrainImplementation) { diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs index e218053..4647c2d 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs @@ -291,7 +291,8 @@ public struct ConfigurationParameters public float avatarStandingFriction; public float avatarDensity; public float avatarRestitution; - public float avatarCapsuleRadius; + public float avatarCapsuleWidth; + public float avatarCapsuleDepth; public float avatarCapsuleHeight; public float avatarContactProcessingThreshold; -- cgit v1.1 From 3b2caa63b0ba890555990a88821ee37daa2607b4 Mon Sep 17 00:00:00 2001 From: Melanie Date: Thu, 22 Nov 2012 14:45:41 +0000 Subject: Rename BulletSim's PhysicsShapeType to BSPhysicsShapeType because it conflicts with PhysicsShape type defined in later libOMV --- .../Region/Physics/BulletSPlugin/BSCharacter.cs | 4 +- OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs | 4 +- .../Physics/BulletSPlugin/BSLinksetCompound.cs | 6 +-- .../Region/Physics/BulletSPlugin/BSPhysObject.cs | 4 +- OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs | 2 +- .../Physics/BulletSPlugin/BSShapeCollection.cs | 56 +++++++++++----------- OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs | 16 +++---- .../Physics/BulletSPlugin/BSTerrainHeightmap.cs | 2 +- .../Physics/BulletSPlugin/BSTerrainManager.cs | 2 +- .../Region/Physics/BulletSPlugin/BSTerrainMesh.cs | 2 +- .../Region/Physics/BulletSPlugin/BulletSimAPI.cs | 10 ++-- 11 files changed, 54 insertions(+), 54 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs index e2aa41e..4c195e1 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSCharacter.cs @@ -208,9 +208,9 @@ public sealed class BSCharacter : BSPhysObject set { BaseShape = value; } } // I want the physics engine to make an avatar capsule - public override PhysicsShapeType PreferredPhysicalShape + public override BSPhysicsShapeType PreferredPhysicalShape { - get {return PhysicsShapeType.SHAPE_CAPSULE; } + get {return BSPhysicsShapeType.SHAPE_CAPSULE; } } public override bool Grabbed { diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs index 4ee047b..0df4310 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinkset.cs @@ -82,9 +82,9 @@ public abstract class BSLinkset // Some linksets have a preferred physical shape. // Returns SHAPE_UNKNOWN if there is no preference. Causes the correct shape to be selected. - public virtual PhysicsShapeType PreferredPhysicalShape(BSPhysObject requestor) + public virtual BSPhysicsShapeType PreferredPhysicalShape(BSPhysObject requestor) { - return PhysicsShapeType.SHAPE_UNKNOWN; + return BSPhysicsShapeType.SHAPE_UNKNOWN; } // Linksets move around the children so the linkset might need to compute the child position diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs index cb37840..b9c2cf9 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSLinksetCompound.cs @@ -42,12 +42,12 @@ public sealed class BSLinksetCompound : BSLinkset } // For compound implimented linksets, if there are children, use compound shape for the root. - public override PhysicsShapeType PreferredPhysicalShape(BSPhysObject requestor) + public override BSPhysicsShapeType PreferredPhysicalShape(BSPhysObject requestor) { - PhysicsShapeType ret = PhysicsShapeType.SHAPE_UNKNOWN; + BSPhysicsShapeType ret = BSPhysicsShapeType.SHAPE_UNKNOWN; if (IsRoot(requestor) && HasAnyChildren) { - ret = PhysicsShapeType.SHAPE_COMPOUND; + ret = BSPhysicsShapeType.SHAPE_COMPOUND; } // DetailLog("{0},BSLinksetCompound.PreferredPhysicalShape,call,shape={1}", LinksetRoot.LocalID, ret); return ret; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs index e68b167..f6a890e 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPhysObject.cs @@ -94,9 +94,9 @@ public abstract class BSPhysObject : PhysicsActor public PrimitiveBaseShape BaseShape { get; protected set; } // Some types of objects have preferred physical representations. // Returns SHAPE_UNKNOWN if there is no preference. - public virtual PhysicsShapeType PreferredPhysicalShape + public virtual BSPhysicsShapeType PreferredPhysicalShape { - get { return PhysicsShapeType.SHAPE_UNKNOWN; } + get { return BSPhysicsShapeType.SHAPE_UNKNOWN; } } // When the physical properties are updated, an EntityProperty holds the update values. diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs index 5d16bbf..2b3fa25 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSPrim.cs @@ -171,7 +171,7 @@ public sealed class BSPrim : BSPhysObject } } // Whatever the linkset wants is what I want. - public override PhysicsShapeType PreferredPhysicalShape + public override BSPhysicsShapeType PreferredPhysicalShape { get { return Linkset.PreferredPhysicalShape(this); } } public override bool ForceBodyShapeRebuild(bool inTaintTime) diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs index 869735c..892c34b 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapeCollection.cs @@ -178,7 +178,7 @@ public sealed class BSShapeCollection : IDisposable bool ret = false; switch (shape.type) { - case PhysicsShapeType.SHAPE_MESH: + case BSPhysicsShapeType.SHAPE_MESH: MeshDesc meshDesc; if (Meshes.TryGetValue(shape.shapeKey, out meshDesc)) { @@ -201,7 +201,7 @@ public sealed class BSShapeCollection : IDisposable meshDesc.lastReferenced = System.DateTime.Now; Meshes[shape.shapeKey] = meshDesc; break; - case PhysicsShapeType.SHAPE_HULL: + case BSPhysicsShapeType.SHAPE_HULL: HullDesc hullDesc; if (Hulls.TryGetValue(shape.shapeKey, out hullDesc)) { @@ -224,7 +224,7 @@ public sealed class BSShapeCollection : IDisposable hullDesc.lastReferenced = System.DateTime.Now; Hulls[shape.shapeKey] = hullDesc; break; - case PhysicsShapeType.SHAPE_UNKNOWN: + case BSPhysicsShapeType.SHAPE_UNKNOWN: break; default: // Native shapes are not tracked and they don't go into any list @@ -255,16 +255,16 @@ public sealed class BSShapeCollection : IDisposable { switch (shape.type) { - case PhysicsShapeType.SHAPE_HULL: + case BSPhysicsShapeType.SHAPE_HULL: DereferenceHull(shape, shapeCallback); break; - case PhysicsShapeType.SHAPE_MESH: + case BSPhysicsShapeType.SHAPE_MESH: DereferenceMesh(shape, shapeCallback); break; - case PhysicsShapeType.SHAPE_COMPOUND: + case BSPhysicsShapeType.SHAPE_COMPOUND: DereferenceCompound(shape, shapeCallback); break; - case PhysicsShapeType.SHAPE_UNKNOWN: + case BSPhysicsShapeType.SHAPE_UNKNOWN: break; default: break; @@ -352,28 +352,28 @@ public sealed class BSShapeCollection : IDisposable BulletShape shapeInfo = new BulletShape(cShape); if (TryGetMeshByPtr(cShape, out meshDesc)) { - shapeInfo.type = PhysicsShapeType.SHAPE_MESH; + shapeInfo.type = BSPhysicsShapeType.SHAPE_MESH; shapeInfo.shapeKey = meshDesc.shapeKey; } else { if (TryGetHullByPtr(cShape, out hullDesc)) { - shapeInfo.type = PhysicsShapeType.SHAPE_HULL; + shapeInfo.type = BSPhysicsShapeType.SHAPE_HULL; shapeInfo.shapeKey = hullDesc.shapeKey; } else { if (BulletSimAPI.IsCompound2(cShape)) { - shapeInfo.type = PhysicsShapeType.SHAPE_COMPOUND; + shapeInfo.type = BSPhysicsShapeType.SHAPE_COMPOUND; } else { if (BulletSimAPI.IsNativeShape2(cShape)) { shapeInfo.isNativeShape = true; - shapeInfo.type = PhysicsShapeType.SHAPE_BOX; // (technically, type doesn't matter) + shapeInfo.type = BSPhysicsShapeType.SHAPE_BOX; // (technically, type doesn't matter) } } } @@ -381,7 +381,7 @@ public sealed class BSShapeCollection : IDisposable DetailLog("{0},BSShapeCollection.DereferenceAnonCollisionShape,shape={1}", BSScene.DetailLogZero, shapeInfo); - if (shapeInfo.type != PhysicsShapeType.SHAPE_UNKNOWN) + if (shapeInfo.type != BSPhysicsShapeType.SHAPE_UNKNOWN) { DereferenceShape(shapeInfo, true, null); } @@ -405,10 +405,10 @@ public sealed class BSShapeCollection : IDisposable bool ret = false; bool haveShape = false; - if (!haveShape && prim.PreferredPhysicalShape == PhysicsShapeType.SHAPE_CAPSULE) + if (!haveShape && prim.PreferredPhysicalShape == BSPhysicsShapeType.SHAPE_CAPSULE) { // an avatar capsule is close to a native shape (it is not shared) - ret = GetReferenceToNativeShape(prim, PhysicsShapeType.SHAPE_CAPSULE, + ret = GetReferenceToNativeShape(prim, BSPhysicsShapeType.SHAPE_CAPSULE, FixedShapeKey.KEY_CAPSULE, shapeCallback); DetailLog("{0},BSShapeCollection.CreateGeom,avatarCapsule,shape={1}", prim.LocalID, prim.PhysShape); ret = true; @@ -417,7 +417,7 @@ public sealed class BSShapeCollection : IDisposable // 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 already been created. - if (!haveShape && prim.PreferredPhysicalShape == PhysicsShapeType.SHAPE_COMPOUND) + if (!haveShape && prim.PreferredPhysicalShape == BSPhysicsShapeType.SHAPE_COMPOUND) { ret = GetReferenceToCompoundShape(prim, shapeCallback); DetailLog("{0},BSShapeCollection.CreateGeom,compoundShape,shape={1}", prim.LocalID, prim.PhysShape); @@ -460,10 +460,10 @@ public sealed class BSShapeCollection : IDisposable haveShape = true; if (forceRebuild || prim.Scale != prim.Size - || prim.PhysShape.type != PhysicsShapeType.SHAPE_SPHERE + || prim.PhysShape.type != BSPhysicsShapeType.SHAPE_SPHERE ) { - ret = GetReferenceToNativeShape(prim, PhysicsShapeType.SHAPE_SPHERE, + ret = GetReferenceToNativeShape(prim, BSPhysicsShapeType.SHAPE_SPHERE, FixedShapeKey.KEY_SPHERE, shapeCallback); DetailLog("{0},BSShapeCollection.CreateGeom,sphere,force={1},shape={2}", prim.LocalID, forceRebuild, prim.PhysShape); @@ -474,10 +474,10 @@ public sealed class BSShapeCollection : IDisposable haveShape = true; if (forceRebuild || prim.Scale != prim.Size - || prim.PhysShape.type != PhysicsShapeType.SHAPE_BOX + || prim.PhysShape.type != BSPhysicsShapeType.SHAPE_BOX ) { - ret = GetReferenceToNativeShape( prim, PhysicsShapeType.SHAPE_BOX, + ret = GetReferenceToNativeShape( prim, BSPhysicsShapeType.SHAPE_BOX, FixedShapeKey.KEY_BOX, shapeCallback); DetailLog("{0},BSShapeCollection.CreateGeom,box,force={1},shape={2}", prim.LocalID, forceRebuild, prim.PhysShape); @@ -519,7 +519,7 @@ public sealed class BSShapeCollection : IDisposable // 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, - PhysicsShapeType shapeType, FixedShapeKey shapeKey, + BSPhysicsShapeType shapeType, FixedShapeKey shapeKey, ShapeDestructionCallback shapeCallback) { // release any previous shape @@ -535,7 +535,7 @@ public sealed class BSShapeCollection : IDisposable return true; } - private BulletShape BuildPhysicalNativeShape(BSPhysObject prim, PhysicsShapeType shapeType, + private BulletShape BuildPhysicalNativeShape(BSPhysObject prim, BSPhysicsShapeType shapeType, FixedShapeKey shapeKey) { BulletShape newShape; @@ -548,7 +548,7 @@ public sealed class BSShapeCollection : IDisposable nativeShapeData.MeshKey = (ulong)shapeKey; nativeShapeData.HullKey = (ulong)shapeKey; - if (shapeType == PhysicsShapeType.SHAPE_CAPSULE) + if (shapeType == BSPhysicsShapeType.SHAPE_CAPSULE) { // The proper scale has been calculated in the prim. newShape = new BulletShape( @@ -586,7 +586,7 @@ public sealed class BSShapeCollection : IDisposable 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 == PhysicsShapeType.SHAPE_MESH) + if (newMeshKey == prim.PhysShape.shapeKey && prim.PhysShape.type == BSPhysicsShapeType.SHAPE_MESH) return false; DetailLog("{0},BSShapeCollection.GetReferenceToMesh,create,oldKey={1},newKey={2}", @@ -644,7 +644,7 @@ public sealed class BSShapeCollection : IDisposable indices.GetLength(0), indices, vertices.Count, verticesAsFloats); } } - BulletShape newShape = new BulletShape(meshPtr, PhysicsShapeType.SHAPE_MESH); + BulletShape newShape = new BulletShape(meshPtr, BSPhysicsShapeType.SHAPE_MESH); newShape.shapeKey = newMeshKey; return newShape; @@ -660,7 +660,7 @@ public sealed class BSShapeCollection : IDisposable 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 == PhysicsShapeType.SHAPE_HULL) + if (newHullKey == prim.PhysShape.shapeKey && prim.PhysShape.type == BSPhysicsShapeType.SHAPE_HULL) return false; DetailLog("{0},BSShapeCollection.GetReferenceToHull,create,oldKey={1},newKey={2}", @@ -781,7 +781,7 @@ public sealed class BSShapeCollection : IDisposable } } - BulletShape newShape = new BulletShape(hullPtr, PhysicsShapeType.SHAPE_HULL); + BulletShape newShape = new BulletShape(hullPtr, BSPhysicsShapeType.SHAPE_HULL); newShape.shapeKey = newHullKey; return newShape; // 'true' means a new shape has been added to this prim @@ -804,7 +804,7 @@ public sealed class BSShapeCollection : IDisposable // DereferenceShape(prim.PhysShape, true, shapeCallback); BulletShape cShape = new BulletShape( - BulletSimAPI.CreateCompoundShape2(PhysicsScene.World.ptr, false), PhysicsShapeType.SHAPE_COMPOUND); + BulletSimAPI.CreateCompoundShape2(PhysicsScene.World.ptr, false), BSPhysicsShapeType.SHAPE_COMPOUND); // Create the shape for the root prim and add it to the compound shape. Cannot be a native shape. CreateGeomMeshOrHull(prim, shapeCallback); @@ -895,7 +895,7 @@ public sealed class BSShapeCollection : IDisposable // While we figure out the real problem, stick a simple native shape on the object. BulletShape fillinShape = - BuildPhysicalNativeShape(prim, PhysicsShapeType.SHAPE_BOX, FixedShapeKey.KEY_BOX); + BuildPhysicalNativeShape(prim, BSPhysicsShapeType.SHAPE_BOX, FixedShapeKey.KEY_BOX); return fillinShape; } diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs index f2e62d9..96cd55e 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSShapes.cs @@ -35,7 +35,7 @@ namespace OpenSim.Region.Physics.BulletSPlugin public abstract class BSShape { public IntPtr ptr { get; set; } - public PhysicsShapeType type { get; set; } + public BSPhysicsShapeType type { get; set; } public System.UInt64 key { get; set; } public int referenceCount { get; set; } public DateTime lastReferenced { get; set; } @@ -43,7 +43,7 @@ public abstract class BSShape public BSShape() { ptr = IntPtr.Zero; - type = PhysicsShapeType.SHAPE_UNKNOWN; + type = BSPhysicsShapeType.SHAPE_UNKNOWN; key = 0; referenceCount = 0; lastReferenced = DateTime.Now; @@ -54,17 +54,17 @@ public abstract class BSShape { BSShape ret = null; - if (prim.PreferredPhysicalShape == PhysicsShapeType.SHAPE_CAPSULE) + if (prim.PreferredPhysicalShape == BSPhysicsShapeType.SHAPE_CAPSULE) { // an avatar capsule is close to a native shape (it is not shared) - ret = BSShapeNative.GetReference(physicsScene, prim, PhysicsShapeType.SHAPE_CAPSULE, + 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 already been created. - if (ret == null && prim.PreferredPhysicalShape == PhysicsShapeType.SHAPE_COMPOUND) + 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); @@ -123,14 +123,14 @@ public class BSShapeNative : BSShape { } public static BSShape GetReference(BSScene physicsScene, BSPhysObject prim, - PhysicsShapeType shapeType, FixedShapeKey shapeKey) + BSPhysicsShapeType shapeType, FixedShapeKey shapeKey) { // Native shapes are not shared and are always built anew. return new BSShapeNative(physicsScene, prim, shapeType, shapeKey); } private BSShapeNative(BSScene physicsScene, BSPhysObject prim, - PhysicsShapeType shapeType, FixedShapeKey shapeKey) + BSPhysicsShapeType shapeType, FixedShapeKey shapeKey) { ShapeData nativeShapeData = new ShapeData(); nativeShapeData.Type = shapeType; @@ -141,7 +141,7 @@ public class BSShapeNative : BSShape nativeShapeData.HullKey = (ulong)shapeKey; - if (shapeType == PhysicsShapeType.SHAPE_CAPSULE) + if (shapeType == BSPhysicsShapeType.SHAPE_CAPSULE) { ptr = BulletSimAPI.BuildCapsuleShape2(physicsScene.World.ptr, 1f, 1f, prim.Scale); physicsScene.DetailLog("{0},BSShapeCollection.BuiletPhysicalNativeShape,capsule,scale={1}", prim.LocalID, prim.Scale); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainHeightmap.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainHeightmap.cs index 8fc36d1..3ca756c 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainHeightmap.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainHeightmap.cs @@ -97,7 +97,7 @@ public sealed class BSTerrainHeightmap : BSTerrainPhys // Create the terrain shape from the mapInfo m_mapInfo.terrainShape = new BulletShape(BulletSimAPI.CreateTerrainShape2(m_mapInfo.Ptr), - PhysicsShapeType.SHAPE_TERRAIN); + BSPhysicsShapeType.SHAPE_TERRAIN); // The terrain object initial position is at the center of the object Vector3 centerPos; diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs index 71fca33..23fcfd3 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainManager.cs @@ -130,7 +130,7 @@ public sealed class BSTerrainManager // The ground plane is here to catch things that are trying to drop to negative infinity BulletShape groundPlaneShape = new BulletShape( BulletSimAPI.CreateGroundPlaneShape2(BSScene.GROUNDPLANE_ID, 1f, TERRAIN_COLLISION_MARGIN), - PhysicsShapeType.SHAPE_GROUNDPLANE); + BSPhysicsShapeType.SHAPE_GROUNDPLANE); m_groundPlane = new BulletBody(BSScene.GROUNDPLANE_ID, BulletSimAPI.CreateBodyWithDefaultMotionState2(groundPlaneShape.ptr, BSScene.GROUNDPLANE_ID, Vector3.Zero, Quaternion.Identity)); diff --git a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainMesh.cs b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainMesh.cs index 3279b6f..dca7150 100755 --- a/OpenSim/Region/Physics/BulletSPlugin/BSTerrainMesh.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BSTerrainMesh.cs @@ -91,7 +91,7 @@ public sealed class BSTerrainMesh : BSTerrainPhys m_terrainShape = new BulletShape(BulletSimAPI.CreateMeshShape2(PhysicsScene.World.ptr, indicesCount, indices, verticesCount, vertices), - PhysicsShapeType.SHAPE_MESH); + BSPhysicsShapeType.SHAPE_MESH); if (m_terrainShape.ptr == IntPtr.Zero) { // DISASTER!! diff --git a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs index 4647c2d..e60a760 100644 --- a/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs +++ b/OpenSim/Region/Physics/BulletSPlugin/BulletSimAPI.cs @@ -88,11 +88,11 @@ public struct BulletShape public BulletShape(IntPtr xx) { ptr = xx; - type=PhysicsShapeType.SHAPE_UNKNOWN; + type=BSPhysicsShapeType.SHAPE_UNKNOWN; shapeKey = (System.UInt64)FixedShapeKey.KEY_NONE; isNativeShape = false; } - public BulletShape(IntPtr xx, PhysicsShapeType typ) + public BulletShape(IntPtr xx, BSPhysicsShapeType typ) { ptr = xx; type = typ; @@ -100,7 +100,7 @@ public struct BulletShape isNativeShape = false; } public IntPtr ptr; - public PhysicsShapeType type; + public BSPhysicsShapeType type; public System.UInt64 shapeKey; public bool isNativeShape; public override string ToString() @@ -178,7 +178,7 @@ public struct ConvexHull int VertexCount; Vector3[] Vertices; } -public enum PhysicsShapeType +public enum BSPhysicsShapeType { SHAPE_UNKNOWN = 0, SHAPE_CAPSULE = 1, @@ -210,7 +210,7 @@ public enum FixedShapeKey : ulong public struct ShapeData { public uint ID; - public PhysicsShapeType Type; + public BSPhysicsShapeType Type; public Vector3 Position; public Quaternion Rotation; public Vector3 Velocity; -- cgit v1.1 From 62244b5ea5d9fcbe24e35906517fb02022cdcc7c Mon Sep 17 00:00:00 2001 From: UbitUmarov Date: Sat, 24 Nov 2012 22:46:24 +0000 Subject: don't zero constant force and torque in selection --- OpenSim/Region/Physics/UbitOdePlugin/ODEPrim.cs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/UbitOdePlugin/ODEPrim.cs b/OpenSim/Region/Physics/UbitOdePlugin/ODEPrim.cs index dc247a9..7dddab6 100644 --- a/OpenSim/Region/Physics/UbitOdePlugin/ODEPrim.cs +++ b/OpenSim/Region/Physics/UbitOdePlugin/ODEPrim.cs @@ -84,7 +84,7 @@ namespace OpenSim.Region.Physics.OdePlugin private Vector3 _position; private Vector3 _velocity; - private Vector3 _torque; + private Vector3 m_torque; private Vector3 m_lastVelocity; private Vector3 m_lastposition; private Vector3 m_rotationalVelocity; @@ -597,7 +597,7 @@ namespace OpenSim.Region.Physics.OdePlugin if (!IsPhysical || Body == IntPtr.Zero) return Vector3.Zero; - return _torque; + return m_torque; } set @@ -2425,10 +2425,10 @@ namespace OpenSim.Region.Physics.OdePlugin { if (!childPrim) { - m_force = Vector3.Zero; +// m_force = Vector3.Zero; m_forceacc = Vector3.Zero; m_angularForceacc = Vector3.Zero; - _torque = Vector3.Zero; +// m_torque = Vector3.Zero; _velocity = Vector3.Zero; _acceleration = Vector3.Zero; m_rotationalVelocity = Vector3.Zero; @@ -2968,7 +2968,7 @@ namespace OpenSim.Region.Physics.OdePlugin d.BodyEnable(Body); } - _torque = newtorque; + m_torque = newtorque; } } @@ -3364,7 +3364,7 @@ namespace OpenSim.Region.Physics.OdePlugin Vector3 trq; - trq = _torque; + trq = m_torque; trq += m_angularForceacc; m_angularForceacc = Vector3.Zero; if (trq.X != 0 || trq.Y != 0 || trq.Z != 0) -- cgit v1.1 From c50fda8bf56b1935805164e6803ab82532ea5418 Mon Sep 17 00:00:00 2001 From: UbitUmarov Date: Sat, 1 Dec 2012 22:58:52 +0000 Subject: adjust avatar standing Z position --- OpenSim/Region/Physics/UbitOdePlugin/ODECharacter.cs | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/UbitOdePlugin/ODECharacter.cs b/OpenSim/Region/Physics/UbitOdePlugin/ODECharacter.cs index f5bf05d..94ed663 100644 --- a/OpenSim/Region/Physics/UbitOdePlugin/ODECharacter.cs +++ b/OpenSim/Region/Physics/UbitOdePlugin/ODECharacter.cs @@ -85,8 +85,12 @@ namespace OpenSim.Region.Physics.OdePlugin public float PID_D = 800.0f; public float PID_P = 900.0f; //private static float POSTURE_SERVO = 10000.0f; + public float CAPSULE_RADIUS = 0.37f; public float CAPSULE_LENGTH = 2.140599f; + + const float CAP_OFFSET = -.2f; // compensation of SL size offset plus spheric collision shape bottom + public float walkDivisor = 1.3f; public float runDivisor = 0.8f; private bool flying = false; @@ -139,6 +143,8 @@ namespace OpenSim.Region.Physics.OdePlugin float mu; + + public OdeCharacter(String avName, OdeScene parent_scene, Vector3 pos, Vector3 size, float pid_d, float pid_p, float capsule_radius, float density, float walk_divisor, float rundivisor) { m_uuid = UUID.Random(); @@ -177,7 +183,7 @@ namespace OpenSim.Region.Physics.OdePlugin walkDivisor = walk_divisor; runDivisor = rundivisor; - CAPSULE_LENGTH = size.Z * 1.15f - CAPSULE_RADIUS * 2.0f; + CAPSULE_LENGTH = size.Z - CAPSULE_RADIUS + CAP_OFFSET; //m_log.Info("[SIZE]: " + CAPSULE_LENGTH.ToString()); m_isPhysical = false; // current status: no ODE information exists @@ -422,7 +428,8 @@ namespace OpenSim.Region.Physics.OdePlugin { get { float d = CAPSULE_RADIUS * 2; - return new Vector3(d, d, (CAPSULE_LENGTH +d)/1.15f); } + return new Vector3(d, d, (CAPSULE_LENGTH + CAPSULE_RADIUS - CAP_OFFSET)); + } set { if (value.IsFinite()) @@ -837,8 +844,7 @@ namespace OpenSim.Region.Physics.OdePlugin // colide with land d.AABB aabb; d.GeomGetAABB(Shell, out aabb); - float chrminZ = aabb.MinZ; - + float chrminZ = aabb.MinZ - 0.04f; // move up a bit Vector3 posch = localpos; float ftmp; @@ -1224,7 +1230,7 @@ namespace OpenSim.Region.Physics.OdePlugin { float caplen = Size.Z; - caplen = caplen * 1.15f - CAPSULE_RADIUS * 2.0f; + caplen = caplen - CAPSULE_RADIUS + CAP_OFFSET; if (caplen != CAPSULE_LENGTH) { -- cgit v1.1 From aa00308b10228cd2c5a04a41fc5b3da8009cd0fd Mon Sep 17 00:00:00 2001 From: UbitUmarov Date: Sun, 2 Dec 2012 03:58:40 +0000 Subject: *TEST* reduce all mesh vertices resolution to 1e-5. This reduces number of unique vertices only originated by math errors in PrimMesher --- OpenSim/Region/Physics/UbitMeshing/Mesh.cs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/UbitMeshing/Mesh.cs b/OpenSim/Region/Physics/UbitMeshing/Mesh.cs index 1e9b8bc..0476b28 100644 --- a/OpenSim/Region/Physics/UbitMeshing/Mesh.cs +++ b/OpenSim/Region/Physics/UbitMeshing/Mesh.cs @@ -205,12 +205,28 @@ namespace OpenSim.Region.Physics.Meshing } + private float fRound(float f) + { + int i = (int)(1e5f * f +0.5f); + return ((float)i * 1e-5f); + } public void Add(Triangle triangle) { if (m_indicesPtr != IntPtr.Zero || m_verticesPtr != IntPtr.Zero) throw new NotSupportedException("Attempt to Add to a pinned Mesh"); + // round down + triangle.v1.X = fRound(triangle.v1.X); + triangle.v1.Y = fRound(triangle.v1.Y); + triangle.v1.Z = fRound(triangle.v1.Z); + triangle.v2.X = fRound(triangle.v2.X); + triangle.v2.Y = fRound(triangle.v2.Y); + triangle.v2.Z = fRound(triangle.v2.Z); + triangle.v3.X = fRound(triangle.v3.X); + triangle.v3.Y = fRound(triangle.v3.Y); + triangle.v3.Z = fRound(triangle.v3.Z); + if ((triangle.v1.X == triangle.v2.X && triangle.v1.Y == triangle.v2.Y && triangle.v1.Z == triangle.v2.Z) || (triangle.v1.X == triangle.v3.X && triangle.v1.Y == triangle.v3.Y && triangle.v1.Z == triangle.v3.Z) || (triangle.v2.X == triangle.v3.X && triangle.v2.Y == triangle.v3.Y && triangle.v2.Z == triangle.v3.Z) -- cgit v1.1 From f21d9908200b4bb21f8002e9c87968767ab77bdb Mon Sep 17 00:00:00 2001 From: UbitUmarov Date: Sun, 2 Dec 2012 05:02:33 +0000 Subject: fix vertex rounding direction --- OpenSim/Region/Physics/UbitMeshing/Mesh.cs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/UbitMeshing/Mesh.cs b/OpenSim/Region/Physics/UbitMeshing/Mesh.cs index 0476b28..b67422f 100644 --- a/OpenSim/Region/Physics/UbitMeshing/Mesh.cs +++ b/OpenSim/Region/Physics/UbitMeshing/Mesh.cs @@ -207,7 +207,14 @@ namespace OpenSim.Region.Physics.Meshing private float fRound(float f) { - int i = (int)(1e5f * f +0.5f); + int i; + if (f == 0f) + return f; + else if (f > 0f) + i = (int)(1e5f * f + 0.5f); + else + i = (int)(1e5f * f - 0.5f); + return ((float)i * 1e-5f); } -- cgit v1.1 From 8aa5fdb6a3f1e4b349757df5d9fcc06ab8dfdb64 Mon Sep 17 00:00:00 2001 From: UbitUmarov Date: Mon, 3 Dec 2012 17:05:05 +0000 Subject: *TEST* diferent avatar collider --- .../Region/Physics/UbitOdePlugin/ODECharacter.cs | 369 ++++++++++++++++----- OpenSim/Region/Physics/UbitOdePlugin/OdeScene.cs | 69 ++-- 2 files changed, 337 insertions(+), 101 deletions(-) (limited to 'OpenSim/Region/Physics') diff --git a/OpenSim/Region/Physics/UbitOdePlugin/ODECharacter.cs b/OpenSim/Region/Physics/UbitOdePlugin/ODECharacter.cs index 94ed663..3d5be3e 100644 --- a/OpenSim/Region/Physics/UbitOdePlugin/ODECharacter.cs +++ b/OpenSim/Region/Physics/UbitOdePlugin/ODECharacter.cs @@ -79,6 +79,8 @@ namespace OpenSim.Region.Physics.OdePlugin private Vector3 _target_velocity; private Vector3 _acceleration; private Vector3 m_rotationalVelocity; + private Vector3 m_size; + private Quaternion m_orientation; private float m_mass = 80f; public float m_density = 60f; private bool m_pidControllerActive = true; @@ -86,10 +88,17 @@ namespace OpenSim.Region.Physics.OdePlugin public float PID_P = 900.0f; //private static float POSTURE_SERVO = 10000.0f; - public float CAPSULE_RADIUS = 0.37f; - public float CAPSULE_LENGTH = 2.140599f; - const float CAP_OFFSET = -.2f; // compensation of SL size offset plus spheric collision shape bottom + private float m_invElipSizeX; + private float m_invElipSizeY; + + private float feetOff = 0; + private float feetSZ = 0.5f; + const float feetScale = 0.9f; + const float invFeetScale = 1.0f / 0.9f; + const float sizeZAdjust = 0.15f; + private float boneOff = 0; + public float walkDivisor = 1.3f; public float runDivisor = 0.8f; @@ -127,10 +136,16 @@ namespace OpenSim.Region.Physics.OdePlugin // we do land collisions not ode | CollisionCategories.Land); public IntPtr Body = IntPtr.Zero; private OdeScene _parent_scene; - public IntPtr Shell = IntPtr.Zero; + public IntPtr topbox = IntPtr.Zero; + public IntPtr midbox = IntPtr.Zero; + public IntPtr feetbox = IntPtr.Zero; + public IntPtr bonebox = IntPtr.Zero; + public IntPtr Amotor = IntPtr.Zero; + public d.Mass ShellMass; -// public bool collidelock = false; + + public int m_eventsubscription = 0; private int m_cureventsubscription = 0; @@ -145,7 +160,7 @@ namespace OpenSim.Region.Physics.OdePlugin - public OdeCharacter(String avName, OdeScene parent_scene, Vector3 pos, Vector3 size, float pid_d, float pid_p, float capsule_radius, float density, float walk_divisor, float rundivisor) + public OdeCharacter(String avName, OdeScene parent_scene, Vector3 pos, Vector3 pSize, float pid_d, float pid_p, float density, float walk_divisor, float rundivisor) { m_uuid = UUID.Random(); @@ -171,9 +186,20 @@ namespace OpenSim.Region.Physics.OdePlugin PID_D = pid_d; PID_P = pid_p; - CAPSULE_RADIUS = capsule_radius; + + m_size.X = pSize.X; + m_size.Y = pSize.Y; + m_size.Z = pSize.Z; + + if(m_size.X <0.01f) + m_size.X = 0.01f; + if(m_size.Y <0.01f) + m_size.Y = 0.01f; + if(m_size.Z <0.01f) + m_size.Z = 0.01f; + + m_orientation = Quaternion.Identity; m_density = density; - m_mass = 80f; // sure we have a default // force lower density for testing m_density = 3.0f; @@ -183,8 +209,7 @@ namespace OpenSim.Region.Physics.OdePlugin walkDivisor = walk_divisor; runDivisor = rundivisor; - CAPSULE_LENGTH = size.Z - CAPSULE_RADIUS + CAP_OFFSET; - //m_log.Info("[SIZE]: " + CAPSULE_LENGTH.ToString()); + m_mass = m_density * m_size.X * m_size.Y * m_size.Z; ; // sure we have a default m_isPhysical = false; // current status: no ODE information exists @@ -426,14 +451,21 @@ namespace OpenSim.Region.Physics.OdePlugin /// public override Vector3 Size { - get { - float d = CAPSULE_RADIUS * 2; - return new Vector3(d, d, (CAPSULE_LENGTH + CAPSULE_RADIUS - CAP_OFFSET)); + get + { + return m_size; } set { if (value.IsFinite()) { + if(value.X <0.01f) + value.X = 0.01f; + if(value.Y <0.01f) + value.Y = 0.01f; + if(value.Z <0.01f) + value.Z = 0.01f; + AddChange(changes.Size, value); } else @@ -459,8 +491,7 @@ namespace OpenSim.Region.Physics.OdePlugin { get { - float AVvolume = (float)(Math.PI * CAPSULE_RADIUS * CAPSULE_RADIUS * (1.3333333333f * CAPSULE_RADIUS + CAPSULE_LENGTH)); - return m_density * AVvolume; + return m_density * m_size.X * m_size.Y * m_size.Z; } } public override void link(PhysicsActor obj) @@ -578,9 +609,14 @@ namespace OpenSim.Region.Physics.OdePlugin public override Quaternion Orientation { - get { return Quaternion.Identity; } + get { return m_orientation; } set { + // fakeori = value; + // givefakeori++; + + value.Normalize(); + AddChange(changes.Orientation, value); } } @@ -632,32 +668,65 @@ namespace OpenSim.Region.Physics.OdePlugin AddChange(changes.Momentum, momentum); } - - // WARNING: This MUST NOT be called outside of ProcessTaints, else we can have unsynchronized access - // to ODE internals. ProcessTaints is called from within thread-locked Simulate(), so it is the only - // place that is safe to call this routine AvatarGeomAndBodyCreation. private void AvatarGeomAndBodyCreation(float npositionX, float npositionY, float npositionZ) { + // sizes one day should came from visual parameters + float sz = m_size.Z + sizeZAdjust; + + m_invElipSizeX = 1.0f / m_size.X; + m_invElipSizeY = 1.0f / m_size.Y; + + float topsx = m_size.X; + float midsx = m_size.X; + float feetsx = m_size.X * feetScale; + float bonesx = feetsx * 0.2f; + + float topsy = m_size.Y * 0.5f; + float midsy = m_size.Y; + float feetsy = m_size.Y * feetScale; + float bonesy = feetsy * 0.2f; + + float topsz = sz * 0.15f; + float feetsz = sz * 0.3f; + if (feetsz > 0.6f) + feetsz = 0.6f; + + float midsz = sz - topsz - feetsz; + float bonesz = sz; + + float bot = -sz * 0.5f; + + boneOff = bot + 0.3f; + + float feetz = bot + feetsz * 0.5f; + bot += feetsz; + + feetOff = bot; + feetSZ = feetsz; + + float midz = bot + midsz * 0.5f; + bot += midsz; + float topz = bot + topsz * 0.5f; + _parent_scene.waitForSpaceUnlock(_parent_scene.ActiveSpace); - if (CAPSULE_LENGTH <= 0) - { - m_log.Warn("[PHYSICS]: The capsule size you specified in opensim.ini is invalid! Setting it to the smallest possible size!"); - CAPSULE_LENGTH = 0.01f; - } + feetbox = d.CreateBox(_parent_scene.ActiveSpace, feetsx, feetsy, feetsz); + d.GeomSetCategoryBits(feetbox, (uint)m_collisionCategories); + d.GeomSetCollideBits(feetbox, (uint)m_collisionFlags); - if (CAPSULE_RADIUS <= 0) - { - m_log.Warn("[PHYSICS]: The capsule size you specified in opensim.ini is invalid! Setting it to the smallest possible size!"); - CAPSULE_RADIUS = 0.01f; + midbox = d.CreateBox(_parent_scene.ActiveSpace, midsx, midsy, midsz); + d.GeomSetCategoryBits(midbox, (uint)m_collisionCategories); + d.GeomSetCollideBits(midbox, (uint)m_collisionFlags); - } - Shell = d.CreateCapsule(_parent_scene.ActiveSpace, CAPSULE_RADIUS, CAPSULE_LENGTH); + topbox = d.CreateBox(_parent_scene.ActiveSpace, topsx, topsy, topsz); + d.GeomSetCategoryBits(topbox, (uint)m_collisionCategories); + d.GeomSetCollideBits(topbox, (uint)m_collisionFlags); - d.GeomSetCategoryBits(Shell, (uint)m_collisionCategories); - d.GeomSetCollideBits(Shell, (uint)m_collisionFlags); + bonebox = d.CreateBox(_parent_scene.ActiveSpace, bonesx, bonesy, bonesz); + d.GeomSetCategoryBits(bonebox, (uint)m_collisionCategories); + d.GeomSetCollideBits(bonebox, (uint)m_collisionFlags); - d.MassSetCapsule(out ShellMass, m_density, 3, CAPSULE_RADIUS, CAPSULE_LENGTH); + d.MassSetBox(out ShellMass, m_density, m_size.X , m_size.Y, m_size.Z); m_mass = ShellMass.mass; // update mass @@ -688,7 +757,14 @@ namespace OpenSim.Region.Physics.OdePlugin _position.Z = npositionZ; d.BodySetMass(Body, ref ShellMass); - d.GeomSetBody(Shell, Body); + d.GeomSetBody(feetbox, Body); + d.GeomSetBody(midbox, Body); + d.GeomSetBody(topbox, Body); + d.GeomSetBody(bonebox, Body); + + d.GeomSetOffsetPosition(feetbox, 0, 0, feetz); + d.GeomSetOffsetPosition(midbox, 0, 0, midz); + d.GeomSetOffsetPosition(topbox, 0, 0, topz); // The purpose of the AMotor here is to keep the avatar's physical // surrogate from rotating while moving @@ -748,15 +824,152 @@ namespace OpenSim.Region.Physics.OdePlugin Body = IntPtr.Zero; } - //kill the Geometry - if (Shell != IntPtr.Zero) + //kill the Geoms + if (topbox != IntPtr.Zero) { -// _parent_scene.geom_name_map.Remove(Shell); - _parent_scene.actor_name_map.Remove(Shell); + _parent_scene.actor_name_map.Remove(topbox); _parent_scene.waitForSpaceUnlock(_parent_scene.ActiveSpace); - d.GeomDestroy(Shell); - Shell = IntPtr.Zero; + d.GeomDestroy(topbox); + topbox = IntPtr.Zero; + } + if (midbox != IntPtr.Zero) + { + _parent_scene.actor_name_map.Remove(midbox); + _parent_scene.waitForSpaceUnlock(_parent_scene.ActiveSpace); + d.GeomDestroy(midbox); + midbox = IntPtr.Zero; + } + if (feetbox != IntPtr.Zero) + { + _parent_scene.actor_name_map.Remove(feetbox); + _parent_scene.waitForSpaceUnlock(_parent_scene.ActiveSpace); + d.GeomDestroy(feetbox); + feetbox = IntPtr.Zero; + } + + if (bonebox != IntPtr.Zero) + { + _parent_scene.actor_name_map.Remove(bonebox); + _parent_scene.waitForSpaceUnlock(_parent_scene.ActiveSpace); + d.GeomDestroy(bonebox); + bonebox = IntPtr.Zero; + } + + } + + public bool Collide(IntPtr me, bool reverse, ref d.ContactGeom contact) + { + + if (me == bonebox) // inner bone + { + if (contact.pos.Z - _position.Z < boneOff) + IsColliding = true; + return true; + } + + if (me == topbox) // keep a box head + return true; + + // rotate elipsoide assuming only rotation around Z + float ca = m_orientation.W * m_orientation.W - m_orientation.Z * m_orientation.Z; + float sa = 2 * m_orientation.W * m_orientation.Z; + + float isx; + float isy; + + if (me == feetbox) // feet have narrow bounds + { + + isx = m_invElipSizeX * invFeetScale; + isy = m_invElipSizeY * invFeetScale; + } + else + { + isx = m_invElipSizeX; + isy = m_invElipSizeY; + } + + float a = isx * ca - isy * sa; + float b = isx * sa + isy * ca; + + float offx = contact.pos.X - _position.X; + float er = offx * a; + er *= er; + + float offy = contact.pos.Y - _position.Y; + float ty = offy * b; + er += ty * ty; + + if (me == midbox) + { + if (er > 4.0f) // no collision + return false; + if (er < 0.2f) + return true; + + float t = offx * offx + offy * offy; + t = (float)Math.Sqrt(t); + t = 1 / t; + offx *= t; + offy *= t; + + if (reverse) + { + contact.normal.X = offx; + contact.normal.Y = offy; + } + else + { + contact.normal.X = -offx; + contact.normal.Y = -offy; + } + + contact.normal.Z = 0; + return true; + } + + else if (me == feetbox) + { + float c = feetSZ * 2; + float h = contact.pos.Z - _position.Z; + float offz = h - feetOff; // distance from top of feetbox + + float tz = offz / c; + er += tz * tz; + + if (er > 4.0f) // no collision + return false; + + if (er > 0.2f) + { + float t = offx * offx + offy * offy + offz * offz; + t = (float)Math.Sqrt(t); + t = 1 / t; + offx *= t; + offy *= t; + offz *= t; + + if (reverse) + { + contact.normal.X = offx; + contact.normal.Y = offy; + contact.normal.Z = offz; + } + else + { + contact.normal.X = -offx; + contact.normal.Y = -offy; + contact.normal.Z = -offz; + } + } + + if(h < boneOff) + IsColliding = true; } + else + return false; + + return true; } /// @@ -776,10 +989,10 @@ namespace OpenSim.Region.Physics.OdePlugin // so force it back to identity d.Quaternion qtmp; - qtmp.W = 1; - qtmp.X = 0; - qtmp.Y = 0; - qtmp.Z = 0; + qtmp.W = m_orientation.W; + qtmp.X = m_orientation.X; + qtmp.Y = m_orientation.Y; + qtmp.Z = m_orientation.Z; d.BodySetQuaternion(Body, ref qtmp); if (m_pidControllerActive == false) @@ -843,7 +1056,7 @@ namespace OpenSim.Region.Physics.OdePlugin //****************************************** // colide with land d.AABB aabb; - d.GeomGetAABB(Shell, out aabb); + d.GeomGetAABB(feetbox, out aabb); float chrminZ = aabb.MinZ - 0.04f; // move up a bit Vector3 posch = localpos; @@ -1182,20 +1395,14 @@ namespace OpenSim.Region.Physics.OdePlugin { if (NewStatus) { - // Create avatar capsule and related ODE data - if ((Shell != IntPtr.Zero)) - { - // a lost shell ? - m_log.Warn("[PHYSICS]: re-creating the following avatar ODE data, even though it already exists - " - + (Shell != IntPtr.Zero ? "Shell " : "") - + (Body != IntPtr.Zero ? "Body " : "") - + (Amotor != IntPtr.Zero ? "Amotor " : "")); - AvatarGeomAndBodyDestroy(); - } + AvatarGeomAndBodyDestroy(); AvatarGeomAndBodyCreation(_position.X, _position.Y, _position.Z); - _parent_scene.actor_name_map[Shell] = (PhysicsActor)this; + _parent_scene.actor_name_map[topbox] = (PhysicsActor)this; + _parent_scene.actor_name_map[midbox] = (PhysicsActor)this; + _parent_scene.actor_name_map[feetbox] = (PhysicsActor)this; + _parent_scene.actor_name_map[bonebox] = (PhysicsActor)this; _parent_scene.AddCharacter(this); } else @@ -1224,37 +1431,29 @@ namespace OpenSim.Region.Physics.OdePlugin { } - private void changeSize(Vector3 Size) + private void changeSize(Vector3 pSize) { - if (Size.IsFinite()) + if (pSize.IsFinite()) { - float caplen = Size.Z; + // for now only look to Z changes since viewers also don't change X and Y + if (pSize.Z != m_size.Z) + { + AvatarGeomAndBodyDestroy(); - caplen = caplen - CAPSULE_RADIUS + CAP_OFFSET; - if (caplen != CAPSULE_LENGTH) - { - if (Shell != IntPtr.Zero && Body != IntPtr.Zero && Amotor != IntPtr.Zero) - { - AvatarGeomAndBodyDestroy(); + float oldsz = m_size.Z; + m_size = pSize; - float prevCapsule = CAPSULE_LENGTH; - CAPSULE_LENGTH = caplen; - AvatarGeomAndBodyCreation(_position.X, _position.Y, - _position.Z + (CAPSULE_LENGTH - prevCapsule) * 0.5f); + AvatarGeomAndBodyCreation(_position.X, _position.Y, + _position.Z + (m_size.Z - oldsz) * 0.5f); - Velocity = Vector3.Zero; + Velocity = Vector3.Zero; - _parent_scene.actor_name_map[Shell] = (PhysicsActor)this; - } - else - { - m_log.Warn("[PHYSICS]: trying to change capsule size, but the following ODE data is missing - " - + (Shell == IntPtr.Zero ? "Shell " : "") - + (Body == IntPtr.Zero ? "Body " : "") - + (Amotor == IntPtr.Zero ? "Amotor " : "")); - } + _parent_scene.actor_name_map[topbox] = (PhysicsActor)this; + _parent_scene.actor_name_map[midbox] = (PhysicsActor)this; + _parent_scene.actor_name_map[feetbox] = (PhysicsActor)this; + _parent_scene.actor_name_map[bonebox] = (PhysicsActor)this; } m_freemove = false; m_pidControllerActive = true; @@ -1276,6 +1475,14 @@ namespace OpenSim.Region.Physics.OdePlugin private void changeOrientation(Quaternion newOri) { + d.Quaternion myrot = new d.Quaternion(); + myrot.X = newOri.X; + myrot.Y = newOri.Y; + myrot.Z = newOri.Z; + myrot.W = newOri.W; + float t = d.JointGetAMotorAngle(Amotor, 2); + d.BodySetQuaternion(Body,ref myrot); + m_orientation = newOri; } private void changeVelocity(Vector3 newVel) @@ -1365,7 +1572,7 @@ namespace OpenSim.Region.Physics.OdePlugin public bool DoAChange(changes what, object arg) { - if (Shell == IntPtr.Zero && what != changes.Add && what != changes.Remove) + if (topbox == IntPtr.Zero && what != changes.Add && what != changes.Remove) { return false; } diff --git a/OpenSim/Region/Physics/UbitOdePlugin/OdeScene.cs b/OpenSim/Region/Physics/UbitOdePlugin/OdeScene.cs index 54bc29f..003a91c 100644 --- a/OpenSim/Region/Physics/UbitOdePlugin/OdeScene.cs +++ b/OpenSim/Region/Physics/UbitOdePlugin/OdeScene.cs @@ -840,6 +840,8 @@ namespace OpenSim.Region.Physics.OdePlugin { case (int)ActorTypes.Agent: { + dop1foot = true; + AvanormOverride = true; Vector3 tmp = p2.Position - p1.Position; normoverride = p2.Velocity - p1.Velocity; @@ -883,6 +885,10 @@ namespace OpenSim.Region.Physics.OdePlugin switch (p2.PhysicsActorType) { case (int)ActorTypes.Agent: + + + dop2foot = true; + AvanormOverride = true; Vector3 tmp = p2.Position - p1.Position; @@ -1017,6 +1023,7 @@ namespace OpenSim.Region.Physics.OdePlugin IntPtr Joint; int i = 0; + int ncontacts = 0; while(true) { @@ -1031,7 +1038,28 @@ namespace OpenSim.Region.Physics.OdePlugin else { + if(dop1foot) + { + if (!(((OdeCharacter)p1).Collide(g1,false, ref curContact))) + { + if (++i >= count) + break; + else + continue; + } + } + else if(dop2foot) + { + if(!(((OdeCharacter) p2).Collide(g2,true,ref curContact))) + { + if (++i >= count) + break; + else + continue; + } + } +/* if (AvanormOverride) { if (curContact.depth > 0.3f) @@ -1081,34 +1109,31 @@ namespace OpenSim.Region.Physics.OdePlugin { float sz = p2.Size.Z; Vector3 vtmp = p2.Position; - float ppos = curContact.pos.Z - vtmp.Z + (sz - avCapRadius) * 0.5f; + vtmp.Z -= sz * 0.5f; + vtmp.Z += 0.5f; + float ppos = vtmp.Z - curContact.pos.Z; if (ppos > 0f) { if (!p2.Flying) { - d.AABB aabb; - d.GeomGetAABB(g1, out aabb); float tmp = vtmp.Z - sz * .18f; - - if (aabb.MaxZ < tmp) - { - vtmp.X = curContact.pos.X - vtmp.X; - vtmp.Y = curContact.pos.Y - vtmp.Y; - vtmp.Z = -0.2f; - vtmp.Normalize(); - curContact.normal.X = vtmp.X; - curContact.normal.Y = vtmp.Y; - curContact.normal.Z = vtmp.Z; - } + vtmp.X = curContact.pos.X - vtmp.X; + vtmp.Y = curContact.pos.Y - vtmp.Y; + vtmp.Z = curContact.pos.Z - vtmp.Z; + vtmp.Normalize(); + curContact.normal.X = vtmp.X; + curContact.normal.Y = vtmp.Y; + curContact.normal.Z = vtmp.Z; } } - else +// else p2.IsColliding = true; } } } - +*/ + ncontacts++; Joint = CreateContacJoint(ref curContact, mu, bounce, cfm, erpscale, dscale); d.JointAttach(Joint, b1, b2); @@ -1134,7 +1159,8 @@ namespace OpenSim.Region.Physics.OdePlugin } } - collision_accounting_events(p1, p2, maxDepthContact); + if(ncontacts > 0) + collision_accounting_events(p1, p2, maxDepthContact); /* if (notskipedcount > geomContactPointsStartthrottle) @@ -1234,14 +1260,17 @@ namespace OpenSim.Region.Physics.OdePlugin { foreach (OdeCharacter chr in _characters) { - if (chr == null || chr.Shell == IntPtr.Zero || chr.Body == IntPtr.Zero) + if (chr == null || chr.Body == IntPtr.Zero) continue; chr.IsColliding = false; // chr.CollidingGround = false; not done here chr.CollidingObj = false; // do colisions with static space - d.SpaceCollide2(StaticSpace, chr.Shell, IntPtr.Zero, nearCallback); + d.SpaceCollide2(StaticSpace, chr.topbox, IntPtr.Zero, nearCallback); + d.SpaceCollide2(StaticSpace, chr.midbox, IntPtr.Zero, nearCallback); + d.SpaceCollide2(StaticSpace, chr.feetbox, IntPtr.Zero, nearCallback); + d.SpaceCollide2(StaticSpace, chr.bonebox, IntPtr.Zero, nearCallback); // no coll with gnd } } @@ -1334,7 +1363,7 @@ namespace OpenSim.Region.Physics.OdePlugin pos.X = position.X; pos.Y = position.Y; pos.Z = position.Z; - OdeCharacter newAv = new OdeCharacter(avName, this, pos, size, avPIDD, avPIDP, avCapRadius, avDensity, avMovementDivisorWalk, avMovementDivisorRun); + OdeCharacter newAv = new OdeCharacter(avName, this, pos, size, avPIDD, avPIDP, avDensity, avMovementDivisorWalk, avMovementDivisorRun); newAv.Flying = isFlying; newAv.MinimumGroundFlightOffset = minimumGroundFlightOffset; -- cgit v1.1