Exemplo n.º 1
0
        public unsafe override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(0, 10, 40);
            camera.Yaw      = 0;
            camera.Pitch    = 0;
            Simulation      = Simulation.Create(BufferPool, new DemoNarrowPhaseCallbacks(), new DemoPoseIntegratorCallbacks(new Vector3(0, -10, 0)), new PositionFirstTimestepper());

            var box     = new Box(2f, 2f, 2f);
            var capsule = new Capsule(1f, 1f);
            var sphere  = new Sphere(1.5f);

            box.ComputeInertia(1, out var boxInertia);
            capsule.ComputeInertia(1, out var capsuleInertia);
            sphere.ComputeInertia(1, out var sphereInertia);
            var       boxIndex     = Simulation.Shapes.Add(box);
            var       capsuleIndex = Simulation.Shapes.Add(capsule);
            var       sphereIndex  = Simulation.Shapes.Add(sphere);
            const int width        = 12;
            const int height       = 3;
            const int length       = 12;

            for (int i = 0; i < width; ++i)
            {
                for (int j = 0; j < height; ++j)
                {
                    for (int k = 0; k < length; ++k)
                    {
                        var location = new Vector3(5, 5, 5) * new Vector3(i, j, k) + new Vector3(-width * 2.5f, 2.5f, -length * 2.5f);
                        //CreateKinematic is just a helper function that sets the inertia to all zeroes. We'll set the inertia to the actual value in the following switch.
                        var bodyDescription = BodyDescription.CreateKinematic(location, new CollidableDescription(default, 0.1f), new BodyActivityDescription(0.1f));
Exemplo n.º 2
0
        private PhyObject CreateSphere(SphereState state)
        {
            var sphere = new Sphere(state.radius);
            CollidableDescription collidableDescription = new CollidableDescription(Simulation.Shapes.Add(sphere), 0.1f);
            BodyInertia           bodyInertia;

            sphere.ComputeInertia(state.mass, out bodyInertia);

            var phy = CreateVanilla(state, collidableDescription, bodyInertia);

            return(phy);
        }
Exemplo n.º 3
0
        public unsafe override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(-30, 40, -30);
            camera.Yaw      = MathHelper.Pi * 3f / 4;
            camera.Pitch    = MathHelper.Pi * 0.2f;

            //The PositionFirstTimestepper is the simplest timestepping mode, but since it integrates velocity into position at the start of the frame, directly modified velocities outside of the timestep
            //will be integrated before collision detection or the solver has a chance to intervene. That's fine in this demo. Other built-in options include the PositionLastTimestepper and the SubsteppingTimestepper.
            //Note that the timestepper also has callbacks that you can use for executing logic between processing stages, like BeforeCollisionDetection.
            Simulation = Simulation.Create(BufferPool, new DemoNarrowPhaseCallbacks(), new DemoPoseIntegratorCallbacks(new Vector3(0, -10, 0)), new PositionFirstTimestepper());

            var ringBoxShape = new Box(0.5f, 1, 3);

            ringBoxShape.ComputeInertia(1, out var ringBoxInertia);
            var boxDescription = BodyDescription.CreateDynamic(new Vector3(), ringBoxInertia,
                                                               new CollidableDescription(Simulation.Shapes.Add(ringBoxShape), 0.1f),
                                                               new BodyActivityDescription(0.01f));

            var       layerPosition     = new Vector3();
            const int layerCount        = 6;
            var       innerRadius       = 15f;
            var       heightPerPlatform = 3;
            var       platformsPerLayer = 1;
            var       ringSpacing       = 0.5f;

            for (int layerIndex = 0; layerIndex < layerCount; ++layerIndex)
            {
                var ringCount = layerCount - layerIndex;
                for (int ringIndex = 0; ringIndex < ringCount; ++ringIndex)
                {
                    CreateRing(Simulation, layerPosition, ringBoxShape, boxDescription, innerRadius + ringIndex * (ringBoxShape.Length + ringSpacing) + layerIndex * (ringBoxShape.Length - ringBoxShape.Width), heightPerPlatform, platformsPerLayer);
                }
                layerPosition.Y += platformsPerLayer * (ringBoxShape.Height * heightPerPlatform + ringBoxShape.Width);
            }

            //Console.WriteLine($"box count: {Simulation.Bodies.ActiveSet.Count}");
            Simulation.Statics.Add(new StaticDescription(new Vector3(0, -0.5f, 0), new CollidableDescription(Simulation.Shapes.Add(new Box(500, 1, 500)), 0.1f)));

            var bulletShape = new Sphere(0.5f);

            bulletShape.ComputeInertia(.1f, out var bulletInertia);
            bulletDescription = BodyDescription.CreateDynamic(new Vector3(), bulletInertia, new CollidableDescription(Simulation.Shapes.Add(bulletShape), 10), new BodyActivityDescription(0.01f));

            var shootiePatootieShape = new Sphere(3f);

            shootiePatootieShape.ComputeInertia(100, out var shootiePatootieInertia);
            shootiePatootieDescription = BodyDescription.CreateDynamic(new Vector3(), shootiePatootieInertia, new CollidableDescription(Simulation.Shapes.Add(shootiePatootieShape), 10), new BodyActivityDescription(0.01f));
        }
Exemplo n.º 4
0
        public unsafe override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(-30, 40, -30);
            camera.Yaw      = MathHelper.Pi * 3f / 4;
            camera.Pitch    = MathHelper.Pi * 0.2f;

            characters = new CharacterControllers(BufferPool);
            Simulation = Simulation.Create(BufferPool, new CharacterNarrowphaseCallbacks(characters), new DemoPoseIntegratorCallbacks(new Vector3(0, -10, 0)));

            var ringBoxShape = new Box(0.5f, 1.5f, 3);

            ringBoxShape.ComputeInertia(1, out var ringBoxInertia);
            var boxDescription = BodyDescription.CreateDynamic(new Vector3(), ringBoxInertia,
                                                               new CollidableDescription(Simulation.Shapes.Add(ringBoxShape), 0.1f),
                                                               new BodyActivityDescription(0.01f));

            var       layerPosition     = new Vector3();
            const int layerCount        = 10;
            var       innerRadius       = 5f;
            var       heightPerPlatform = 2;
            var       platformsPerLayer = 1;
            var       ringSpacing       = 0.5f;

            for (int layerIndex = 0; layerIndex < layerCount; ++layerIndex)
            {
                var ringCount = layerCount - layerIndex;
                for (int ringIndex = 0; ringIndex < ringCount; ++ringIndex)
                {
                    CreateRing(layerPosition, ringBoxShape, boxDescription, innerRadius + ringIndex * (ringBoxShape.Length + ringSpacing) + layerIndex * (ringBoxShape.Length - ringBoxShape.Width), heightPerPlatform, platformsPerLayer);
                }
                layerPosition.Y += platformsPerLayer * (ringBoxShape.Height * heightPerPlatform + ringBoxShape.Width);
            }

            Console.WriteLine($"box count: {Simulation.Bodies.ActiveSet.Count}");
            Simulation.Statics.Add(new StaticDescription(new Vector3(0, -0.5f, 0), new CollidableDescription(Simulation.Shapes.Add(new Box(500, 1, 500)), 0.1f)));

            var bulletShape = new Sphere(0.5f);

            bulletShape.ComputeInertia(.1f, out var bulletInertia);
            bulletDescription = BodyDescription.CreateDynamic(new Vector3(), bulletInertia, new CollidableDescription(Simulation.Shapes.Add(bulletShape), 10), new BodyActivityDescription(0.01f));

            var shootiePatootieShape = new Sphere(3f);

            shootiePatootieShape.ComputeInertia(1000, out var shootiePatootieInertia);
            shootiePatootieDescription = BodyDescription.CreateDynamic(new Vector3(), shootiePatootieInertia, new CollidableDescription(Simulation.Shapes.Add(shootiePatootieShape), 10), new BodyActivityDescription(0.01f));
        }
        static int AddDynamicBody(Simulation simulation, System.Numerics.Vector3 position, BepuUtilities.Quaternion rotation, object shapeType, float mass)
        {
            switch (shapeType)
            {
            case IBoxDetection boxDetection:
                IBoxDetection box      = shapeType as IBoxDetection;
                var           boxShape = new Box(box.GetSize().x, box.GetSize().y, box.GetSize().z);
                boxShape.ComputeInertia(mass, out var boxInertia);
                var boxIndex  = simulation.Shapes.Add(boxShape);
                var boxPose   = new RigidPose(position, rotation);
                var boxHandle = simulation.Bodies.Add(BodyDescription.CreateDynamic(boxPose,
                                                                                    boxInertia,
                                                                                    new CollidableDescription(boxIndex, 0.01f),
                                                                                    new BodyActivityDescription(0.01f)));
                return(boxHandle);

            case ISphereDetection sphereDetection:
                ISphereDetection sphere = shapeType as ISphereDetection;
                var sphereShape         = new Sphere(sphere.GetRadius());
                sphereShape.ComputeInertia(mass, out var sphereInertia);
                var sphereIndex  = simulation.Shapes.Add(sphereShape);
                var spherePose   = new RigidPose(position, rotation);
                var sphereHandle = simulation.Bodies.Add(BodyDescription.CreateDynamic(spherePose,
                                                                                       sphereInertia,
                                                                                       new CollidableDescription(sphereIndex, 0.01f),
                                                                                       new BodyActivityDescription(0.01f)));
                return(sphereHandle);

            case ICapsuleDetection capsuleDetection:
                ICapsuleDetection capsule = shapeType as ICapsuleDetection;
                var capsuleShape          = new Capsule(capsule.GetRadius(), capsule.GetHeight());
                capsuleShape.ComputeInertia(mass, out var capsuleInertia);
                var capsuleIndex  = simulation.Shapes.Add(capsuleShape);
                var capsulePose   = new RigidPose(position, rotation);
                var capsuleHandle = simulation.Bodies.Add(BodyDescription.CreateDynamic(capsulePose,
                                                                                        capsuleInertia,
                                                                                        new CollidableDescription(capsuleIndex, 0.01f),
                                                                                        new BodyActivityDescription(0.01f)));
                return(capsuleHandle);

            default:
                throw new ArgumentException(message: CouldNotInitializeMessage, nameof(shapeType));
            }
        }
Exemplo n.º 6
0
        public unsafe override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(-5f, 5.5f, 5f);
            camera.Yaw      = MathHelper.Pi / 4;
            camera.Pitch    = MathHelper.Pi * 0.15f;

            var filters = new BodyProperty <DeformableCollisionFilter>();

            Simulation = Simulation.Create(BufferPool, new DeformableCallbacks {
                Filters = filters
            }, new DemoPoseIntegratorCallbacks(new Vector3(0, -10, 0)));

            var   meshContent = content.Load <MeshContent>("Content\\newt.obj");
            float cellSize    = 0.1f;

            DumbTetrahedralizer.Tetrahedralize(meshContent.Triangles, cellSize, BufferPool,
                                               out var vertices, out var vertexSpatialIndices, out var cellVertexIndices, out var tetrahedraVertexIndices);
            var weldSpringiness   = new SpringSettings(30f, 0);
            var volumeSpringiness = new SpringSettings(30f, 1);

            for (int i = 0; i < 5; ++i)
            {
                NewtDemo.CreateDeformable(Simulation, new Vector3(i * 3, 5 + i * 1.5f, 0), Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), MathF.PI * (i * 0.55f)), 1f, cellSize, weldSpringiness, volumeSpringiness, i, filters, ref vertices, ref vertexSpatialIndices, ref cellVertexIndices, ref tetrahedraVertexIndices);
            }

            BufferPool.Return(ref vertices);
            vertexSpatialIndices.Dispose(BufferPool);
            BufferPool.Return(ref cellVertexIndices);
            BufferPool.Return(ref tetrahedraVertexIndices);

            Simulation.Bodies.Add(BodyDescription.CreateConvexDynamic(new Vector3(0, 100, -.5f), 10, Simulation.Shapes, new Sphere(5)));

            Simulation.Statics.Add(new StaticDescription(new Vector3(0, -0.5f, 0), new CollidableDescription(Simulation.Shapes.Add(new Box(1500, 1, 1500)), 0.1f)));
            Simulation.Statics.Add(new StaticDescription(new Vector3(0, -1.5f, 0), new CollidableDescription(Simulation.Shapes.Add(new Sphere(3)), 0.1f)));

            var bulletShape = new Sphere(0.5f);

            bulletShape.ComputeInertia(.25f, out var bulletInertia);
            bulletDescription = BodyDescription.CreateDynamic(RigidPose.Identity, bulletInertia, new CollidableDescription(Simulation.Shapes.Add(bulletShape), 1f), new BodyActivityDescription(0.01f));

            DemoMeshHelper.LoadModel(content, BufferPool, "Content\\newt.obj", new Vector3(20), out var mesh);
            Simulation.Statics.Add(new StaticDescription(new Vector3(200, 0.5f, 120), Quaternion.CreateFromAxisAngle(Vector3.UnitY, -3 * MathHelper.PiOver4), new CollidableDescription(Simulation.Shapes.Add(mesh), 0.1f)));
        }
Exemplo n.º 7
0
        public PhysicsSystem()
        {
            //The buffer pool is a source of raw memory blobs for the engine to use.
            Pool        = new BufferPool();
            _characters = new CharacterControllers(Pool);
            //Note that you can also control the order of internal stage execution using a different ITimestepper implementation.
            //For the purposes of this demo, we just use the default by passing in nothing (which happens to be PositionFirstTimestepper at the time of writing).
            Simulation = Simulation.Create(Pool, new CharacterNarrowphaseCallbacks(_characters), new PoseIntegratorCallbacks(new Vector3(0, 0, 0)));

            //Drop a ball on a big static box.
            var sphere = new Sphere(1);

            sphere.ComputeInertia(1, out var sphereInertia);

            _threadDispatcher = new SimpleThreadDispatcher(Environment.ProcessorCount);

            _staticContexts  = new Dictionary <int, object>();
            _dynamicContexts = new Dictionary <int, object>();
            _shapeContexts   = new Dictionary <TypedIndex, object>();
        }
