示例#1
0
        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            float dt = (float)gameTime.ElapsedGameTime.TotalSeconds;

            KeyboardState = Keyboard.GetState();
            MouseState    = Mouse.GetState();
            // Allows the game to exit
            if (KeyboardState.IsKeyDown(Keys.Escape))
            {
                this.Exit();
                return;
            }

            Camera.Update(dt);


            if (MouseState.LeftButton == ButtonState.Pressed)
            {
                Box toAdd = new Box(Camera.Position, 1, 1, 1, 1);
                toAdd.LinearVelocity = Camera.WorldMatrix.Forward * 10;
                Space.Add(toAdd);

                ModelDrawer.Add(toAdd);
            }

            Space.Update();
            ModelDrawer.Update();

            base.Update(gameTime);
        }
示例#2
0
        public void Submit(BEPUCollisionMove bepuCollisionMove)
        {
            if (ModelDrawer.Contains(bepuCollisionMove.SpaceObject))
            {
                return;
            }

            ModelDrawer.Add(bepuCollisionMove.SpaceObject);
        }
示例#3
0
        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            //Set up drawers
            ModelDrawer = new InstancedModelDrawer(this);

            //Create the space itself
            Space = new Space();

            var parallelLooper = new ParallelLooper();

            //This section lets the engine know that it can make use of multithreaded systems
            //by adding threads to its thread pool.
            if (Environment.ProcessorCount > 1)
            {
                for (int i = 0; i < Environment.ProcessorCount; i++)
                {
                    parallelLooper.AddThread();
                }
            }

            Space = new Space(parallelLooper);

            Space.ForceUpdater.Gravity = new Vector3(0, -9.81f, 0);
            Space.Add(new Box(Vector3.Zero, 30, 1, 30));

            //Create a bunch of boxes randomly.

            Random      random      = new Random();
            int         boxCount    = 100;
            BoundingBox spawnVolume = new BoundingBox(new Vector3(-10, 10, -10), new Vector3(10, 30, 10));

            for (int i = 0; i < boxCount; i++)
            {
                Vector3 position = new Vector3((float)(random.NextDouble() - 0.5f) * (spawnVolume.Max.X - spawnVolume.Min.X),
                                               (float)(random.NextDouble() - 0.5f) * (spawnVolume.Max.Y - spawnVolume.Min.Y),
                                               (float)(random.NextDouble() - 0.5f) * (spawnVolume.Max.Z - spawnVolume.Min.Z)) +
                                   (spawnVolume.Min + spawnVolume.Max) / 2;
                Space.Add(new Box(position, 1, 1, 1, 1));
            }


            #region DisplayObject creation
            foreach (Entity e in Space.Entities)
            {
                if ((string)e.Tag != "noDisplayObject")
                {
                    ModelDrawer.Add(e);
                }
                else//Remove the now unnecessary tag.
                {
                    e.Tag = null;
                }
            }
            #endregion
        }
        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            //Set up drawers
            modelDrawer = new InstancedModelDrawer(this);


            //Create the space and tell it that it should keep track of buffered states.  This will let the
            //positions/orientations of entities be interpolated, producing a cleaner appearance.
            Space = new Space();
            Space.BufferedStates.Enabled = true;


            Space.ForceUpdater.Gravity = new Vector3(0, -9.81f, 0);
            Space.Add(new Box(Vector3.Zero, 30, 1, 30));  //Make the ground

            //Create a bunch of boxes randomly.

            Random random      = new Random();
            int    boxCount    = 50;
            var    spawnVolume = new BoundingBox(new Vector3(-5, 15, -5), new Vector3(5, 25, 5));

            for (int i = 0; i < boxCount; i++)
            {
                var position = new Vector3((float)(random.NextDouble() - 0.5f) * (spawnVolume.Max.X - spawnVolume.Min.X),
                                           (float)(random.NextDouble() - 0.5f) * (spawnVolume.Max.Y - spawnVolume.Min.Y),
                                           (float)(random.NextDouble() - 0.5f) * (spawnVolume.Max.Z - spawnVolume.Min.Z)) +
                               (spawnVolume.Min + spawnVolume.Max) / 2;
                Space.Add(new Box(position, 1, 1, 1, 1));
            }


            //Start up the physics loop.
            physicsThread = new Thread(PhysicsLoop);
            physicsThread.IsBackground = true;
            physicsThread.Start();

            #region DisplayObject creation
            foreach (Entity e in Space.Entities)
            {
                if ((string)e.Tag != "noDisplayObject")
                {
                    modelDrawer.Add(e);
                }
                else//Remove the now unnecessary tag.
                {
                    e.Tag = null;
                }
            }
            #endregion
        }
        void FillSpace(Space space, ModelDrawer modelDrawer = null)
        {
            Entity ground = new MorphableEntity(new BoxShape(50, 1, 50));

            space.Add(ground);
            space.ForceUpdater.Gravity = new Vector3(0, -10, 0);

            ModelDataExtractor.GetVerticesAndIndicesFromModel(Game.Content.Load <Model>("playground"), out Vector3[] vertices, out int[] indices);
            var mesh = new StaticMesh(vertices, indices, new AffineTransform(new Vector3(50, -20, 0)));

            space.Add(mesh);
            modelDrawer?.Add(mesh);

            for (int i = 0; i < 100; i++)
            {
                Entity e = new Box(new Vector3(.1f * i, 1 * i + 1, 0), 1, 1, 1, 1);
                //Entity e = new Capsule(new Vector3(.1f * i, 1 * i + 1, 0), .5f, .5f, 1);
                //Entity e = new Sphere(new Vector3(.1f * i, 1 * i + 1, 0), .5f, 1);
                e.ActivityInformation.IsAlwaysActive = true;
                e.CollisionInformation.Tag           = i;
                space.Add(e);
            }
            for (int i = 0; i < 200; i++)
            {
                //Entity e = new Box(new Vector3(.1f * i, 1 * i + 1, 2), 1, 1, 1, 1);
                Entity e = new Capsule(new Vector3(.1f * i, 1 * i + 1, 2), .5f, .5f, 1);
                //Entity e = new Sphere(new Vector3(.1f * i, 1 * i + 1, 2), .5f, 1);
                e.ActivityInformation.IsAlwaysActive = true;
                e.CollisionInformation.Tag           = i;
                space.Add(e);
            }
            for (int i = 0; i < 300; i++)
            {
                //Entity e = new Box(new Vector3(.1f * i, 1 * i + 1, 4), 1, 1, 1, 1);
                //Entity e = new Capsule(new Vector3(.1f * i, 1 * i + 1, 4), .5f, .5f, 1);
                Entity e = new Sphere(new Vector3(.1f * i, 1 * i + 1, 4), .5f, 1);
                e.ActivityInformation.IsAlwaysActive = true;
                e.CollisionInformation.Tag           = i;
                space.Add(e);
            }
            if (modelDrawer != null)
            {
                for (int i = 0; i < space.Entities.Count; ++i)
                {
                    modelDrawer.Add(space.Entities[i]);
                }
            }
        }
