Esempio n. 1
0
        public void Draw(Effect effect, Space space)
        {
            contactLines.Clear();
            int contactCount = 0;

            foreach (var pair in space.NarrowPhase.Pairs)
            {
                var pairHandler = pair as CollidablePairHandler;
                if (pairHandler != null)
                {
                    foreach (ContactInformation information in pairHandler.Contacts)
                    {
                        contactCount++;
                        contactLines.Add(new VertexPositionColor(MathConverter.Convert(information.Contact.Position), Color.White));
                        contactLines.Add(new VertexPositionColor(MathConverter.Convert(information.Contact.Position + information.Contact.Normal * information.Contact.PenetrationDepth), Color.Red));
                        contactLines.Add(new VertexPositionColor(MathConverter.Convert(information.Contact.Position + information.Contact.Normal * information.Contact.PenetrationDepth), Color.White));
                        contactLines.Add(new VertexPositionColor(MathConverter.Convert(information.Contact.Position + information.Contact.Normal * (information.Contact.PenetrationDepth + .3f)), Color.White));
                    }
                }
            }

            if (contactCount > 0)
            {
                foreach (var pass in effect.CurrentTechnique.Passes)
                {
                    pass.Apply();

                    game.GraphicsDevice.DrawUserPrimitives(PrimitiveType.LineList, contactLines.Elements, 0, contactLines.Count / 2);
                }
            }
        }
Esempio n. 2
0
 public Scene()
 {
     SceneInterface = null;
     _objs          = new List <SceneEntity>();
     _space         = new Space();
     _space.ForceUpdater.Gravity = MathConverter.Convert(new Vector3(0, -9.81f, 0));
 }
Esempio n. 3
0
        public override void Draw(GameTime gameTime)
        {
            //Notice that the entity's worldTransform property is being accessed here.
            //This property is returns a rigid transformation representing the orientation
            //and translation of the entity combined.
            //There are a variety of properties available in the entity, try looking around
            //in the list to familiarize yourself with it.
            Matrix worldMatrix = Transform * MathConverter.Convert(Entity.WorldTransform);

            model.CopyAbsoluteBoneTransformsTo(boneTransforms);
            foreach (ModelMesh mesh in model.Meshes)
            {
                foreach (BasicEffect effect in mesh.Effects)
                {
                    effect.LightingEnabled = true;                                          // turn on the lighting subsystem.
                    effect.DirectionalLight0.DiffuseColor  = new Vector3(0.6f, 0.6f, 0.6f); // a red light
                    effect.DirectionalLight0.Direction     = new Vector3(1f, -1.2f, 0f);    // coming along the x-axis
                    effect.DirectionalLight0.SpecularColor = new Vector3(0.1f, 0.1f, 0.1f); // with green highlights
                    effect.AmbientLightColor = new Vector3(0.6f, 0.6f, 0.6f);
                    effect.EmissiveColor     = new Vector3(0f, 0f, 0);

                    effect.World      = boneTransforms[mesh.ParentBone.Index] * worldMatrix;
                    effect.View       = Camera.View;
                    effect.Projection = Camera.Projection;
                }
                mesh.Draw();
            }
            base.Draw(gameTime);
        }
        public override void Draw()
        {
            base.Draw();

            if (!hitAnything)
            {
                //If we didn't hit anything, just point out into something approximating infinity.
                result.HitData.Location = origin + direction * 10000;
            }
            Game.LineDrawer.LightingEnabled    = false;
            Game.LineDrawer.VertexColorEnabled = true;
            Game.LineDrawer.World                 = Microsoft.Xna.Framework.Matrix.Identity;
            Game.LineDrawer.View                  = MathConverter.Convert(Game.Camera.ViewMatrix);
            Game.LineDrawer.Projection            = MathConverter.Convert(Game.Camera.ProjectionMatrix);
            Game.GraphicsDevice.BlendState        = BlendState.Opaque;
            Game.GraphicsDevice.DepthStencilState = DepthStencilState.Default;

            foreach (var pass in Game.LineDrawer.CurrentTechnique.Passes)
            {
                pass.Apply();
                Game.GraphicsDevice.DrawUserPrimitives(PrimitiveType.LineList,
                                                       new[]
                {
                    new VertexPositionColor(MathConverter.Convert(origin), Color.Blue),
                    new VertexPositionColor(MathConverter.Convert(result.HitData.Location), Color.Blue),
                    new VertexPositionColor(MathConverter.Convert(result.HitData.Location), Color.Blue),
                    new VertexPositionColor(MathConverter.Convert(result.HitData.Normal + result.HitData.Location), Color.Blue)
                },
                                                       0, 2);
            }
        }