Exemplo n.º 8
0
        public unsafe override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(0, 40, 200);
            camera.Yaw      = 0;
            camera.Pitch    = 0;
            //This type of position-based bounciness requires feedback from position error to drive the corrective impulses that make stuff bounce.
            //The briefer a collision is, the more damped the bounce becomes relative to the physical ideal.
            //To counteract this, a substepping timestepper is used. In the demos, we update the simulation at 60hz, so a substep count of 4 means the solver and integrator will run at 240hz.
            //That allows higher stiffnesses to be used since collisions last longer relative to the solver timestep duration.
            //(Note that substepping tends to be an extremely strong simulation stabilizer, so you can usually get away with lower solver iteration counts for better performance.)
            var collidableMaterials = new CollidableProperty <SimpleMaterial>();

            Simulation = Simulation.Create(BufferPool, new BounceCallbacks()
            {
                CollidableMaterials = collidableMaterials
            }, new DemoPoseIntegratorCallbacks(new Vector3(0, -10, 0)), new SubsteppingTimestepper(4), solverIterationCount: 2);

            var shape = new Sphere(1);

            shape.ComputeInertia(1, out var inertia);
            var ballDescription = BodyDescription.CreateDynamic(RigidPose.Identity, inertia, new CollidableDescription(Simulation.Shapes.Add(shape), 20f), new BodyActivityDescription(1e-2f));

            for (int i = 0; i < 100; ++i)
            {
                for (int j = 0; j < 100; ++j)
                {
                    //We'll drop balls in a grid. From left to right, we increase stiffness, and from back to front (relative to the camera), we'll increase damping.
                    //Note that higher frequency values tend to result in smaller bounces even at 0 damping. This is not physically realistic; it's a byproduct of the solver timestep being too long to properly handle extremely brief contacts.
                    //(Try increasing the substep count above to higher values and watch how the bounce gets closer and closer to equal height across frequency values.)
                    ballDescription.Pose.Position = new Vector3(i * 3 - 99f * 3f / 2f, 100, j * 3 - 230);
                    collidableMaterials.Allocate(Simulation.Bodies.Add(ballDescription)) = new SimpleMaterial {
                        FrictionCoefficient = 1, MaximumRecoveryVelocity = float.MaxValue, SpringSettings = new SpringSettings(5 + 0.25f * i, j * j / 10000f)
                    };
                }
            }

            collidableMaterials.Allocate(Simulation.Statics.Add(new StaticDescription(new Vector3(0, -15f, 0), new CollidableDescription(Simulation.Shapes.Add(new Box(2500, 30, 2500)), 0.1f)))) =
                new SimpleMaterial {
                FrictionCoefficient = 1, MaximumRecoveryVelocity = 2, SpringSettings = new SpringSettings(30, 1)
            };
        }
Exemplo n.º 9
0
 public override void Update(Input input, float dt)
 {
     if (input.WasPushed(OpenTK.Input.Key.Q))
     {
         //Create the shape that we'll launch at the pyramids when the user presses a button.
         var bulletShape = new Sphere(0.5f + 5 * (float)random.NextDouble());
         //Note that this can produce some pretty serious mass ratios. Observe what happens when a large ball sits on top of a few boxes with a fraction of the mass-
         //the collision appears much squishier and less stable. For most games, if you want to maintain rigidity, you'll want to use some combination of:
         //1) Limit the ratio of heavy object masses to light object masses when those heavy objects depend on the light objects.
         //2) Use a greater number of solver iterations.
         //3) Use a shorter timestep duration and update more frequently.
         //#2 and #3 can become very expensive. In pathological cases, it can end up slower than using a quality-focused solver for the same simulation.
         //Unfortunately, at the moment, bepuphysics v2 does not contain any alternative solvers, so if you can't afford to brute force the the problem away,
         //the best solution is to cheat as much as possible to avoid the corner cases.
         bulletShape.ComputeInertia(bulletShape.Radius * bulletShape.Radius * bulletShape.Radius, out var bulletInertia);
         var bulletShapeIndex = Simulation.Shapes.Add(bulletShape);
         var bodyDescription  = new BodyDescription
         {
             LocalInertia = bulletInertia,
             Pose         = new RigidPose
             {
                 Position    = new Vector3(0, 8, -130),
                 Orientation = BepuUtilities.Quaternion.Identity
             },
             Activity = new BodyActivityDescription {
                 MinimumTimestepCountUnderThreshold = 32, SleepThreshold = .01f
             },
             Collidable = new CollidableDescription {
                 Shape = bulletShapeIndex, SpeculativeMargin = .1f
             },
             Velocity = new BodyVelocity {
                 Linear = new Vector3(0, 0, 150)
             }
         };
         Simulation.Bodies.Add(bodyDescription);
     }
     base.Update(input, dt);
 }
Exemplo n.º 10
0
 public override void Update(Window window, Camera camera, Input input, float dt)
 {
     if (input != null && input.WasPushed(OpenTK.Input.Key.Z))
     {
         //Create the shape that we'll launch at the pyramids when the user presses a button.
         var bulletShape = new Sphere(0.5f + 5 * (float)random.NextDouble());
         //Note that the use of radius^3 for mass can produce some pretty serious mass ratios.
         //Observe what happens when a large ball sits on top of a few boxes with a fraction of the mass-
         //the collision appears much squishier and less stable. For most games, if you want to maintain rigidity, you'll want to use some combination of:
         //1) Limit the ratio of heavy object masses to light object masses when those heavy objects depend on the light objects.
         //2) Use a shorter timestep duration and update more frequently.
         //3) Use a greater number of solver iterations.
         //#2 and #3 can become very expensive. In pathological cases, it can end up slower than using a quality-focused solver for the same simulation.
         //Unfortunately, at the moment, bepuphysics v2 does not contain any alternative solvers, so if you can't afford to brute force the the problem away,
         //the best solution is to cheat as much as possible to avoid the corner cases.
         bulletShape.ComputeInertia(bulletShape.Radius * bulletShape.Radius * bulletShape.Radius, out var bulletInertia);
         var bulletShapeIndex = Simulation.Shapes.Add(bulletShape);
         var bodyDescription  = BodyDescription.CreateConvexDynamic(
             new Vector3(0, 8, -130), new BodyVelocity(new Vector3(0, 0, 150)), bulletShape.Radius * bulletShape.Radius * bulletShape.Radius, Simulation.Shapes, bulletShape);
         Simulation.Bodies.Add(bodyDescription);
     }
     base.Update(window, camera, input, dt);
 }
 public override void Update(Window window, Camera camera, Input input, float dt)
 {
     frameIndex++;
     if (frameIndex % 64 == 0)
     {
         var bulletShape = new Sphere(0.5f + 5 * (float)random.NextDouble());
         bulletShape.ComputeInertia(bulletShape.Radius * bulletShape.Radius * bulletShape.Radius, out var bulletInertia);
         var bulletShapeIndex = Simulation.Shapes.Add(bulletShape);
         var bodyDescription  = BodyDescription.CreateConvexDynamic(
             new Vector3(0, 8, -130), new BodyVelocity(new Vector3(0, 0, 350)), bulletShape.Radius * bulletShape.Radius * bulletShape.Radius, Simulation.Shapes, bulletShape);
         Simulation.Bodies.Add(bodyDescription);
     }
     if (frameIndex % 192 == 0)
     {
         Simulation.Dispose();
         BufferPool.Clear();
         for (int i = 0; i < ThreadDispatcher.ThreadCount; ++i)
         {
             ThreadDispatcher.GetThreadMemoryPool(i).Clear();
         }
         Initialize(null, camera);
     }
     base.Update(window, camera, input, dt);
 }
Exemplo n.º 12
0
        public unsafe override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(-10, 0, -10);
            //camera.Yaw = MathHelper.Pi ;
            camera.Yaw = MathHelper.Pi * 3f / 4;
            //camera.Pitch = MathHelper.PiOver2 * 0.999f;
            Simulation = Simulation.Create(BufferPool, new DemoNarrowPhaseCallbacks(), new DemoPoseIntegratorCallbacks(new Vector3(0, -10, 0)), new PositionFirstTimestepper());

            var box     = new Box(1f, 3f, 2f);
            var capsule = new Capsule(1f, 1f);
            var sphere  = new Sphere(1f);

            box.ComputeInertia(1, out var boxInertia);
            capsule.ComputeInertia(1, out var capsuleInertia);
            sphere.ComputeInertia(1, out var sphereInertia);
            var       boxIndex     = Simulation.Shapes.Add(box);
            var       capsuleIndex = Simulation.Shapes.Add(capsule);
            var       sphereIndex  = Simulation.Shapes.Add(sphere);
            const int width        = 16;
            const int height       = 3;
            const int length       = 16;

            for (int i = 0; i < width; ++i)
            {
                for (int j = 0; j < height; ++j)
                {
                    for (int k = 0; k < length; ++k)
                    {
                        var location        = new Vector3(5, 5, 5) * new Vector3(i, j, k);// + new Vector3(-width * 1.5f, 1.5f, -length * 1.5f);
                        var bodyDescription = new BodyDescription
                        {
                            Activity = new BodyActivityDescription {
                                MinimumTimestepCountUnderThreshold = 32, SleepThreshold = 0.01f
                            },
                            Pose = new RigidPose
                            {
                                Orientation = Quaternion.Identity,
                                Position    = location
                            },
                            Collidable = new CollidableDescription
                            {
                                Continuity = new ContinuousDetectionSettings {
                                    Mode = ContinuousDetectionMode.Discrete
                                },
                                SpeculativeMargin = 0.1f
                            }
                        };
                        switch ((i + j) % 3)
                        {
                        case 0:
                            bodyDescription.Collidable.Shape = sphereIndex;
                            bodyDescription.LocalInertia     = sphereInertia;
                            break;

                        case 1:
                            bodyDescription.Collidable.Shape = capsuleIndex;
                            bodyDescription.LocalInertia     = capsuleInertia;
                            break;

                        case 2:
                            bodyDescription.Collidable.Shape = boxIndex;
                            bodyDescription.LocalInertia     = boxInertia;
                            break;
                        }
                        Simulation.Bodies.Add(bodyDescription);
                    }
                }
            }

            //var testShape = new Box(50, 2, 0.2f);
            //testShape.ComputeInertia(1, out var testInertia);
            //Simulation.Bodies.Add(BodyDescription.CreateDynamic(new Vector3(10, 10, 10), testInertia, new CollidableDescription(Simulation.Shapes.Add(testShape), 10.1f), new BodyActivityDescription(-0.01f)));


            DemoMeshHelper.LoadModel(content, BufferPool, @"Content\newt.obj", new Vector3(5, 5, 5), out var newtMesh);
            newtMesh.ComputeClosedInertia(10, out var newtInertia, out _);
            Simulation.Bodies.Add(BodyDescription.CreateDynamic(new RigidPose(new Vector3(30, 20, 30)), newtInertia,
                                                                new CollidableDescription(Simulation.Shapes.Add(newtMesh), 0.1f), new BodyActivityDescription(0.01f)));

            Simulation.Statics.Add(new StaticDescription(new Vector3(30, 15, 30), new CollidableDescription(Simulation.Shapes.Add(new Box(15, 1, 15)), 0.1f)));

            DemoMeshHelper.LoadModel(content, BufferPool, @"Content\box.obj", new Vector3(5, 1, 5), out var boxMesh);
            Simulation.Statics.Add(new StaticDescription(new Vector3(10, 5, -20), new CollidableDescription(Simulation.Shapes.Add(boxMesh), 0.1f)));

            DemoMeshHelper.CreateFan(64, 16, new Vector3(1, 1, 1), BufferPool, out var fanMesh);
            Simulation.Statics.Add(new StaticDescription(new Vector3(-10, 0, -20), new CollidableDescription(Simulation.Shapes.Add(fanMesh), 0.1f)));

            const int planeWidth  = 128;
            const int planeHeight = 128;

            DemoMeshHelper.CreateDeformedPlane(planeWidth, planeHeight,
                                               (int x, int y) =>
            {
                return(new Vector3(x - planeWidth / 2, 1 * MathF.Cos(x / 2f) * MathF.Sin(y / 2f), y - planeHeight / 2));
            }, new Vector3(2, 1, 2), BufferPool, out var planeMesh);
            Simulation.Statics.Add(new StaticDescription(new Vector3(64, -10, 64), BepuUtilities.QuaternionEx.CreateFromAxisAngle(new Vector3(0, 1, 0), MathF.PI / 2),
                                                         new CollidableDescription(Simulation.Shapes.Add(planeMesh), 0.1f)));
        }
Exemplo n.º 13
0
 public void ComputeAnalyticInertia(float mass, out BodyInertia inertia)
 {
     Sphere.ComputeInertia(mass, out inertia);
 }
Exemplo n.º 14
0
        public unsafe override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(-20f, 13, -20f);
            camera.Yaw      = MathHelper.Pi * 3f / 4;
            camera.Pitch    = MathHelper.Pi * 0.1f;
            Simulation      = Simulation.Create(BufferPool, new TestCallbacks());

            var shape = new Sphere(0.5f);

            shape.ComputeInertia(1, out var sphereInertia);
            var       shapeIndex     = Simulation.Shapes.Add(shape);
            const int width          = 16;
            const int height         = 16;
            const int length         = 16;
            var       latticeSpacing = 1.1f;
            var       latticeOffset  = -0.5f * width * latticeSpacing;

            SimulationSetup.BuildLattice(
                new RegularGridBuilder(new Vector3(latticeSpacing, 1.1f, latticeSpacing), new Vector3(latticeOffset, 3, latticeOffset), sphereInertia, shapeIndex),
                new BallSocketConstraintBuilder(),
                width, height, length, Simulation, out var bodyHandles, out var constraintHandles);
            Simulation.PoseIntegrator.Gravity = new Vector3(0, -10, 0);
            Simulation.Deterministic          = false;

            var         staticShape              = new Sphere(4);
            var         staticShapeIndex         = Simulation.Shapes.Add(staticShape);
            const int   staticGridWidthInSpheres = 100;
            const float staticSpacing            = 6;

            for (int i = 0; i < staticGridWidthInSpheres; ++i)
            {
                for (int j = 0; j < staticGridWidthInSpheres; ++j)
                {
                    var staticDescription = new StaticDescription
                    {
                        Collidable = new CollidableDescription
                        {
                            Continuity = new ContinuousDetectionSettings {
                                Mode = ContinuousDetectionMode.Discrete
                            },
                            Shape             = staticShapeIndex,
                            SpeculativeMargin = 0.1f
                        },
                        Pose = new RigidPose
                        {
                            Position = new Vector3(
                                -staticGridWidthInSpheres * staticSpacing * 0.5f + i * staticSpacing,
                                -4,
                                -staticGridWidthInSpheres * staticSpacing * 0.5f + j * staticSpacing),
                            Orientation = BepuUtilities.Quaternion.Identity
                        }
                    };
                    Simulation.Statics.Add(staticDescription);
                }
            }

            //ref var velocity = ref Simulation.Bodies.Velocities[Simulation.Bodies.HandleToIndex[bodyHandles[width]]];
            //velocity.Linear = new Vector3(0.1f, 0, 0.1f);
            //velocity.Angular = new Vector3();

            //Simulation.Solver.IterationCount = 100;
        }