示例#6
0
        /// <summary>
        /// Manages the switch to a new physics engine simulation.
        /// </summary>
        /// <param name="sim">Index of the simulation to switch to.</param>
        public void SwitchSimulation(int sim)
        {
            currentSimulationIndex = sim;

            //Clear out any old rendering stuff.
            ModelDrawer.Clear();
            ConstraintDrawer.Clear();

            //Tell the previous simulation it's done.
            if (currentSimulation != null)
            {
                currentSimulation.CleanUp();
            }
            //Create the new demo.
            Type demoType = demoTypes[currentSimulationIndex - 1];

#if !WINDOWS
            currentSimulation = (Demo)demoType.GetConstructor(new[] { typeof(DemosGame) }).Invoke(new object[] { this });
#else
            currentSimulation = (Demo)Activator.CreateInstance(demoType, new object[] { this });
#endif
            #region DisplayObject creation

            foreach (Entity e in currentSimulation.Space.Entities)
            {
                if ((string)e.Tag != "noDisplayObject")
                {
                    ModelDrawer.Add(e);
                }
                else //Remove the now unnecessary tag.
                {
                    e.Tag = null;
                }
            }
            for (int i = 0; i < currentSimulation.Space.Solver.SolverUpdateables.Count; i++)
            {
                //Add the solver updateable and match up the activity setting.
                LineDisplayObjectBase objectAdded = ConstraintDrawer.Add(currentSimulation.Space.Solver.SolverUpdateables[i]);
                if (objectAdded != null)
                {
                    objectAdded.IsDrawing = currentSimulation.Space.Solver.SolverUpdateables[i].IsActive;
                }
            }

            #endregion

            GC.Collect();
        }
        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            KeyboardState = Keyboard.GetState();
            MouseState    = Mouse.GetState();
            // Allows the game to exit
            if (KeyboardState.IsKeyDown(Keys.Escape))
            {
                this.Exit();
                return;
            }
            camera.Update((float)gameTime.ElapsedGameTime.TotalSeconds);


            //Calling Space.Add while it is possibly running is a no-no; it will interfere
            //with the update process and probably crash!  Instead, enqueue everything
            //to a thread-safe buffer which will be flushed in the physics loop.

            if (MouseState.LeftButton == ButtonState.Pressed)
            {
                Box toAdd = new Box(camera.Position, 1, 1, 1, 1);
                toAdd.LinearVelocity = camera.WorldMatrix.Forward * 10;
                Space.SpaceObjectBuffer.Add(toAdd);

                modelDrawer.Add(toAdd);
            }

            //Prevent the engine from flipping read buffers while we're reading data out of it.
            //It's a good idea to hold the LockerMotionStateBuffers as briefly as possible;
            //This will block if the engine tries to flip its internal buffers.
            //Technically, Space.BufferedStates.InterpolatedStates.GetStates() would
            //hold the lock more briefly, but this lock lets us use the BEPUphysicsDrawer
            //system without significant difficulty or modifications.
            lock (Space.BufferedStates.InterpolatedStates.FlipLocker)
            {
                modelDrawer.Update();
            }

            base.Update(gameTime);
        }