Esempio n. 5
0
        public override void Initialize()
        {
            var model = TryAndGetModelFromOwner();

            if (model != null)
            {
                Vector3[] vertices;
                int[]     indices;

                ModelDataExtractor.GetVerticesAndIndicesFromModel(model, out vertices, out indices);

                BoundingBox _aabb = BoundingBox.CreateFromPoints(vertices);
                Vector3     xsize = _aabb.Max - _aabb.Min;

                if (Mass <= 0)
                {
                    //kinematic
                    Entity = new Cylinder(MathConverter.Convert(Owner.World.Translation),
                                          xsize.Y, xsize.X / 2);
                }
                else
                {
                    //dynamic
                    Entity = new Cylinder(MathConverter.Convert(Owner.World.Translation),
                                          xsize.Y, xsize.X / 2, Mass);
                }
            }

            base.Initialize();
        }
Esempio n. 6
0
        public bool RayCastAgainstEntity(Vector3 from, Vector3 to, out Vector3 pos, out float distance, out Entity hitEntity)
        {
            hitEntity = null;
            var dir  = to - from;
            var dist = dir.Length();
            var ndir = dir.Normalized();

            distance = float.MaxValue;
            Ray ray = new Ray(from, ndir);

            pos = to;

            var rcr  = new RayCastResult();
            var bRay = MathConverter.Convert(ray);

            bool result = PhysSpace.RayCast(bRay, dist, out rcr);

            if (!result)
            {
                return(false);
            }

            var convex = rcr.HitObject as ConvexCollidable;

            pos = MathConverter.Convert(rcr.HitData.Location);

            if (convex != null)
            {
                hitEntity = convex.Entity.Tag as Entity;
            }

            distance = rcr.HitData.T;

            return(true);
        }
Esempio n. 7
0
            public TextureMissile(GameModel model, Vector3 target, GameTexture carriedTex, Player p, GameModel targetModel, bool followPlayer = true)
            {
                FollowPlayer     = followPlayer;
                player           = p;
                this.targetModel = targetModel;

                Model      = model;
                Target     = target;
                CarriedTex = carriedTex;

                Vector3 up      = Vector3.UnitZ;
                Vector3 forward = Target - MathConverter.Convert(model.Entity.Position);

                forward.Normalize();
                Vector3 left = Vector3.Cross(up, forward);

                BEPUutilities.Matrix3x3 m = new BEPUutilities.Matrix3x3();
                m.Left    = left;
                m.Forward = forward;
                m.Up      = up;
                Model.Entity.OrientationMatrix = m;

                linearMotor = new SingleEntityLinearMotor(model.Entity, model.Entity.Position);
                linearMotor.Settings.Mode       = BEPUphysics.Constraints.TwoEntity.Motors.MotorMode.Servomechanism;
                linearMotor.Settings.Servo.Goal = Target;
                linearMotor.IsActive            = true;
            }
Esempio n. 8
0
        public static void GetShapeMeshData(EntityCollidable collidable, List <VertexPositionNormalTexture> vertices, List <ushort> indices)
        {
            var convexHullShape = collidable.Shape as ConvexHullShape;

            if (convexHullShape == null)
            {
                throw new ArgumentException("Wrong shape type.");
            }

            var hullTriangleVertices = new List <BEPUphysics.MathExtensions.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]);
            }

            var     toReturn = new VertexPositionNormalTexture[hullTriangleVertices.Count];
            Vector3 normal;

            for (ushort i = 0; i < hullTriangleVertices.Count; i += 3)
            {
                normal = MathConverter.Convert(BEPUphysics.MathExtensions.Vector3.Normalize(BEPUphysics.MathExtensions.Vector3.Cross(hullTriangleVertices[i + 2] - hullTriangleVertices[i], hullTriangleVertices[i + 1] - hullTriangleVertices[i])));
                vertices.Add(new VertexPositionNormalTexture(MathConverter.Convert(hullTriangleVertices[i]), normal, new Vector2(0, 0)));
                vertices.Add(new VertexPositionNormalTexture(MathConverter.Convert(hullTriangleVertices[i + 1]), normal, new Vector2(1, 0)));
                vertices.Add(new VertexPositionNormalTexture(MathConverter.Convert(hullTriangleVertices[i + 2]), normal, new Vector2(0, 1)));
                indices.Add(i);
                indices.Add((ushort)(i + 1));
                indices.Add((ushort)(i + 2));
            }
        }