Exemplo n.º 15
0
        public unsafe override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(-13f, 6, -13f);
            camera.Yaw      = MathHelper.Pi * 3f / 4;
            camera.Pitch    = MathHelper.Pi * 0.05f;
            Simulation      = Simulation.Create(BufferPool, new TestCallbacks());
            Simulation.PoseIntegrator.Gravity = new Vector3(0, -10, 0);

            using (var compoundBuilder = new CompoundBuilder(BufferPool, Simulation.Shapes, 8))
            {
                {
                    //Note that, in bepuphysics v2, there is no 'recentering' when constructing a shape. The pose you pass in for a child is exactly the pose that the compound will use,
                    //even if the 'true' center of mass isn't at the local origin.
                    //Instead, if recentering is desired, it should performed ahead of time. The CompoundBuilder can help with this.
                    //We'll construct this compound using shapes far from the origin, and then use the CompoundBuilder overload that recenters the children and outputs the computed center.
                    var capsuleChildShape = new Capsule(0.5f, 0.5f);
                    var capsuleLocalPose  = new RigidPose {
                        Position = new Vector3(-0.5f, 4, 4), Orientation = BepuUtilities.Quaternion.Identity
                    };
                    var boxChildShape = new Box(0.5f, 1f, 1.5f);
                    var boxLocalPose  = new RigidPose {
                        Position = new Vector3(0.5f, 4, 4), Orientation = BepuUtilities.Quaternion.Identity
                    };

                    //All allocations from the buffer pool used for the final compound shape will be disposed when the demo is disposed. Don't have to worry about leaks in these demos.
                    compoundBuilder.Add(capsuleChildShape, capsuleLocalPose, 1);
                    compoundBuilder.Add(boxChildShape, boxLocalPose, 1);
                    compoundBuilder.BuildDynamicCompound(out var compoundChildren, out var compoundInertia, out var compoundCenter);
                    compoundBuilder.Reset();
                    var compound            = new Compound(compoundChildren);
                    var compoundDescription = new BodyDescription
                    {
                        Activity = new BodyActivityDescription {
                            SleepThreshold = 0.01f, MinimumTimestepCountUnderThreshold = 32
                        },
                        Collidable = new CollidableDescription
                        {
                            Shape             = Simulation.Shapes.Add(compound),
                            SpeculativeMargin = 0.1f,
                        },
                        LocalInertia = compoundInertia,
                        Pose         = new RigidPose {
                            Position = compoundCenter, Orientation = BepuUtilities.Quaternion.Identity
                        },
                    };

                    Simulation.Bodies.Add(compoundDescription);
                }

                //Build a stack of sphere grids to stress manifold reduction heuristics in a convex-ish situation.
                {
                    var         gridShape      = new Sphere(0.5f);
                    const float gridSpacing    = 1.5f;
                    const int   gridWidth      = 3;
                    var         gridShapeIndex = Simulation.Shapes.Add(gridShape);
                    gridShape.ComputeInertia(1, out var gridBoxInertia);
                    float localPoseOffset = -0.5f * gridSpacing * (gridWidth - 1);
                    for (int i = 0; i < gridWidth; ++i)
                    {
                        for (int j = 0; j < gridWidth; ++j)
                        {
                            var localPose = new RigidPose
                            {
                                Orientation = BepuUtilities.Quaternion.Identity,
                                Position    = new Vector3(localPoseOffset, 0, localPoseOffset) + new Vector3(gridSpacing) * new Vector3(i, 0, j)
                            };
                            compoundBuilder.Add(gridShapeIndex, localPose, gridBoxInertia.InverseInertiaTensor, 1);
                        }
                    }
                    compoundBuilder.BuildDynamicCompound(out var gridChildren, out var gridInertia, out var center);
                    compoundBuilder.Reset();
                    var gridCompound    = new Compound(gridChildren);
                    var bodyDescription = new BodyDescription
                    {
                        Activity = new BodyActivityDescription {
                            SleepThreshold = 0.01f, MinimumTimestepCountUnderThreshold = 32
                        },
                        Collidable = new CollidableDescription
                        {
                            Shape             = Simulation.Shapes.Add(gridCompound),
                            SpeculativeMargin = 0.1f,
                        },
                        LocalInertia = gridInertia,
                        Pose         = new RigidPose {
                            Orientation = BepuUtilities.Quaternion.Identity
                        }
                    };

                    for (int i = 0; i < 4; ++i)
                    {
                        bodyDescription.Pose.Position = new Vector3(0, 2 + i * 3, 0);
                        //if (i == 0)
                        //    gridDescription.LocalInertia = new BodyInertia();
                        //else
                        //    gridDescription.LocalInertia = gridInertia;
                        Simulation.Bodies.Add(bodyDescription);
                    }
                }

                //Build a table and use it for a couple of different tests.
                {
                    var legShape = new Box(0.2f, 1, 0.2f);
                    legShape.ComputeInertia(1f, out var legInverseInertia);
                    var legShapeIndex = Simulation.Shapes.Add(legShape);
                    var legPose0      = new RigidPose {
                        Position = new Vector3(-1.5f, 0, -1.5f), Orientation = BepuUtilities.Quaternion.Identity
                    };
                    var legPose1 = new RigidPose {
                        Position = new Vector3(-1.5f, 0, 1.5f), Orientation = BepuUtilities.Quaternion.Identity
                    };
                    var legPose2 = new RigidPose {
                        Position = new Vector3(1.5f, 0, -1.5f), Orientation = BepuUtilities.Quaternion.Identity
                    };
                    var legPose3 = new RigidPose {
                        Position = new Vector3(1.5f, 0, 1.5f), Orientation = BepuUtilities.Quaternion.Identity
                    };
                    compoundBuilder.Add(legShapeIndex, legPose0, legInverseInertia.InverseInertiaTensor, 1);
                    compoundBuilder.Add(legShapeIndex, legPose1, legInverseInertia.InverseInertiaTensor, 1);
                    compoundBuilder.Add(legShapeIndex, legPose2, legInverseInertia.InverseInertiaTensor, 1);
                    compoundBuilder.Add(legShapeIndex, legPose3, legInverseInertia.InverseInertiaTensor, 1);
                    var tableTopPose = new RigidPose {
                        Position = new Vector3(0, 0.6f, 0), Orientation = BepuUtilities.Quaternion.Identity
                    };
                    var tableTopShape = new Box(3.2f, 0.2f, 3.2f);
                    compoundBuilder.Add(tableTopShape, tableTopPose, 3);

                    compoundBuilder.BuildDynamicCompound(out var tableChildren, out var tableInertia, out var tableCenter);
                    compoundBuilder.Reset();
                    var table            = new Compound(tableChildren);
                    var tableDescription = new BodyDescription
                    {
                        Activity = new BodyActivityDescription {
                            SleepThreshold = 0.01f, MinimumTimestepCountUnderThreshold = 32
                        },
                        Collidable = new CollidableDescription
                        {
                            Shape             = Simulation.Shapes.Add(table),
                            SpeculativeMargin = 0.1f,
                        },
                        LocalInertia = tableInertia,
                        Pose         = new RigidPose {
                            Orientation = BepuUtilities.Quaternion.Identity
                        }
                    };

                    //Stack some tables.
                    {
                        for (int i = 0; i < 10; ++i)
                        {
                            tableDescription.Pose.Position = new Vector3(10, 3 + i * 1.4f, 10);
                            Simulation.Bodies.Add(tableDescription);
                        }
                    }

                    //Put a table on top of a sphere to stress out nonconvex reduction for divergent normals.
                    {
                        tableDescription.Pose.Position = new Vector3(10, 6, 0);
                        Simulation.Bodies.Add(tableDescription);

                        var sphereShape       = new Sphere(3);
                        var sphereIndex       = Simulation.Shapes.Add(sphereShape);
                        var sphereDescription = new StaticDescription
                        {
                            Collidable = new CollidableDescription
                            {
                                Shape             = sphereIndex,
                                SpeculativeMargin = 0.1f,
                            },
                            Pose = new RigidPose {
                                Position = new Vector3(10, 2, 0), Orientation = BepuUtilities.Quaternion.Identity
                            }
                        };
                        Simulation.Statics.Add(sphereDescription);
                    }

                    //Put another table on the ground, but with a clamp-ish thing on it that generates opposing normals.
                    {
                        tableDescription.Pose.Position = new Vector3(10, 3, -10);
                        Simulation.Bodies.Add(tableDescription);

                        var clampPieceShape = new Box(2f, 0.1f, 0.3f);
                        clampPieceShape.ComputeInertia(1f, out var clampPieceInverseInertia);
                        var clampPieceShapeIndex = Simulation.Shapes.Add(clampPieceShape);
                        var clamp0 = new RigidPose {
                            Position = new Vector3(0, -0.2f, -1.1f), Orientation = BepuUtilities.Quaternion.Identity
                        };
                        var clamp1 = new RigidPose {
                            Position = new Vector3(0, 0.2f, -1.1f), Orientation = BepuUtilities.Quaternion.Identity
                        };
                        var clamp2 = new RigidPose {
                            Position = new Vector3(0, -0.2f, 0), Orientation = BepuUtilities.Quaternion.Identity
                        };
                        var clamp3 = new RigidPose {
                            Position = new Vector3(0, 0.2f, 0), Orientation = BepuUtilities.Quaternion.Identity
                        };
                        var clamp4 = new RigidPose {
                            Position = new Vector3(0, -0.2f, 1.1f), Orientation = BepuUtilities.Quaternion.Identity
                        };
                        var clamp5 = new RigidPose {
                            Position = new Vector3(0, 0.2f, 1.1f), Orientation = BepuUtilities.Quaternion.Identity
                        };
                        compoundBuilder.Add(clampPieceShapeIndex, clamp0, clampPieceInverseInertia.InverseInertiaTensor, 1);
                        compoundBuilder.Add(clampPieceShapeIndex, clamp1, clampPieceInverseInertia.InverseInertiaTensor, 1);
                        compoundBuilder.Add(clampPieceShapeIndex, clamp2, clampPieceInverseInertia.InverseInertiaTensor, 1);
                        compoundBuilder.Add(clampPieceShapeIndex, clamp3, clampPieceInverseInertia.InverseInertiaTensor, 1);
                        compoundBuilder.Add(clampPieceShapeIndex, clamp4, clampPieceInverseInertia.InverseInertiaTensor, 1);
                        compoundBuilder.Add(clampPieceShapeIndex, clamp5, clampPieceInverseInertia.InverseInertiaTensor, 1);

                        compoundBuilder.BuildDynamicCompound(out var clampChildren, out var clampInertia, out var clampCenter);
                        compoundBuilder.Reset();
                        var clamp            = new Compound(clampChildren);
                        var clampDescription = new BodyDescription
                        {
                            Activity = new BodyActivityDescription {
                                SleepThreshold = 0.01f, MinimumTimestepCountUnderThreshold = 32
                            },
                            Collidable = new CollidableDescription
                            {
                                Shape             = Simulation.Shapes.Add(clamp),
                                SpeculativeMargin = 0.1f,
                            },
                            LocalInertia = clampInertia,
                            Pose         = new RigidPose {
                                Position = tableDescription.Pose.Position + new Vector3(2f, 0.3f, 0), Orientation = BepuUtilities.Quaternion.Identity
                            }
                        };
                        Simulation.Bodies.Add(clampDescription);
                    }
                }
            }

            //Prevent stuff from falling into the infinite void.
            {
                var boxShape          = new Box(100, 1, 100);
                var groundShapeIndex  = Simulation.Shapes.Add(boxShape);
                var groundDescription = new StaticDescription
                {
                    Collidable = new CollidableDescription
                    {
                        Shape             = groundShapeIndex,
                        SpeculativeMargin = 0.1f,
                    },
                    Pose = new RigidPose {
                        Position = new Vector3(0, 0, 0), Orientation = BepuUtilities.Quaternion.Identity
                    }
                };
                Simulation.Statics.Add(groundDescription);
            }
        }
        public unsafe override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(-30, 8, -60);
            camera.Yaw      = MathHelper.Pi * 3f / 4;

            Simulation = Simulation.Create(BufferPool, new DemoNarrowPhaseCallbacks(), new DemoPoseIntegratorCallbacks(new Vector3(0, -10, 0)));

            var boxShape = new Box(1, 1, 1);

            boxShape.ComputeInertia(1, out var boxInertia);
            var       boxIndex       = Simulation.Shapes.Add(boxShape);
            const int forkCount      = 20;
            const int blocksPerChain = 20;

            int[] blockHandles = new int[blocksPerChain];
            for (int forkIndex = 0; forkIndex < forkCount; ++forkIndex)
            {
                //Build the blocks.
                for (int blockIndex = 0; blockIndex < blocksPerChain; ++blockIndex)
                {
                    var bodyDescription = new BodyDescription
                    {
                        //Make the uppermost block kinematic to hold up the rest of the chain.
                        LocalInertia = blockIndex == blocksPerChain - 1 ? new BodyInertia() : boxInertia,
                        Pose         = new RigidPose
                        {
                            Position = new Vector3(0,
                                                   5 + blockIndex * (boxShape.Height + 1),
                                                   (forkIndex - forkCount * 0.5f) * (boxShape.Length + 4)),
                            Orientation = BepuUtilities.Quaternion.Identity
                        },
                        Activity = new BodyActivityDescription {
                            MinimumTimestepCountUnderThreshold = 32, SleepThreshold = .01f
                        },
                        Collidable = new CollidableDescription {
                            Shape = boxIndex, SpeculativeMargin = .1f
                        },
                    };
                    blockHandles[blockIndex] = Simulation.Bodies.Add(bodyDescription);
                }
                //Build the chains.
                for (int i = 1; i < blocksPerChain; ++i)
                {
                    var ballSocket = new BallSocket
                    {
                        LocalOffsetA   = new Vector3(0, 1f, 0),
                        LocalOffsetB   = new Vector3(0, -1f, 0),
                        SpringSettings = new SpringSettings(30, 5)
                    };
                    Simulation.Solver.Add(blockHandles[i - 1], blockHandles[i], ref ballSocket);
                }
            }

            var staticShape      = new Box(200, 1, 200);
            var staticShapeIndex = Simulation.Shapes.Add(staticShape);

            var staticDescription = new StaticDescription
            {
                Collidable = new CollidableDescription
                {
                    Continuity = new ContinuousDetectionSettings {
                        Mode = ContinuousDetectionMode.Discrete
                    },
                    Shape             = staticShapeIndex,
                    SpeculativeMargin = 0.1f
                },
                Pose = new RigidPose
                {
                    Position    = new Vector3(1, -0.5f, 1),
                    Orientation = BepuUtilities.Quaternion.Identity
                }
            };

            Simulation.Statics.Add(staticDescription);

            //Build the coin description for the ponz-I mean ICO.
            var coinShape = new Sphere(1f); //TODO: Obviously, when cylinders get added, this needs to be changed.

            coinShape.ComputeInertia(1, out var coinInertia);
            coinDescription = new BodyDescription
            {
                LocalInertia = coinInertia,
                Pose         = new RigidPose
                {
                    Orientation = BepuUtilities.Quaternion.Identity
                },
                Activity = new BodyActivityDescription {
                    MinimumTimestepCountUnderThreshold = 32, SleepThreshold = .01f
                },
                Collidable = new CollidableDescription {
                    Shape = Simulation.Shapes.Add(coinShape), SpeculativeMargin = .1f
                },
            };
        }
