Ejemplo n.º 1
0
		/// <summary>
		/// Поставит углы, схватит gimbal lock у pitch, но пока так, хоть Yaw верный.
		/// </summary>
		private static Frame3D SetAngles(Frame3D frame, BEPUphysics.MathExtensions.Matrix matrix)
		{
			AIRLab.Mathematics.Matrix m = new AIRLab.Mathematics.Matrix(4, 4); 
			m[0, 0] = matrix.M11;
			m[0, 1] = matrix.M12;
			m[0, 2] = matrix.M13;
			m[0, 3] = 0.0f;
			m[1, 0] = matrix.M21;
			m[1, 1] = matrix.M22;
			m[1, 2] = matrix.M23;
			m[1, 3] = 0.0f;
			m[2, 0] = matrix.M31;
			m[2, 1] = matrix.M32;
			m[2, 2] = matrix.M33;
			m[2, 3] = 0.0f;
			m[3, 0] = frame.X;
			m[3, 1] = frame.Y;
			m[3, 2] = frame.Z;
			m[3, 3] = 1.0f;

			var yaw = Geometry.Atan2(m[1, 0], m[0, 0]);
            var pitch = Geometry.Atan2(-m[2, 0], Geometry.Hypot(m[2, 1], m[2, 2]));
            var roll = Geometry.Atan2(m[2, 1], m[2, 2]);

			Frame3D fr = new Frame3D(frame.X, frame.Y, frame.Z, pitch, yaw, roll); 

			return fr;
		}
 /// <summary>
 /// [Utility] Recovers the object from entity.
 /// </summary>
 /// <param name="entity">The entity.</param>
 /// <returns></returns>
 public static IObject RecoverObjectFromEntity(BEPUphysics.Entities.Entity entity)
 {
     IPhysicObject phy = (entity.CollisionInformation.Tag as IPhysicObject);
     if (phy != null)
         return phy.ObjectOwner;
     return null;
 }
        public static DebugInfo GetDebugInfo(BEPUphysics.Entities.Entity DisplayedObject, Color color)
        {
            var wrappedShape = DisplayedObject.CollisionInformation.Shape as WrappedShape;
            if (wrappedShape == null)
                throw new ArgumentException("Wrong shape type");
            var points = new List<Vector3>();
            Vector3 max;
            var direction = new Vector3();
            float angleChange = MathHelper.TwoPi / NumSamples;

            for (int i = 1; i < NumSamples / 2 - 1; i++)
            {
                float phi = MathHelper.PiOver2 - i * angleChange;
                var sinPhi = (float)Math.Sin(phi);
                var cosPhi = (float)Math.Cos(phi);
                for (int j = 0; j < NumSamples; j++)
                {
                    float theta = j * angleChange;
                    direction.X = (float)Math.Cos(theta) * cosPhi;
                    direction.Y = sinPhi;
                    direction.Z = (float)Math.Sin(theta) * cosPhi;

                    wrappedShape.GetLocalExtremePoint(direction, out max);
                    points.Add(max);
                }
            }

            List<VertexPositionColor> vertices = new List<VertexPositionColor>();
            List<short> indices = new List<short>();

            wrappedShape.GetLocalExtremePoint(Toolbox.UpVector, out max);
            points.Add(max);
            wrappedShape.GetLocalExtremePoint(Toolbox.DownVector, out max);
            points.Add(max);

            var hullTriangleVertices = new List<Vector3>();
            var hullTriangleIndices = new List<int>();
            Toolbox.GetConvexHull(points, hullTriangleIndices, hullTriangleVertices);
            //The hull triangle vertices are used as a dummy to get the unnecessary hull vertices, which are cleared afterwards.
            hullTriangleVertices.Clear();
            foreach (int i in hullTriangleIndices)
            {
                hullTriangleVertices.Add(points[i]);
            }

            for (short i = 0; i < hullTriangleVertices.Count; i += 3)
            {
                Vector3 normal = Vector3.Normalize(Vector3.Cross(hullTriangleVertices[i + 2] - hullTriangleVertices[i], hullTriangleVertices[i + 1] - hullTriangleVertices[i]));
                vertices.Add(new VertexPositionColor(hullTriangleVertices[i], color));
                vertices.Add(new VertexPositionColor(hullTriangleVertices[i + 1], color));
                vertices.Add(new VertexPositionColor(hullTriangleVertices[i + 2], color));
                indices.Add(i);
                indices.Add((short)(i + 1));
                indices.Add((short)(i + 2));
            }
            DebugInfo DebugInfo = new DebugInfo();
            DebugInfo.vertices = vertices.ToArray();
            DebugInfo.indices = indices.ToArray();
            return DebugInfo;
        }