Esempio n. 9
0
        private static void drawMesh(ModelMesh mesh, GameModel model, string tech, Plane?clipPlane, Matrix view)
        {
            Matrix entityWorld = ConversionHelper.MathConverter.Convert(model.Entity.CollisionInformation.WorldTransform.Matrix);

            foreach (Effect currentEffect in mesh.Effects)
            {
                currentEffect.CurrentTechnique = currentEffect.Techniques[tech];

                currentEffect.Parameters["Texture"].SetValue(model.Texture.ActualTexture);

                currentEffect.Parameters["xCamerasViewProjection"].SetValue(view * MathConverter.Convert(Camera.ProjectionMatrix));
                currentEffect.Parameters["xWorld"].SetValue(mesh.ParentBone.Transform * model.Transform * entityWorld);// * Camera.World);
                currentEffect.Parameters["xPassThroughLighting"].SetValue(true);
                //currentEffect.Parameters["xLightPos"].SetValue(lights.LightPosition);
                //currentEffect.Parameters["xLightPower"].SetValue(0.4f);
                //currentEffect.Parameters["xAmbient"].SetValue(lights.AmbientPower);
                //currentEffect.Parameters["xLightDir"].SetValue(lights.LightDirection);

                if (clipPlane.HasValue)
                {
                    currentEffect.Parameters["xEnableClipping"].SetValue(true);
                    currentEffect.Parameters["xClipPlane"].SetValue(new Vector4(clipPlane.Value.Normal, clipPlane.Value.D));
                }
                else
                {
                    currentEffect.Parameters["xEnableClipping"].SetValue(false);
                }
            }
            mesh.Draw();
        }
Esempio n. 10
0
        public override void Initialized()
        {
            var Model = TryAndGetModelFromOwner();

            if (Model != null)
            {
                Vector3[] Vertices;
                int[]     indices;

                ModelDataExtractor.GetVerticesAndIndicesFromModel(Model, out Vertices, out indices);
                BoundingBox aabb = BoundingBox.CreateFromPoints(Vertices);
                Vector3     size = aabb.Max - aabb.Min;

                if (Mass <= 0)
                {
                    Entity = new Box(MathConverter.Convert(Owner.World.Translation), size.X, size.Y, size.Z);
                }
                else
                {
                    Entity = new Box(MathConverter.Convert(Owner.World.Translation), size.X, size.Y, size.Z, Mass);
                }
            }



            base.Initialized();
        }
        public StaticMeshColliderComponent(object tag, List <Microsoft.Xna.Framework.Vector3> verts, int[] indices)
        {
            if (tag != null)
            {
                Tag = tag;
            }

            ParentObject = tag as GameObject;

            List <BEPUutilities.Vector3> bepuVerts =
                MathConverter.Convert(verts.ToArray())
                .ToList();

            staticMesh = new StaticMesh(bepuVerts.ToArray(), indices, AffineTransform.Identity);
            offset     = staticMesh.WorldTransform.Translation.ToXNAVector();

            staticMesh.Tag = this.Tag;


            if (!SystemCore.PhysicsOnBackgroundThread)
            {
                SystemCore.PhysicsSimulation.Add(staticMesh);
            }
            else
            {
                SystemCore.PhysicsSimulation.SpaceObjectBuffer.Add(staticMesh);
            }
        }
        /// <summary>
        /// Moves the constraint lines to the proper location relative to the entities involved.
        /// </summary>
        public override void Update()
        {
            //Move lines around
            axis.PositionA = MathConverter.Convert(LineObject.ConnectionB.Position);
            axis.PositionB = MathConverter.Convert(LineObject.ConnectionB.Position + LineObject.TwistAxisB * BEPUutilities.F64.C1p5);


            Fix64 angleIncrement = 4 * BEPUutilities.MathHelper.Pi / (Fix64)limitLines.Length;             //Each loop iteration moves this many radians forward.

            for (int i = 0; i < limitLines.Length / 2; i++)
            {
                Line pointToPreviousPoint = limitLines[2 * i];
                Line centerToPoint        = limitLines[2 * i + 1];

                Fix64 currentAngle = i * angleIncrement;

                //Using the parametric equation for an ellipse, compute the axis of rotation and angle.
                Vector3 rotationAxis = MathConverter.Convert(LineObject.Basis.XAxis * LineObject.MaximumAngleX * Fix64.Cos(currentAngle) +
                                                             LineObject.Basis.YAxis * LineObject.MaximumAngleY * Fix64.Sin(currentAngle));
                float angle = rotationAxis.Length();
                rotationAxis /= angle;

                pointToPreviousPoint.PositionA = MathConverter.Convert(LineObject.ConnectionB.Position) +
                                                 //Rotate the primary axis to the ellipse boundary...
                                                 Vector3.TransformNormal(MathConverter.Convert(LineObject.Basis.PrimaryAxis), Matrix.CreateFromAxisAngle(rotationAxis, angle));

                centerToPoint.PositionA = pointToPreviousPoint.PositionA;
                centerToPoint.PositionB = MathConverter.Convert(LineObject.ConnectionB.Position);
            }
            for (int i = 0; i < limitLines.Length / 2; i++)
            {
                //Connect all the pointToPreviousPoint lines to the previous points.
                limitLines[2 * i].PositionB = limitLines[2 * ((i + 1) % (limitLines.Length / 2))].PositionA;
            }
        }
