コード例 #1
0
        public static RigidBody CreateRigidBodyFromTgcMesh(TgcMesh mesh, TGCVector3 position, float mass, float friction)
        {
            var meshAxisRadius = mesh.BoundingBox.calculateAxisRadius().ToBsVector;
            var boxShape       = new BoxShape(meshAxisRadius);

            var transformationMatrix = TGCMatrix.RotationYawPitchRoll(0, 0, 0).ToBsMatrix;

            transformationMatrix.Origin = position.ToBsVector;
            DefaultMotionState motionState = new DefaultMotionState(transformationMatrix);

            var boxLocalInertia = boxShape.CalculateLocalInertia(mass);

            var bodyInfo = new RigidBodyConstructionInfo(mass, motionState, boxShape, boxLocalInertia);

            var rigidBody = new RigidBody(bodyInfo)
            {
                LinearFactor     = TGCVector3.One.ToBsVector,
                Friction         = friction,
                RollingFriction  = 1f,
                AngularFactor    = new Vector3(1f, 0.2f, 1f),
                SpinningFriction = 0.7f
            };

            return(rigidBody);
        }
コード例 #2
0
        /*
         * void MyContactCallback(object sender, ContactAddedEventArgs e)
         * {
         *  if (e.CollisionObject0Wrapper.CollisionObject.CollisionShape.ShapeType == BroadphaseNativeType.CompoundShape)
         *  {
         *      CompoundShape compound = e.CollisionObject0Wrapper.CollisionObject.CollisionShape as CompoundShape;
         *      CollisionShape childShape = compound.GetChildShape(e.Index0);
         *  }
         *
         *  if (e.CollisionObject1Wrapper.CollisionObject.CollisionShape.ShapeType == BroadphaseNativeType.CompoundShape)
         *  {
         *      CompoundShape compound = e.CollisionObject1Wrapper.CollisionObject.CollisionShape as CompoundShape;
         *      CollisionShape childShape = compound.GetChildShape(e.Index1);
         *  }
         *
         *  e.IsContactModified = true;
         * }
         */

        public void SetupEmptyDynamicsWorld()
        {
            // collision configuration contains default setup for memory, collision setup
            CollisionConf = new DefaultCollisionConfiguration();
            Dispatcher    = new CollisionDispatcher(CollisionConf);

            CompoundCollisionAlgorithm.CompoundChildShapePairCallback = MyCompoundChildShapeCallback;

            convexDecompositionObjectOffset = new Vector3(10, 0, 0);

            Broadphase = new AxisSweep3(new Vector3(-10000, -10000, -10000), new Vector3(10000, 10000, 10000));
            //Broadphase = new SimpleBroadphase();

            Solver = new SequentialImpulseConstraintSolver();
            World  = new DiscreteDynamicsWorld(Dispatcher, Broadphase, Solver, CollisionConf);

            // create the ground
            CollisionShape groundShape = new BoxShape(30, 2, 30);

            CollisionShapes.Add(groundShape);
            CollisionObject ground = LocalCreateRigidBody(0, Matrix.Translation(0, -4.5f, 0), groundShape);

            ground.UserObject = "Ground";

            // create a few dynamic rigidbodies
            float mass = 1.0f;

            CollisionShape colShape = new BoxShape(1);

            CollisionShapes.Add(colShape);
            Vector3 localInertia = colShape.CalculateLocalInertia(mass);
        }
コード例 #3
0
        private void CreateBoxes()
        {
            const float mass     = 1.0f;
            var         colShape = new BoxShape(1);

            CollisionShapes.Add(colShape);
            Vector3 localInertia = colShape.CalculateLocalInertia(mass);

            var rbInfo = new RigidBodyConstructionInfo(mass, null, colShape, localInertia);

            for (int y = 0; y < ArraySizeY; y++)
            {
                for (int x = 0; x < ArraySizeX; x++)
                {
                    for (int z = 0; z < ArraySizeZ; z++)
                    {
                        Vector3 position = startPosition + 2 * new Vector3(x, y, z);

                        // make it drop from a height
                        position += new Vector3(0, 10, 0);

                        // using MotionState is recommended, it provides interpolation capabilities
                        // and only synchronizes 'active' objects
                        rbInfo.MotionState = new DefaultMotionState(Matrix.Translation(position));
                        var body = new RigidBody(rbInfo);

                        World.AddRigidBody(body);
                    }
                }
            }

            rbInfo.Dispose();
        }
コード例 #4
0
        void CreateTowerCircle(Vector3 offsetPosition, int stackSize, int rotSize, Vector3 boxSize)
        {
            BoxShape blockShape = new BoxShape(boxSize[0] - collisionRadius, boxSize[1] - collisionRadius, boxSize[2] - collisionRadius);

            float   mass = 1.0f;
            Vector3 localInertia;

            blockShape.CalculateLocalInertia(mass, out localInertia);

            float radius = 1.3f * rotSize * boxSize[0] / (float)Math.PI;

            // create active boxes
            float posY = boxSize[1];
            float rot  = 0;

            for (int i = 0; i < stackSize; i++)
            {
                for (int j = 0; j < rotSize; j++)
                {
                    Matrix trans = Matrix.Translation(0, 0, radius);
                    trans *= Matrix.RotationY(rot);
                    trans *= Matrix.Translation(offsetPosition + new Vector3(0, posY, 0));
                    LocalCreateRigidBody(mass, trans, blockShape);

                    rot += (2.0f * (float)Math.PI) / rotSize;
                }

                posY += boxSize[1] * 2.0f;
                rot  += (float)Math.PI / (float)rotSize;
            }
        }
コード例 #5
0
        private void CreateBoxes()
        {
            const float mass         = 1.0f;
            var         shape        = new BoxShape(Scale);
            Vector3     localInertia = shape.CalculateLocalInertia(mass);
            var         bodyInfo     = new RigidBodyConstructionInfo(mass, null, shape, localInertia);

            for (int y = 0; y < NumBoxesY; y++)
            {
                for (int x = 0; x < NumBoxesX; x++)
                {
                    for (int z = 0; z < NumBoxesZ; z++)
                    {
                        Vector3 position = _startPosition + Scale * 2 * new Vector3(x, y, z);

                        // make it drop from a height
                        position += new Vector3(0, Scale * 10, 0);

                        // using MotionState is recommended, it provides interpolation capabilities
                        // and only synchronizes 'active' objects
                        bodyInfo.MotionState = new DefaultMotionState(Matrix.Translation(position));
                        var body = new RigidBody(bodyInfo);

                        World.AddRigidBody(body);
                    }
                }
            }

            bodyInfo.Dispose();
        }
コード例 #6
0
ファイル: Physics.cs プロジェクト: raiker/BulletSharp
        public Physics()
        {
            // collision configuration contains default setup for memory, collision setup
            CollisionConf = new DefaultCollisionConfiguration();
            Dispatcher    = new CollisionDispatcher(CollisionConf);

            Broadphase = new DbvtBroadphase();

            World         = new DiscreteDynamicsWorld(Dispatcher, Broadphase, null, CollisionConf);
            World.Gravity = new Vector3(0, -10, 0);

            // create the ground
            CollisionShape groundShape = new BoxShape(50, 1, 50);

            CollisionShapes.Add(groundShape);
            CollisionObject ground = LocalCreateRigidBody(0, Matrix.Identity, groundShape);

            ground.UserObject = "Ground";

            // create a few dynamic rigidbodies
            float mass = 1.0f;

            CollisionShape colShape = new BoxShape(1);

            CollisionShapes.Add(colShape);
            Vector3 localInertia = colShape.CalculateLocalInertia(mass);

            float start_x = StartPosX - ArraySizeX / 2;
            float start_y = StartPosY;
            float start_z = StartPosZ - ArraySizeZ / 2;

            int k, i, j;

            for (k = 0; k < ArraySizeY; k++)
            {
                for (i = 0; i < ArraySizeX; i++)
                {
                    for (j = 0; j < ArraySizeZ; j++)
                    {
                        Matrix startTransform = Matrix.Translation(
                            2 * i + start_x,
                            2 * k + start_y,
                            2 * j + start_z
                            );

                        // using motionstate is recommended, it provides interpolation capabilities
                        // and only synchronizes 'active' objects
                        DefaultMotionState        myMotionState = new DefaultMotionState(startTransform);
                        RigidBodyConstructionInfo rbInfo        =
                            new RigidBodyConstructionInfo(mass, myMotionState, colShape, localInertia);
                        RigidBody body = new RigidBody(rbInfo);

                        // make it drop from a height
                        body.Translate(new Vector3(0, 20, 0));

                        World.AddRigidBody(body);
                    }
                }
            }
        }