Ejemplo n.º 4
0
 //this is called when we hit something
 public void HitObject(BEPUphysics.Collidables.MobileCollidables.EntityCollidable sender, BEPUphysics.Collidables.Collidable other, 
     BEPUphysics.NarrowPhaseSystems.Pairs.CollidablePairHandler pair, BEPUphysics.CollisionTests.ContactData contact)
 {
     if (!sploded && !actor.IsShutdown && !actor.MarkedForDeath)
     {
         Vector3 mypos = actor.PhysicsObject.Position;
         StartAttack(ref mypos);
     }
 }
Ejemplo n.º 5
0
        public static DebugInfo GetDebugInfo(BEPUphysics.Entities.Entity DisplayedObject, Color color)
        {
            ConeShape coneShape = DisplayedObject.CollisionInformation.Shape as ConeShape;
            if (coneShape == null)
                throw new ArgumentException("Wrong shape type.");

            float verticalOffset = -coneShape.Height / 4;
            float angleBetweenFacets = MathHelper.TwoPi / NumSides;
            float radius = coneShape.Radius;

            //Create the vertex list

            var topVertexPosition = new Vector3(0, coneShape.Height + verticalOffset, 0);
            List<VertexPositionColor> vertices = new List<VertexPositionColor>();
            List<short> indices = new List<short>();

            for (int i = 0; i < NumSides; i++)
            {
                float theta = i * angleBetweenFacets;
                var position = new Vector3((float)Math.Cos(theta) * radius, verticalOffset, (float)Math.Sin(theta) * radius);
                Vector3 offset = topVertexPosition - position;
                Vector3 normal = Vector3.Normalize(Vector3.Cross(Vector3.Cross(offset, Vector3.Up), offset));
                //Top vertex
                vertices.Add(new VertexPositionColor(topVertexPosition, color));
                //Sloped vertices
                vertices.Add(new VertexPositionColor(position, color));
                //Bottom vertices
                vertices.Add(new VertexPositionColor(position, color));
            }


            //Create the index list
            for (short i = 0; i < vertices.Count; i += 3)
            {
                //Each iteration, the loop advances to the next vertex 'column.'
                //Four triangles per column (except for the four degenerate cap triangles).

                //Sloped Triangles
                indices.Add(i);
                indices.Add((short)(i + 1));
                indices.Add((short)((i + 4) % vertices.Count));

                //Bottom cap triangles.
                var nextIndex = (short)((i + 5) % vertices.Count);
                if (nextIndex != 2) //Don't add cap indices if it's going to be a degenerate triangle.
                {
                    indices.Add((short)(i + 2));
                    indices.Add(2);
                    indices.Add(nextIndex);
                }
            }

            DebugInfo DebugInfo = new DebugInfo();
            DebugInfo.vertices = vertices.ToArray();
            DebugInfo.indices = indices.ToArray();
            return DebugInfo;
        }
Ejemplo n.º 6
0
        public override void InitialCollisionDetected(BEPUphysics.Collidables.MobileCollidables.EntityCollidable sender, Collidable other, BEPUphysics.NarrowPhaseSystems.Pairs.CollidablePairHandler collisionPair)
        {
            base.InitialCollisionDetected(sender, other, collisionPair);

            if (other.Tag is CharacterSynchronizer)
            {
                ((other.Tag as CharacterSynchronizer).body.Tag as Creature).Poisoned = true;
                ((other.Tag as CharacterSynchronizer).body.Tag as Creature).Damage(0, mOwner as Creature);
            }
            World.Remove(this);
        }
            /// <summary>
            /// Calculates the gravitational force to apply to the entity.
            /// </summary>
            /// <param name="e">Target of the impulse.</param>
            /// <param name="dt">Time since the last frame in simulation seconds.</param>
            /// <param name="impulse">Force to apply at the given position.</param>
            protected override void CalculateImpulse(BEPUphysics.Entities.Entity e, float dt, out Vector3 impulse)
            {
                Vector3 r = e.Position - Origin;
                float length = r.Length();
                float force = dt * Math.Min(MaxForce, Multiplier * e.Mass / (length * length * length));
                impulse = -force * r;

                //Could use a linear dropoff for a slightly faster calculation (divide by length^2 instead of length^3).
                //Vector3 r = e.Position - Origin;
                //float force = dt * Math.Min(MaxForce, Multiplier * e.Mass / (r.LengthSquared()));
                //impulse = -force * r;
            }
Ejemplo n.º 8
0
 public bool FilterHandle(BEPUphysics.BroadPhaseEntries.BroadPhaseEntry entry)
 {
     if (entry is BEPUphysics.BroadPhaseEntries.MobileCollidables.EntityCollidable)
     {
         long eid = ((PhysicsEntity)((BEPUphysics.BroadPhaseEntries.MobileCollidables.EntityCollidable)entry).Entity.Tag).EID;
         if (NoCollide.Contains(eid))
         {
             return false;
         }
     }
     return TheRegion.Collision.ShouldCollide(entry);
 }