示例#8
0
        /// <summary>
        /// Constructs the front end and the internal physics representation of the vehicle.
        /// </summary>
        /// <param name="position">Position of the tank.</param>
        /// <param name="owningSpace">Space to add the vehicle to.</param>
        /// <param name="cameraToUse">Camera to attach to the vehicle.</param>
        /// <param name="drawer">Drawer used to draw the tank.</param>
        /// <param name="wheelModel">Model to use for the 'wheels' of the tank.</param>
        /// <param name="wheelTexture">Texture of the wheels on the tank.</param>
        public TankInput(Vector3 position, Space owningSpace, Camera cameraToUse, ModelDrawer drawer, Model wheelModel, Texture2D wheelTexture)
        {
            var bodies = new List <CompoundShapeEntry>()
            {
                new CompoundShapeEntry(new BoxShape(4f, 1, 8), new Vector3(0, 0, 0), 500),
                new CompoundShapeEntry(new BoxShape(3, .7f, 4f), new Vector3(0, .5f + .35f, .5f), 1)
            };
            var body = new CompoundBody(bodies, 501);

            body.CollisionInformation.LocalPosition = new Vector3(0, -.5f, 0);
            body.Position = (position); //At first, just keep it out of the way.
            Vehicle       = new Vehicle(body);

            #region RaycastWheelShapes

            //The wheel model used is not aligned initially with how a wheel would normally look, so rotate them.
            MaximumDriveForce   = 1800;
            BaseSlidingFriction = 7;
            Matrix wheelGraphicRotation = Matrix.CreateFromAxisAngle(Vector3.Forward, MathHelper.PiOver2);
            for (int i = 0; i < 6; i++)
            {
                var toAdd = new Wheel(
                    new RaycastWheelShape(.375f, wheelGraphicRotation),
                    new WheelSuspension(2000, 300f, Vector3.Down, 1.3f, new Vector3(-1.9f, 0, -2.9f + i * 1.15f)),
                    new WheelDrivingMotor(10, MaximumDriveForce, MaximumDriveForce),
                    new WheelBrake(BaseSlidingFriction, BaseSlidingFriction, 1.0f),
                    new WheelSlidingFriction(3.5f, 3.5f));
                Vehicle.AddWheel(toAdd);
                leftTrack.Add(toAdd);
            }
            for (int i = 0; i < 6; i++)
            {
                var toAdd = new Wheel(
                    new RaycastWheelShape(.375f, wheelGraphicRotation),
                    new WheelSuspension(2000, 300f, Vector3.Down, 1.3f, new Vector3(1.9f, 0, -2.9f + i * 1.15f)),
                    new WheelDrivingMotor(10, 2000, 1000),
                    new WheelBrake(BaseSlidingFriction, BaseSlidingFriction, 1.0f),
                    new WheelSlidingFriction(3.5f, 3.5f));
                Vehicle.AddWheel(toAdd);
                rightTrack.Add(toAdd);
            }

            #endregion

            foreach (Wheel wheel in Vehicle.Wheels)
            {
                //This is a cosmetic setting that makes it looks like the car doesn't have antilock brakes.
                wheel.Shape.FreezeWheelsWhileBraking = true;

                //By default, wheels use as many iterations as the space.  By lowering it,
                //performance can be improved at the cost of a little accuracy.
                wheel.Suspension.SolverSettings.MaximumIterations      = 1;
                wheel.Brake.SolverSettings.MaximumIterations           = 1;
                wheel.SlidingFriction.SolverSettings.MaximumIterations = 1;
                wheel.DrivingMotor.SolverSettings.MaximumIterations    = 1;
            }

            Space = owningSpace;

            Space.Add(Vehicle);
            ModelDrawer = drawer;
            DisplayModel model;
            WheelModels = new List <DisplayModel>();
            for (int k = 0; k < Vehicle.Wheels.Count; k++)
            {
                Vehicle.Wheels[k].Shape.Detector.Tag = "noDisplayObject";
                model = new DisplayModel(wheelModel, ModelDrawer);
                ModelDrawer.Add(model);
                WheelModels.Add(model);
                model.Texture = wheelTexture;
            }


            Camera = cameraToUse;
        }