コード例 #7
0
        MultiBody CreateFeatherstoneMultiBody(MultiBodyDynamicsWorld world, int numLinks,
                                              Vector3 basePosition, Vector3 baseHalfExtents, Vector3 linkHalfExtents, bool spherical, bool floating)
        {
            float   mass    = 1;
            Vector3 inertia = Vector3.Zero;

            if (mass != 0)
            {
                using (var box = new BoxShape(baseHalfExtents))
                {
                    box.CalculateLocalInertia(mass, out inertia);
                }
            }

            var mb = new MultiBody(numLinks, mass, inertia, !floating, false);

            //body.HasSelfCollision = false;

            //body.BaseVelocity = Vector3.Zero;
            mb.BasePosition = basePosition;
            //body.WorldToBaseRot = new Quaternion(0, 0, 1, -0.125f * (float)Math.PI);
            mb.WorldToBaseRot = Quaternion.Identity;

            float   linkMass    = 1;
            Vector3 linkInertia = Vector3.Zero;

            if (linkMass != 0)
            {
                using (var box = new BoxShape(linkHalfExtents))
                {
                    box.CalculateLocalInertia(linkMass, out linkInertia);
                }
            }

            //y-axis assumed up
            Vector3 parentComToCurrentCom    = new Vector3(0, -linkHalfExtents[1] * 2.0f, 0);    //par body's COM to cur body's COM offset
            Vector3 currentPivotToCurrentCom = new Vector3(0, -linkHalfExtents[1], 0);           //cur body's COM to cur body's PIV offset
            Vector3 parentComToCurrentPivot  = parentComToCurrentCom - currentPivotToCurrentCom; //par body's COM to cur body's PIV offset

            for (int i = 0; i < numLinks; i++)
            {
                if (spherical)
                {
                    mb.SetupSpherical(i, linkMass, linkInertia, i - 1,
                                      Quaternion.Identity, parentComToCurrentPivot, currentPivotToCurrentCom, false);
                }
                else
                {
                    Vector3 hingeJointAxis = new Vector3(1, 0, 0);
                    mb.SetupRevolute(i, linkMass, linkInertia, i - 1,
                                     Quaternion.Identity, hingeJointAxis, parentComToCurrentPivot, currentPivotToCurrentCom, false);
                }
            }

            mb.FinalizeMultiDof();

            (World as MultiBodyDynamicsWorld).AddMultiBody(mb);

            return(mb);
        }
コード例 #8
0
        void CreateWall(Vector3 offsetPosition, int stackSize, Vector3 boxSize)
        {
            BoxShape blockShape = new BoxShape(boxSize[0] - collisionRadius, boxSize[1] - collisionRadius, boxSize[2] - collisionRadius);

            float   mass = 1.0f;
            Vector3 localInertia;

            blockShape.CalculateLocalInertia(mass, out localInertia);

            //	float diffX = boxSize[0] * 1.0f;
            float diffY = boxSize[1] * 1.0f;
            float diffZ = boxSize[2] * 1.0f;

            float   offset = -stackSize * (diffZ * 2.0f) * 0.5f;
            Vector3 pos    = new Vector3(0.0f, diffY, 0.0f);

            while (stackSize > 0)
            {
                for (int i = 0; i < stackSize; i++)
                {
                    pos[2] = offset + (float)i * (diffZ * 2.0f);
                    LocalCreateRigidBody(mass, Matrix.Translation(offsetPosition + pos), blockShape);
                }
                offset += diffZ;
                pos[1] += (diffY * 2.0f);
                stackSize--;
            }
        }
コード例 #9
0
        public override void Init(BulletExampleWall ctx)
        {
            base.Init(ctx);

            //Creamos shapes y bodies.

            //El piso es un plano estatico se dice que si tiene masa 0 es estatico.
            var floorShape       = new StaticPlaneShape(TGCVector3.Up.ToBulletVector3(), 0);
            var floorMotionState = new DefaultMotionState();
            var floorInfo        = new RigidBodyConstructionInfo(0, floorMotionState, floorShape);

            floorBody = new RigidBody(floorInfo);
            dynamicsWorld.AddRigidBody(floorBody);

            //Se crea una caja de tamaño 20 con rotaciones y origien en 10,100,10 y 1kg de masa.
            var boxShape     = new BoxShape(10, 10, 10);
            var boxTransform = TGCMatrix.RotationYawPitchRoll(MathUtil.SIMD_HALF_PI, MathUtil.SIMD_QUARTER_PI, MathUtil.SIMD_2_PI).ToBsMatrix;

            boxTransform.Origin = new TGCVector3(10, 100, 10).ToBulletVector3();
            DefaultMotionState boxMotionState = new DefaultMotionState(boxTransform);
            //Es importante calcular la inercia caso contrario el objeto no rotara.
            var boxLocalInertia = boxShape.CalculateLocalInertia(1f);
            var boxInfo         = new RigidBodyConstructionInfo(1f, boxMotionState, boxShape, boxLocalInertia);

            boxBody = new RigidBody(boxInfo);
            dynamicsWorld.AddRigidBody(boxBody);

            //Crea una bola de radio 10 origen 50 de 1 kg.
            var ballShape     = new SphereShape(10);
            var ballTransform = TGCMatrix.Identity;

            ballTransform.Origin = new TGCVector3(0, 50, 0);
            var ballMotionState = new DefaultMotionState(ballTransform.ToBsMatrix);
            //Podriamos no calcular la inercia para que no rote, pero es correcto que rote tambien.
            var ballLocalInertia = ballShape.CalculateLocalInertia(1f);
            var ballInfo         = new RigidBodyConstructionInfo(1, ballMotionState, ballShape, ballLocalInertia);

            ballBody = new RigidBody(ballInfo);
            dynamicsWorld.AddRigidBody(ballBody);

            //Cargamos objetos de render del framework.
            var floorTexture = TgcTexture.createTexture(D3DDevice.Instance.Device, Ctx.MediaDir + @"Texturas\granito.jpg");

            floorMesh = new TgcPlane(new TGCVector3(-200, 0, -200), new TGCVector3(400, 0f, 400), TgcPlane.Orientations.XZplane, floorTexture);

            var texture = TgcTexture.createTexture(D3DDevice.Instance.Device, Ctx.MediaDir + @"Texturas\madera.jpg");

            //Es importante crear todos los mesh con centro en el 0,0,0 y que este coincida con el centro de masa definido caso contrario rotaria de otra forma diferente a la dada por el motor de fisica.
            boxMesh = TGCBox.fromSize(new TGCVector3(20, 20, 20), texture);
            //Se crea una esfera de tamaño 1 para escalarla luego (en render)
            sphereMesh = new TGCSphere(1, texture.Clone(), TGCVector3.Empty);
            //Tgc no crea el vertex buffer hasta invocar a update values.
            sphereMesh.updateValues();
        }
コード例 #10
0
        public void AddRigidBody(Physics3DRigidBody rb, Components.RigidBodyDesc desc)
        {
            MotionState motionState;
            Matrix4x4   mat = MatrixExt.Transform(desc.Position, desc.Rotation);

            rb.defaultPosition = desc.Position;
            rb.defaultRotation = desc.Rotation;

            motionState = new DefaultMotionState(GetMatrix(mat));
            CollisionShape collisionShape;

            switch (desc.Shape)
            {
            case Components.RigidBodyShape.Sphere:
                collisionShape = new SphereShape(desc.Dimemsions.X);
                break;

            case Components.RigidBodyShape.Capsule:
                collisionShape = new CapsuleShape(desc.Dimemsions.X, desc.Dimemsions.Y);
                break;

            case Components.RigidBodyShape.Box:
            default:
                collisionShape = new BoxShape(GetVector3(desc.Dimemsions));
                break;
            }
            float mass = desc.Mass;

            BulletSharp.Math.Vector3 localInertia = new BulletSharp.Math.Vector3();
            if (desc.Type == 0)
            {
                mass = 0;
            }
            else
            {
                collisionShape.CalculateLocalInertia(mass, out localInertia);
            }
            var rigidbodyInfo = new RigidBodyConstructionInfo(mass, motionState, collisionShape, localInertia);

            rigidbodyInfo.Friction       = desc.Friction;
            rigidbodyInfo.LinearDamping  = desc.LinearDamping;
            rigidbodyInfo.AngularDamping = desc.AngularDamping;
            rigidbodyInfo.Restitution    = desc.Restitution;

            rb.rigidBody = new RigidBody(rigidbodyInfo);
            rb.rigidBody.ActivationState = ActivationState.DisableDeactivation;
            rb.rigidBody.SetSleepingThresholds(0, 0);
            if (desc.Type == Components.RigidBodyType.Kinematic)
            {
                rb.rigidBody.CollisionFlags |= CollisionFlags.KinematicObject;
            }
            world.AddRigidBody(rb.rigidBody, 1 << desc.CollisionGroup, desc.CollisionMask);
        }