Ejemplo n.º 9
0
 public void ApplyHook(PlayerEntity player, ItemStack item, Location Position, BEPUphysics.Entities.Entity HitEnt)
 {
     RemoveHook(player);
     PhysicsEntity pe;
     double len = (double)(Position - player.GetCenter()).Length();
     Location step = (player.GetCenter() - Position) / len;
     Location forw = Utilities.VectorToAngles(step);
     BEPUutilities.Quaternion quat = Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), (double)(forw.Pitch * Utilities.PI180)) *
         Quaternion.CreateFromAxisAngle(new Vector3(0, 0, 1), (double)(forw.Yaw * Utilities.PI180));
     if (HitEnt == null)
     {
         ModelEntity mod = new ModelEntity("cube", player.TheRegion);
         mod.Mass = 0;
         mod.CanSave = false;
         mod.scale = new Location(0.023, 0.05, 0.05);
         mod.mode = ModelCollisionMode.AABB;
         mod.SetPosition(Position);
         mod.SetOrientation(quat);
         player.TheRegion.SpawnEntity(mod);
         pe = mod;
         player.Hooks.Add(new HookInfo() { Joint = null, Hit = pe, IsBar = true });
     }
     else
     {
         pe = (PhysicsEntity)HitEnt.Tag;
     }
     JointDistance jd;
     //jd = new JointDistance(player, pe, 0.01f, len + 0.01f, player.GetCenter(), Position);
     //player.TheRegion.AddJoint(jd);
     //player.Hooks.Add(new HookInfo() { Joint = jd, Hit = pe, IsBar = false });
     PhysicsEntity cent = pe;
     for (double f = 0; f < len - 1f; f += 0.5f)
     {
         Location cpos = Position + step * f;
         ModelEntity ce = new ModelEntity("cube", player.TheRegion);
         ce.Mass = 15;
         ce.CanSave = false;
         ce.scale = new Location(0.023, 0.05, 0.05);
         ce.mode = ModelCollisionMode.AABB;
         ce.SetPosition(cpos + step * 0.5);
         ce.SetOrientation(quat);
         player.TheRegion.SpawnEntity(ce);
         jd = new JointDistance(ce, cent, 0.01f, 0.5f, ce.GetPosition(), (ReferenceEquals(cent, pe) ? Position: cent.GetPosition()));
         CollisionRules.AddRule(player.Body, ce.Body, CollisionRule.NoBroadPhase);
         player.TheRegion.AddJoint(jd);
         player.Hooks.Add(new HookInfo() { Joint = jd, Hit = ce, IsBar = true });
         cent = ce;
     }
     jd = new JointDistance(cent, player, 0.01f, 0.5f, cent.GetPosition(), player.GetCenter());
     player.TheRegion.AddJoint(jd);
     player.Hooks.Add(new HookInfo() { Joint = jd, Hit = player, IsBar = false });
 }