Exemplo n.º 17
0
        public unsafe override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(-30, 10, -30);
            //camera.Yaw = MathHelper.Pi ;
            camera.Yaw = MathHelper.Pi * 3f / 4;
            //camera.Pitch = MathHelper.PiOver2 * 0.999f;
            Simulation = Simulation.Create(BufferPool, new TestCallbacks());

            var box     = new Box(1f, 3f, 2f);
            var capsule = new Capsule(1f, 1f);
            var sphere  = new Sphere(1.5f);

            box.ComputeInertia(1, out var boxInertia);
            capsule.ComputeInertia(1, out var capsuleInertia);
            sphere.ComputeInertia(1, out var sphereInertia);
            var       boxIndex     = Simulation.Shapes.Add(box);
            var       capsuleIndex = Simulation.Shapes.Add(capsule);
            var       sphereIndex  = Simulation.Shapes.Add(sphere);
            const int width        = 8;
            const int height       = 16;
            const int length       = 8;

            for (int i = 0; i < width; ++i)
            {
                for (int j = 0; j < height; ++j)
                {
                    for (int k = 0; k < length; ++k)
                    {
                        var location        = new Vector3(3, 3, 3) * new Vector3(i, j, k) + new Vector3(-width * 1.5f, 2.5f, -length * 1.5f);
                        var bodyDescription = new BodyDescription
                        {
                            Activity = new BodyActivityDescription(0.01f),
                            Pose     = new RigidPose
                            {
                                Orientation = BepuUtilities.Quaternion.Identity,
                                Position    = location
                            },
                            Collidable = new CollidableDescription
                            {
                                Continuity = new ContinuousDetectionSettings {
                                    Mode = ContinuousDetectionMode.Discrete
                                },
                                SpeculativeMargin = 0.1f
                            }
                        };
                        switch (j % 3)
                        {
                        case 0:
                            bodyDescription.Collidable.Shape = boxIndex;
                            bodyDescription.LocalInertia     = boxInertia;
                            break;

                        case 1:
                            bodyDescription.Collidable.Shape = capsuleIndex;
                            bodyDescription.LocalInertia     = capsuleInertia;
                            break;

                        case 2:
                            bodyDescription.Collidable.Shape = sphereIndex;
                            bodyDescription.LocalInertia     = sphereInertia;
                            break;
                        }
                        Simulation.Bodies.Add(bodyDescription);
                    }
                }
            }

            Simulation.PoseIntegrator.Gravity = new Vector3(0, -10, 0);

            var         staticShape      = new Box(1, 1, 1);
            var         staticShapeIndex = Simulation.Shapes.Add(staticShape);
            const int   staticGridWidth  = 100;
            const float staticSpacing    = 1.2f;
            var         gridOffset       = -0.5f * staticGridWidth * staticSpacing;

            for (int i = 0; i < staticGridWidth; ++i)
            {
                for (int j = 0; j < staticGridWidth; ++j)
                {
                    var staticDescription = new StaticDescription
                    {
                        Collidable = new CollidableDescription
                        {
                            Continuity = new ContinuousDetectionSettings {
                                Mode = ContinuousDetectionMode.Discrete
                            },
                            Shape             = staticShapeIndex,
                            SpeculativeMargin = 0.1f
                        },
                        Pose = new RigidPose
                        {
                            Position = new Vector3(
                                1 + gridOffset + i * staticSpacing,
                                -0.707f,
                                0.5f + gridOffset + j * staticSpacing),
                            //Orientation = BepuUtilities.Quaternion.Identity
                            Orientation = BepuUtilities.Quaternion.CreateFromAxisAngle(Vector3.Normalize(new Vector3(1 + i, i * j % 10, -10 + -j)), (i ^ j) * 0.5f * (MathHelper.PiOver4))
                                          //Orientation = BepuUtilities.Quaternion.CreateFromAxisAngle(Vector3.Normalize(new Vector3(0, 0, 1)), MathHelper.Pi)
                        }
                    };
                    Simulation.Statics.Add(staticDescription);
                }
            }
        }
Exemplo n.º 18
0
        public unsafe override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(0, 10, 40);
            camera.Yaw      = 0;
            camera.Pitch    = 0;
            Simulation      = Simulation.Create(BufferPool, new DemoNarrowPhaseCallbacks(), new DemoPoseIntegratorCallbacks(new Vector3(0, -10, 0)));

            var box     = new Box(2f, 2f, 2f);
            var capsule = new Capsule(1f, 1f);
            var sphere  = new Sphere(1.5f);

            box.ComputeInertia(1, out var boxInertia);
            capsule.ComputeInertia(1, out var capsuleInertia);
            sphere.ComputeInertia(1, out var sphereInertia);
            var       boxIndex     = Simulation.Shapes.Add(box);
            var       capsuleIndex = Simulation.Shapes.Add(capsule);
            var       sphereIndex  = Simulation.Shapes.Add(sphere);
            const int width        = 12;
            const int height       = 3;
            const int length       = 12;

            for (int i = 0; i < width; ++i)
            {
                for (int j = 0; j < height; ++j)
                {
                    for (int k = 0; k < length; ++k)
                    {
                        var location        = new Vector3(5, 5, 5) * new Vector3(i, j, k) + new Vector3(-width * 2.5f, 2.5f, -length * 2.5f);
                        var bodyDescription = new BodyDescription
                        {
                            Activity = new BodyActivityDescription {
                                MinimumTimestepCountUnderThreshold = 32, SleepThreshold = 0.1f
                            },
                            Pose = new RigidPose
                            {
                                Orientation = Quaternion.Identity,
                                Position    = location
                            },
                            Collidable = new CollidableDescription
                            {
                                Continuity = new ContinuousDetectionSettings {
                                    Mode = ContinuousDetectionMode.Discrete
                                },
                                SpeculativeMargin = 0.1f
                            }
                        };
                        switch (j % 3)
                        {
                        case 0:
                            bodyDescription.Collidable.Shape = boxIndex;
                            bodyDescription.LocalInertia     = boxInertia;
                            break;

                        case 1:
                            bodyDescription.Collidable.Shape = capsuleIndex;
                            bodyDescription.LocalInertia     = capsuleInertia;
                            break;

                        case 2:
                            bodyDescription.Collidable.Shape = sphereIndex;
                            bodyDescription.LocalInertia     = sphereInertia;
                            break;
                        }
                        Simulation.Bodies.Add(bodyDescription);
                    }
                }
            }

            //Don't really want to regenerate a convex hull every frame; just cache one out.
            const int pointCount = 32;
            var       points     = new QuickList <Vector3>(pointCount, BufferPool);
            var       random     = new Random(5);

            for (int i = 0; i < pointCount; ++i)
            {
                points.AllocateUnsafely() = new Vector3((float)random.NextDouble() - 0.5f, (float)random.NextDouble() - 0.5f, (float)random.NextDouble() - 0.5f);
            }
            ConvexHullHelper.CreateShape(points.Span.Slice(0, points.Count), BufferPool, out _, out hull);
            points.Dispose(BufferPool);

            //var staticShapeIndex = Simulation.Shapes.Add(new Box(100, 1, 100));
            //var staticDescription = new StaticDescription
            //{
            //    Collidable = new CollidableDescription
            //    {
            //        Continuity = new ContinuousDetectionSettings { Mode = ContinuousDetectionMode.Discrete },
            //        Shape = Simulation.Shapes.Add(new Box(100, 1, 100)),
            //        SpeculativeMargin = 0.1f
            //    },
            //    Pose = new RigidPose { Position = new Vector3(0, -1, 0), Orientation = Quaternion.Identity }
            //};
            //Simulation.Statics.Add(staticDescription);

            const int planeWidth  = 64;
            const int planeHeight = 64;

            DemoMeshHelper.CreateDeformedPlane(planeWidth, planeHeight,
                                               (int x, int y) =>
            {
                return(new Vector3(x, 1 * (float)Math.Cos(x / 4f) * (float)Math.Sin(y / 4f), y));
            }, new Vector3(2, 3, 2), BufferPool, out var planeMesh);
            Simulation.Statics.Add(new StaticDescription(new Vector3(-64, -10, -64), new CollidableDescription(Simulation.Shapes.Add(planeMesh), 0.1f)));
        }
Exemplo n.º 19
0
        public unsafe override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(0, 10, 40);
            camera.Yaw      = 0;
            camera.Pitch    = 0;
            Simulation      = Simulation.Create(BufferPool, new TestCallbacks());
            Simulation.PoseIntegrator.Gravity = new Vector3(0, -10, 0);

            var box     = new Box(2f, 2f, 2f);
            var capsule = new Capsule(1f, 1f);
            var sphere  = new Sphere(1.5f);

            box.ComputeInertia(1, out var boxInertia);
            capsule.ComputeInertia(1, out var capsuleInertia);
            sphere.ComputeInertia(1, out var sphereInertia);
            var       boxIndex     = Simulation.Shapes.Add(box);
            var       capsuleIndex = Simulation.Shapes.Add(capsule);
            var       sphereIndex  = Simulation.Shapes.Add(sphere);
            const int width        = 8;
            const int height       = 16;
            const int length       = 8;

            for (int i = 0; i < width; ++i)
            {
                for (int j = 0; j < height; ++j)
                {
                    for (int k = 0; k < length; ++k)
                    {
                        var location        = new Vector3(3, 3, 3) * new Vector3(i, j, k) + new Vector3(-width * 1.5f, 1.5f, -length * 1.5f);
                        var bodyDescription = new BodyDescription
                        {
                            Activity = new BodyActivityDescription {
                                MinimumTimestepCountUnderThreshold = 32, SleepThreshold = 0.3f
                            },
                            Pose = new RigidPose
                            {
                                Orientation = Quaternion.Identity,
                                Position    = location
                            },
                            Collidable = new CollidableDescription
                            {
                                Continuity = new ContinuousDetectionSettings {
                                    Mode = ContinuousDetectionMode.Discrete
                                },
                                SpeculativeMargin = 0.1f
                            }
                        };
                        switch (j % 3)
                        {
                        case 0:
                            bodyDescription.Collidable.Shape = boxIndex;
                            bodyDescription.LocalInertia     = boxInertia;
                            break;

                        case 1:
                            bodyDescription.Collidable.Shape = capsuleIndex;
                            bodyDescription.LocalInertia     = capsuleInertia;
                            break;

                        case 2:
                            bodyDescription.Collidable.Shape = sphereIndex;
                            bodyDescription.LocalInertia     = sphereInertia;
                            break;
                        }
                        Simulation.Bodies.Add(bodyDescription);
                    }
                }
            }


            var staticShapeIndex  = Simulation.Shapes.Add(new Box(100, 1, 100));
            var staticDescription = new StaticDescription
            {
                Collidable = new CollidableDescription
                {
                    Continuity = new ContinuousDetectionSettings {
                        Mode = ContinuousDetectionMode.Discrete
                    },
                    Shape             = Simulation.Shapes.Add(new Box(100, 1, 100)),
                    SpeculativeMargin = 0.1f
                },
                Pose = new RigidPose {
                    Position = new Vector3(0, -1, 0), Orientation = Quaternion.Identity
                }
            };

            Simulation.Statics.Add(staticDescription);
        }