コード例 #11
0
        public Physics()
        {
            // collision configuration contains default setup for memory, collision setup
            _collisionConf = new DefaultCollisionConfiguration();
            _dispatcher    = new CollisionDispatcher(_collisionConf);

            _broadphase = new DbvtBroadphase();
            World       = new DiscreteDynamicsWorld(_dispatcher, _broadphase, null, _collisionConf);

            // create the ground
            var groundShape = new BoxShape(50, 50, 50);

            _collisionShapes.Add(groundShape);
            CollisionObject ground = CreateStaticBody(Matrix.Translation(0, -50, 0), groundShape);

            ground.UserObject = "Ground";

            // create a few dynamic rigidbodies
            var colShape = new BoxShape(1);

            _collisionShapes.Add(colShape);

            float   mass         = 1.0f;
            Vector3 localInertia = colShape.CalculateLocalInertia(mass);

            var rbInfo = new RigidBodyConstructionInfo(mass, null, colShape, localInertia);

            for (int y = 0; y < ArraySizeY; y++)
            {
                for (int x = 0; x < ArraySizeX; x++)
                {
                    for (int z = 0; z < ArraySizeZ; z++)
                    {
                        Matrix startTransform = Matrix.Translation(
                            _startPosition + 2 * new Vector3(x, y, z));

                        // using motionstate is recommended, it provides interpolation capabilities
                        // and only synchronizes 'active' objects
                        rbInfo.MotionState = new DefaultMotionState(startTransform);
                        var body = new RigidBody(rbInfo);

                        // make it drop from a height
                        body.Translate(new Vector3(0, 15, 0));

                        World.AddRigidBody(body);
                    }
                }
            }

            rbInfo.Dispose();
        }
コード例 #12
0
        public static RigidBody crearBodyCubico(float masa, TGCVector3 escala, TGCVector3 origen)
        {
            #region CAJA

            var boxShape = new BoxShape(escala.X, escala.Y, escala.Z);
            //var boxTransform = TGCMatrix.RotationYawPitchRoll(MathUtil.SIMD_HALF_PI, MathUtil.SIMD_QUARTER_PI, MathUtil.SIMD_2_PI).ToBsMatrix;
            //boxTransform.Origin = origen.ToBsVector;
            DefaultMotionState boxMotionState = new DefaultMotionState(Matrix.Translation(origen.X, origen.Y, origen.Z));// boxTransform);
            //Es importante calcular la inercia caso contrario el objeto no rotara.
            var boxLocalInertia = boxShape.CalculateLocalInertia(masa);
            var boxInfo         = new RigidBodyConstructionInfo(masa, boxMotionState, boxShape, boxLocalInertia);
            return(new RigidBody(boxInfo));

            #endregion
        }
コード例 #13
0
        /// <summary>
        ///  Se crea una caja con una masa (si se quiere que sea estatica la masa debe ser 0),
        ///  con dimensiones x(ancho) ,y(alto) ,z(profundidad), Rotacion de ejes Yaw, Pitch, Roll y un coeficiente de rozamiento.
        /// </summary>
        /// <param name="size">Tamaño de la Cajas</param>
        /// <param name="mass">Masa de la Caja</param>
        /// <param name="position">Posicion de la Caja</param>
        /// <param name="yaw">Rotacion de la Caja respecto del eje x</param>
        /// <param name="pitch">Rotacion de la Caja respecto del eje z</param>
        /// <param name="roll">Rotacion de la Caja respecto del eje y</param>
        /// <param name="friction">Coeficiente de rozamiento de la Caja</param>
        /// <returns>Rigid Body de la caja</returns>
        public static RigidBody CreateBox(TGCVector3 size, float mass, TGCVector3 position, float yaw, float pitch, float roll, float friction)
        {
            var boxShape     = new BoxShape(size.X, size.Y, size.Z);
            var boxTransform = TGCMatrix.RotationYawPitchRoll(yaw, pitch, roll).ToBsMatrix;

            boxTransform.Origin = position.ToBsVector;
            DefaultMotionState boxMotionState = new DefaultMotionState(boxTransform);
            //Es importante calcular la inercia caso contrario el objeto no rotara.
            var boxLocalInertia = boxShape.CalculateLocalInertia(mass);
            var boxInfo         = new RigidBodyConstructionInfo(mass, boxMotionState, boxShape, boxLocalInertia);
            var boxBody         = new RigidBody(boxInfo);

            boxBody.LinearFactor = TGCVector3.One.ToBsVector;
            boxBody.Friction     = friction;
            return(boxBody);
        }
コード例 #14
0
        static void TestAlignment()
        {
            const float      mass  = 1.0f;
            Vector3WriteTest vTest = new Vector3WriteTest();

            vTest.Value1 = 2.0f;
            vTest.Value2 = 3.0f;
            using (BoxShape shape = new BoxShape(1))
            {
                shape.CalculateLocalInertia(mass, out vTest.Vector);
            }
            if (vTest.Value1 != 2.0f || vTest.Value2 != 3.0f)
            {
                Console.WriteLine("Vector3 value was overwritten with padding!");
            }
        }
コード例 #15
0
ファイル: FallingBody.cs プロジェクト: hiroshi-nz/GLManager
        public RigidBody AddFallingRigidBody(Vector3 location, float mass)
        {
            //CollisionShape fallShape = new SphereShape(1);
            CollisionShape fallShape = new BoxShape(2.5f, 2.5f, 2.5f);

            BulletSharp.Math.Vector3 fallInertia = new BulletSharp.Math.Vector3(0, 0, 0);
            fallShape.CalculateLocalInertia(mass, out fallInertia);

            RigidBodyConstructionInfo fallRigidBodyCI = new RigidBodyConstructionInfo(mass, new DefaultMotionState(), fallShape, BulletSharp.Math.Vector3.Zero);
            RigidBody fallRigidBody = new RigidBody(fallRigidBodyCI);

            fallRigidBody.Translate(new BulletSharp.Math.Vector3(location.X, location.Y, location.Z));
            dynamicsWorld.AddRigidBody(fallRigidBody);

            return(fallRigidBody);
        }
コード例 #16
0
        public void ReadVector3WithMarginTest()
        {
            const float mass         = 1.0f;
            var         vectorStruct = new Vector3WithPadding
            {
                LeftPadding  = 2.0f,
                RightPadding = 3.0f
            };

            using (BoxShape shape = new BoxShape(1))
            {
                shape.CalculateLocalInertia(mass, out vectorStruct.Vector);
            }
            Assert.That(vectorStruct.LeftPadding, Is.EqualTo(2.0f));
            Assert.That(vectorStruct.RightPadding, Is.EqualTo(3.0f));
        }
コード例 #17
0
        public Caja(GameLogic logica)//GamePhysics world)
        {
            body = FactoryBody.crearBodyCubico(masa, new TGCVector3(10, 10, 10), new TGCVector3(0, 600, 0));
            var d3dDevice = D3DDevice.Instance.Device;

            //   physicWorld = world;

            #region configurarEfecto
            efecto = TgcShaders.loadEffect(GameModel.shadersDir + "shaderPlanta.fx");
            #endregion

            #region configurarObjeto

            planta          = new TgcSceneLoader().loadSceneFromFile(GameModel.mediaDir + "modelos\\PLANTA-TgcScene.xml").Meshes[0];
            planta.Scale    = new TGCVector3(35.5f, 35.5f, 35.5f);
            planta.Position = new TGCVector3(0, 600f, 0);

            planta.Effect    = efecto;
            planta.Technique = "RenderScene";
            objetos.Add(planta);
            //glowObjects.Add(planta);

            #endregion

            #region CAJA

            //Se crea una caja de tamaño 20 con rotaciones y origien en 10,100,10 y 1kg de masa.
            var boxShape     = new BoxShape(10, 10, 10);
            var boxTransform = TGCMatrix.RotationYawPitchRoll(MathUtil.SIMD_HALF_PI, MathUtil.SIMD_QUARTER_PI, MathUtil.SIMD_2_PI).ToBsMatrix;
            boxTransform.Origin = new TGCVector3(0, 600, 0).ToBsVector;
            DefaultMotionState boxMotionState = new DefaultMotionState(boxTransform);
            //Es importante calcular la inercia caso contrario el objeto no rotara.
            var boxLocalInertia = boxShape.CalculateLocalInertia(1f);
            var boxInfo         = new RigidBodyConstructionInfo(1f, boxMotionState, boxShape, boxLocalInertia);
            body = new RigidBody(boxInfo);

            var texture = TgcTexture.createTexture(D3DDevice.Instance.Device, GameModel.mediaDir + "texturas\\terrain\\NormalMapMar.png");
            //Es importante crear todos los mesh con centro en el 0,0,0 y que este coincida con el centro de masa definido caso contrario rotaria de otra forma diferente a la dada por el motor de fisica.
            // boxMesh = TGCBox.fromSize(new TGCVector3(50, 50, 50), texture);

            #endregion
            callback = new CollisionCallback(logica, this);

            // objetos.Add(boxMesh);
        }