示例#9
0
        /// <summary>
        /// Constructs the front end and the internal physics representation of the Vehicle.
        /// </summary>
        /// <param name="position">Position of the Vehicle.</param>
        /// <param name="space">Space to add the Vehicle to.</param>
        /// <param name="camera">Camera to attach to the Vehicle.</param>
        /// <param name="game">The running game.</param>
        /// <param name="drawer">Drawer used to draw the Vehicle.</param>
        /// <param name="wheelModel">Model of the wheels.</param>
        /// <param name="wheelTexture">Texture to use for the wheels.</param>
        public VehicleInput(Vector3 position, Space space, Camera camera, DemosGame game, ModelDrawer drawer, Model wheelModel, Texture2D wheelTexture)
        {
            var bodies = new List <CompoundShapeEntry>
            {
                new CompoundShapeEntry(new BoxShape((Fix64)2.5m, (Fix64).75m, (Fix64)4.5m), new Vector3(0, 0, 0), 60),
                new CompoundShapeEntry(new BoxShape((Fix64)2.5m, (Fix64).3m, (Fix64)2f), new Vector3(0, (Fix64).75m / 2 + (Fix64).3m / 2, (Fix64).5m), 1)
            };
            var body = new CompoundBody(bodies, 61);

            body.CollisionInformation.LocalPosition = new Vector3(0, (Fix64).5m, 0);
            body.Position = position; //At first, just keep it out of the way.
            Vehicle       = new Vehicle(body);

            var localWheelRotation = Quaternion.CreateFromAxisAngle(new Vector3(0, 0, 1), MathHelper.PiOver2);

            //The wheel model used is not aligned initially with how a wheel would normally look, so rotate them.
            Matrix wheelGraphicRotation = Matrix.CreateFromAxisAngle(Vector3.Forward, MathHelper.PiOver2);

            Vehicle.AddWheel(new Wheel(
                                 new CylinderCastWheelShape((Fix64).375m, (Fix64)0.2m, localWheelRotation, wheelGraphicRotation, false),
                                 new WheelSuspension(2000, 100, Vector3.Down, (Fix64)0.325m, new Vector3((Fix64)(-1.1m), (Fix64)(-0.1m), (Fix64)1.8m)),
                                 new WheelDrivingMotor((Fix64)2.5m, 30000, 10000),
                                 new WheelBrake((Fix64)1.5m, 2, (Fix64).02m),
                                 new WheelSlidingFriction(4, 5)));
            Vehicle.AddWheel(new Wheel(
                                 new CylinderCastWheelShape((Fix64).375m, (Fix64)0.2m, localWheelRotation, wheelGraphicRotation, false),
                                 new WheelSuspension(2000, 100, Vector3.Down, (Fix64)0.325m, new Vector3((Fix64)(-1.1m), (Fix64)(-0.1m), (Fix64)(-1.8m))),
                                 new WheelDrivingMotor((Fix64)2.5m, 30000, 10000),
                                 new WheelBrake((Fix64)1.5m, 2, (Fix64).02m),
                                 new WheelSlidingFriction(4, 5)));
            Vehicle.AddWheel(new Wheel(
                                 new CylinderCastWheelShape((Fix64).375m, (Fix64)0.2m, localWheelRotation, wheelGraphicRotation, false),
                                 new WheelSuspension(2000, 100, Vector3.Down, (Fix64)0.325m, new Vector3((Fix64)1.1m, (Fix64)(-0.1m), (Fix64)1.8m)),
                                 new WheelDrivingMotor((Fix64)2.5m, 30000, 10000),
                                 new WheelBrake((Fix64)1.5m, 2, (Fix64).02m),
                                 new WheelSlidingFriction(4, 5)));
            Vehicle.AddWheel(new Wheel(
                                 new CylinderCastWheelShape((Fix64).375m, (Fix64)0.2m, localWheelRotation, wheelGraphicRotation, false),
                                 new WheelSuspension(2000, 100, Vector3.Down, (Fix64)0.325m, new Vector3((Fix64)1.1m, (Fix64)(-0.1m), (Fix64)(-1.8m))),
                                 new WheelDrivingMotor((Fix64)2.5m, 30000, 10000),
                                 new WheelBrake((Fix64)1.5m, 2, (Fix64).02m),
                                 new WheelSlidingFriction(4, 5)));


            foreach (Wheel wheel in Vehicle.Wheels)
            {
                //This is a cosmetic setting that makes it looks like the car doesn't have antilock brakes.
                wheel.Shape.FreezeWheelsWhileBraking = true;

                //By default, wheels use as many iterations as the space.  By lowering it,
                //performance can be improved at the cost of a little accuracy.
                //However, because the suspension and friction are not really rigid,
                //the lowered accuracy is not so much of a problem.
                wheel.Suspension.SolverSettings.MaximumIterationCount      = 1;
                wheel.Brake.SolverSettings.MaximumIterationCount           = 1;
                wheel.SlidingFriction.SolverSettings.MaximumIterationCount = 1;
                wheel.DrivingMotor.SolverSettings.MaximumIterationCount    = 1;
            }

            Space = space;

            Space.Add(Vehicle);
            ModelDrawer = drawer;
            DisplayModel model;

            WheelModels = new List <DisplayModel>();
            for (int k = 0; k < 4; k++)
            {
                Vehicle.Wheels[k].Shape.Detector.Tag = "noDisplayObject";
                model = new DisplayModel(wheelModel, ModelDrawer);
                ModelDrawer.Add(model);
                WheelModels.Add(model);
                model.Texture = wheelTexture;
            }



            CameraControlScheme = new ChaseCameraControlScheme(Vehicle.Body, new Vector3(0, (Fix64)0.6m, 0), true, 10, camera, game);
        }