Esempio n. 13
0
        public void Invert()
        {
            var maxDelta = 0.001m;

            var deltas = new List <decimal>();

            // Scalability and edge cases
            foreach (var m in testCases)
            {
                Matrix3x3 testCase = m;

                FloatMatrix3x3 floatMatrix = MathConverter.Convert(testCase);
                FloatMatrix3x3 expected;
                FloatMatrix3x3.Invert(ref floatMatrix, out expected);

                Matrix3x3 actual;
                if (float.IsInfinity(expected.M11) || float.IsNaN(expected.M11))
                {
                    expected = new FloatMatrix3x3();
                }

                Matrix3x3.Invert(ref testCase, out actual);
                bool success = true;
                foreach (decimal delta in GetDeltas(expected, actual))
                {
                    deltas.Add(delta);
                    success &= delta <= maxDelta;
                }
                Assert.True(success, string.Format("Precision: Matrix3x3Invert({0}): Expected {1} Actual {2}", testCase, expected, actual));
            }
            output.WriteLine("Max error: {0} ({1} times precision)", deltas.Max(), deltas.Max() / Fix64.Precision);
            output.WriteLine("Average precision: {0} ({1} times precision)", deltas.Average(), deltas.Average() / Fix64.Precision);
        }
Esempio n. 14
0
        public override void ResetNode(GameWorld world)
        {
            if (scene == null)
            {
                return;
            }

            for (int i = 0; i < scene.Nodes.Count; i++)
            {
                var collidable = collidables[i];

                if (collidable != null)
                {
                    var q = MathConverter.Convert(Rotation);
                    var p = MathConverter.Convert(Position);

                    collidable.WorldTransform = new BEPUTransform(q, p);
                }

                var instance = instances[i];

                if (instance != null)
                {
                    instances[i].World = transforms[i] * WorldMatrix;
                }
            }
        }
Esempio n. 15
0
        public static void GetShapeMeshData(EntityCollidable collidable, List <VertexPositionNormalTexture> vertices, List <ushort> indices)
        {
            var triangleShape = collidable.Shape as TriangleShape;

            if (triangleShape == null)
            {
                throw new ArgumentException("Wrong shape type.");
            }
            Vector3 normal = MathConverter.Convert(triangleShape.GetLocalNormal());

            vertices.Add(new VertexPositionNormalTexture(MathConverter.Convert(triangleShape.VertexA), -normal, new Vector2(0, 0)));
            vertices.Add(new VertexPositionNormalTexture(MathConverter.Convert(triangleShape.VertexB), -normal, new Vector2(0, 1)));
            vertices.Add(new VertexPositionNormalTexture(MathConverter.Convert(triangleShape.VertexC), -normal, new Vector2(1, 0)));

            vertices.Add(new VertexPositionNormalTexture(MathConverter.Convert(triangleShape.VertexA), normal, new Vector2(0, 0)));
            vertices.Add(new VertexPositionNormalTexture(MathConverter.Convert(triangleShape.VertexB), normal, new Vector2(0, 1)));
            vertices.Add(new VertexPositionNormalTexture(MathConverter.Convert(triangleShape.VertexC), normal, new Vector2(1, 0)));

            indices.Add(0);
            indices.Add(1);
            indices.Add(2);

            indices.Add(3);
            indices.Add(5);
            indices.Add(4);
        }