コード例 #18
0
        private void CreateBoxes()
        {
            const float mass         = 1.0f;
            var         shape        = new BoxShape(Scale);
            Vector3     localInertia = shape.CalculateLocalInertia(mass);

            using (var bodyInfo = new RigidBodyConstructionInfo(mass, null, shape, localInertia))
            {
                for (int x = 0; x < NumStacksX; x++)
                {
                    for (int z = 0; z < NumStacksZ; z++)
                    {
                        Vector3 offset = _startPosition + new Vector3(x * StackSpacingX, 0, z * StackSpacingZ);
                        CreateStack(offset, bodyInfo);
                    }
                }
            }
        }
コード例 #19
0
        /// <summary>
        ///  Se crea una caja con una masa (si se quiere que sea estatica la masa debe ser 0),
        ///  con dimensiones x(ancho) ,y(alto) ,z(profundidad), Rotacion de ejes Yaw, Pitch, Roll y un coeficiente de rozamiento.
        /// </summary>
        /// <param name="size"></param>
        /// <param name="mass"></param>
        /// <param name="position"></param>
        /// <param name="yaw"></param>
        /// <param name="pitch"></param>
        /// <param name="roll"></param>
        /// <param name="friction"></param>
        /// <returns></returns>
        public static RigidBody CreateBox(TGCVector3 size, float mass, TGCVector3 position, float yaw, float pitch, float roll, float friction, float?inertia = null)
        {
            var boxShape     = new BoxShape(size.X, size.Y, size.Z);
            var boxTransform = TGCMatrix.RotationYawPitchRoll(yaw, pitch, roll).ToBsMatrix;

            boxTransform.Origin = position.ToBsVector;
            var boxMotionState = new DefaultMotionState(boxTransform);
            //Es importante calcular la inercia caso contrario el objeto no rotara.
            //Si se quiere que no rote el objeto hay que considerar la masa 0Kg
            var boxLocalInertia = boxShape.CalculateLocalInertia(inertia.HasValue ? inertia.Value :mass);
            var boxInfo         = new RigidBodyConstructionInfo(mass, boxMotionState, boxShape, boxLocalInertia);
            var boxBody         = new RigidBody(boxInfo);

            boxBody.LinearFactor = TGCVector3.One.ToBsVector;
            //boxBody.SetDamping(0.7f, 0.9f);
            //boxBody.Restitution = 1f;
            boxBody.Friction = friction;
            return(boxBody);
        }
コード例 #20
0
        void AddBoxes()
        {
            // create a few dynamic rigidbodies
            const float mass = 1.0f;

            BoxShape colShape = new BoxShape(1);

            CollisionShapes.Add(colShape);
            Vector3 localInertia = colShape.CalculateLocalInertia(mass);

            const float startX = StartPosX - ArraySizeX / 2;
            const float startY = StartPosY;
            const float startZ = StartPosZ - ArraySizeZ / 2;

            int k, i, j;

            for (k = 0; k < ArraySizeY; k++)
            {
                for (i = 0; i < ArraySizeX; i++)
                {
                    for (j = 0; j < ArraySizeZ; j++)
                    {
                        Matrix startTransform = Matrix.Translation(
                            3 * i + startX,
                            3 * k + startY,
                            3 * j + startZ
                            );

                        // using motionstate is recommended, it provides interpolation capabilities
                        // and only synchronizes 'active' objects
                        DefaultMotionState myMotionState = new DefaultMotionState(startTransform);
                        using (var rbInfo = new RigidBodyConstructionInfo(mass, myMotionState, colShape, localInertia))
                        {
                            var body = new RigidBody(rbInfo);
                            World.AddRigidBody(body);
                        }
                    }
                }
            }
        }
コード例 #21
0
        public MachinegunBullet(DiscreteDynamicsWorld world, Character origin) : base(3f, origin)
        {
            var boxRadius = new TGCVector3(0.093f, 0.093f, 0.836f);
            var tgcBox    = TGCBox.fromSize(boxRadius, Color.FromArgb(255, 255, 249, 56));

            mesh = tgcBox.ToMesh("MachinegunBullet");
            tgcBox.Dispose();

            var boxShape     = new BoxShape(boxRadius.ToBsVector * 0.5f);
            var boxTransform = TGCMatrix.RotationYawPitchRoll(0, 0, 0).ToBsMatrix;

            boxTransform.Origin = new TGCVector3(0, -100, 0).ToBsVector;
            var boxMotionState  = new DefaultMotionState(boxTransform);
            var boxLocalInertia = boxShape.CalculateLocalInertia(0.5f);
            var boxInfo         = new RigidBodyConstructionInfo(0.5f, boxMotionState, boxShape, boxLocalInertia);

            rigidBody = new RigidBody(boxInfo);
            rigidBody.ForceActivationState(ActivationState.DisableDeactivation);
            rigidBody.Flags          = RigidBodyFlags.DisableWorldGravity;
            rigidBody.CollisionFlags = CollisionFlags.NoContactResponse;

            world.AddCollisionObject(rigidBody);
        }
コード例 #22
0
ファイル: Power.cs プロジェクト: Joaro92/2018_2C_3572_Codec
        public PowerMissile(DiscreteDynamicsWorld world, Character origin) : base(15f, origin)
        {
            var loader  = new TgcSceneLoader();
            var xmlPath = Game.Default.MediaDirectory + Game.Default.ItemsDirectory + "power-missile-TgcScene.xml";

            mesh = loader.loadSceneFromFile(xmlPath).Meshes[0];
            mesh.AutoTransform = false;

            var meshAxisRadius = mesh.BoundingBox.calculateAxisRadius().ToBsVector;
            var boxShape       = new BoxShape(meshAxisRadius);
            var boxTransform   = TGCMatrix.RotationYawPitchRoll(0, 0, 0).ToBsMatrix;

            boxTransform.Origin = new TGCVector3(0, -100, 0).ToBsVector;
            var boxMotionState  = new DefaultMotionState(boxTransform);
            var boxLocalInertia = boxShape.CalculateLocalInertia(0.5f);
            var boxInfo         = new RigidBodyConstructionInfo(0.5f, boxMotionState, boxShape, boxLocalInertia);

            rigidBody = new RigidBody(boxInfo);
            rigidBody.ForceActivationState(ActivationState.DisableDeactivation);
            rigidBody.Flags          = RigidBodyFlags.DisableWorldGravity;
            rigidBody.CollisionFlags = CollisionFlags.NoContactResponse;

            world.AddCollisionObject(rigidBody);
        }
コード例 #23
0
        public static RigidBody CreateRigidBodyFromTgcMesh(TgcMesh mesh, TGCVector3 position)
        {
            var meshAxisRadius = mesh.BoundingBox.calculateAxisRadius().ToBsVector;
            var boxShape       = new BoxShape(meshAxisRadius);

            var transformationMatrix = TGCMatrix.RotationYawPitchRoll(0, 0, 0).ToBsMatrix;

            transformationMatrix.Origin = position.ToBsVector;
            DefaultMotionState motionState = new DefaultMotionState(transformationMatrix);

            var boxLocalInertia = boxShape.CalculateLocalInertia(0);

            var qwe       = new TriangleMesh();
            var asd       = new BvhTriangleMeshShape(qwe, false);
            var bodyInfo  = new RigidBodyConstructionInfo(0, motionState, asd, boxLocalInertia);
            var rigidBody = new RigidBody(bodyInfo);

            rigidBody.Friction        = 0.4f;
            rigidBody.RollingFriction = 1;
            // ballBody.SetDamping(0.1f, 0.9f);
            rigidBody.Restitution = 1f;

            return(rigidBody);
        }