Exemplo n.º 20
0
        public unsafe override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(-13f, 6, -13f);
            camera.Yaw      = MathHelper.Pi * 3f / 4;
            camera.Pitch    = MathHelper.Pi * 0.05f;
            Simulation      = Simulation.Create(BufferPool, new DemoNarrowPhaseCallbacks(), new DemoPoseIntegratorCallbacks(new Vector3(0, -10f, 0)));

            using (var compoundBuilder = new CompoundBuilder(BufferPool, Simulation.Shapes, 8))
            {
                {
                    //Note that, in bepuphysics v2, there is no 'recentering' when constructing a shape. The pose you pass in for a child is exactly the pose that the compound will use,
                    //even if the 'true' center of mass isn't at the local origin.
                    //Instead, if recentering is desired, it should performed ahead of time. The CompoundBuilder can help with this.
                    //We'll construct this compound using shapes far from the origin, and then use the CompoundBuilder overload that recenters the children and outputs the computed center.
                    var capsuleChildShape = new Capsule(0.5f, 0.5f);
                    var capsuleLocalPose  = new RigidPose {
                        Position = new Vector3(-0.5f, 4, 4), Orientation = Quaternion.Identity
                    };
                    var boxChildShape = new Box(0.5f, 1f, 1.5f);
                    var boxLocalPose  = new RigidPose {
                        Position = new Vector3(0.5f, 4, 4), Orientation = Quaternion.Identity
                    };

                    //All allocations from the buffer pool used for the final compound shape will be disposed when the demo is disposed. Don't have to worry about leaks in these demos.
                    compoundBuilder.Add(capsuleChildShape, capsuleLocalPose, 1);
                    compoundBuilder.Add(boxChildShape, boxLocalPose, 1);
                    compoundBuilder.BuildDynamicCompound(out var compoundChildren, out var compoundInertia, out var compoundCenter);
                    compoundBuilder.Reset();
                    var compound            = new Compound(compoundChildren);
                    var compoundDescription = new BodyDescription
                    {
                        Activity = new BodyActivityDescription {
                            SleepThreshold = 0.01f, MinimumTimestepCountUnderThreshold = 32
                        },
                        Collidable = new CollidableDescription
                        {
                            Shape             = Simulation.Shapes.Add(compound),
                            SpeculativeMargin = 0.1f,
                        },
                        LocalInertia = compoundInertia,
                        Pose         = new RigidPose {
                            Position = compoundCenter, Orientation = Quaternion.Identity
                        },
                    };

                    Simulation.Bodies.Add(compoundDescription);
                }

                //Build a stack of sphere grids to stress manifold reduction heuristics in a convex-ish situation.
                {
                    var         gridShape      = new Sphere(0.5f);
                    const float gridSpacing    = 1.5f;
                    const int   gridWidth      = 3;
                    var         gridShapeIndex = Simulation.Shapes.Add(gridShape);
                    gridShape.ComputeInertia(1, out var gridBoxInertia);
                    float localPoseOffset = -0.5f * gridSpacing * (gridWidth - 1);
                    for (int i = 0; i < gridWidth; ++i)
                    {
                        for (int j = 0; j < gridWidth; ++j)
                        {
                            var localPose = new RigidPose
                            {
                                Orientation = Quaternion.Identity,
                                Position    = new Vector3(localPoseOffset, 0, localPoseOffset) + new Vector3(gridSpacing) * new Vector3(i, 0, j)
                            };
                            compoundBuilder.Add(gridShapeIndex, localPose, gridBoxInertia.InverseInertiaTensor, 1);
                        }
                    }
                    compoundBuilder.BuildDynamicCompound(out var gridChildren, out var gridInertia, out var center);
                    compoundBuilder.Reset();
                    var gridCompound    = new Compound(gridChildren);
                    var bodyDescription = new BodyDescription
                    {
                        Activity = new BodyActivityDescription {
                            SleepThreshold = 0.01f, MinimumTimestepCountUnderThreshold = 32
                        },
                        Collidable = new CollidableDescription
                        {
                            Shape             = Simulation.Shapes.Add(gridCompound),
                            SpeculativeMargin = 0.1f,
                        },
                        LocalInertia = gridInertia,
                        Pose         = new RigidPose {
                            Orientation = Quaternion.Identity
                        }
                    };

                    for (int i = 0; i < 4; ++i)
                    {
                        bodyDescription.Pose.Position = new Vector3(0, 2 + i * 3, 0);
                        //if (i == 0)
                        //    gridDescription.LocalInertia = new BodyInertia();
                        //else
                        //    gridDescription.LocalInertia = gridInertia;
                        Simulation.Bodies.Add(bodyDescription);
                    }
                }

                //Build a table and use it for a couple of different tests.
                {
                    var legShape = new Box(0.2f, 1, 0.2f);
                    legShape.ComputeInertia(1f, out var legInverseInertia);
                    var legShapeIndex = Simulation.Shapes.Add(legShape);
                    var legPose0      = new RigidPose {
                        Position = new Vector3(-1.5f, 0, -1.5f), Orientation = Quaternion.Identity
                    };
                    var legPose1 = new RigidPose {
                        Position = new Vector3(-1.5f, 0, 1.5f), Orientation = Quaternion.Identity
                    };
                    var legPose2 = new RigidPose {
                        Position = new Vector3(1.5f, 0, -1.5f), Orientation = Quaternion.Identity
                    };
                    var legPose3 = new RigidPose {
                        Position = new Vector3(1.5f, 0, 1.5f), Orientation = Quaternion.Identity
                    };
                    compoundBuilder.Add(legShapeIndex, legPose0, legInverseInertia.InverseInertiaTensor, 1);
                    compoundBuilder.Add(legShapeIndex, legPose1, legInverseInertia.InverseInertiaTensor, 1);
                    compoundBuilder.Add(legShapeIndex, legPose2, legInverseInertia.InverseInertiaTensor, 1);
                    compoundBuilder.Add(legShapeIndex, legPose3, legInverseInertia.InverseInertiaTensor, 1);
                    var tableTopPose = new RigidPose {
                        Position = new Vector3(0, 0.6f, 0), Orientation = Quaternion.Identity
                    };
                    var tableTopShape = new Box(3.2f, 0.2f, 3.2f);
                    compoundBuilder.Add(tableTopShape, tableTopPose, 3);

                    compoundBuilder.BuildDynamicCompound(out var tableChildren, out var tableInertia, out var tableCenter);
                    compoundBuilder.Reset();
                    var table            = new Compound(tableChildren);
                    var tableDescription = new BodyDescription
                    {
                        Activity = new BodyActivityDescription {
                            SleepThreshold = 0.01f, MinimumTimestepCountUnderThreshold = 32
                        },
                        Collidable = new CollidableDescription
                        {
                            Shape             = Simulation.Shapes.Add(table),
                            SpeculativeMargin = 0.1f,
                        },
                        LocalInertia = tableInertia,
                        Pose         = new RigidPose {
                            Orientation = Quaternion.Identity
                        }
                    };

                    //Stack some tables.
                    {
                        for (int i = 0; i < 10; ++i)
                        {
                            tableDescription.Pose.Position = new Vector3(10, 3 + i * 1.4f, 10);
                            Simulation.Bodies.Add(tableDescription);
                        }
                    }
                    {
                        for (int k = 0; k < 5; ++k)
                        {
                            tableDescription.Pose.Position = new Vector3(64 + k * 3, 6 + k * 1.4f, 32);
                            Simulation.Bodies.Add(tableDescription);
                        }
                        //for (int i = 0; i < 10; ++i)
                        //{
                        //    for (int j = 0; j < 20; ++j)
                        //    {
                        //        for (int k = 0; k < 10; ++k)
                        //        {
                        //            tableDescription.Pose.Position = new Vector3(32 + i * 6, 6 + j * 1.4f, 16 + k * 6);
                        //            Simulation.Bodies.Add(tableDescription);
                        //        }
                        //    }
                        //}
                    }

                    //Put a table on top of a sphere to stress out nonconvex reduction for divergent normals.
                    {
                        tableDescription.Pose.Position = new Vector3(10, 6, 0);
                        Simulation.Bodies.Add(tableDescription);

                        var sphereShape       = new Sphere(3);
                        var sphereIndex       = Simulation.Shapes.Add(sphereShape);
                        var sphereDescription = new StaticDescription
                        {
                            Collidable = new CollidableDescription
                            {
                                Shape             = sphereIndex,
                                SpeculativeMargin = 0.1f,
                            },
                            Pose = new RigidPose {
                                Position = new Vector3(10, 2, 0), Orientation = Quaternion.Identity
                            }
                        };
                        Simulation.Statics.Add(sphereDescription);
                    }

                    //Put another table on the ground, but with a clamp-ish thing on it that generates opposing normals.
                    {
                        tableDescription.Pose.Position = new Vector3(10, 3, -10);
                        Simulation.Bodies.Add(tableDescription);

                        var clampPieceShape = new Box(2f, 0.1f, 0.3f);
                        clampPieceShape.ComputeInertia(1f, out var clampPieceInverseInertia);
                        var clampPieceShapeIndex = Simulation.Shapes.Add(clampPieceShape);
                        var clamp0 = new RigidPose {
                            Position = new Vector3(0, -0.2f, -1.1f), Orientation = Quaternion.Identity
                        };
                        var clamp1 = new RigidPose {
                            Position = new Vector3(0, 0.2f, -1.1f), Orientation = Quaternion.Identity
                        };
                        var clamp2 = new RigidPose {
                            Position = new Vector3(0, -0.2f, 0), Orientation = Quaternion.Identity
                        };
                        var clamp3 = new RigidPose {
                            Position = new Vector3(0, 0.2f, 0), Orientation = Quaternion.Identity
                        };
                        var clamp4 = new RigidPose {
                            Position = new Vector3(0, -0.2f, 1.1f), Orientation = Quaternion.Identity
                        };
                        var clamp5 = new RigidPose {
                            Position = new Vector3(0, 0.2f, 1.1f), Orientation = Quaternion.Identity
                        };
                        compoundBuilder.Add(clampPieceShapeIndex, clamp0, clampPieceInverseInertia.InverseInertiaTensor, 1);
                        compoundBuilder.Add(clampPieceShapeIndex, clamp1, clampPieceInverseInertia.InverseInertiaTensor, 1);
                        compoundBuilder.Add(clampPieceShapeIndex, clamp2, clampPieceInverseInertia.InverseInertiaTensor, 1);
                        compoundBuilder.Add(clampPieceShapeIndex, clamp3, clampPieceInverseInertia.InverseInertiaTensor, 1);
                        compoundBuilder.Add(clampPieceShapeIndex, clamp4, clampPieceInverseInertia.InverseInertiaTensor, 1);
                        compoundBuilder.Add(clampPieceShapeIndex, clamp5, clampPieceInverseInertia.InverseInertiaTensor, 1);

                        compoundBuilder.BuildDynamicCompound(out var clampChildren, out var clampInertia, out var clampCenter);
                        compoundBuilder.Reset();
                        var clamp            = new Compound(clampChildren);
                        var clampDescription = new BodyDescription
                        {
                            Activity = new BodyActivityDescription {
                                SleepThreshold = 0.01f, MinimumTimestepCountUnderThreshold = 32
                            },
                            Collidable = new CollidableDescription
                            {
                                Shape             = Simulation.Shapes.Add(clamp),
                                SpeculativeMargin = 0.1f,
                            },
                            LocalInertia = clampInertia,
                            Pose         = new RigidPose {
                                Position = tableDescription.Pose.Position + new Vector3(2f, 0.3f, 0), Orientation = Quaternion.Identity
                            }
                        };
                        Simulation.Bodies.Add(clampDescription);
                    }
                }

                //Create a tree-accelerated big compound.
                {
                    var random = new Random(5);
                    var treeCompoundBoxShape      = new Box(0.5f, 1.5f, 1f);
                    var treeCompoundBoxShapeIndex = Simulation.Shapes.Add(treeCompoundBoxShape);
                    treeCompoundBoxShape.ComputeInertia(1, out var childInertia);
                    for (int i = 0; i < 128; ++i)
                    {
                        RigidPose localPose;
                        localPose.Position = new Vector3(12, 6, 12) * (0.5f * new Vector3((float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble()) - Vector3.One);
                        float orientationLengthSquared;
                        do
                        {
                            localPose.Orientation    = new Quaternion((float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble());
                            orientationLengthSquared = QuaternionEx.LengthSquared(ref localPose.Orientation);
                        }while (orientationLengthSquared < 1e-9f);
                        QuaternionEx.Scale(localPose.Orientation, 1f / MathF.Sqrt(orientationLengthSquared), out localPose.Orientation);
                        //Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), MathF.PI, out localPose.Orientation);

                        compoundBuilder.Add(treeCompoundBoxShapeIndex, localPose, childInertia.InverseInertiaTensor, 1);
                    }
                    compoundBuilder.BuildDynamicCompound(out var children, out var inertia, out var center);
                    compoundBuilder.Reset();

                    var compound = new BigCompound(children, Simulation.Shapes, BufferPool);
                    //var compound = new Compound(children);
                    var compoundIndex = Simulation.Shapes.Add(compound);
                    for (int i = 0; i < 8; ++i)
                    {
                        Simulation.Bodies.Add(BodyDescription.CreateDynamic(new Vector3(0, 4 + 5 * i, 32), inertia, new CollidableDescription(compoundIndex, 0.1f), new BodyActivityDescription(0.01f)));
                    }
                }
            }

            //Prevent stuff from falling into the infinite void.
            {
                var boxShape          = new Box(256, 1, 256);
                var groundShapeIndex  = Simulation.Shapes.Add(boxShape);
                var groundDescription = new StaticDescription
                {
                    Collidable = new CollidableDescription
                    {
                        Shape             = groundShapeIndex,
                        SpeculativeMargin = 0.1f,
                    },
                    Pose = new RigidPose {
                        Position = new Vector3(0, 0, 0), Orientation = Quaternion.Identity
                    }
                };
                Simulation.Statics.Add(groundDescription);
            }
            const int planeWidth  = 48;
            const int planeHeight = 48;

            DemoMeshHelper.CreateDeformedPlane(planeWidth, planeHeight,
                                               (int x, int y) =>
            {
                Vector2 offsetFromCenter = new Vector2(x - planeWidth / 2, y - planeHeight / 2);
                return(new Vector3(offsetFromCenter.X, MathF.Cos(x / 4f) * MathF.Sin(y / 4f) - 0.01f * offsetFromCenter.LengthSquared(), offsetFromCenter.Y));
            }, new Vector3(2, 1, 2), BufferPool, out var planeMesh);
            Simulation.Statics.Add(new StaticDescription(new Vector3(64, 4, 32), QuaternionEx.CreateFromAxisAngle(new Vector3(0, 1, 0), MathF.PI / 2),
                                                         new CollidableDescription(Simulation.Shapes.Add(planeMesh), 0.1f)));
        }
Exemplo n.º 21
0
        public unsafe override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(-20f, 13, -20f);
            camera.Yaw      = MathHelper.Pi * 3f / 4;
            camera.Pitch    = MathHelper.Pi * 0.1f;
            Simulation      = Simulation.Create(BufferPool, new DemoNarrowPhaseCallbacks(), new DemoPoseIntegratorCallbacks(new Vector3(0, -10, 0)));

            var shape = new Sphere(0.5f);

            shape.ComputeInertia(1, out var sphereInertia);
            var       shapeIndex        = Simulation.Shapes.Add(shape);
            const int width             = 64;
            const int height            = 64;
            const int length            = 64;
            var       spacing           = new Vector3(1.01f);
            var       halfSpacing       = spacing / 2;
            float     randomization     = 0.9f;
            var       randomizationSpan = (spacing - new Vector3(1)) * randomization;
            var       randomizationBase = randomizationSpan * -0.5f;
            var       random            = new Random(5);

            for (int i = 0; i < width; ++i)
            {
                for (int j = 0; j < height; ++j)
                {
                    for (int k = 0; k < length; ++k)
                    {
                        var r        = new Vector3((float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble());
                        var location = spacing * (new Vector3(i, j, k) + new Vector3(-width, 1, -length)) + randomizationBase + r * randomizationSpan;
                        if ((i + j + k) % 2 == 1)
                        {
                            var bodyDescription = new BodyDescription
                            {
                                Activity = new BodyActivityDescription {
                                    MinimumTimestepCountUnderThreshold = 32, SleepThreshold = -0.1f
                                },
                                Pose = new RigidPose
                                {
                                    Orientation = Quaternion.Identity,
                                    Position    = location
                                },
                                Collidable = new CollidableDescription
                                {
                                    Continuity = new ContinuousDetectionSettings {
                                        Mode = ContinuousDetectionMode.Discrete
                                    },
                                    SpeculativeMargin = 0.1f,
                                    Shape             = shapeIndex
                                },
                                LocalInertia = sphereInertia
                            };
                            Simulation.Bodies.Add(bodyDescription);
                        }
                        else
                        {
                            var staticDescription = new StaticDescription
                            {
                                Pose = new RigidPose
                                {
                                    Orientation = Quaternion.Identity,
                                    Position    = location
                                },
                                Collidable = new CollidableDescription
                                {
                                    Continuity = new ContinuousDetectionSettings {
                                        Mode = ContinuousDetectionMode.Discrete
                                    },
                                    SpeculativeMargin = 0.1f,
                                    Shape             = shapeIndex
                                }
                            };
                            Simulation.Statics.Add(staticDescription);
                        }
                    }
                }
            }
            refineTimes = new TimingsRingBuffer(sampleCount, BufferPool);
            testTimes   = new TimingsRingBuffer(sampleCount, BufferPool);
        }
Exemplo n.º 22
0
 internal override BodyInertia ComputeIntertia(float mass)
 {
     sphere.ComputeInertia(mass, out BodyInertia inertia);
     return(inertia);
 }
Exemplo n.º 23
0
        public unsafe override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(-30, 10, -30);
            //camera.Yaw = MathHelper.Pi ;
            camera.Yaw = MathHelper.Pi * 3f / 4;
            //camera.Pitch = MathHelper.PiOver2 * 0.999f;
            Simulation = Simulation.Create(BufferPool, new DemoNarrowPhaseCallbacks(), new DemoPoseIntegratorCallbacks(new Vector3(0, -10, 0)));
            Simulation.Deterministic = true;

            var       sphere     = new Sphere(1.5f);
            var       capsule    = new Capsule(1f, 1f);
            var       box        = new Box(1f, 3f, 2f);
            var       cylinder   = new Cylinder(1.5f, 0.3f);
            const int pointCount = 32;
            var       points     = new QuickList <Vector3>(pointCount, BufferPool);
            //points.Allocate(BufferPool) = new Vector3(0, 0, 0);
            //points.Allocate(BufferPool) = new Vector3(0, 0, 1);
            //points.Allocate(BufferPool) = new Vector3(0, 1, 0);
            //points.Allocate(BufferPool) = new Vector3(0, 1, 1);
            //points.Allocate(BufferPool) = new Vector3(1, 0, 0);
            //points.Allocate(BufferPool) = new Vector3(1, 0, 1);
            //points.Allocate(BufferPool) = new Vector3(1, 1, 0);
            //points.Allocate(BufferPool) = new Vector3(1, 1, 1);
            var random = new Random(5);

            for (int i = 0; i < pointCount; ++i)
            {
                points.AllocateUnsafely() = new Vector3(3 * (float)random.NextDouble(), 1 * (float)random.NextDouble(), 3 * (float)random.NextDouble());
                //points.AllocateUnsafely() = new Vector3(0, 1, 0) + Vector3.Normalize(new Vector3((float)random.NextDouble() * 2 - 1, (float)random.NextDouble() * 2 - 1, (float)random.NextDouble() * 2 - 1)) * (float)random.NextDouble();
            }
            var convexHull = new ConvexHull(points.Span.Slice(points.Count), BufferPool, out _);

            box.ComputeInertia(1, out var boxInertia);
            capsule.ComputeInertia(1, out var capsuleInertia);
            sphere.ComputeInertia(1, out var sphereInertia);
            cylinder.ComputeInertia(1, out var cylinderInertia);
            convexHull.ComputeInertia(1, out var hullInertia);
            var       boxIndex      = Simulation.Shapes.Add(box);
            var       capsuleIndex  = Simulation.Shapes.Add(capsule);
            var       sphereIndex   = Simulation.Shapes.Add(sphere);
            var       cylinderIndex = Simulation.Shapes.Add(cylinder);
            var       hullIndex     = Simulation.Shapes.Add(convexHull);
            const int width         = 8;
            const int height        = 16;
            const int length        = 8;
            var       shapeCount    = 0;

            for (int i = 0; i < width; ++i)
            {
                for (int j = 0; j < height; ++j)
                {
                    for (int k = 0; k < length; ++k)
                    {
                        var location        = new Vector3(6, 3, 6) * new Vector3(i, j, k) + new Vector3(-width * 1.5f, 5.5f, -length * 1.5f);
                        var bodyDescription = new BodyDescription
                        {
                            Activity = new BodyActivityDescription(0.01f),
                            Pose     = new RigidPose
                            {
                                Orientation = Quaternion.Identity,
                                Position    = location
                            },
                            Collidable = new CollidableDescription
                            {
                                Continuity = new ContinuousDetectionSettings {
                                    Mode = ContinuousDetectionMode.Discrete
                                },
                                SpeculativeMargin = 0.1f
                            }
                        };
                        var index = shapeCount++;
                        switch (2 + index % 5)
                        {
                        case 0:
                            bodyDescription.Collidable.Shape = sphereIndex;
                            bodyDescription.LocalInertia     = sphereInertia;
                            break;

                        case 1:
                            bodyDescription.Collidable.Shape = capsuleIndex;
                            bodyDescription.LocalInertia     = capsuleInertia;
                            break;

                        case 2:
                            bodyDescription.Collidable.Shape = boxIndex;
                            bodyDescription.LocalInertia     = boxInertia;
                            break;

                        case 3:
                            bodyDescription.Collidable.Shape = cylinderIndex;
                            bodyDescription.LocalInertia     = cylinderInertia;
                            break;

                        case 4:
                            bodyDescription.Collidable.Shape = hullIndex;
                            bodyDescription.LocalInertia     = hullInertia;
                            break;
                        }
                        Simulation.Bodies.Add(bodyDescription);
                    }
                }
            }

            DemoMeshHelper.CreateDeformedPlane(128, 128, (x, y) => new Vector3(x - 64, 2f * (float)(Math.Sin(x * 0.5f) * Math.Sin(y * 0.5f)), y - 64), new Vector3(4, 1, 4), BufferPool, out var mesh);
            Simulation.Statics.Add(new StaticDescription(new Vector3(), new CollidableDescription(Simulation.Shapes.Add(mesh), 0.1f)));
        }