示例#10
0
        protected override void Update(GameTime gameTime)
        {
            Input.Get().Update();

            if (Input.Get().IsKeyDown(Keys.Escape, true))
            {
                _paused = !_paused;
            }

            if (Input.Get().IsKeyDown(Keys.F2, true))
            {
                _chunkManager.ChunkSystem.Renderer.ToggleDebugMode(ChunkRendererDebugOptions.DEBUG_DRAW_WIREFRAME);
                wireFrame = !wireFrame;
            }

            if (Input.Get().IsKeyDown(Keys.F3, true))
            {
                _chunkManager.ChunkSystem.Renderer.ToggleDebugMode(ChunkRendererDebugOptions.DEBUG_DRAW_NORMALS);
            }
            if (Input.Get().IsKeyDown(Keys.F4, true))
            {
                _chunkManager.ChunkSystem.Renderer.ToggleDebugMode(ChunkRendererDebugOptions.DEBUG_DRAW_RENDERTARGETS);
            }
            if (Input.Get().IsKeyDown(Keys.F5, true))
            {
                drawPhysics = !drawPhysics;
            }

            if (Input.Get().IsKeyDown(Keys.F5, true))
            {
                if (pickedPos != Vector3I.One * -1)
                {
                    Chunk c = _world.ChunkAt(pickedPos.X, pickedPos.Y, pickedPos.Z);

                    _chunkManager.EnqueueChunkForBuild(c);
                }
            }

            int centerX = GraphicsDevice.Viewport.Width / 2;
            int centerY = GraphicsDevice.Viewport.Height / 2;

            if (!_paused)
            {
                cam.Yaw   += -(Input.Get().MouseXCoordinate() - centerX) * cam.RotateSpeed;
                cam.Pitch += -(Input.Get().MouseYCoordinate() - centerY) * cam.RotateSpeed;

                Mouse.SetPosition(centerX, centerY);
            }

            Vector3 moveVector = Vector3.Zero;

            if (Input.Get().IsKeyDown(Keys.LeftControl, true))
            {
                cam.Position = new Vector3((int)cam.Position.X, (int)cam.Position.Y, (int)cam.Position.Z);
                cam.Yaw      = (int)(cam.Yaw / MathHelper.PiOver2) * MathHelper.PiOver2;
                cam.Pitch    = (int)(cam.Pitch / MathHelper.PiOver2) * MathHelper.PiOver2;
            }

            bool shouldBeNew = Input.Get().IsKeyDown(Keys.LeftControl);

            if (Input.Get().IsKeyDown(Keys.W, shouldBeNew))
            {
                moveVector += cam.Forward * 0.5f;
            }
            if (Input.Get().IsKeyDown(Keys.S, shouldBeNew))
            {
                moveVector -= cam.Forward * 0.5f;
            }
            if (Input.Get().IsKeyDown(Keys.D, shouldBeNew))
            {
                moveVector += cam.Right * 0.5f;
            }
            if (Input.Get().IsKeyDown(Keys.A, shouldBeNew))
            {
                moveVector -= cam.Right * 0.5f;
            }
            if (Input.Get().IsKeyDown(Keys.E, shouldBeNew))
            {
                moveVector += Vector3.Up * 0.5f;
            }
            if (Input.Get().IsKeyDown(Keys.Q, shouldBeNew))
            {
                moveVector -= Vector3.Up * 0.5f;
            }
            if (!Input.Get().IsKeyDown(Keys.Tab))
            {
                moveVector *= 0.125f;
            }

            moveVector *= (float)gameTime.ElapsedGameTime.TotalSeconds / (1f / 60f);

            float mult = 1 / 2048f * (float)gameTime.ElapsedGameTime.TotalSeconds / (1f / 1000f);

            if (Input.Get().IsKeyDown(Keys.LeftShift))
            {
                mult *= 2;
            }

            if (Input.Get().IsKeyDown(Keys.Right))
            {
                cam.Yaw -= MathHelper.Pi * mult;
            }
            if (Input.Get().IsKeyDown(Keys.Left))
            {
                cam.Yaw += MathHelper.Pi * mult;
            }
            if (Input.Get().IsKeyDown(Keys.Up))
            {
                cam.Pitch -= MathHelper.Pi * mult;
            }
            if (Input.Get().IsKeyDown(Keys.Down))
            {
                cam.Pitch += MathHelper.Pi * mult;
            }

            cam.Position += moveVector;

            cam.Update();

            pickedPos     = Vector3I.One * -1;
            sidePickedPos = Vector3I.One * -1;

            Vector3I lastEmptyBlock = new Vector3I((int)(cam.Position.X + 0.5f), (int)(cam.Position.Y + 0.5f), (int)(cam.Position.Z + 0.5f));

            // block picking
            for (float f = 0; f < 32f; f += 0.1f)
            {
                Vector3 pos = cam.Position + cam.Forward * f;

                int rx = (int)(pos.X + 0.5f);
                int ry = (int)(pos.Y + 0.5f);
                int rz = (int)(pos.Z + 0.5f);

                GridPoint gridPoint = _world.PointAt(rx, ry, rz);

                if (gridPoint.Density >= 0.0f)
                {
                    pickedPos     = new Vector3I(rx, ry, rz);
                    sidePickedPos = lastEmptyBlock;
                    break;
                }
                else
                {
                    lastEmptyBlock = new Vector3I(rx, ry, rz);
                }
            }

            if (pickedPos == Vector3I.One * -1)
            {
                sidePickedPos = pickedPos;
            }

            if ((timeout -= (float)gameTime.ElapsedGameTime.TotalSeconds) <= 0 && Input.Get().IsLeftMouseButtonDown() && pickedPos != Vector3I.One * -1)
            {
                int rx = pickedPos.X;
                int ry = pickedPos.Y;
                int rz = pickedPos.Z;

                GridPoint gridPoint = _world.PointAt(rx, ry, rz);

                if (gridPoint.Density >= 0.0f)
                {
                    pickedPos = new Vector3I(rx, ry, rz);

                    GridPoint selected = new GridPoint(gridPoint, (int)DualContouringMetadataIndex.Length);
                    // modify the normals and density
                    selected.Density = -1.0f;
                    // make the vectors point towards the point
                    selected.XPositiveNormal = new Vector3(-1, 0, 0);
                    selected.YPositiveNormal = new Vector3(0, -1, 0);
                    selected.ZPositiveNormal = new Vector3(0, 0, -1);

                    _world.SetPoint(rx, ry, rz, selected);

                    gridPoint = _world.PointAt(rx, ry - 1, rz);

                    if (gridPoint.Density >= 0)
                    {
                        selected                 = new GridPoint(gridPoint, (int)DualContouringMetadataIndex.Length);
                        selected.Density         = 1.0f;
                        selected.YPositiveNormal = new Vector3(0, 1, 0);

                        _world.SetPoint(rx, ry - 1, rz, selected);
                    }

                    gridPoint = _world.PointAt(rx - 1, ry, rz);

                    if (gridPoint.Density >= 0)
                    {
                        selected                 = new GridPoint(gridPoint, (int)DualContouringMetadataIndex.Length);
                        selected.Density         = 1.0f;
                        selected.XPositiveNormal = new Vector3(1, 0, 0);

                        _world.SetPoint(rx - 1, ry, rz, selected);
                    }

                    gridPoint = _world.PointAt(rx, ry, rz - 1);

                    if (gridPoint.Density >= 0)
                    {
                        selected                 = new GridPoint(gridPoint, (int)DualContouringMetadataIndex.Length);
                        selected.Density         = 1.0f;
                        selected.ZPositiveNormal = new Vector3(0, 0, 1);

                        _world.SetPoint(rx, ry, rz - 1, selected);
                    }

                    gridPoint = _world.PointAt(rx, ry, rz + 1);

                    if (gridPoint.Density >= 0)
                    {
                        selected         = new GridPoint(gridPoint, (int)DualContouringMetadataIndex.Length);
                        selected.Density = 1.0f;

                        _world.SetPoint(rx, ry, rz + 1, selected);
                    }

                    gridPoint = _world.PointAt(rx, ry + 1, rz);

                    if (gridPoint.Density >= 0)
                    {
                        selected         = new GridPoint(gridPoint, (int)DualContouringMetadataIndex.Length);
                        selected.Density = 1.0f;

                        _world.SetPoint(rx, ry + 1, rz, selected);
                    }

                    gridPoint = _world.PointAt(rx + 1, ry, rz);

                    if (gridPoint.Density >= 0)
                    {
                        selected         = new GridPoint(gridPoint, (int)DualContouringMetadataIndex.Length);
                        selected.Density = 1.0f;

                        _world.SetPoint(rx + 1, ry, rz, selected);
                    }

                    timeout = 0.2f;

                    if (Input.Get().IsKeyDown(Keys.Space))
                    {
                        timeout = 0.01f;
                    }
                }
            }

            if (timeout <= 0 && Input.Get().IsRightMouseButtonDown() && sidePickedPos != Vector3I.One * -1)
            {
                int rx = sidePickedPos.X;
                int ry = sidePickedPos.Y;
                int rz = sidePickedPos.Z;

                GridPoint gridPoint = _world.PointAt(rx, ry, rz);

                if (gridPoint.Density < 0.0f)
                {
                    pickedPos = new Vector3I(rx, ry, rz);

                    GridPoint selected = new GridPoint(gridPoint, (int)DualContouringMetadataIndex.Length);
                    // modify the normals and density
                    selected.Density = 1.0f;
                    // make the vectors point away from the point
                    selected.XPositiveNormal = new Vector3(1, 0, 0);
                    selected.YPositiveNormal = new Vector3(0, 1, 0);
                    selected.ZPositiveNormal = new Vector3(0, 0, 1);

                    _world.SetPoint(rx, ry, rz, selected);

                    gridPoint = _world.PointAt(rx, ry - 1, rz);

                    if (gridPoint.Density < 0)
                    {
                        selected                 = new GridPoint(gridPoint, (int)DualContouringMetadataIndex.Length);
                        selected.Density         = -1.0f;
                        selected.YPositiveNormal = new Vector3(0, -1, 0);

                        _world.SetPoint(rx, ry - 1, rz, selected);
                    }

                    gridPoint = _world.PointAt(rx - 1, ry, rz);

                    if (gridPoint.Density < 0)
                    {
                        selected                 = new GridPoint(gridPoint, (int)DualContouringMetadataIndex.Length);
                        selected.Density         = -1.0f;
                        selected.XPositiveNormal = new Vector3(-1, 0, 0);

                        _world.SetPoint(rx - 1, ry, rz, selected);
                    }

                    gridPoint = _world.PointAt(rx, ry, rz - 1);

                    if (gridPoint.Density < 0)
                    {
                        selected                 = new GridPoint(gridPoint, (int)DualContouringMetadataIndex.Length);
                        selected.Density         = -1.0f;
                        selected.ZPositiveNormal = new Vector3(0, 0, -1);

                        _world.SetPoint(rx, ry, rz - 1, selected);
                    }

                    gridPoint = _world.PointAt(rx, ry, rz + 1);

                    if (gridPoint.Density < 0)
                    {
                        selected         = new GridPoint(gridPoint, (int)DualContouringMetadataIndex.Length);
                        selected.Density = -1.0f;

                        _world.SetPoint(rx, ry, rz + 1, selected);
                    }

                    gridPoint = _world.PointAt(rx, ry + 1, rz);

                    if (gridPoint.Density < 0)
                    {
                        selected         = new GridPoint(gridPoint, (int)DualContouringMetadataIndex.Length);
                        selected.Density = -1.0f;

                        _world.SetPoint(rx, ry + 1, rz, selected);
                    }

                    gridPoint = _world.PointAt(rx + 1, ry, rz);

                    if (gridPoint.Density < 0)
                    {
                        selected         = new GridPoint(gridPoint, (int)DualContouringMetadataIndex.Length);
                        selected.Density = -1.0f;

                        _world.SetPoint(rx + 1, ry, rz, selected);
                    }

                    timeout = 0.2f;

                    if (Input.Get().IsKeyDown(Keys.Space))
                    {
                        timeout = 0.01f;
                    }
                }
            }

            if (Input.Get().IsKeyDown(Keys.B, true))
            {
                Sphere sphere = new Sphere(MathConverter.Convert(cam.Position + cam.Forward * 2), 1.0f, 1);
                sphere.LinearVelocity = MathConverter.Convert(cam.Forward * 5);

                lock (_physicsMutex)
                {
                    _space.Add(sphere);
                    modelDrawer.Add(sphere);
                }
            }

            _world.Update(gameTime);

            lock (_physicsMutex)
            {
                _space.Update();

                if (drawPhysics)
                {
                    modelDrawer.IsWireframe = wireFrame;
                    modelDrawer.Update();
                }
            }

            _fpsCounter.Update(gameTime);

            base.Update(gameTime);
        }