コード例 #24
0
        void CreatePyramid(Vector3 offsetPosition, int stackSize, Vector3 boxSize)
        {
            float   space = 0.0001f;
            Vector3 pos   = new Vector3(0.0f, boxSize[1], 0.0f);

            BoxShape blockShape = new BoxShape(boxSize[0] - collisionRadius, boxSize[1] - collisionRadius, boxSize[2] - collisionRadius);

            float   mass = 1.0f;
            Vector3 localInertia;

            blockShape.CalculateLocalInertia(mass, out localInertia);

            float diffX = boxSize[0] * 1.02f;
            float diffY = boxSize[1] * 1.02f;
            float diffZ = boxSize[2] * 1.02f;

            float offsetX = -stackSize * (diffX * 2.0f + space) * 0.5f;
            float offsetZ = -stackSize * (diffZ * 2.0f + space) * 0.5f;

            while (stackSize > 0)
            {
                for (int j = 0; j < stackSize; j++)
                {
                    pos[2] = offsetZ + (float)j * (diffZ * 2.0f + space);
                    for (int i = 0; i < stackSize; i++)
                    {
                        pos[0] = offsetX + (float)i * (diffX * 2.0f + space);
                        RigidBody body = LocalCreateRigidBody(mass, Matrix.Translation(offsetPosition + pos), blockShape);
                    }
                }
                offsetX += diffX;
                offsetZ += diffZ;
                pos[1]  += (diffY * 2.0f + space);
                stackSize--;
            }
        }
コード例 #25
0
        public override void InitializeDemo()
        {
            //maxiterations = 10;
            SetCameraDistance(SCALING * 50f);

            //string filename = @"E:\users\man\bullet\xna-basic-output-1.txt";
            //FileStream filestream = File.Open(filename, FileMode.Create, FileAccess.Write, FileShare.Read);
            //BulletGlobals.g_streamWriter = new StreamWriter(filestream);

            ///collision configuration contains default setup for memory, collision setup
            m_collisionConfiguration = new DefaultCollisionConfiguration();

            ///use the default collision dispatcher. For parallel processing you can use a diffent dispatcher (see Extras/BulletMultiThreaded)
            m_dispatcher = new CollisionDispatcher(m_collisionConfiguration);


            IndexedVector3 worldMin = new IndexedVector3(-1000, -1000, -1000);
            IndexedVector3 worldMax = -worldMin;

            m_broadphase = new AxisSweep3Internal(ref worldMin, ref worldMax, 0xfffe, 0xffff, 16384, null, false);

            //m_broadphase = new DbvtBroadphase();
            IOverlappingPairCache pairCache = null;
            //pairCache = new SortedOverlappingPairCache();

            //m_broadphase = new SimpleBroadphase(1000, pairCache);

            ///the default constraint solver. For parallel processing you can use a different solver (see Extras/BulletMultiThreaded)
            SequentialImpulseConstraintSolver sol = new SequentialImpulseConstraintSolver();

            m_constraintSolver = sol;

            m_dynamicsWorld = new DiscreteDynamicsWorld(m_dispatcher, m_broadphase, m_constraintSolver, m_collisionConfiguration);

            IndexedVector3 gravity = new IndexedVector3(0, -10, 0);

            m_dynamicsWorld.SetGravity(ref gravity);

            ///create a few basic rigid bodies
            IndexedVector3 halfExtents = new IndexedVector3(50, 50, 50);
            //IndexedVector3 halfExtents = new IndexedVector3(10, 10, 10);
            CollisionShape groundShape = new BoxShape(ref halfExtents);

            //CollisionShape groundShape = new StaticPlaneShape(new IndexedVector3(0,1,0), 50);

            m_collisionShapes.Add(groundShape);

            IndexedMatrix groundTransform = IndexedMatrix.CreateTranslation(new IndexedVector3(0, -50, 0));
            //IndexedMatrix groundTransform = IndexedMatrix.CreateTranslation(new IndexedVector3(0,-10,0));
            float mass = 0f;

            LocalCreateRigidBody(mass, ref groundTransform, groundShape);
            {
                //create a few dynamic rigidbodies
                CollisionShape colShape = new BoxShape(new IndexedVector3(SCALING, SCALING, SCALING));
                //CollisionShape colShape = BuildCorner();
                //btCollisionShape* colShape = new btSphereShape(btScalar(1.));
                //CollisionShape colShape = new CylinderShape(new IndexedVector3(1f, 1, 1f));
                m_collisionShapes.Add(colShape);

                /// Create Dynamic Objects
                IndexedMatrix startTransform = IndexedMatrix.Identity;

                mass = 1f;

                //rigidbody is dynamic if and only if mass is non zero, otherwise static
                bool isDynamic = mass != 0f;

                IndexedVector3 localInertia = IndexedVector3.Zero;
                if (isDynamic)
                {
                    colShape.CalculateLocalInertia(mass, out localInertia);
                }
                float start_x = START_POS_X - ARRAY_SIZE_X / 2;
                float start_y = START_POS_Y;
                float start_z = START_POS_Z - ARRAY_SIZE_Z / 2;

                for (int k = 0; k < ARRAY_SIZE_Y; k++)
                {
                    for (int i = 0; i < ARRAY_SIZE_X; i++)
                    {
                        for (int j = 0; j < ARRAY_SIZE_Z; j++)
                        {
                            startTransform._origin = (new IndexedVector3(2.0f * i + start_x, 20 + 2.0f * k + start_y, 2.0f * j + start_z) * SCALING);

                            //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects
                            DefaultMotionState        myMotionState = new DefaultMotionState(startTransform, IndexedMatrix.Identity);
                            RigidBodyConstructionInfo rbInfo        = new RigidBodyConstructionInfo(mass, myMotionState, colShape, localInertia);
                            RigidBody body = new RigidBody(rbInfo);
                            //body->setContactProcessingThreshold(colShape->getContactBreakingThreshold());
                            //body.SetActivationState(ActivationState.ISLAND_SLEEPING);

                            m_dynamicsWorld.AddRigidBody(body);
                            //body.SetActivationState(ActivationState.ISLAND_SLEEPING);
                            body.SetUserPointer(String.Format("Box X{0} Y{1} Z{2}", k, i, j));
                        }
                    }
                }
            }

            //ClientResetScene();
        }
コード例 #26
0
    void Start()
    {
        //Create a World
        Debug.Log("Initialize physics");
        List<CollisionShape> CollisionShapes = new List<CollisionShape>();

        DefaultCollisionConfiguration CollisionConf = new DefaultCollisionConfiguration();
        CollisionDispatcher Dispatcher = new CollisionDispatcher(CollisionConf);

        DbvtBroadphase Broadphase = new DbvtBroadphase();

        DiscreteDynamicsWorld World = new DiscreteDynamicsWorld(Dispatcher, Broadphase, null, CollisionConf);
        World.Gravity = new BulletSharp.Math.Vector3(0, -10, 0);

        // create a few dynamic rigidbodies
        const float mass = 1.0f;
        //Add a single cube
        RigidBody fallRigidBody;
        BoxShape shape = new BoxShape(1f, 1f, 1f);
        BulletSharp.Math.Vector3 localInertia = BulletSharp.Math.Vector3.Zero;
        shape.CalculateLocalInertia(mass, out localInertia);
        RigidBodyConstructionInfo rbInfo = new RigidBodyConstructionInfo(mass, null, shape, localInertia);
        fallRigidBody = new RigidBody(rbInfo);
        rbInfo.Dispose();
        Matrix st = Matrix.Translation(new BulletSharp.Math.Vector3(0f, 10f, 0f));
        fallRigidBody.WorldTransform = st;
        World.AddRigidBody(fallRigidBody);

        //Step the simulation 300 steps
        for (int i = 0; i < 300; i++)
        {
            World.StepSimulation(1f / 60f, 10);

            Matrix trans;
            fallRigidBody.GetWorldTransform(out trans);

            Debug.Log("box height: " + trans.Origin);
        }

        //Clean up.
        World.RemoveRigidBody(fallRigidBody);
        fallRigidBody.Dispose();

        UnityEngine.Debug.Log("ExitPhysics");
        if (World != null)
        {
            //remove/dispose constraints
            int i;
            for (i = World.NumConstraints - 1; i >= 0; i--)
            {
                TypedConstraint constraint = World.GetConstraint(i);
                World.RemoveConstraint(constraint);
                constraint.Dispose();
            }

            //remove the rigidbodies from the dynamics world and delete them
            for (i = World.NumCollisionObjects - 1; i >= 0; i--)
            {
                CollisionObject obj = World.CollisionObjectArray[i];
                RigidBody body = obj as RigidBody;
                if (body != null && body.MotionState != null)
                {
                    body.MotionState.Dispose();
                }
                World.RemoveCollisionObject(obj);
                obj.Dispose();
            }

            //delete collision shapes
            foreach (CollisionShape ss in CollisionShapes)
                ss.Dispose();
            CollisionShapes.Clear();

            World.Dispose();
            Broadphase.Dispose();
            Dispatcher.Dispose();
            CollisionConf.Dispose();
        }

        if (Broadphase != null)
        {
            Broadphase.Dispose();
        }
        if (Dispatcher != null)
        {
            Dispatcher.Dispose();
        }
        if (CollisionConf != null)
        {
            CollisionConf.Dispose();
        }
    }