Exemplo n.º 24
0
        public unsafe override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(-3f, 3, -3f);
            camera.Yaw      = MathHelper.Pi * 3f / 4;
            camera.Pitch    = MathHelper.Pi * 0.1f;
            Simulation      = Simulation.Create(BufferPool, new DemoNarrowPhaseCallbacks(), new DemoPoseIntegratorCallbacks(new Vector3(0, -10, 0)),
                                                initialAllocationSizes: new SimulationAllocationSizes
            {
                Bodies = 1,
                ConstraintCountPerBodyEstimate = 1,
                Constraints             = 1,
                ConstraintsPerTypeBatch = 1,
                Islands       = 1,
                ShapesPerType = 1,
                Statics       = 1
            });

            var shape = new Sphere(0.5f);

            shape.ComputeInertia(1, out var sphereInertia);
            var       shapeIndex     = Simulation.Shapes.Add(shape);
            const int width          = 12;
            const int height         = 4;
            const int length         = 12;
            var       latticeSpacing = 5.1f;
            var       latticeOffset  = -0.5f * width * latticeSpacing;

            SimulationSetup.BuildLattice(
                new RegularGridBuilder(new Vector3(latticeSpacing, 1.5f, latticeSpacing), new Vector3(latticeOffset, 10, latticeOffset), sphereInertia, shapeIndex),
                new ConstraintlessLatticeBuilder(),
                width, height, length, Simulation, out var bodyHandles, out var constraintHandles);
            Simulation.Deterministic = false;

            var         staticShape              = new Sphere(4);
            var         staticShapeIndex         = Simulation.Shapes.Add(staticShape);
            const int   staticGridWidthInSpheres = 100;
            const float staticSpacing            = 6;

            for (int i = 0; i < staticGridWidthInSpheres; ++i)
            {
                for (int j = 0; j < staticGridWidthInSpheres; ++j)
                {
                    var staticDescription = new StaticDescription
                    {
                        Collidable = new CollidableDescription
                        {
                            Continuity = new ContinuousDetectionSettings {
                                Mode = ContinuousDetectionMode.Discrete
                            },
                            Shape             = staticShapeIndex,
                            SpeculativeMargin = 0.1f
                        },
                        Pose = new RigidPose
                        {
                            Position = new Vector3(
                                -staticGridWidthInSpheres * staticSpacing * 0.5f + i * staticSpacing,
                                -4,
                                -staticGridWidthInSpheres * staticSpacing * 0.5f + j * staticSpacing),
                            Orientation = Quaternion.Identity
                        }
                    };
                    Simulation.Statics.Add(staticDescription);
                }
            }
        }
Exemplo n.º 25
0
        public unsafe override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(-10, 0, -10);
            //camera.Yaw = MathHelper.Pi ;
            camera.Yaw = MathHelper.Pi * 3f / 4;
            //camera.Pitch = MathHelper.PiOver2 * 0.999f;
            Simulation = Simulation.Create(BufferPool, new TestCallbacks());
            //Simulation.PoseIntegrator.Gravity = new Vector3(0, -10, 0);

            var box     = new Box(1f, 3f, 2f);
            var capsule = new Capsule(1f, 1f);
            var sphere  = new Sphere(.5f);

            box.ComputeInertia(1, out var boxInertia);
            capsule.ComputeInertia(1, out var capsuleInertia);
            sphere.ComputeInertia(1, out var sphereInertia);
            var       boxIndex     = Simulation.Shapes.Add(box);
            var       capsuleIndex = Simulation.Shapes.Add(capsule);
            var       sphereIndex  = Simulation.Shapes.Add(sphere);
            const int width        = 1;
            const int height       = 3;
            const int length       = 1;

            for (int i = 0; i < width; ++i)
            {
                for (int j = 0; j < height; ++j)
                {
                    for (int k = 0; k < length; ++k)
                    {
                        var location        = new Vector3(3, 3, 3) * new Vector3(i, j, k);// + new Vector3(-width * 1.5f, 1.5f, -length * 1.5f);
                        var bodyDescription = new BodyDescription
                        {
                            Activity = new BodyActivityDescription {
                                MinimumTimestepCountUnderThreshold = 32, SleepThreshold = -0.01f
                            },
                            Pose = new RigidPose
                            {
                                Orientation = BepuUtilities.Quaternion.Identity,
                                Position    = location
                            },
                            Collidable = new CollidableDescription
                            {
                                Continuity = new ContinuousDetectionSettings {
                                    Mode = ContinuousDetectionMode.Discrete
                                },
                                SpeculativeMargin = 0.1f
                            }
                        };
                        switch (j % 3)
                        {
                        case 0:
                            bodyDescription.Collidable.Shape = boxIndex;
                            bodyDescription.LocalInertia     = boxInertia;
                            break;

                        case 1:
                            bodyDescription.Collidable.Shape = capsuleIndex;
                            bodyDescription.LocalInertia     = capsuleInertia;
                            break;

                        case 2:
                            bodyDescription.Collidable.Shape = sphereIndex;
                            bodyDescription.LocalInertia     = sphereInertia;
                            break;
                        }
                        //Simulation.Bodies.Add(bodyDescription);
                    }
                }
            }
            //Simulation.Bodies.Add(new BodyDescription
            //{
            //    Activity = new BodyActivityDescription(-1),
            //    Pose = new RigidPose(new Vector3(1, 2.999f, 0), BepuUtilities.Quaternion.CreateFromYawPitchRoll(0, 0, -0.00001f)),
            //    Collidable = new CollidableDescription(capsuleIndex, 1),
            //    LocalInertia = capsuleInertia
            //});
            Simulation.Bodies.Add(new BodyDescription
            {
                Activity     = new BodyActivityDescription(-1),
                Pose         = new RigidPose(new Vector3(0, 0, 0), BepuUtilities.Quaternion.Identity),
                Collidable   = new CollidableDescription(boxIndex, .1f),
                LocalInertia = boxInertia
            });
            Simulation.Bodies.Add(new BodyDescription
            {
                Activity     = new BodyActivityDescription(-1),
                Pose         = new RigidPose(new Vector3(1, 3, 0), BepuUtilities.Quaternion.Identity),
                Collidable   = new CollidableDescription(boxIndex, .1f),
                LocalInertia = new BodyInertia()
            });

            var meshContent = content.Load <MeshContent>(@"Content\box.obj");

            //BufferPool.Take<Triangle>(meshContent.Triangles.Length, out var triangles);
            //for (int i = 0; i < meshContent.Triangles.Length; ++i)
            //{
            //    triangles[i] = new Triangle(meshContent.Triangles[i].A, meshContent.Triangles[i].B, meshContent.Triangles[i].C);
            //}
            //var meshShape = new Mesh(triangles.Slice(0, meshContent.Triangles.Length), new Vector3(5, 1, 5), BufferPool);
            BufferPool.Take <Triangle>(2, out var triangles);
            for (int i = 2; i < 4; ++i)
            {
                triangles[i - 2] = new Triangle(meshContent.Triangles[i].A, meshContent.Triangles[i].B, meshContent.Triangles[i].C);
            }
            var meshShape        = new Mesh(triangles.Slice(0, 2), new Vector3(5, 1, 5), BufferPool);
            var staticShapeIndex = Simulation.Shapes.Add(meshShape);

            for (int i = 0; i < 1; ++i)
            {
                var staticDescription = new StaticDescription
                {
                    Collidable = new CollidableDescription(staticShapeIndex, 0.1f),
                    Pose       = new RigidPose
                    {
                        Position    = new Vector3(i * 10, -10, 0),
                        Orientation = BepuUtilities.Quaternion.Identity
                                      //Orientation = BepuUtilities.Quaternion.CreateFromAxisAngle(Vector3.Normalize(new Vector3(1 + i, i * j % 10, -10 + -j)), (i ^ j) * 0.5f * (MathHelper.PiOver4))
                                      //Orientation = BepuUtilities.Quaternion.CreateFromAxisAngle(Vector3.Normalize(new Vector3(0, 0, 1)), MathHelper.Pi)
                    }
                };
                Simulation.Statics.Add(staticDescription);
            }
        }