Ejemplo n.º 10
0
 public bool FilterHandle(BEPUphysics.BroadPhaseEntries.BroadPhaseEntry entry)
 {
     if (entry is BEPUphysics.BroadPhaseEntries.MobileCollidables.EntityCollidable)
     {
         long eid = ((PhysicsEntity)((BEPUphysics.BroadPhaseEntries.MobileCollidables.EntityCollidable)entry).Entity.Tag).EID;
         if (NoCollide.Contains(eid))
         {
             return false;
         }
     }
     if (entry.CollisionRules.Group == CollisionUtil.NonSolid)
     {
         return false;
     }
     return true;
 }
        public static DebugInfo GetDebugInfo(BEPUphysics.Entities.Entity DisplayedObject, Color color)
        {
            MobileMeshShape shape = DisplayedObject.CollisionInformation.Shape as MobileMeshShape;
            var tempVertices = new VertexPositionNormalTexture[shape.TriangleMesh.Data.Vertices.Length];
            for (int i = 0; i < shape.TriangleMesh.Data.Vertices.Length; i++)
            {
                Vector3 position;
                shape.TriangleMesh.Data.GetVertexPosition(i, out position);
                tempVertices[i] = new VertexPositionNormalTexture(
                    position,
                    Vector3.Zero, 
                    Vector2.Zero);
            }

            List<VertexPositionColor> vertices = new List<VertexPositionColor>();
            List<short> indices = new List<short>();

            for (int i = 0; i < shape.TriangleMesh.Data.Indices.Length; i++)
            {
                indices.Add((short)shape.TriangleMesh.Data.Indices[i]);
            }
            for (int i = 0; i < indices.Count; i += 3)
            {
                int a = indices[i];
                int b = indices[i + 1];
                int c = indices[i + 2];
                Vector3 normal = Vector3.Normalize(Vector3.Cross(
                    tempVertices[c].Position - tempVertices[a].Position,
                    tempVertices[b].Position - tempVertices[a].Position));
                tempVertices[a].Normal += normal;
                tempVertices[b].Normal += normal;
                tempVertices[c].Normal += normal;
            }

            for (int i = 0; i < tempVertices.Length; i++)
            {
                tempVertices[i].Normal.Normalize();
                
                vertices.Add(new VertexPositionColor(tempVertices[i].Position,color));
            }

            DebugInfo DebugInfo = new DebugInfo();
            DebugInfo.vertices = vertices.ToArray();
            DebugInfo.indices = indices.ToArray();
            return DebugInfo;
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Constructs a new demo.
        /// </summary>
        /// <param name="game">Game owning this demo.</param>
        public ConvexHullTestDemo(DemosGame game)
            : base(game)
        {
            var vertices = new[]
            {
                new Vector3(0, -1.750886E-9f, -1.5f),
                new Vector3(1, 1, 0.5f),
                new Vector3(1, -1, 0.5f),
                new Vector3(-1, 1, 0.5f),
                new Vector3(-1, -1, 0.5f),
            };
            RawList<Vector3> hullVertices = new RawList<Vector3>();
            ConvexHullHelper.GetConvexHull(vertices, hullVertices);

            ConvexHull hull = new ConvexHull(vertices, 5);
            ShapeDistributionInformation shapeInfo;
            hull.CollisionInformation.Shape.ComputeDistributionInformation(out shapeInfo);
            Space.Add(hull);

            Box ground = new Box(new Vector3(0, -.5f, 0), 50, 1, 50);
            Space.Add(ground);
            game.Camera.Position = new Vector3(0, 6, 15);
        }
        public static DebugInfo GetDebugInfo(BEPUphysics.Entities.Entity DisplayedObject, Color color)
        {
            var convexHullShape = DisplayedObject.CollisionInformation.Shape as ConvexHullShape;
            if (convexHullShape == null)
                throw new ArgumentException("Wrong shape type.");

            var hullTriangleVertices = new List<Vector3>();
            var hullTriangleIndices = new List<int>();
            Toolbox.GetConvexHull(convexHullShape.Vertices, hullTriangleIndices, hullTriangleVertices);
            //The hull triangle vertices are used as a dummy to get the unnecessary hull vertices, which are cleared afterwards.
            hullTriangleVertices.Clear();
            foreach (int i in hullTriangleIndices)
            {
                hullTriangleVertices.Add(convexHullShape.Vertices[i]);
            }

            List<VertexPositionColor> vertices = new List<VertexPositionColor>();
            List<short> indices = new List<short>();
                        
            Vector3 normal;
            for (short i = 0; i < hullTriangleVertices.Count; i += 3)
            {
                normal = Vector3.Normalize(Vector3.Cross(hullTriangleVertices[i + 2] - hullTriangleVertices[i], hullTriangleVertices[i + 1] - hullTriangleVertices[i]));
                vertices.Add(new VertexPositionColor(hullTriangleVertices[i], color));
                vertices.Add(new VertexPositionColor(hullTriangleVertices[i + 1], color));
                vertices.Add(new VertexPositionColor(hullTriangleVertices[i + 2],color));
                indices.Add(i);
                indices.Add((short)(i + 1));
                indices.Add((short)(i + 2));
            }

            DebugInfo DebugInfo = new DebugInfo();
            DebugInfo.vertices = vertices.ToArray();
            DebugInfo.indices = indices.ToArray();
            return DebugInfo;
            
        }
Ejemplo n.º 14
0
        public static DebugInfo GetDebugInfo(BEPUphysics.Entities.Entity DisplayedObject, Color color)
        {
            var boxShape = DisplayedObject.CollisionInformation.Shape as BoxShape;


            var boundingBox = new BoundingBox(
                new Vector3(-boxShape.HalfWidth,
                            -boxShape.HalfHeight,
                            -boxShape.HalfLength),
                new Vector3(boxShape.HalfWidth,
                            boxShape.HalfHeight,
                            boxShape.HalfLength));


            Vector3[] corners = boundingBox.GetCorners();


            List<VertexPositionColor> vertices = new List<VertexPositionColor>();
            List<short> indices = new List<short>();

            vertices.Add(new VertexPositionColor(corners[0], color));
            vertices.Add(new VertexPositionColor(corners[1], color));
            vertices.Add(new VertexPositionColor(corners[2], color));
            vertices.Add(new VertexPositionColor(corners[3], color));
            indices.Add(0);
            indices.Add(1);
            indices.Add(2);
            indices.Add(0);
            indices.Add(2);
            indices.Add(3);

            vertices.Add(new VertexPositionColor(corners[1], color));
            vertices.Add(new VertexPositionColor(corners[2], color));
            vertices.Add(new VertexPositionColor(corners[5], color));
            vertices.Add(new VertexPositionColor(corners[6], color));
            indices.Add(4);
            indices.Add(6);
            indices.Add(7);
            indices.Add(4);
            indices.Add(7);
            indices.Add(5);

            vertices.Add(new VertexPositionColor(corners[4], color));
            vertices.Add(new VertexPositionColor(corners[5], color));
            vertices.Add(new VertexPositionColor(corners[6], color));
            vertices.Add(new VertexPositionColor(corners[7], color));
            indices.Add(9);
            indices.Add(8);
            indices.Add(11);
            indices.Add(9);
            indices.Add(11);
            indices.Add(10);

            vertices.Add(new VertexPositionColor(corners[0], color));
            vertices.Add(new VertexPositionColor(corners[3], color));
            vertices.Add(new VertexPositionColor(corners[4], color));
            vertices.Add(new VertexPositionColor(corners[7], color));
            indices.Add(14);
            indices.Add(12);
            indices.Add(13);
            indices.Add(14);
            indices.Add(13);
            indices.Add(15);

            vertices.Add(new VertexPositionColor(corners[0], color));
            vertices.Add(new VertexPositionColor(corners[1], color));
            vertices.Add(new VertexPositionColor(corners[4], color));
            vertices.Add(new VertexPositionColor(corners[5], color));
            indices.Add(16);
            indices.Add(19);
            indices.Add(17);
            indices.Add(16);
            indices.Add(18);
            indices.Add(19);

            vertices.Add(new VertexPositionColor(corners[2], color));
            vertices.Add(new VertexPositionColor(corners[3], color));
            vertices.Add(new VertexPositionColor(corners[6], color));
            vertices.Add(new VertexPositionColor(corners[7], color));
            indices.Add(21);
            indices.Add(20);
            indices.Add(22);
            indices.Add(21);
            indices.Add(22);
            indices.Add(23);

            DebugInfo DebugInfo = new DebugInfo();
            DebugInfo.vertices = vertices.ToArray();
            DebugInfo.indices = indices.ToArray();
            return DebugInfo;
        }
 /// <summary>
 /// [Utility] Recovers the physic object from entity.
 /// </summary>
 /// <param name="entity">The entity.</param>
 /// <returns></returns>
 public static IPhysicObject RecoverIPhysicObjectFromEntity(BEPUphysics.Entities.Entity entity)
 {
     return (entity.CollisionInformation.Tag as IPhysicObject);
 }
Ejemplo n.º 16
0
        public override void AddToGame(BEPUphysics.Space s)
        {
            levelTheme.SetUpLighting();
            TemporarilyMuteVoice = false;

            MediaSystem.PlayTrack(levelTheme.Song);
            overlay = new OpeningOverlay(levelNumber, false, levelName);
            time = new TimeSpan();
            RebuildTiming();

            int i = 0;
            foreach(OperationalMachine m in MachineList.Keys)
                if(i < 11)
                {
                    s.Add(m);
                    i++;
                }
                else
                    break;
            s.Add(levelModel);
            i = 0;
            foreach(Tube t in tubeList)
            {
                if(i < 110)
                    s.Add(t);
                else
                    break;
                i++;
            }
            i = 0;
            foreach(BaseModel m in glassModels)
                if(i < 6)
                {
                    if(m.Ent.Space == null)
                        s.Add(m);
                    i++;
                }
                else
                    break;
            s.Add(dispenser);
            if(levelTheme.Fluid != null)
                s.Add(levelTheme.Fluid);

            addModelsToRenderer();
            results = null;
            ending = badEnding = false;
        }
Ejemplo n.º 17
0
        public override void RemoveFromGame(BEPUphysics.Space s)
        {
            RenderingDevice.Remove(buff);
            normalCatcher = catcherTheFirst;
            if(moved)
            {
                RenderingDevice.Remove(baseTheSecond);
                catcherTheSecond.RemoveFromGame();
            }
            moved = false;

            base.RemoveFromGame(s);
        }
Ejemplo n.º 18
0
 bool IgnorePlayer(BEPUphysics.BroadPhaseEntries.BroadPhaseEntry entry)
 {
     if (entry is EntityCollidable)
     {
         Entity e = (Entity)((EntityCollidable)entry).Entity.Tag;
         if (e == Player || e == Player.Vehicle)
         {
             return false;
         }
     }
     return TheRegion.Collision.ShouldCollide(entry);
 }
Ejemplo n.º 19
0
 public override void AddToGame(BEPUphysics.Space s)
 {
     base.AddToGame(s);
     //s.Add(extras); // no real reason to give these collision
 }
Ejemplo n.º 20
0
        /// <summary>
        /// Locates the closest support entity by performing a raycast at collected candidates.
        /// </summary>
        /// <param name="supportEntity">The closest supporting entity.</param>
        /// <param name="supportLocation">The support location where the ray hit the entity.</param>
        /// <param name="supportNormal">The normal at the surface where the ray hit the entity.</param>
        /// <param name="supportDistance">Distance from the character to the support location.</param>
        /// <returns>Whether or not a support was located.</returns>
        private bool findSupport(out object supportEntityTag, out BEPUphysics.Entities.Entity supportEntity, out Vector3 supportLocation, out Vector3 supportNormal, out float supportDistance)
        {
            supportEntity = null;
            supportEntityTag = null;
            supportLocation = BEPUutilities.Toolbox.NoVector;
            supportNormal = BEPUutilities.Toolbox.NoVector;
            supportDistance = float.MaxValue;

            const float fudgeFactor = 0.1f;
            Vector3 rayOrigin = this.Body.Position;
            rayOrigin.Y += fudgeFactor + this.Body.Height * -0.5f;

            for (int i = 0; i < this.collisionPairCollector.CollisionInformation.Pairs.Count; i++)
            {
                var pair = this.collisionPairCollector.CollisionInformation.Pairs[i];
                //Determine which member of the collision pair is the possible support.
                Collidable candidate = (pair.BroadPhaseOverlap.EntryA == collisionPairCollector.CollisionInformation ? pair.BroadPhaseOverlap.EntryB : pair.BroadPhaseOverlap.EntryA) as Collidable;
                //Ensure that the candidate is a valid supporting entity.
                if (candidate.CollisionRules.Personal >= CollisionRule.NoSolver)
                    continue; //It is invalid!

                if (candidate.CollisionRules.Group == Character.NoCollideGroup)
                    continue;

                //The maximum length is supportHeight * 2 instead of supportHeight alone because the character should be able to step downwards.
                //This acts like a sort of 'glue' to help the character stick on the ground in general.
                float maximumDistance;
                //The 'glue' effect should only occur if the character has a solid hold on the ground though.
                //Otherwise, the character is falling or sliding around uncontrollably.
                if (this.HasTraction && !this.IsSwimming)
                    maximumDistance = fudgeFactor + (this.SupportHeight * 2.0f);
                else
                    maximumDistance = fudgeFactor + this.SupportHeight;

                foreach (Vector3 rayStart in this.rayOffsets.Select(x => x + rayOrigin))
                {
                    BEPUutilities.RayHit rayHit;
                    // Fire a ray at the candidate and determine some details!
                    if (candidate.RayCast(new Ray(rayStart, Vector3.Down), maximumDistance, out rayHit))
                    {
                        Vector3 n = Vector3.Normalize(rayHit.Normal);

                        if (n.Y > supportNormal.Y)
                            supportNormal = n;

                        // We want to find the closest support, so compare it against the last closest support.
                        if (rayHit.T < supportDistance && n.Y > 0.25f)
                        {
                            supportDistance = rayHit.T - fudgeFactor;
                            supportLocation = rayHit.Location;
                            if (rayHit.T < 0.0f)
                                supportNormal = Vector3.Up;

                            var entityInfo = candidate as EntityCollidable;
                            if (entityInfo != null)
                            {
                                supportEntity = entityInfo.Entity;
                                supportEntityTag = supportEntity != null ? supportEntity.Tag : candidate.Tag;
                            }
                            else
                                supportEntityTag = candidate.Tag;
                        }
                    }
                }
            }

            bool isSupported = supportDistance < float.MaxValue;

            if (!isSupported && this.WallRunState.Value == Player.WallRun.None)
            {
                foreach (Contact contact in this.Body.CollisionInformation.Pairs.SelectMany(x => x.Contacts.Select(y => y.Contact)))
                {
                    Vector3 normal = (contact.Position - this.Body.Position).SetComponent(Direction.PositiveY, 0);
                    float length = normal.Length();
                    if (length > 0.5f)
                        this.Body.LinearVelocity += -0.1f * (normal / length);
                }
            }
            return isSupported;
        }
Ejemplo n.º 21
0
 void Events_ContactCreated(EntityCollidable sender, Collidable other, BEPUphysics.NarrowPhaseSystems.Pairs.CollidablePairHandler pair, ContactData contact)
 {
     this.Collided.Execute(other, pair.Contacts);
 }
Ejemplo n.º 22
0
 public override void Create(Vector3 position, Quaternion orientation, Vector3 velocity, BEPUphysics.Entities.Entity target)
 {
     Create(position, orientation, velocity);
 }
        public static DebugInfo GetDebugInfo(BEPUphysics.Entities.Entity DisplayedObject, Color color)
        {
            var cylinderShape = DisplayedObject.CollisionInformation.Shape as CylinderShape;
            if (cylinderShape == null)
                throw new ArgumentException("Wrong shape type.");

            float verticalOffset = cylinderShape.Height / 2;
            float angleBetweenFacets = MathHelper.TwoPi / NumSides;
            float radius = cylinderShape.Radius;

            List<VertexPositionColor> vertices = new List<VertexPositionColor>();
            List<short> indices = new List<short>();

            //Create the vertex list
            for (int i = 0; i < NumSides; i++)
            {
                float theta = i * angleBetweenFacets;
                float x = (float)Math.Cos(theta) * radius;
                float z = (float)Math.Sin(theta) * radius;
                //Top cap
                vertices.Add(new VertexPositionColor(new Vector3(x, verticalOffset, z), color));
                //Top part of body
                vertices.Add(new VertexPositionColor(new Vector3(x, verticalOffset, z), color));
                //Bottom part of body
                vertices.Add(new VertexPositionColor(new Vector3(x, -verticalOffset, z), color));
                //Bottom cap
                vertices.Add(new VertexPositionColor(new Vector3(x, -verticalOffset, z), color));
            }


            //Create the index list
            //The vertices are arranged a little nonintuitively.
            //0 is part of the top cap, 1 is the upper body, 2 is lower body, and 3 is bottom cap.
            for (short i = 0; i < vertices.Count; i += 4)
            {
                //Each iteration, the loop advances to the next vertex 'column.'
                //Four triangles per column (except for the four degenerate cap triangles).

                //Top cap triangles
                var nextIndex = (short)((i + 4) % vertices.Count);
                if (nextIndex != 0) //Don't add cap indices if it's going to be a degenerate triangle.
                {
                    indices.Add(i);
                    indices.Add(nextIndex);
                    indices.Add(0);
                }

                //Body triangles
                nextIndex = (short)((i + 5) % vertices.Count);
                indices.Add((short)(i + 1));
                indices.Add((short)(i + 2));
                indices.Add(nextIndex);

                indices.Add(nextIndex);
                indices.Add((short)(i + 2));
                indices.Add((short)((i + 6) % vertices.Count));

                //Bottom cap triangles.
                nextIndex = (short)((i + 7) % vertices.Count);
                if (nextIndex != 3) //Don't add cap indices if it's going to be a degenerate triangle.
                {
                    indices.Add((short)(i + 3));
                    indices.Add(3);
                    indices.Add(nextIndex);
                }
            }
            DebugInfo DebugInfo = new DebugInfo();
            DebugInfo.vertices = vertices.ToArray();
            DebugInfo.indices = indices.ToArray();
            return DebugInfo;
        }
Ejemplo n.º 24
0
 public override void Create(Vector3 position, Quaternion orientation, Vector3 velocity, BEPUphysics.Entities.Entity target)
 {
     throw new NotImplementedException();
 }
 public static IPhysicObject RecoverIPhysicObjectFromCollidable(BEPUphysics.Collidables.Collidable collidable)
 {
     IPhysicObject phy = (collidable.Tag as IPhysicObject);
     if (phy != null)
         return phy;
     return null;
 }
        /// <summary>
        /// Collision happened
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="other"></param>
        /// <param name="pair"></param>
        void Events_InitialCollisionDetected(BEPUphysics.Collidables.MobileCollidables.EntityCollidable sender, BEPUphysics.Collidables.Collidable other, BEPUphysics.NarrowPhaseSystems.Pairs.CollidablePairHandler pair)
        {
            IObject send = BepuEntityObject.RecoverObjectFromEntity(sender.Entity);
            IObject obj = BepuEntityObject.RecoverObjectFromCollidable(other); 

            ///Verifica se esta bola ja foi considerada
            ///Consider just the first collision
            if (alreadProcessed.Contains(obj.GetId()))
                return;

            alreadProcessed.Add(obj.GetId());

            ///se o objeto colidido for diferente do cenario 
            ///dont consider the island model (triangle meshes in general)
            if (obj.PhysicObject.PhysicObjectTypes != PhysicObjectTypes.TRIANGLEMESHOBJECT)
            {
                shouldDraw = true;

                ///Envia uma mensagem para o canal de comunicacao CUBO
                ///Send a message to the channel
                Message m = new Message(send.GetId(), PrincipalConstants.InvalidId, "cubo", Priority.MEDIUM, -1, SenderType.OBJECT, null, "CHANGECOLOR");
                MessageDeliver.SendMessage(m);

                ///Esta mensagem foi enviada sem Sender (Quem receber a mensagem nao sabera quem enviou)
                ///Envia uma mensagem para o "CUBO QUE VAI MUDAR DE COR" (lembre que o id dele eh 77 !!)
                ///Send a message to the specific  id (first cube)
                m = new Message(PrincipalConstants.InvalidId, 77, null, Priority.MEDIUM, -1, SenderType.OBJECT, null, "CHANGECOLOR");
                MessageDeliver.SendMessage(m);
            }

            objNameTemp = obj.Name;
        }
 public override void OnAdditionToSpace(BEPUphysics.ISpace s)
 {
     s.Add(baseJoint);
     foreach(WeldJoint j in joints)
         s.Add(j);
     base.OnAdditionToSpace(s);
 }
        public static DebugInfo GetDebugInfo(BEPUphysics.Entities.Entity DisplayedObject, Color color)
        {
            var capsuleShape = DisplayedObject.CollisionInformation.Shape as CapsuleShape;
            if (capsuleShape == null)
                throw new ArgumentException("Wrong shape type.");

            var n = new Vector3();
            var offset = new Vector3(0, capsuleShape.Length / 2, 0);
            float angleBetweenFacets = MathHelper.TwoPi / NumSides;
            float radius = capsuleShape.Radius;

            //Create the vertex list
            //Top
            List<VertexPositionColor> vertices = new List<VertexPositionColor>();
            List<short> indices = new List<short>();
            vertices.Add(new VertexPositionColor(new Vector3(0, radius + capsuleShape.Length / 2, 0),color));
            //Upper hemisphere
            for (int i = 1; i <= NumSides / 4; i++)
            {
                float phi = MathHelper.PiOver2 - i * angleBetweenFacets;
                var sinPhi = (float)Math.Sin(phi);
                var cosPhi = (float)Math.Cos(phi);

                for (int j = 0; j < NumSides; j++)
                {
                    float theta = j * angleBetweenFacets;

                    n.X = (float)Math.Cos(theta) * cosPhi;
                    n.Y = sinPhi;
                    n.Z = (float)Math.Sin(theta) * cosPhi;

                    vertices.Add(new VertexPositionColor(n * radius + offset, color));
                }
            }
            //Lower hemisphere
            for (int i = NumSides / 4; i < NumSides / 2; i++)
            {
                float phi = MathHelper.PiOver2 - i * angleBetweenFacets;
                var sinPhi = (float)Math.Sin(phi);
                var cosPhi = (float)Math.Cos(phi);

                for (int j = 0; j < NumSides; j++)
                {
                    float theta = j * angleBetweenFacets;

                    n.X = (float)Math.Cos(theta) * cosPhi;
                    n.Y = sinPhi;
                    n.Z = (float)Math.Sin(theta) * cosPhi;

                    vertices.Add(new VertexPositionColor(n * radius - offset, color));
                }
            }
            //Bottom
            vertices.Add(new VertexPositionColor(new Vector3(0, -radius - capsuleShape.Length / 2, 0), color));


            //Create the index list
            for (int i = 0; i < NumSides; i++)
            {
                indices.Add((short)(vertices.Count - 1));
                indices.Add((short)(vertices.Count - 2 - i));
                indices.Add((short)(vertices.Count - 2 - (i + 1) % NumSides));
            }

            for (int i = 0; i < NumSides / 2 - 1; i++)
            {
                for (int j = 0; j < NumSides; j++)
                {
                    int nextColumn = (j + 1) % NumSides;

                    indices.Add((short)(i * NumSides + nextColumn + 1));
                    indices.Add((short)(i * NumSides + j + 1));
                    indices.Add((short)((i + 1) * NumSides + j + 1));

                    indices.Add((short)((i + 1) * NumSides + nextColumn + 1));
                    indices.Add((short)(i * NumSides + nextColumn + 1));
                    indices.Add((short)((i + 1) * NumSides + j + 1));
                }
            }

            for (int i = 0; i < NumSides; i++)
            {
                indices.Add(0);
                indices.Add((short)(i + 1));
                indices.Add((short)((i + 1) % NumSides + 1));
            }
            DebugInfo DebugInfo = new DebugInfo();
            DebugInfo.vertices = vertices.ToArray();
            DebugInfo.indices = indices.ToArray();
            return DebugInfo;
        }        
Ejemplo n.º 29
0
 void detectorVolume_EntityStoppedTouching(DetectorVolume volume, BEPUphysics.Entities.Entity toucher)
 {
     actor.EndCollision((Actor)toucher.CollisionInformation.OwningActor);
 }
 public override void OnAdditionToSpace(BEPUphysics.ISpace s)
 {
     foreach(WeldJoint j in joints)
         s.Add(j);
     s.Add(glassJoint1);
     s.Add(glassJoint2);
     s.Add(baseJoint);
     s.Add(wheelsJoint1);
     s.Add(wheelsJoint2);
     base.OnAdditionToSpace(s);
 }