コード例 #27
0
        protected override void OnInitializePhysics()
        {
            // collision configuration contains default setup for memory, collision setup
            CollisionConf = new DefaultCollisionConfiguration();
            Dispatcher    = new CollisionDispatcher(CollisionConf);

            Broadphase = new DbvtBroadphase();

            World         = new DiscreteDynamicsWorld(Dispatcher, Broadphase, null, CollisionConf);
            World.Gravity = new Vector3(0, -10, 0);

            // create the ground
            BoxShape groundShape = new BoxShape(50, 1, 50);

            //groundShape.InitializePolyhedralFeatures();
            //CollisionShape groundShape = new StaticPlaneShape(new Vector3(0,1,0), 50);

            CollisionShapes.Add(groundShape);
            CollisionObject ground = LocalCreateRigidBody(0, Matrix.Identity, groundShape);

            ground.UserObject = "Ground";

            // create a few dynamic rigidbodies
            const float mass = 1.0f;

            BoxShape colShape = new BoxShape(1);

            CollisionShapes.Add(colShape);
            Vector3 localInertia = colShape.CalculateLocalInertia(mass);

            const float startX = StartPosX - ArraySizeX / 2;
            const float startY = StartPosY;
            const float startZ = StartPosZ - ArraySizeZ / 2;

            RigidBodyConstructionInfo rbInfo =
                new RigidBodyConstructionInfo(mass, null, colShape, localInertia);

            for (int k = 0; k < ArraySizeY; k++)
            {
                for (int i = 0; i < ArraySizeX; i++)
                {
                    for (int j = 0; j < ArraySizeZ; j++)
                    {
                        Matrix startTransform = Matrix.Translation(
                            2 * i + startX,
                            2 * k + startY,
                            2 * j + startZ
                            );

                        // using motionstate is recommended, it provides interpolation capabilities
                        // and only synchronizes 'active' objects
                        rbInfo.MotionState = new DefaultMotionState(startTransform);
                        RigidBody body = new RigidBody(rbInfo);

                        // make it drop from a height
                        body.Translate(new Vector3(0, 20, 0));

                        World.AddRigidBody(body);
                    }
                }
            }

            rbInfo.Dispose();
        }
コード例 #28
0
        protected override void OnInitializePhysics()
        {
            // collision configuration contains default setup for memory, collision setup
            CollisionConf = new DefaultCollisionConfiguration();
            Dispatcher    = new CollisionDispatcher(CollisionConf);

            Broadphase = new DbvtBroadphase();

            World         = new DiscreteDynamicsWorld(Dispatcher, Broadphase, null, CollisionConf);
            World.Gravity = new Vector3(0, -10, 0);

            // create the ground
            CollisionShape groundShape = new BoxShape(20, 50, 10);

            CollisionShapes.Add(groundShape);
            CollisionObject ground = LocalCreateRigidBody(0,
                                                          Matrix.RotationAxis(new Vector3(0, 0, 1), (float)Math.PI * 0.03f) * Matrix.Translation(0, -50, 0),
                                                          groundShape);

            ground.Friction        = 1;
            ground.RollingFriction = 1;
            ground.UserObject      = "Ground";

            groundShape = new BoxShape(100, 50, 100);
            CollisionShapes.Add(groundShape);
            ground                 = LocalCreateRigidBody(0, Matrix.Translation(0, -54, 0), groundShape);
            ground.Friction        = 1;
            ground.RollingFriction = 1;
            ground.UserObject      = "Ground";

            // create a few dynamic rigidbodies
            const int NUM_SHAPES = 10;

            CollisionShape[] colShapes = new CollisionShape[NUM_SHAPES] {
                new SphereShape(1),
                new CapsuleShape(0.5f, 1),
                new CapsuleShapeX(0.5f, 1),
                new CapsuleShapeZ(0.5f, 1),
                new ConeShape(0.5f, 1),
                new ConeShapeX(0.5f, 1),
                new ConeShapeZ(0.5f, 1),
                new CylinderShape(new Vector3(0.5f, 1, 0.5f)),
                new CylinderShapeX(new Vector3(1, 0.5f, 0.5f)),
                new CylinderShapeZ(new Vector3(0.5f, 0.5f, 1)),
            };
            foreach (var collisionShape in colShapes)
            {
                CollisionShapes.Add(collisionShape);
            }

            const float mass = 1.0f;

            CollisionShape colShape = new BoxShape(1);

            CollisionShapes.Add(colShape);
            Vector3 localInertia = colShape.CalculateLocalInertia(mass);

            const float start_x = StartPosX - ArraySizeX / 2;
            const float start_y = StartPosY;
            const float start_z = StartPosZ - ArraySizeZ / 2;

            int shapeIndex = 0;
            int k, i, j;

            for (k = 0; k < ArraySizeY; k++)
            {
                for (i = 0; i < ArraySizeX; i++)
                {
                    for (j = 0; j < ArraySizeZ; j++)
                    {
                        Matrix startTransform = Matrix.Translation(
                            2 * i + start_x,
                            2 * k + start_y + 20,
                            2 * j + start_z
                            );
                        shapeIndex++;

                        // using motionstate is recommended, it provides interpolation capabilities
                        // and only synchronizes 'active' objects
                        DefaultMotionState myMotionState = new DefaultMotionState(startTransform);
                        RigidBody          body;
                        using (var rbInfo =
                                   new RigidBodyConstructionInfo(mass, myMotionState, colShapes[shapeIndex % NUM_SHAPES], localInertia))
                        {
                            body = new RigidBody(rbInfo);
                        }

                        body.Friction        = 1;
                        body.RollingFriction = 0.3f;
                        body.SetAnisotropicFriction(colShape.AnisotropicRollingFrictionDirection, AnisotropicFrictionFlags.RollingFriction);

                        World.AddRigidBody(body);
                    }
                }
            }
        }