Exemplo n.º 26
0
        public unsafe override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(0, 25, 80);
            camera.Yaw      = 0;
            camera.Pitch    = 0;
            timestepper     = new SubsteppingTimestepper(8);
            Simulation      = Simulation.Create(BufferPool, new DemoNarrowPhaseCallbacks()
            {
                ContactSpringiness = new SpringSettings(120, 120)
            }, new DemoPoseIntegratorCallbacks(new Vector3(0, -10, 0)), timestepper, 8);

            rolloverInfo = new RolloverInfo();
            {
                //We'll create a 0 level arm rope like the one from the RopeStabilityDemo. No skip constraints, though- and the mass ratio will be 1000:1 instead of 100:1!
                var         startLocation  = new Vector3(15, 40, 0);
                const float bodySpacing    = 0.3f;
                const float bodyRadius     = 0.5f;
                var         springSettings = new SpringSettings(240, 480);
                var         bodyHandles    = RopeStabilityDemo.BuildRope(Simulation, startLocation, 12, bodyRadius, bodySpacing, 0, 1, 0, springSettings);

                var bigWreckingBall = new Sphere(5);
                bigWreckingBall.ComputeInertia(1000, out var bigWreckingBallInertia);

                RopeStabilityDemo.AttachWreckingBall(Simulation, bodyHandles, bodyRadius, bodySpacing, 0, bigWreckingBall.Radius, bigWreckingBallInertia, Simulation.Shapes.Add(bigWreckingBall), springSettings);
                rolloverInfo.Add(startLocation + new Vector3(0, 2, 0), "1000:1 mass ratio");
            }

            {
                //Stack with a heavy block on top. Note that the contact springiness we chose in the DemoNarrowPhaseCallbacks above is important to making the stack resist the weight of the top block.
                //It's also the reason why we need higher substeps- 120hz frequency is too high for 60hz solving! Watch what happens when you drop the substep count to 3.
                //(Note that the demos timestep frequency is 60hz, so 4 substeps is a 240hz solve rate- twice the 120hz contact frequency.)
                var boxShape = new Box(4, 0.5f, 6f);
                boxShape.ComputeInertia(1, out var boxInertia);
                //Note that sleeping is disabled with a negative velocity threshold. We want to watch the stack as we change simulation settings; if it's inactive, it won't respond!
                var boxDescription = BodyDescription.CreateDynamic(new Vector3(), boxInertia, new CollidableDescription(Simulation.Shapes.Add(boxShape), 0.1f), new BodyActivityDescription(-1f));
                for (int i = 0; i < 20; ++i)
                {
                    boxDescription.Pose = new RigidPose(new Vector3(0, 0.5f + boxShape.Height * (i + 0.5f), 0), QuaternionEx.CreateFromAxisAngle(Vector3.UnitY, MathF.PI * 0.05f * i));
                    Simulation.Bodies.Add(boxDescription);
                }
                var topBlockShape = new Box(8, 2, 8);
                topBlockShape.ComputeInertia(200, out var topBlockInertia);
                Simulation.Bodies.Add(
                    BodyDescription.CreateDynamic(boxDescription.Pose.Position + new Vector3(0, boxShape.HalfHeight + 1f, 0), topBlockInertia,
                                                  new CollidableDescription(Simulation.Shapes.Add(topBlockShape), 0.1f), new BodyActivityDescription(-1f)));

                rolloverInfo.Add(boxDescription.Pose.Position + new Vector3(0, 4, 0), "200:1 mass ratio");
            }

            {
                //Now a weird rotating multi-arm thing. Long constraint sequences with high leverages under stress are a really tough problem for iterative velocity solvers.
                //(Fortunately, all 5 degrees of freedom of each hinge constraint are solved analytically, so the convergence issues aren't quite as bad as they could be.)
                var basePosition  = new Vector3(-20, 20, 0);
                var boxShape      = new Box(0.5f, 0.5f, 3f);
                var boxCollidable = new CollidableDescription(Simulation.Shapes.Add(boxShape), 0.1f);
                boxShape.ComputeInertia(1, out var boxInertia);
                var linkDescription = BodyDescription.CreateDynamic(new Vector3(), boxInertia, boxCollidable, new BodyActivityDescription(0.01f));


                for (int chainIndex = 0; chainIndex < 4; ++chainIndex)
                {
                    linkDescription.Pose.Position = basePosition + new Vector3(0, 0, chainIndex * 15);
                    var previousLinkHandle = Simulation.Bodies.Add(BodyDescription.CreateKinematic(linkDescription.Pose.Position, boxCollidable, new BodyActivityDescription(0.01f)));
                    for (int linkIndex = 0; linkIndex < 8; ++linkIndex)
                    {
                        var previousPosition = linkDescription.Pose.Position;
                        var offset           = new Vector3(boxShape.Width * 1.05f, 0, boxShape.Length - boxShape.Width);
                        linkDescription.Pose.Position += offset;
                        var linkHandle = Simulation.Bodies.Add(linkDescription);
                        Simulation.Solver.Add(previousLinkHandle, linkHandle, new Hinge
                        {
                            LocalHingeAxisA = Vector3.UnitX,
                            LocalHingeAxisB = Vector3.UnitX,
                            LocalOffsetA    = offset * 0.5f,
                            LocalOffsetB    = offset * -0.5f,
                            //Once again, the choice of high stiffness makes this potentially unstable without substepping.
                            SpringSettings = new SpringSettings(120, 1)
                        });
                        Simulation.Solver.Add(previousLinkHandle, linkHandle, new AngularAxisMotor
                        {
                            LocalAxisA     = Vector3.UnitX,
                            TargetVelocity = .25f,
                            Settings       = new MotorSettings(float.MaxValue, 0.0001f)
                        });
                        previousLinkHandle = linkHandle;
                    }
                }
                rolloverInfo.Add(basePosition + new Vector3(0, 4, 0), "High stiffness, long lever arm motorized chain");
            }


            Simulation.Statics.Add(new StaticDescription(new Vector3(0, 0, 0), new CollidableDescription(Simulation.Shapes.Add(new Box(200, 1, 200)), 0.1f)));
        }
Exemplo n.º 27
0
        public override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(0, 5, 10);
            camera.Yaw      = 0;
            camera.Pitch    = 0;

            bodyProperties = new CollidableProperty <TankDemoBodyProperties>();
            //We assign velocities outside of the timestep to fire bullets, so using the PositionLastTimestepper avoids integrating those velocities into positions before the solver has a chance to intervene.
            //We could have also modified velocities in the PositionFirstTimestepper's BeforeCollisionDetection callback, but it's just a little simpler to do this with very little cost.
            Simulation = Simulation.Create(BufferPool, new TankCallbacks()
            {
                Properties = bodyProperties
            }, new DemoPoseIntegratorCallbacks(new Vector3(0, -10, 0)), new PositionLastTimestepper());

            var builder = new CompoundBuilder(BufferPool, Simulation.Shapes, 2);

            builder.Add(new Box(1.85f, 0.7f, 4.73f), RigidPose.Identity, 10);
            builder.Add(new Box(1.85f, 0.6f, 2.5f), new RigidPose(new Vector3(0, 0.65f, -0.35f)), 0.5f);
            builder.BuildDynamicCompound(out var children, out var bodyInertia, out _);
            builder.Dispose();
            var bodyShape      = new Compound(children);
            var bodyShapeIndex = Simulation.Shapes.Add(bodyShape);
            var wheelShape     = new Cylinder(0.4f, .18f);

            wheelShape.ComputeInertia(0.25f, out var wheelInertia);
            var wheelShapeIndex = Simulation.Shapes.Add(wheelShape);

            var projectileShape = new Sphere(0.1f);

            projectileShape.ComputeInertia(0.2f, out var projectileInertia);
            var tankDescription = new TankDescription
            {
                Body         = TankPartDescription.Create(10, new Box(4f, 1, 5), RigidPose.Identity, 0.5f, Simulation.Shapes),
                Turret       = TankPartDescription.Create(1, new Box(1.5f, 0.7f, 2f), new RigidPose(new Vector3(0, 0.85f, 0.4f)), 0.5f, Simulation.Shapes),
                Barrel       = TankPartDescription.Create(0.5f, new Box(0.2f, 0.2f, 3f), new RigidPose(new Vector3(0, 0.85f, 0.4f - 1f - 1.5f)), 0.5f, Simulation.Shapes),
                TurretAnchor = new Vector3(0f, 0.5f, 0.4f),
                BarrelAnchor = new Vector3(0, 0.5f + 0.35f, 0.4f - 1f),
                TurretBasis  = Quaternion.Identity,
                TurretServo  = new ServoSettings(1f, 0f, 40f),
                TurretSpring = new SpringSettings(10f, 1f),
                BarrelServo  = new ServoSettings(1f, 0f, 40f),
                BarrelSpring = new SpringSettings(10f, 1f),

                ProjectileShape            = Simulation.Shapes.Add(projectileShape),
                ProjectileSpeed            = 100f,
                BarrelLocalProjectileSpawn = new Vector3(0, 0, -1.5f),
                ProjectileInertia          = projectileInertia,

                LeftTreadOffset    = new Vector3(-1.9f, 0f, 0),
                RightTreadOffset   = new Vector3(1.9f, 0f, 0),
                SuspensionLength   = 1f,
                SuspensionSettings = new SpringSettings(2.5f, 1.5f),
                WheelShape         = wheelShapeIndex,
                WheelInertia       = wheelInertia,
                WheelFriction      = 2f,
                TreadSpacing       = 1f,
                WheelCountPerTread = 5,
                WheelOrientation   = QuaternionEx.CreateFromAxisAngle(Vector3.UnitZ, MathF.PI * -0.5f),
            };

            playerController = new TankController(Tank.Create(Simulation, bodyProperties, BufferPool, new RigidPose(new Vector3(0, 10, 0), Quaternion.Identity), tankDescription), 20, 5, 2, 1, 3.5f);


            const int   planeWidth          = 257;
            const float terrainScale        = 3;
            const float inverseTerrainScale = 1f / terrainScale;
            var         terrainPosition     = new Vector2(1 - planeWidth, 1 - planeWidth) * terrainScale * 0.5f;

            random = new Random(5);

            //Add some building-ish landmarks.
            var landmarkMin  = new Vector3(planeWidth * terrainScale * -0.45f, 0, planeWidth * terrainScale * -0.45f);
            var landmarkMax  = new Vector3(planeWidth * terrainScale * 0.45f, 0, planeWidth * terrainScale * 0.45f);
            var landmarkSpan = landmarkMax - landmarkMin;

            for (int j = 0; j < 25; ++j)
            {
                var buildingShape = new Box(10 + (float)random.NextDouble() * 10, 20 + (float)random.NextDouble() * 20, 10 + (float)random.NextDouble() * 10);
                var position      = landmarkMin + landmarkSpan * new Vector3((float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble());
                Simulation.Statics.Add(new StaticDescription(
                                           new Vector3(0, buildingShape.HalfHeight - 4f + GetHeightForPosition(position.X, position.Z, planeWidth, inverseTerrainScale, terrainPosition), 0) + position,
                                           QuaternionEx.CreateFromAxisAngle(Vector3.UnitY, (float)random.NextDouble() * MathF.PI),
                                           new CollidableDescription(Simulation.Shapes.Add(buildingShape), 0.1f)));
            }

            DemoMeshHelper.CreateDeformedPlane(planeWidth, planeWidth,
                                               (int vX, int vY) =>
            {
                var position2D = new Vector2(vX, vY) * terrainScale + terrainPosition;
                return(new Vector3(position2D.X, GetHeightForPosition(position2D.X, position2D.Y, planeWidth, inverseTerrainScale, terrainPosition), position2D.Y));
            }, new Vector3(1, 1, 1), BufferPool, out var planeMesh);
            Simulation.Statics.Add(new StaticDescription(new Vector3(0, 0, 0),
                                                         new CollidableDescription(Simulation.Shapes.Add(planeMesh), 0.1f)));

            explosions = new QuickList <Explosion>(32, BufferPool);

            //Create the AI tanks.
            const int aiTankCount = 100;

            aiTanks     = new QuickList <AITank>(aiTankCount, BufferPool);
            playAreaMin = new Vector2(landmarkMin.X, landmarkMin.Z);
            playAreaMax = new Vector2(landmarkMax.X, landmarkMax.Z);
            var playAreaSpan = playAreaMax - playAreaMin;

            for (int i = 0; i < aiTankCount; ++i)
            {
                var horizontalPosition = playAreaMin + new Vector2((float)random.NextDouble(), (float)random.NextDouble()) * playAreaSpan;
                aiTanks.AllocateUnsafely() = new AITank
                {
                    Controller = new TankController(
                        Tank.Create(Simulation, bodyProperties, BufferPool, new RigidPose(
                                        new Vector3(horizontalPosition.X, 10, horizontalPosition.Y),
                                        QuaternionEx.CreateFromAxisAngle(new Vector3(0, 1, 0), (float)random.NextDouble() * 0.1f)),
                                    tankDescription), 20, 5, 2, 1, 3.5f),
                    HitPoints = 5
                };
            }
        }