示例#11
0
 public DynamicVisualizer(LinearDynamic dynamic, ModelDrawer modelDrawer)
 {
     Dynamic           = dynamic;
     DisplayCollidable = new DisplayEntityCollidable(modelDrawer, new ConvexCollidable <BoxShape>(new BoxShape(0.5f, 0.5f, 0.5f)));
     modelDrawer.Add(DisplayCollidable);
 }
示例#12
0
        /// <summary>
        /// Constructs the front end and the internal physics representation of the Vehicle.
        /// </summary>
        /// <param name="position">Position of the Vehicle.</param>
        /// <param name="owningSpace">Space to add the Vehicle to.</param>
        /// <param name="cameraToUse">Camera to attach to the Vehicle.</param>
        /// <param name="drawer">Drawer used to draw the Vehicle.</param>
        /// <param name="wheelModel">Model of the wheels.</param>
        /// <param name="wheelTexture">Texture to use for the wheels.</param>
        public VehicleInput(Vector3 position, Space owningSpace, Camera cameraToUse, ModelDrawer drawer, Model wheelModel, Texture2D wheelTexture)
        {
            var bodies = new List <CompoundShapeEntry>()
            {
                new CompoundShapeEntry(new BoxShape(2.5f, .75f, 4.5f), new Vector3(0, 0, 0), 60),
                new CompoundShapeEntry(new BoxShape(2.5f, .3f, 2f), new Vector3(0, .75f / 2 + .3f / 2, .5f), 1)
            };
            var body = new CompoundBody(bodies, 61);

            body.CollisionInformation.LocalPosition = new Vector3(0, .5f, 0);
            body.Position = (position); //At first, just keep it out of the way.
            Vehicle       = new Vehicle(body);

            #region RaycastWheelShapes

            //The wheel model used is not aligned initially with how a wheel would normally look, so rotate them.
            Matrix wheelGraphicRotation = Matrix.CreateFromAxisAngle(Vector3.Forward, MathHelper.PiOver2);
            Vehicle.AddWheel(new Wheel(
                                 new RaycastWheelShape(.375f, wheelGraphicRotation),
                                 new WheelSuspension(2000, 100f, Vector3.Down, .8f, new Vector3(-1.1f, 0, 1.8f)),
                                 new WheelDrivingMotor(2.5f, 30000, 10000),
                                 new WheelBrake(1.5f, 2, .02f),
                                 new WheelSlidingFriction(4, 5)));
            Vehicle.AddWheel(new Wheel(
                                 new RaycastWheelShape(.375f, wheelGraphicRotation),
                                 new WheelSuspension(2000, 100f, Vector3.Down, .8f, new Vector3(-1.1f, 0, -1.8f)),
                                 new WheelDrivingMotor(2.5f, 30000, 10000),
                                 new WheelBrake(1.5f, 2, .02f),
                                 new WheelSlidingFriction(4, 5)));
            Vehicle.AddWheel(new Wheel(
                                 new RaycastWheelShape(.375f, wheelGraphicRotation),
                                 new WheelSuspension(2000, 100f, Vector3.Down, .8f, new Vector3(1.1f, 0, 1.8f)),
                                 new WheelDrivingMotor(2.5f, 30000, 10000),
                                 new WheelBrake(1.5f, 2, .02f),
                                 new WheelSlidingFriction(4, 5)));
            Vehicle.AddWheel(new Wheel(
                                 new RaycastWheelShape(.375f, wheelGraphicRotation),
                                 new WheelSuspension(2000, 100f, Vector3.Down, .8f, new Vector3(1.1f, 0, -1.8f)),
                                 new WheelDrivingMotor(2.5f, 30000, 10000),
                                 new WheelBrake(1.5f, 2, .02f),
                                 new WheelSlidingFriction(4, 5)));

            #endregion


            foreach (Wheel wheel in Vehicle.Wheels)
            {
                //This is a cosmetic setting that makes it looks like the car doesn't have antilock brakes.
                wheel.Shape.FreezeWheelsWhileBraking = true;

                //By default, wheels use as many iterations as the space.  By lowering it,
                //performance can be improved at the cost of a little accuracy.
                //However, because the suspension and friction are not really rigid,
                //the lowered accuracy is not so much of a problem.
                wheel.Suspension.SolverSettings.MaximumIterations      = 1;
                wheel.Brake.SolverSettings.MaximumIterations           = 1;
                wheel.SlidingFriction.SolverSettings.MaximumIterations = 1;
                wheel.DrivingMotor.SolverSettings.MaximumIterations    = 1;
            }

            Space = owningSpace;

            Space.Add(Vehicle);
            ModelDrawer = drawer;
            DisplayModel model;
            WheelModels = new List <DisplayModel>();
            for (int k = 0; k < 4; k++)
            {
                Vehicle.Wheels[k].Shape.Detector.Tag = "noDisplayObject";
                model = new DisplayModel(wheelModel, ModelDrawer);
                ModelDrawer.Add(model);
                WheelModels.Add(model);
                model.Texture = wheelTexture;
            }


            Camera = cameraToUse;
        }