Esempio n. 16
0
        public override void Draw(GameTime gameTime)
        {
            //SpaceSimGame.bloom.BeginDraw();
            //Notice that the entity's worldTransform property is being accessed here.
            //This property is returns a rigid transformation representing the orientation
            //and translation of the entity combined.
            //There are a variety of properties available in the entity, try looking around
            //in the list to familiarize yourself with it.

            Matrix worldMatrix = MathConverter.Convert(Transform * entity.WorldTransform);


            model.CopyAbsoluteBoneTransformsTo(boneTransforms);
            foreach (ModelMesh mesh in model.Meshes)
            {
                foreach (BasicEffect effect in mesh.Effects)
                {
                    effect.World      = boneTransforms[mesh.ParentBone.Index] * worldMatrix;
                    effect.View       = ((SpaceSimGame)this.Game).camera.View;
                    effect.Projection = ((SpaceSimGame)this.Game).camera.Projection;
                }
                mesh.Draw();
            }
            base.Draw(gameTime);
        }
Esempio n. 17
0
        /// <summary>
        /// Constructs a new demo.
        /// </summary>
        /// <param name="game">Game owning this demo.</param>
        public BridgeDemo(DemosGame game)
            : base(game)
        {
            //Form a long chain of planks connected by revolute joints.
            //The revolute joints control the three linear degrees of freedom and two angular degrees of freedom.
            //The third allowed angular degree of freedom allows the bridge to flex like a rope bridge.
            Vector3 startPosition = new Vector3(0, 0, 0);
            var     startPlatform = new Box(startPosition - new Vector3(0, 0, 3.2f), 8, .5f, 8);

            Space.Add(startPlatform);
            Vector3 offset       = new Vector3(0, 0, 1.7f);
            Box     previousLink = startPlatform;
            Vector3 position     = new Vector3();

            for (int i = 1; i <= 200; i++)
            {
                position = startPosition + offset * i;
                Box link = new Box(position, 4.5f, .3f, 1.5f, 50);
                Space.Add(link);
                Space.Add(new RevoluteJoint(previousLink, link, position - offset * .5f, Vector3.Right));

                previousLink = link;
            }
            var endPlatform = new Box(position - new Vector3(0, 0, -4.8f), 8, .5f, 8);

            Space.Add(endPlatform);

            Space.Add(new RevoluteJoint(previousLink, endPlatform, position + offset * .5f, Vector3.Right));


            game.Camera.Position = MathConverter.Convert(startPosition + new Vector3(0, 1, offset.Z * 200 + 5));
        }
Esempio n. 18
0
        void UpdateFallSFX(Entity e, float elapsedTime)
        {
            bool newTraction = controller.SupportFinder.HasTraction;

            if (oldTraction != newTraction && newTraction)
            {
                //if (((ShooterServer)World.GameServer).ShowFallings) {
                //	Log.Verbose("{0} falls : {1}", e.ID, oldVelocity.Y );
                //}

                if (oldVelocity.Y < -10)
                {
                    //	medium landing :
                    World.SpawnFX("PlayerLanding", e.ID, e.Position, oldVelocity, Quaternion.Identity);
                }
                else
                {
                    //	light landing :
                    World.SpawnFX("PlayerFootStepL", e.ID, e.Position);
                }
            }

            oldTraction = newTraction;
            oldVelocity = MathConverter.Convert(controller.Body.LinearVelocity);
        }
Esempio n. 19
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="gameTime"></param>
        public override void Update(float elapsedTime)
        {
            var c = controller;
            var e = Entity;

            UpdateWeaponState(Entity, (short)(elapsedTime * 1000));

            Move();

            e.Position        = MathConverter.Convert(c.Body.Position) - GetPovOffset();
            e.LinearVelocity  = MathConverter.Convert(c.Body.LinearVelocity);
            e.AngularVelocity = MathConverter.Convert(c.Body.AngularVelocity);

            if (c.SupportFinder.HasTraction)
            {
                e.State |= EntityState.HasTraction;
            }
            else
            {
                e.State &= ~EntityState.HasTraction;
            }

            if (c.StanceManager.CurrentStance == Stance.Crouching)
            {
                e.State |= EntityState.Crouching;
            }
            else
            {
                e.State &= ~EntityState.Crouching;
            }


            UpdateWalkSFX(e, elapsedTime);
            UpdateFallSFX(e, elapsedTime);
        }