Exemplo n.º 28
0
        public unsafe override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(0, 10, 40);
            camera.Yaw      = 0;
            camera.Pitch    = 0;
            Simulation      = Simulation.Create(BufferPool, new TestCallbacks());
            Simulation.PoseIntegrator.Gravity = new Vector3(0, -10, 0);

            var box     = new Box(2f, 2f, 2f);
            var capsule = new Capsule(1f, 1f);
            var sphere  = new Sphere(1.5f);

            box.ComputeInertia(1, out var boxInertia);
            capsule.ComputeInertia(1, out var capsuleInertia);
            sphere.ComputeInertia(1, out var sphereInertia);
            var       boxIndex     = Simulation.Shapes.Add(box);
            var       capsuleIndex = Simulation.Shapes.Add(capsule);
            var       sphereIndex  = Simulation.Shapes.Add(sphere);
            const int width        = 12;
            const int height       = 3;
            const int length       = 12;

            for (int i = 0; i < width; ++i)
            {
                for (int j = 0; j < height; ++j)
                {
                    for (int k = 0; k < length; ++k)
                    {
                        var location        = new Vector3(5, 5, 5) * new Vector3(i, j, k) + new Vector3(-width * 2.5f, 2.5f, -length * 2.5f);
                        var bodyDescription = new BodyDescription
                        {
                            Activity = new BodyActivityDescription {
                                MinimumTimestepCountUnderThreshold = 32, SleepThreshold = 0.1f
                            },
                            Pose = new RigidPose
                            {
                                Orientation = Quaternion.Identity,
                                Position    = location
                            },
                            Collidable = new CollidableDescription
                            {
                                Continuity = new ContinuousDetectionSettings {
                                    Mode = ContinuousDetectionMode.Discrete
                                },
                                SpeculativeMargin = 0.1f
                            }
                        };
                        switch (j % 3)
                        {
                        case 0:
                            bodyDescription.Collidable.Shape = boxIndex;
                            bodyDescription.LocalInertia     = boxInertia;
                            break;

                        case 1:
                            bodyDescription.Collidable.Shape = capsuleIndex;
                            bodyDescription.LocalInertia     = capsuleInertia;
                            break;

                        case 2:
                            bodyDescription.Collidable.Shape = sphereIndex;
                            bodyDescription.LocalInertia     = sphereInertia;
                            break;
                        }
                        Simulation.Bodies.Add(bodyDescription);
                    }
                }
            }


            //var staticShapeIndex = Simulation.Shapes.Add(new Box(100, 1, 100));
            //var staticDescription = new StaticDescription
            //{
            //    Collidable = new CollidableDescription
            //    {
            //        Continuity = new ContinuousDetectionSettings { Mode = ContinuousDetectionMode.Discrete },
            //        Shape = Simulation.Shapes.Add(new Box(100, 1, 100)),
            //        SpeculativeMargin = 0.1f
            //    },
            //    Pose = new RigidPose { Position = new Vector3(0, -1, 0), Orientation = Quaternion.Identity }
            //};
            //Simulation.Statics.Add(staticDescription);

            const int planeWidth  = 64;
            const int planeHeight = 64;

            MeshDemo.CreateDeformedPlane(planeWidth, planeHeight,
                                         (int x, int y) =>
            {
                return(new Vector3(x, 1 * MathF.Cos(x / 4f) * MathF.Sin(y / 4f), y));
            }, new Vector3(2, 3, 2), BufferPool, out var planeMesh);
            Simulation.Statics.Add(new StaticDescription(new Vector3(-64, -10, -64), new CollidableDescription(Simulation.Shapes.Add(planeMesh), 0.1f)));
        }
Exemplo n.º 29
0
        public unsafe override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(-120, 30, -120);
            camera.Yaw      = MathHelper.Pi * 3f / 4;
            camera.Pitch    = 0.1f;
            Simulation      = Simulation.Create(BufferPool, new DemoNarrowPhaseCallbacks(), new DemoPoseIntegratorCallbacks(new Vector3(0, -10, 0)));
            Simulation.Solver.IterationCount = 8;

            //Build a grid of shapes to be connected.
            var clothNodeShape = new Sphere(0.5f);

            clothNodeShape.ComputeInertia(1, out var clothNodeInertia);
            var         clothNodeShapeIndex = Simulation.Shapes.Add(clothNodeShape);
            const int   width   = 128;
            const int   length  = 128;
            const float spacing = 1.75f;

            int[][] nodeHandles = new int[width][];
            for (int i = 0; i < width; ++i)
            {
                nodeHandles[i] = new int[length];
                for (int j = 0; j < length; ++j)
                {
                    var location        = new Vector3(0, 30, 0) + new Vector3(spacing, 0, spacing) * (new Vector3(i, 0, j) + new Vector3(-width * 0.5f, 0, -length * 0.5f));
                    var bodyDescription = new BodyDescription
                    {
                        Activity = new BodyActivityDescription {
                            MinimumTimestepCountUnderThreshold = 32, SleepThreshold = 0.01f
                        },
                        Pose = new RigidPose
                        {
                            Orientation = BepuUtilities.Quaternion.Identity,
                            Position    = location
                        },
                        Collidable = new CollidableDescription
                        {
                            Shape      = clothNodeShapeIndex,
                            Continuity = new ContinuousDetectionSettings {
                                Mode = ContinuousDetectionMode.Discrete
                            },
                            SpeculativeMargin = 0.1f
                        },
                        LocalInertia = clothNodeInertia
                    };
                    nodeHandles[i][j] = Simulation.Bodies.Add(bodyDescription);
                }
            }
            //Construct some joints between the nodes.
            var left = new BallSocket
            {
                LocalOffsetA   = new Vector3(-spacing * 0.5f, 0, 0),
                LocalOffsetB   = new Vector3(spacing * 0.5f, 0, 0),
                SpringSettings = new SpringSettings(10, 1)
            };
            var up = new BallSocket
            {
                LocalOffsetA   = new Vector3(0, 0, -spacing * 0.5f),
                LocalOffsetB   = new Vector3(0, 0, spacing * 0.5f),
                SpringSettings = new SpringSettings(10, 1)
            };
            var leftUp = new BallSocket
            {
                LocalOffsetA   = new Vector3(-spacing * 0.5f, 0, -spacing * 0.5f),
                LocalOffsetB   = new Vector3(spacing * 0.5f, 0, spacing * 0.5f),
                SpringSettings = new SpringSettings(10, 1)
            };
            var rightUp = new BallSocket
            {
                LocalOffsetA   = new Vector3(spacing * 0.5f, 0, -spacing * 0.5f),
                LocalOffsetB   = new Vector3(-spacing * 0.5f, 0, spacing * 0.5f),
                SpringSettings = new SpringSettings(10, 1)
            };

            for (int i = 0; i < width; ++i)
            {
                for (int j = 0; j < length; ++j)
                {
                    if (i >= 1)
                    {
                        Simulation.Solver.Add(nodeHandles[i][j], nodeHandles[i - 1][j], ref left);
                    }
                    if (j >= 1)
                    {
                        Simulation.Solver.Add(nodeHandles[i][j], nodeHandles[i][j - 1], ref up);
                    }
                    if (i >= 1 && j >= 1)
                    {
                        Simulation.Solver.Add(nodeHandles[i][j], nodeHandles[i - 1][j - 1], ref leftUp);
                    }
                    if (i < width - 1 && j >= 1)
                    {
                        Simulation.Solver.Add(nodeHandles[i][j], nodeHandles[i + 1][j - 1], ref rightUp);
                    }
                }
            }
            var bigBallShape      = new Sphere(45);
            var bigBallShapeIndex = Simulation.Shapes.Add(bigBallShape);

            var bigBallDescription = new BodyDescription
            {
                Collidable = new CollidableDescription
                {
                    Continuity = new ContinuousDetectionSettings {
                        Mode = ContinuousDetectionMode.Discrete
                    },
                    Shape             = bigBallShapeIndex,
                    SpeculativeMargin = 0.1f
                },
                Activity = new BodyActivityDescription(0),
                Pose     = new RigidPose
                {
                    Position    = new Vector3(-10, -15, 0),
                    Orientation = BepuUtilities.Quaternion.Identity
                }
            };

            bigBallHandle = Simulation.Bodies.Add(bigBallDescription);

            var groundShape      = new Box(200, 1, 200);
            var groundShapeIndex = Simulation.Shapes.Add(groundShape);

            var groundDescription = new BodyDescription
            {
                Collidable = new CollidableDescription
                {
                    Continuity = new ContinuousDetectionSettings {
                        Mode = ContinuousDetectionMode.Discrete
                    },
                    Shape             = groundShapeIndex,
                    SpeculativeMargin = 0.1f
                },
                Activity = new BodyActivityDescription(0),
                Pose     = new RigidPose
                {
                    Position    = new Vector3(0, -10, 0),
                    Orientation = BepuUtilities.Quaternion.Identity
                }
            };

            Simulation.Bodies.Add(groundDescription);
        }
Exemplo n.º 30
0
        public unsafe override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(-120, 30, -120);
            camera.Yaw      = MathHelper.Pi * 3f / 4;
            camera.Pitch    = 0.1f;
            //The PositionFirstTimestepper is the simplest timestepping mode, but since it integrates velocity into position at the start of the frame, directly modified velocities outside of the timestep
            //will be integrated before collision detection or the solver has a chance to intervene. That's fine in this demo. Other built-in options include the PositionLastTimestepper and the SubsteppingTimestepper.
            //Note that the timestepper also has callbacks that you can use for executing logic between processing stages, like BeforeCollisionDetection.
            Simulation = Simulation.Create(BufferPool, new DemoNarrowPhaseCallbacks(), new DemoPoseIntegratorCallbacks(new Vector3(0, -10, 0)), new PositionFirstTimestepper());

            //Build a grid of shapes to be connected.
            var clothNodeShape = new Sphere(0.5f);

            clothNodeShape.ComputeInertia(1, out var clothNodeInertia);
            var         clothNodeShapeIndex = Simulation.Shapes.Add(clothNodeShape);
            const int   width   = 128;
            const int   length  = 128;
            const float spacing = 1.75f;

            BodyHandle[][] nodeHandles = new BodyHandle[width][];
            for (int i = 0; i < width; ++i)
            {
                nodeHandles[i] = new BodyHandle[length];
                for (int j = 0; j < length; ++j)
                {
                    var location        = new Vector3(0, 30, 0) + new Vector3(spacing, 0, spacing) * (new Vector3(i, 0, j) + new Vector3(-width * 0.5f, 0, -length * 0.5f));
                    var bodyDescription = new BodyDescription
                    {
                        Activity = new BodyActivityDescription {
                            MinimumTimestepCountUnderThreshold = 32, SleepThreshold = 0.01f
                        },
                        Pose = new RigidPose
                        {
                            Orientation = Quaternion.Identity,
                            Position    = location
                        },
                        Collidable = new CollidableDescription
                        {
                            Shape      = clothNodeShapeIndex,
                            Continuity = new ContinuousDetectionSettings {
                                Mode = ContinuousDetectionMode.Discrete
                            },
                            SpeculativeMargin = 0.1f
                        },
                        LocalInertia = clothNodeInertia
                    };
                    nodeHandles[i][j] = Simulation.Bodies.Add(bodyDescription);
                }
            }
            //Construct some joints between the nodes.
            var left = new BallSocket
            {
                LocalOffsetA   = new Vector3(-spacing * 0.5f, 0, 0),
                LocalOffsetB   = new Vector3(spacing * 0.5f, 0, 0),
                SpringSettings = new SpringSettings(10, 1)
            };
            var up = new BallSocket
            {
                LocalOffsetA   = new Vector3(0, 0, -spacing * 0.5f),
                LocalOffsetB   = new Vector3(0, 0, spacing * 0.5f),
                SpringSettings = new SpringSettings(10, 1)
            };
            var leftUp = new BallSocket
            {
                LocalOffsetA   = new Vector3(-spacing * 0.5f, 0, -spacing * 0.5f),
                LocalOffsetB   = new Vector3(spacing * 0.5f, 0, spacing * 0.5f),
                SpringSettings = new SpringSettings(10, 1)
            };
            var rightUp = new BallSocket
            {
                LocalOffsetA   = new Vector3(spacing * 0.5f, 0, -spacing * 0.5f),
                LocalOffsetB   = new Vector3(-spacing * 0.5f, 0, spacing * 0.5f),
                SpringSettings = new SpringSettings(10, 1)
            };

            for (int i = 0; i < width; ++i)
            {
                for (int j = 0; j < length; ++j)
                {
                    if (i >= 1)
                    {
                        Simulation.Solver.Add(nodeHandles[i][j], nodeHandles[i - 1][j], ref left);
                    }
                    if (j >= 1)
                    {
                        Simulation.Solver.Add(nodeHandles[i][j], nodeHandles[i][j - 1], ref up);
                    }
                    if (i >= 1 && j >= 1)
                    {
                        Simulation.Solver.Add(nodeHandles[i][j], nodeHandles[i - 1][j - 1], ref leftUp);
                    }
                    if (i < width - 1 && j >= 1)
                    {
                        Simulation.Solver.Add(nodeHandles[i][j], nodeHandles[i + 1][j - 1], ref rightUp);
                    }
                }
            }
            var bigBallShape      = new Sphere(25);
            var bigBallShapeIndex = Simulation.Shapes.Add(bigBallShape);

            var bigBallDescription = new StaticDescription
            {
                Collidable = new CollidableDescription
                {
                    Continuity = new ContinuousDetectionSettings {
                        Mode = ContinuousDetectionMode.Discrete
                    },
                    Shape             = bigBallShapeIndex,
                    SpeculativeMargin = 0.1f
                },
                Pose = new RigidPose
                {
                    Position    = new Vector3(-10, -15, 0),
                    Orientation = Quaternion.Identity
                }
            };

            Simulation.Statics.Add(bigBallDescription);

            var groundShape      = new Box(200, 1, 200);
            var groundShapeIndex = Simulation.Shapes.Add(groundShape);

            var groundDescription = new StaticDescription
            {
                Collidable = new CollidableDescription
                {
                    Continuity = new ContinuousDetectionSettings {
                        Mode = ContinuousDetectionMode.Discrete
                    },
                    Shape             = groundShapeIndex,
                    SpeculativeMargin = 0.1f
                },
                Pose = new RigidPose
                {
                    Position    = new Vector3(0, -10, 0),
                    Orientation = Quaternion.Identity
                }
            };

            Simulation.Statics.Add(groundDescription);
        }