コード例 #29
0
        /*
         * ThreadSupportInterface CreateSolverThreadSupport(int maxNumThreads)
         * {
         *  //#define SEQUENTIAL
         *  /* if (SEQUENTIAL)
         *  {
         *      SequentialThreadSupport::SequentialThreadConstructionInfo tci("solverThreads",SolverThreadFunc,SolverlsMemoryFunc);
         *      SequentialThreadSupport* threadSupport = new SequentialThreadSupport(tci);
         *      threadSupport->startSPU();
         *  }
         *  else * /
         *
         *  Win32ThreadConstructionInfo threadConstructionInfo = new Win32ThreadConstructionInfo("solverThreads",
         *      Win32ThreadFunc.SolverThreadFunc, Win32LSMemorySetupFunc.SolverLSMemoryFunc, maxNumThreads);
         *  Win32ThreadSupport threadSupport = new Win32ThreadSupport(threadConstructionInfo);
         *  threadSupport.StartSpu();
         *  return threadSupport;
         * }
         */
        protected override void OnInitializePhysics()
        {
            // collision configuration contains default setup for memory, collision setup
            DefaultCollisionConstructionInfo cci = new DefaultCollisionConstructionInfo();

            cci.DefaultMaxPersistentManifoldPoolSize = 32768;
            CollisionConf = new DefaultCollisionConfiguration(cci);

            if (UseParallelDispatcherBenchmark)
            {
                //int maxNumOutstandingTasks = 4;

                /*Win32ThreadConstructionInfo info = new Win32ThreadConstructionInfo("collision",
                 *  Win32ThreadFunc.ProcessCollisionTask, Win32LSMemorySetupFunc.CreateCollisionLocalStoreMemory,
                 *  maxNumOutstandingTasks);
                 *
                 * Win32ThreadSupport threadSupportCollision = new Win32ThreadSupport(info);
                 * Dispatcher = new SpuGatheringCollisionDispatcher(threadSupportCollision, 1, CollisionConf);*/
            }
            else
            {
                Dispatcher = new CollisionDispatcher(CollisionConf);
                Dispatcher.DispatcherFlags = DispatcherFlags.DisableContactPoolDynamicAllocation;
            }

            // the maximum size of the collision world. Make sure objects stay within these boundaries
            // Don't make the world AABB size too large, it will harm simulation quality and performance
            Vector3 worldAabbMin = new Vector3(-1000, -1000, -1000);
            Vector3 worldAabbMax = new Vector3(1000, 1000, 1000);

            HashedOverlappingPairCache pairCache = new HashedOverlappingPairCache();

            Broadphase = new AxisSweep3(worldAabbMin, worldAabbMax, 3500, pairCache);
            //Broadphase = new DbvtBroadphase();

            if (UseParallelDispatcherBenchmark)
            {
                //ThreadSupportInterface thread = CreateSolverThreadSupport(4);
                //Solver = new ParallelConstraintSolver(thread);
            }
            else
            {
                Solver = new SequentialImpulseConstraintSolver();
            }

            World         = new DiscreteDynamicsWorld(Dispatcher, Broadphase, Solver, CollisionConf);
            World.Gravity = new Vector3(0, -10, 0);

            if (UseParallelDispatcherBenchmark)
            {
                ((DiscreteDynamicsWorld)World).SimulationIslandManager.SplitIslands = false;
            }
            World.SolverInfo.SolverMode   |= SolverModes.EnableFrictionDirectionCaching;
            World.SolverInfo.NumIterations = 5;

            if (benchmark < 5)
            {
                // create the ground
                CollisionShape groundShape = new BoxShape(250, 50, 250);
                CollisionShapes.Add(groundShape);
                CollisionObject ground = base.LocalCreateRigidBody(0, Matrix.Translation(0, -50, 0), groundShape);
                ground.UserObject = "Ground";
            }

            float   cubeSize = 1.0f;
            float   spacing  = cubeSize;
            float   mass     = 1.0f;
            int     size     = 8;
            Vector3 localInertia;
            Vector3 pos    = new Vector3(0.0f, cubeSize * 2, 0.0f);
            float   offset = -size * (cubeSize * 2.0f + spacing) * 0.5f;

            switch (benchmark)
            {
            case 1:
                // 3000

                BoxShape blockShape = new BoxShape(cubeSize - collisionRadius);
                mass = 2.0f;
                blockShape.CalculateLocalInertia(mass, out localInertia);

                for (int k = 0; k < 47; k++)
                {
                    for (int j = 0; j < size; j++)
                    {
                        pos[2] = offset + (float)j * (cubeSize * 2.0f + spacing);
                        for (int i = 0; i < size; i++)
                        {
                            pos[0] = offset + (float)i * (cubeSize * 2.0f + spacing);
                            RigidBody cmbody = LocalCreateRigidBody(mass, Matrix.Translation(pos), blockShape);
                        }
                    }
                    offset -= 0.05f * spacing * (size - 1);
                    // spacing *= 1.01f;
                    pos[1] += (cubeSize * 2.0f + spacing);
                }
                break;

            case 2:
                CreatePyramid(new Vector3(-20, 0, 0), 12, new Vector3(cubeSize));
                CreateWall(new Vector3(-2.0f, 0.0f, 0.0f), 12, new Vector3(cubeSize));
                CreateWall(new Vector3(4.0f, 0.0f, 0.0f), 12, new Vector3(cubeSize));
                CreateWall(new Vector3(10.0f, 0.0f, 0.0f), 12, new Vector3(cubeSize));
                CreateTowerCircle(new Vector3(25.0f, 0.0f, 0.0f), 8, 24, new Vector3(cubeSize));
                break;

            case 3:
                // TODO: Ragdolls
                break;

            case 4:
                cubeSize = 1.5f;

                ConvexHullShape convexHullShape = new ConvexHullShape();

                float scaling = 1;

                convexHullShape.LocalScaling = new Vector3(scaling);

                for (int i = 0; i < Taru.Vtx.Length / 3; i++)
                {
                    Vector3 vtx = new Vector3(Taru.Vtx[i * 3], Taru.Vtx[i * 3 + 1], Taru.Vtx[i * 3 + 2]);
                    convexHullShape.AddPoint(vtx * (1.0f / scaling));
                }

                //this will enable polyhedral contact clipping, better quality, slightly slower
                convexHullShape.InitializePolyhedralFeatures();

                convexHullShape.CalculateLocalInertia(mass, out localInertia);

                for (int k = 0; k < 15; k++)
                {
                    for (int j = 0; j < size; j++)
                    {
                        pos[2] = offset + (float)j * (cubeSize * 2.0f + spacing);
                        for (int i = 0; i < size; i++)
                        {
                            pos[0] = offset + (float)i * (cubeSize * 2.0f + spacing);
                            LocalCreateRigidBody(mass, Matrix.Translation(pos), convexHullShape);
                        }
                    }
                    offset  -= 0.05f * spacing * (size - 1);
                    spacing *= 1.01f;
                    pos[1]  += (cubeSize * 2.0f + spacing);
                }
                break;

            case 5:
                Vector3 boxSize       = new Vector3(1.5f);
                float   boxMass       = 1.0f;
                float   sphereRadius  = 1.5f;
                float   sphereMass    = 1.0f;
                float   capsuleHalf   = 2.0f;
                float   capsuleRadius = 1.0f;
                float   capsuleMass   = 1.0f;

                size = 10;
                int height = 10;

                cubeSize = boxSize[0];
                spacing  = 2.0f;
                pos      = new Vector3(0.0f, 20.0f, 0.0f);
                offset   = -size * (cubeSize * 2.0f + spacing) * 0.5f;

                int numBodies = 0;

                Random random = new Random();

                for (int k = 0; k < height; k++)
                {
                    for (int j = 0; j < size; j++)
                    {
                        pos[2] = offset + (float)j * (cubeSize * 2.0f + spacing);
                        for (int i = 0; i < size; i++)
                        {
                            pos[0] = offset + (float)i * (cubeSize * 2.0f + spacing);
                            Vector3 bpos  = new Vector3(0, 25, 0) + new Vector3(5.0f * pos.X, pos.Y, 5.0f * pos.Z);
                            int     idx   = random.Next(10);
                            Matrix  trans = Matrix.Translation(bpos);

                            switch (idx)
                            {
                            case 0:
                            case 1:
                            case 2:
                            {
                                float    r        = 0.5f * (idx + 1);
                                BoxShape boxShape = new BoxShape(boxSize * r);
                                LocalCreateRigidBody(boxMass * r, trans, boxShape);
                            }
                            break;

                            case 3:
                            case 4:
                            case 5:
                            {
                                float       r           = 0.5f * (idx - 3 + 1);
                                SphereShape sphereShape = new SphereShape(sphereRadius * r);
                                LocalCreateRigidBody(sphereMass * r, trans, sphereShape);
                            }
                            break;

                            case 6:
                            case 7:
                            case 8:
                            {
                                float        r            = 0.5f * (idx - 6 + 1);
                                CapsuleShape capsuleShape = new CapsuleShape(capsuleRadius * r, capsuleHalf * r);
                                LocalCreateRigidBody(capsuleMass * r, trans, capsuleShape);
                            }
                            break;
                            }

                            numBodies++;
                        }
                    }
                    offset  -= 0.05f * spacing * (size - 1);
                    spacing *= 1.1f;
                    pos[1]  += (cubeSize * 2.0f + spacing);
                }

                //CreateLargeMeshBody();

                break;

            case 6:
                boxSize = new Vector3(1.5f, 1.5f, 1.5f);

                convexHullShape = new ConvexHullShape();

                for (int i = 0; i < Taru.Vtx.Length / 3; i++)
                {
                    Vector3 vtx = new Vector3(Taru.Vtx[i * 3], Taru.Vtx[i * 3 + 1], Taru.Vtx[i * 3 + 2]);
                    convexHullShape.AddPoint(vtx);
                }

                convexHullShape.CalculateLocalInertia(mass, out localInertia);


                size   = 10;
                height = 10;

                cubeSize = boxSize[0];
                spacing  = 2.0f;
                pos      = new Vector3(0.0f, 20.0f, 0.0f);
                offset   = -size * (cubeSize * 2.0f + spacing) * 0.5f;


                for (int k = 0; k < height; k++)
                {
                    for (int j = 0; j < size; j++)
                    {
                        pos[2] = offset + (float)j * (cubeSize * 2.0f + spacing);
                        for (int i = 0; i < size; i++)
                        {
                            pos[0] = offset + (float)i * (cubeSize * 2.0f + spacing);
                            Vector3 bpos = new Vector3(0, 25, 0) + new Vector3(5.0f * pos.X, pos.Y, 5.0f * pos.Z);

                            LocalCreateRigidBody(mass, Matrix.Translation(bpos), convexHullShape);
                        }
                    }
                    offset  -= 0.05f * spacing * (size - 1);
                    spacing *= 1.1f;
                    pos[1]  += (cubeSize * 2.0f + spacing);
                }

                //CreateLargeMeshBody();

                break;

            case 7:
                // TODO
                //CreateTest6();
                //InitRays();
                break;
            }
        }