Esempio n. 20
0
        public override void GetMeshData(List <VertexPositionNormalTexture> vertices, List <ushort> indices)
        {
            var tempVertices = new VertexPositionNormalTexture[DisplayedObject.Shape.TriangleMesh.Data.Vertices.Length];

            for (int i = 0; i < DisplayedObject.Shape.TriangleMesh.Data.Vertices.Length; i++)
            {
                tempVertices[i] = new VertexPositionNormalTexture(
                    MathConverter.Convert(BEPUphysics.MathExtensions.AffineTransform.Transform(DisplayedObject.Shape.TriangleMesh.Data.Vertices[i], DisplayedObject.WorldTransform)),
                    Vector3.Zero,
                    Vector2.Zero);
            }

            for (int i = 0; i < DisplayedObject.Shape.TriangleMesh.Data.Indices.Length; i++)
            {
                indices.Add((ushort)DisplayedObject.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(tempVertices[i]);
            }
        }
        /// <summary>
        /// Moves the constraint lines to the proper location relative to the entities involved.
        /// </summary>
        public override void Update()
        {
            //Move lines around
            if (LineObject.IsActiveInSolver)
            {
                toPoint.PositionA = MathConverter.Convert(LineObject.Entity.Position);
                toPoint.PositionB = MathConverter.Convert(LineObject.Point);

                if (LineObject.Settings.Mode == MotorMode.Servomechanism)
                {
                    error.PositionA = toPoint.PositionB;
                    error.PositionB = MathConverter.Convert(LineObject.Settings.Servo.Goal);
                }
                else
                {
                    error.PositionA = toPoint.PositionB;
                    error.PositionB = toPoint.PositionB;
                }
            }
            else
            {
                error.PositionA = toPoint.PositionB;
                error.PositionB = toPoint.PositionB;
            }
        }
Esempio n. 22
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="game"></param>
        /// <param name="space"></param>
        public RigidBody(Entity entity, GameWorld world, RigidBodyFactory factory) : base(entity, world)
        {
            this.space = world.PhysSpace;

            var width  = factory.Width;
            var height = factory.Height;
            var depth  = factory.Depth;
            var mass   = factory.Mass;
            var model  = factory.Model;

            var ms = new MotionState();

            ms.AngularVelocity = MathConverter.Convert(entity.AngularVelocity);
            ms.LinearVelocity  = MathConverter.Convert(entity.LinearVelocity);
            ms.Orientation     = MathConverter.Convert(entity.Rotation);
            ms.Position        = MathConverter.Convert(entity.Position);
            box = new Box(ms, width, height, depth, mass);
            box.PositionUpdateMode = PositionUpdateMode.Continuous;

            box.Tag = entity;

            entity.Model = world.Atoms[model];

            space.Add(box);
        }
Esempio n. 23
0
        /// <summary>
        /// Draws the component.
        /// </summary>
        /// <param name="viewMatrix">View matrix to use when rendering the lines.</param>
        /// <param name="projectionMatrix">Projection matrix to use when rendering the lines.</param>
        public void Draw(BEPUutilities.Matrix viewMatrix, BEPUutilities.Matrix projectionMatrix)
        {
            int numElements = firstOpenIndex / 2;

            if (numElements > 0)
            {
                //Set state

                game.GraphicsDevice.BlendState = blendState;

                lineDrawer.LightingEnabled    = false;
                lineDrawer.VertexColorEnabled = true;
                lineDrawer.World      = Matrix.Identity;
                lineDrawer.View       = MathConverter.Convert(viewMatrix);
                lineDrawer.Projection = MathConverter.Convert(projectionMatrix);

                //Draw

                for (int i = 0; i < lineDrawer.CurrentTechnique.Passes.Count; i++)
                {
                    lineDrawer.CurrentTechnique.Passes[i].Apply();

                    game.GraphicsDevice.DrawUserPrimitives(PrimitiveType.LineList, vertices, 0, numElements);
                }
            }
        }
Esempio n. 24
0
        public static void GetMeshData(TriangleMesh mesh, List <VertexPositionNormalTexture> vertices, List <ushort> indices)
        {
            var tempVertices = new VertexPositionNormalTexture[mesh.Data.Vertices.Length];

            for (int i = 0; i < mesh.Data.Vertices.Length; i++)
            {
                BEPUphysics.MathExtensions.Vector3 v;
                mesh.Data.GetVertexPosition(i, out v);
                tempVertices[i] = new VertexPositionNormalTexture(MathConverter.Convert(v), Vector3.Zero, Vector2.Zero);
            }

            for (int i = 0; i < mesh.Data.Indices.Length; i++)
            {
                indices.Add((ushort)mesh.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(tempVertices[i]);
            }
        }
Esempio n. 25
0
        public override void Initialize()
        {
            var model = TryAndGetModelFromOwner();

            if (model != null)
            {
                Vector3[] vertices;
                int[]     indices;

                ModelDataExtractor.GetVerticesAndIndicesFromModel(model, out vertices, out indices);

                BoundingSphere _aabb = BoundingSphere.CreateFromPoints(vertices);

                if (Mass <= 0)
                {
                    //kinematic
                    Entity = new Sphere(MathConverter.Convert(Owner.World.Translation),
                                        _aabb.Radius);
                }
                else
                {
                    //dynamic
                    Entity = new Sphere(MathConverter.Convert(Owner.World.Translation),
                                        _aabb.Radius, Mass);
                }
            }

            base.Initialize();
        }
Esempio n. 26
0
        public override void Draw(GameTime gameTime)
        {
            //Notice that the entity's worldTransform property is being accessed here.
            //This property is returns a rigid transformation representing the orientation
            //and translation of the entity combined.
            //There are a variety of properties available in the entity, try looking around
            //in the list to familiarize yourself with it.
            var worldMatrix = Transform * MathConverter.Convert(entity.WorldTransform);


            model.CopyAbsoluteBoneTransformsTo(boneTransforms);
            foreach (ModelMesh mesh in model.Meshes)
            {
                foreach (BasicEffect effect in mesh.Effects)
                {
                    effect.World      = boneTransforms[mesh.ParentBone.Index] * worldMatrix;
                    effect.View       = MathConverter.Convert((Game as BepuFluidGame).Camera.ViewMatrix);
                    effect.Projection = MathConverter.Convert((Game as BepuFluidGame).Camera.ProjectionMatrix);

                    if (this.IsOpaque || true)
                    {
                        effect.GraphicsDevice.DepthStencilState = DepthStencilState.Default;

                        effect.GraphicsDevice.BlendState = BlendState.AlphaBlend;
                        effect.Alpha = 1.0f;
                    }
                }
                mesh.Draw();
            }
            base.Draw(gameTime);
        }
Esempio n. 27
0
        public void BenchmarkAdaptiveInvert()
        {
            var swf = new Stopwatch();
            var swd = new Stopwatch();

            var deltas = new List <decimal>();

            foreach (var m in testCases)
            {
                Matrix3x3 testCase = m;

                for (int i = 0; i < 10000; i++)
                {
                    FloatMatrix3x3 floatMatrix = MathConverter.Convert(testCase);
                    FloatMatrix3x3 expected;
                    swf.Start();
                    FloatMatrix3x3.AdaptiveInvert(ref floatMatrix, out expected);
                    swf.Stop();


                    Matrix3x3 actual;
                    swd.Start();
                    Matrix3x3.AdaptiveInvert(ref testCase, out actual);
                    swd.Stop();

                    foreach (decimal delta in GetDeltas(expected, actual))
                    {
                        deltas.Add(delta);
                    }
                }
            }
            output.WriteLine("Max error: {0} ({1} times precision)", deltas.Max(), deltas.Max() / Fix64.Precision);
            output.WriteLine("Average precision: {0} ({1} times precision)", deltas.Average(), deltas.Average() / Fix64.Precision);
            output.WriteLine("Fix64.AdaptiveInvert time = {0}ms, float.AdaptiveInvert time = {1}ms", swf.ElapsedMilliseconds, swd.ElapsedMilliseconds);
        }
        /// <summary>
        /// Draws the display object.
        /// </summary>
        /// <param name="viewMatrix">Current view matrix.</param>
        /// <param name="projectionMatrix">Current projection matrix.</param>
        public override void Draw(Matrix viewMatrix, Matrix projectionMatrix)
        {
            //This is not a particularly fast method of drawing.
            //It's used very rarely in the demos.
            model.CopyAbsoluteBoneTransformsTo(transforms);
            for (int i = 0; i < Model.Meshes.Count; i++)
            {
                for (int j = 0; j < Model.Meshes[i].Effects.Count; j++)
                {
                    var effect = Model.Meshes[i].Effects[j] as BasicEffect;
                    if (effect != null)
                    {
                        effect.World             = transforms[Model.Meshes[i].ParentBone.Index] * MathConverter.Convert(WorldTransform);
                        effect.View              = MathConverter.Convert(viewMatrix);
                        effect.Projection        = MathConverter.Convert(projectionMatrix);
                        effect.AmbientLightColor = Color;

                        if (Texture != null)
                        {
                            effect.TextureEnabled = true;
                            effect.Texture        = Texture;
                        }
                        else
                        {
                            effect.TextureEnabled = false;
                        }
                    }
                }
                Model.Meshes[i].Draw();
            }
        }
Esempio n. 29
0
        /// <summary>
        /// Constructs a new demo.
        /// </summary>
        /// <param name="game">Game owning this demo.</param>
        public BroadPhaseRemovalTestDemo(DemosGame game)
            : base(game)
        {
            Entity toAdd;
            //BoundingBox box = new BoundingBox(new Vector3(-5, 1, 1), new Vector3(5, 7, 7));
            BoundingBox box = new BoundingBox(new Vector3(-500, -500, -500), new Vector3(500, 500, 500));

            DynamicHierarchy dh = new DynamicHierarchy();

            Random rand = new Random(0);

            RawList <Entity> entities = new RawList <Entity>();

            for (int k = 0; k < 1000; k++)
            {
                Vector3 position = new Vector3((float)(rand.NextDouble() * (box.Max.X - box.Min.X) + box.Min.X),
                                               (float)(rand.NextDouble() * (box.Max.Y - box.Min.Y) + box.Min.Y),
                                               (float)(rand.NextDouble() * (box.Max.Z - box.Min.Z) + box.Min.Z));
                toAdd = new Box(MathConverter.Convert(position), 1, 1, 1, 1);

                entities.Add(toAdd);
            }

            testResults = new double[2];
            int runCount = 10;

            for (int k = 0; k < runCount; k++)
            {
                for (int i = 0; i < entities.Count; i++)
                {
                    dh.Add(entities[i].CollisionInformation);
                }

                long start = Stopwatch.GetTimestamp();
                for (int i = 0; i < entities.Count; i++)
                {
                    //dh.RemoveFast(entities[i].CollisionInformation);
                }
                long end = Stopwatch.GetTimestamp();
                testResults[0] += (end - start) / (double)Stopwatch.Frequency;



                for (int i = 0; i < entities.Count; i++)
                {
                    dh.Add(entities[i].CollisionInformation);
                }

                start = Stopwatch.GetTimestamp();
                for (int i = 0; i < entities.Count; i++)
                {
                    //dh.RemoveBrute(entities[i].CollisionInformation);
                }
                end             = Stopwatch.GetTimestamp();
                testResults[1] += (end - start) / (double)Stopwatch.Frequency;
            }
            testResults[0] /= runCount;
            testResults[1] /= runCount;
        }
Esempio n. 30
0
        public override void Draw(GameTime gameTime)
        {
            //Notice that the entity's worldTransform property is being accessed here.
            //This property is returns a rigid transformation representing the orientation
            //and translation of the entity combined.
            //There are a variety of properties available in the entity, try looking around
            //in the list to familiarize yourself with it.

            Matrix worldMatrix = MathConverter.Convert(Transform * entity.WorldTransform);

            foreach (ModelMesh m in model.Meshes)
            {
                foreach (Effect e in m.Effects)
                {
                    if (false) //hideClouds)
                    {
                        e.CurrentTechnique = e.Techniques["EarthWithoutClouds"];
                    }
                    else
                    {
                        e.CurrentTechnique = e.Techniques["EarthWithClouds"];
                        e.Parameters["cloudStrength"].SetValue(cloudStrength);
                    }

                    e.Parameters["world"].SetValue(worldMatrix);
                    e.Parameters["view"].SetValue(((SpaceSimGame)this.Game).camera.View);
                    e.Parameters["projection"].SetValue(((SpaceSimGame)this.Game).camera.Projection);
                    e.Parameters["cameraPos"].SetValue(new Vector4(((SpaceSimGame)this.Game).camera.Position, 1.0f));
                    e.Parameters["globalAmbient"].SetValue(globalAmbient);
                    e.Parameters["lightDir"].SetValue(sunlight.direction);
                    e.Parameters["lightColor"].SetValue(sunlight.color);
                    e.Parameters["materialAmbient"].SetValue(ambient);
                    e.Parameters["materialDiffuse"].SetValue(diffuse);
                    e.Parameters["materialSpecular"].SetValue(specular);
                    e.Parameters["materialShininess"].SetValue(shininess);
                    e.Parameters["landOceanColorGlossMap"].SetValue(dayTexture);
                    e.Parameters["cloudColorMap"].SetValue(cloudTexture);
                    e.Parameters["nightColorMap"].SetValue(nightTexture);
                    e.Parameters["normalMap"].SetValue(normalMapTexture);
                }

                m.Draw();
            }

            /*
             * model.CopyAbsoluteBoneTransformsTo(boneTransforms);
             * foreach (ModelMesh mesh in model.Meshes)
             * {
             *  foreach (BasicEffect effect in mesh.Effects)
             *  {
             *      effect.World = boneTransforms[mesh.ParentBone.Index] * worldMatrix;
             *      effect.View = SpaceSimGame.camera.View;
             *      effect.Projection = SpaceSimGame.camera.Projection;
             *  }
             *  mesh.Draw();
             * }
             */
            base.Draw(gameTime);
        }