コード例 #30
0
        public void Init()
        {
            #region MUNDO_FISICO //Creamos el mundo fisico por defecto.
            collisionConfiguration = new DefaultCollisionConfiguration();
            dispatcher             = new CollisionDispatcher(collisionConfiguration);

            GImpactCollisionAlgorithm.RegisterAlgorithm(dispatcher);
            constraintSolver     = new SequentialImpulseConstraintSolver();
            overlappingPairCache = new DbvtBroadphase();
            dynamicsWorld        = new DiscreteDynamicsWorld(dispatcher, overlappingPairCache, constraintSolver, collisionConfiguration)
            {
                Gravity = new TGCVector3(0, -20f, 0).ToBsVector
            };
            #endregion

            var texture = TgcTexture.createTexture(D3DDevice.Instance.Device, GameModel.mediaDir + "texturas\\terrain\\NormalMapMar.png");
            //Creamos shapes y bodies.

            #region PISO
            //El piso es un plano estatico se dice que si tiene masa 0 es estatico.
            var floorShape       = new StaticPlaneShape(TGCVector3.Up.ToBsVector, 0);
            var floorMotionState = new DefaultMotionState();
            var floorInfo        = new RigidBodyConstructionInfo(0, floorMotionState, floorShape);
            floorBody = new RigidBody(floorInfo);
            dynamicsWorld.AddRigidBody(floorBody);

            //Cargamos objetos de render del framework.
            var floorTexture = TgcTexture.createTexture(D3DDevice.Instance.Device, GameModel.mediaDir + "modelos\\Textures\\Canionero.jpg");
            floorMesh = new TgcPlane(new TGCVector3(0, 500, 0), new TGCVector3(400, 0f, 400), TgcPlane.Orientations.XZplane, floorTexture);
            #endregion

            #region CAJA
            //Se crea una caja de tamaño 20 con rotaciones y origien en 10,100,10 y 1kg de masa.
            var boxShape     = new BoxShape(10, 10, 10);
            var boxTransform = TGCMatrix.RotationYawPitchRoll(MathUtil.SIMD_HALF_PI, MathUtil.SIMD_QUARTER_PI, MathUtil.SIMD_2_PI).ToBsMatrix;
            boxTransform.Origin = new TGCVector3(0, 600, 0).ToBsVector;
            DefaultMotionState boxMotionState = new DefaultMotionState(boxTransform);
            //Es importante calcular la inercia caso contrario el objeto no rotara.
            var boxLocalInertia = boxShape.CalculateLocalInertia(1f);
            var boxInfo         = new RigidBodyConstructionInfo(1f, boxMotionState, boxShape, boxLocalInertia);
            boxBody = new RigidBody(boxInfo);
            dynamicsWorld.AddRigidBody(boxBody);

            //Es importante crear todos los mesh con centro en el 0,0,0 y que este coincida con el centro de masa definido caso contrario rotaria de otra forma diferente a la dada por el motor de fisica.
            boxMesh = TGCBox.fromSize(new TGCVector3(20, 20, 20), texture);

            #endregion

            #region BOLA
            //Se crea una esfera de tamaño 1 para escalarla luego (en render)
            //Crea una bola de radio 10 origen 50 de 1 kg.
            var ballShape     = new SphereShape(10);
            var ballTransform = TGCMatrix.Identity;
            ballTransform.Origin = new TGCVector3(0, 200, 0);
            var ballMotionState = new DefaultMotionState(ballTransform.ToBsMatrix);
            //Podriamos no calcular la inercia para que no rote, pero es correcto que rote tambien.
            var ballLocalInertia = ballShape.CalculateLocalInertia(1f);
            var ballInfo         = new RigidBodyConstructionInfo(1, ballMotionState, ballShape, ballLocalInertia);
            ballBody = new RigidBody(ballInfo);
            dynamicsWorld.AddRigidBody(ballBody);

            sphereMesh = new TGCSphere(1, texture.Clone(), TGCVector3.Empty);
            //Tgc no crea el vertex buffer hasta invocar a update values.
            sphereMesh.updateValues();

            #endregion

            callback = new MyContactResultCallback(dispatcher, dynamicsWorld, floorBody);// boxBody);
        }
コード例 #31
0
        protected override void OnInitializePhysics()
        {
            // collision configuration contains default setup for memory, collision setup
            CollisionConf = new DefaultCollisionConfiguration();
            Dispatcher    = new CollisionDispatcher(CollisionConf);

            Broadphase = new DbvtBroadphase();
            Solver     = new MultiBodyConstraintSolver();

            World         = new MultiBodyDynamicsWorld(Dispatcher, Broadphase, Solver as MultiBodyConstraintSolver, CollisionConf);
            World.Gravity = new Vector3(0, -10, 0);

            // create a few basic rigid bodies
            BoxShape groundShape = new BoxShape(50, 50, 50);

            //groundShape.InitializePolyhedralFeatures();
            //CollisionShape groundShape = new StaticPlaneShape(new Vector3(0,1,0), 50);

            CollisionShapes.Add(groundShape);
            CollisionObject ground = LocalCreateRigidBody(0, Matrix.Translation(0, -50, 0), groundShape);

            ground.UserObject = "Ground";

            // create a few dynamic rigidbodies
            const float mass = 1.0f;

            BoxShape colShape = new BoxShape(1);

            CollisionShapes.Add(colShape);
            Vector3 localInertia = colShape.CalculateLocalInertia(mass);

            const float start_x = StartPosX - ArraySizeX / 2;
            const float start_y = StartPosY;
            const float start_z = StartPosZ - ArraySizeZ / 2;

            int k, i, j;

            for (k = 0; k < ArraySizeY; k++)
            {
                for (i = 0; i < ArraySizeX; i++)
                {
                    for (j = 0; j < ArraySizeZ; j++)
                    {
                        Matrix startTransform = Matrix.Translation(
                            3 * i + start_x,
                            3 * k + start_y,
                            3 * j + start_z
                            );

                        // using motionstate is recommended, it provides interpolation capabilities
                        // and only synchronizes 'active' objects
                        DefaultMotionState        myMotionState = new DefaultMotionState(startTransform);
                        RigidBodyConstructionInfo rbInfo        =
                            new RigidBodyConstructionInfo(mass, myMotionState, colShape, localInertia);
                        RigidBody body = new RigidBody(rbInfo);
                        rbInfo.Dispose();

                        World.AddRigidBody(body);
                    }
                }
            }

            var settings = new MultiBodySettings()
            {
                BasePosition           = new Vector3(60, 29.5f, -2) * Scaling,
                CanSleep               = true,
                CreateConstraints      = true,
                DisableParentCollision = true, // the self-collision has conflicting/non-resolvable contact normals
                IsFixedBase            = false,
                NumLinks               = 2,
                UsePrismatic           = true
            };
            var multiBodyA = CreateFeatherstoneMultiBody(World as MultiBodyDynamicsWorld, settings);

            settings.NumLinks     = 10;
            settings.BasePosition = new Vector3(0, 29.5f, -settings.NumLinks * 4);
            settings.IsFixedBase  = true;
            settings.UsePrismatic = false;
            var multiBodyB = CreateFeatherstoneMultiBody(World as MultiBodyDynamicsWorld, settings);

            settings.BasePosition = new Vector3(-20 * Scaling, 29.5f * Scaling, -settings.NumLinks * 4 * Scaling);
            settings.IsFixedBase  = false;
            var multiBodyC = CreateFeatherstoneMultiBody(World as MultiBodyDynamicsWorld, settings);

            settings.BasePosition           = new Vector3(-20, 9.5f, -settings.NumLinks * 4);
            settings.IsFixedBase            = true;
            settings.UsePrismatic           = true;
            settings.DisableParentCollision = true;
            var multiBodyPrim = CreateFeatherstoneMultiBody(World as MultiBodyDynamicsWorld, settings);
        }