void InitGImpactCollision()
        {
            // Create Torus Shape

            indexVertexArrays = new TriangleIndexVertexArray(Torus.Indices, Torus.Vertices);

#if BULLET_GIMPACT
#if BULLET_GIMPACT_CONVEX_DECOMPOSITION
            //GImpactConvexDecompositionShape trimesh =
            //    new GImpactConvexDecompositionShape(indexVertexArrays, new Vector3(1), 0.01f);
            //trimesh.Margin = 0.07f;
            //trimesh.UpdateBound();
#else
            GImpactMeshShape trimesh = new GImpactMeshShape(indexVertexArrays);
            trimesh.LocalScaling = new Vector3(1);
#if BULLET_TRIANGLE_COLLISION
            trimesh.Margin = 0.07f; //?????
#else
            trimesh.Margin = 0;
#endif
            trimesh.UpdateBound();
#endif
            trimeshShape = trimesh;
#else
            //trimeshShape = new GImpactMeshData(indexVertexArrays);
#endif
            CollisionShapes.Add(trimeshShape);


            // Create Bunny Shape
            indexVertexArrays2 = new TriangleIndexVertexArray(Bunny.Indices, Bunny.Vertices);

#if BULLET_GIMPACT
#if BULLET_GIMPACT_CONVEX_DECOMPOSITION
            //GImpactConvexDecompositionShape trimesh2 =
            //    new GImpactConvexDecompositionShape(indexVertexArrays, new Vector3(1), 0.01f);
            //trimesh.Margin = 0.07f;
            //trimesh.UpdateBound();
            //trimeshShape = trimesh2;
#else
            GImpactMeshShape trimesh2 = new GImpactMeshShape(indexVertexArrays2);
            trimesh2.LocalScaling = new Vector3(1);
#if BULLET_TRIANGLE_COLLISION
            trimesh2.Margin = 0.07f; //?????
#else
            trimesh2.Margin = 0;
#endif
            trimesh2.UpdateBound();
            trimeshShape2 = trimesh2;
#endif
#else
            //trimeshShape2 = new GImpactMeshData(indexVertexArrays2);
#endif
            CollisionShapes.Add(trimeshShape2);

            //register GIMPACT algorithm
#if BULLET_GIMPACT
            GImpactCollisionAlgorithm.RegisterAlgorithm(Dispatcher);
#else
            //ConcaveConcaveCollisionAlgorithm.RegisterAlgorithm(Dispatcher);
#endif
        }
Esempio n. 2
0
        public void Init(IGameModel ctx)
        {
            #region World configuration
            this.ctx = ctx;
            // Create a physics world using default config
            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, -15f, 0).ToBsVector
            };

            var heightMap = BulletRigidBodyConstructor.CreateSurfaceFromHeighMap(ctx.Terrain.getData());
            heightMap.Restitution = 0;
            dynamicsWorld.AddRigidBody(heightMap);
            #endregion

            #region BandicootRigidBody
            var position = new TGCVector3(0, 1, 0);
            var mass     = 1.5f;
            var radius   = 10;
            var height   = 5;

            BandicootRigidBody = BulletRigidBodyConstructor.CreateCapsule(radius, height, position, mass, false);
            BandicootRigidBody.SetDamping(0.1f, 0);
            BandicootRigidBody.Restitution           = 0f;
            BandicootRigidBody.Friction              = 0.15f;
            BandicootRigidBody.InvInertiaDiagLocal   = TGCVector3.Empty.ToBsVector;
            BandicootRigidBody.CenterOfMassTransform = TGCMatrix.Translation(-900, 1000, 900).ToBsMatrix;
            dynamicsWorld.AddRigidBody(BandicootRigidBody);
            #endregion

            #region Rocks
            var size = new TGCVector3(200, 150, 200);
            mass = 0;
            var centerOfMass = TGCVector3.Empty;
            var rockFriction = 1.5f;
            var translation  = TGCMatrix.Translation(-900, size.Y, 900);

            // Rock1 Body
            Rock1Body = BulletRigidBodyConstructor.CreateBox(size, mass, centerOfMass, 0, 0, 0, rockFriction);
            Rock1Body.CenterOfMassTransform = translation.ToBsMatrix;
            dynamicsWorld.AddRigidBody(Rock1Body);

            // Rock1 Mesh
            var canyonTexture = TgcTexture.createTexture(D3DDevice.Instance.Device, $"{ctx.MediaDir}\\Textures\\canyon-horizontal.png");
            Rock1Mesh           = TGCBox.fromSize(centerOfMass, 2 * size, canyonTexture);
            Rock1Mesh.Transform = new TGCMatrix(Rock1Body.InterpolationWorldTransform);

            // Rock2 Body
            size         = new TGCVector3(100, 150, 100);
            Rock2Body    = BulletRigidBodyConstructor.CreateBox(size, mass, centerOfMass, 0, 0, 0, rockFriction);
            translation *= TGCMatrix.Translation(400, 1, 1);
            Rock2Body.CenterOfMassTransform = translation.ToBsMatrix;
            dynamicsWorld.AddRigidBody(Rock2Body);

            // Rock2 Mesh
            Rock2Mesh           = TGCBox.fromSize(centerOfMass, 2 * size, canyonTexture);
            Rock2Mesh.Transform = new TGCMatrix(Rock2Body.InterpolationWorldTransform);

            // Rock3 Body
            Rock3Body    = BulletRigidBodyConstructor.CreateBox(size, mass, centerOfMass, 0, 0, 0, rockFriction);
            translation *= TGCMatrix.Translation(800, 1, 1);
            Rock3Body.CenterOfMassTransform = translation.ToBsMatrix;
            dynamicsWorld.AddRigidBody(Rock3Body);

            // Rock3 Mesh
            Rock3Mesh           = TGCBox.fromSize(centerOfMass, 2 * size, canyonTexture);
            Rock3Mesh.Transform = new TGCMatrix(Rock3Body.InterpolationWorldTransform);


            // Rock4 Body
            size         = new TGCVector3(100, 200, 100);
            Rock4Body    = BulletRigidBodyConstructor.CreateBox(size, mass, centerOfMass, 0, 0, 0, rockFriction);
            translation *= TGCMatrix.Translation(0, 1, -700);
            Rock4Body.CenterOfMassTransform = translation.ToBsMatrix;
            dynamicsWorld.AddRigidBody(Rock4Body);

            // Rock4 Mesh
            Rock4Mesh           = TGCBox.fromSize(centerOfMass, 2 * size, canyonTexture);
            Rock4Mesh.Transform = new TGCMatrix(Rock4Body.InterpolationWorldTransform);


            // Rock5 Body
            Rock5Body    = BulletRigidBodyConstructor.CreateBox(size, mass, centerOfMass, 0, 0, 0, rockFriction);
            translation *= TGCMatrix.Translation(1, 1, -900);
            Rock5Body.CenterOfMassTransform = translation.ToBsMatrix;
            dynamicsWorld.AddRigidBody(Rock5Body);


            // Rock5 Mesh
            Rock5Mesh           = TGCBox.fromSize(centerOfMass, 2 * size, canyonTexture);
            Rock5Mesh.Transform = new TGCMatrix(Rock5Body.InterpolationWorldTransform);
            #endregion

            #region Dynamic Platforms
            mass = 1f;
            size = new TGCVector3(70, 10, 40);
            var platformFriction = 2.5f;

            // DynamicPlatform1 Body
            DynamicPlatform1Body = BulletRigidBodyConstructor.CreateBox(size, mass, centerOfMass, 0, 0, 0, platformFriction);
            DynamicPlatform1Body.AngularFactor         = new Vector3(0, 0, 0);
            DynamicPlatform1Body.CenterOfMassTransform =
                TGCMatrix.RotationY(FastMath.PI_HALF).ToBsMatrix
                *TGCMatrix.Translation(distance, 300, 900).ToBsMatrix;
            dynamicsWorld.AddRigidBody(DynamicPlatform1Body);

            // DynamicPlatform1 Mesh
            var platformtexture = TgcTexture.createTexture(D3DDevice.Instance.Device, $"{ctx.MediaDir}\\textures\\rockwall.jpg");
            DynamicPlatform1Mesh           = TGCBox.fromSize(2 * size, platformtexture);
            DynamicPlatform1Mesh.Transform = new TGCMatrix(DynamicPlatform1Body.InterpolationWorldTransform);

            // DynamicPlatform2 Body
            DynamicPlatform2Body = BulletRigidBodyConstructor.CreateBox(size, mass, centerOfMass, 0, 0, 0, platformFriction);
            DynamicPlatform2Body.AngularFactor         = new Vector3(0, 0, 0);
            DynamicPlatform2Body.CenterOfMassTransform = TGCMatrix.Translation(300, 300, 700).ToBsMatrix;
            dynamicsWorld.AddRigidBody(DynamicPlatform2Body);

            // DynamicPlatform2 Mesh
            var platformtexture2 = TgcTexture.createTexture(D3DDevice.Instance.Device, $"{ctx.MediaDir}\\textures\\rockwall.jpg");
            DynamicPlatform2Mesh           = TGCBox.fromSize(2 * size, platformtexture);
            DynamicPlatform2Mesh.Transform = new TGCMatrix(DynamicPlatform2Body.InterpolationWorldTransform);

            // DynamicPlatform3 Body
            DynamicPlatform3Body = BulletRigidBodyConstructor.CreateBox(size, mass, centerOfMass, 0, 0, 0, platformFriction);
            DynamicPlatform3Body.AngularFactor         = new Vector3(0, 0, 0);
            DynamicPlatform3Body.CenterOfMassTransform = TGCMatrix.Translation(300, 350, 0).ToBsMatrix;
            dynamicsWorld.AddRigidBody(DynamicPlatform3Body);

            // DynamicPlatform3 Mesh
            platformtexture2               = TgcTexture.createTexture(D3DDevice.Instance.Device, $"{ctx.MediaDir}\\textures\\rockwall.jpg");
            DynamicPlatform3Mesh           = TGCBox.fromSize(2 * size, platformtexture);
            DynamicPlatform3Mesh.Transform = new TGCMatrix(DynamicPlatform3Body.InterpolationWorldTransform);
            #endregion
        }
        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);

            GImpactCollisionAlgorithm.RegisterAlgorithm(Dispatcher);

            string bulletFile;

            string[] args = Environment.GetCommandLineArgs();
            if (args.Length == 1)
            {
                bulletFile = "testFile.bullet";
            }
            else
            {
                bulletFile = args[1];
            }

            BulletWorldImporter fileLoader = new CustomBulletWorldImporter(World);

            if (!fileLoader.LoadFile(bulletFile))
            {
                CollisionShape groundShape = new BoxShape(50);
                CollisionShapes.Add(groundShape);
                RigidBody ground = LocalCreateRigidBody(0, Matrix.Translation(0, -50, 0), groundShape);
                ground.UserObject = "Ground";

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

                Vector3[] positions = new Vector3[2] {
                    new Vector3(0.1f, 0.2f, 0.3f), new Vector3(0.4f, 0.5f, 0.6f)
                };
                float[] radi = new float[2] {
                    0.3f, 0.4f
                };

                CollisionShape colShape = new MultiSphereShape(positions, radi);

                //CollisionShape colShape = new CapsuleShapeZ(1, 1);
                //CollisionShape colShape = new CylinderShapeZ(1, 1, 1);
                //CollisionShape colShape = new BoxShape(1);
                //CollisionShape colShape = new SphereShape(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);
                            rbInfo.Dispose();

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

                            World.AddRigidBody(body);
                        }
                    }
                }

                const int         maxSerializeBufferSize = 1024 * 1024 * 5;
                DefaultSerializer serializer             = new DefaultSerializer(maxSerializeBufferSize);

                serializer.RegisterNameForObject(ground, "GroundName");

                for (i = 0; i < CollisionShapes.Count; i++)
                {
                    serializer.RegisterNameForObject(CollisionShapes[i], "name" + i.ToString());
                }

                Point2PointConstraint p2p = new Point2PointConstraint((RigidBody)World.CollisionObjectArray[2], new Vector3(0, 1, 0));
                World.AddConstraint(p2p);

                serializer.RegisterNameForObject(p2p, "constraintje");

                World.Serialize(serializer);

                byte[] dataBytes = new byte[serializer.CurrentBufferSize];
                Marshal.Copy(serializer.BufferPointer, dataBytes, 0, dataBytes.Length);

                FileStream file = new FileStream("testFile.bullet", FileMode.Create);
                file.Write(dataBytes, 0, dataBytes.Length);
                file.Dispose();
            }
        }
    protected UnityEngine.Vector3 m_eulerrotf;    // euler rotation last frame

    // Sets up initial collision shapes and objects for the simulation.
    protected override void InitSim()
    {
        Debug.Log("InitSim");

        // create data directory if doesn't exist
        Directory.CreateDirectory(dataOutDir);

        // get list of all objs to sim
        if (!BUILD_MODE)
        {
            m_baseDataDir = Application.dataPath + "/Resources/" + dataInDir + "/";
        }
        else
        {
            m_baseDataDir = Application.dataPath + "/../../Assets/Resources/" + dataInDir + "/";
        }
        DirectoryInfo resDirPath = new DirectoryInfo(m_baseDataDir);

        FileInfo[] objFileInfos = resDirPath.GetFiles("*.obj", SearchOption.AllDirectories);
        Debug.Log("Files to sim: " + objFileInfos.Length.ToString());
        m_objFiles = new string[objFileInfos.Length];
        int fileIdx = 0;

        foreach (FileInfo file in objFileInfos)
        {
            m_objFiles[fileIdx++] = file.Name;
        }

        // First read in all volumes
        m_masses = new float[m_objFiles.Length];
        float maxVol = -float.MaxValue;

        m_inertias = new List <BulletSharp.Math.Vector3>();
        for (int i = 0; i < m_masses.Length; i++)
        {
            string infoFile = dataInDir + "/" + m_objFiles[i].Replace(".obj", "");
            /*if (DEBUG)*/ Debug.Log("Idx " + i.ToString() + ": " + infoFile);
            var jsonTextFile = Resources.Load <TextAsset>(infoFile);
            if (DEBUG)
            {
                Debug.Log(jsonTextFile.ToString());
            }
            ObjInfo curInfo = ObjInfo.CreateFromJSON(jsonTextFile.ToString());
            m_masses[i] = curInfo.vol;
            // moment of inertias assume the density is 1 (i.e. mass = volume)
            m_inertias.Add(new BulletSharp.Math.Vector3(curInfo.inertia[0], curInfo.inertia[1], curInfo.inertia[2]));
            if (DEBUG)
            {
                Debug.Log(m_masses[i].ToString());
            }
            if (m_masses[i] > maxVol)
            {
                maxVol = m_masses[i];
            }
        }

        // Normalize volumes and use as mass
        // float normCoeff = massMax / maxVol; // need to scale density by this much.
        // for (int i = 0; i < m_masses.Length; i++) {
        //  m_masses[i] = normCoeff * m_masses[i];
        //  m_inertias[i] = normCoeff * m_inertias[i];
        //  if (DEBUG) Debug.Log(m_masses[i].ToString());
        //  if (DEBUG) Debug.Log(m_inertias[i].ToString());
        // }

        // only simulate one of interest for debugging
        if (DEBUG_simFileIdx != -1)
        {
            string simObjFile = m_objFiles[DEBUG_simFileIdx];
            float  simMass    = m_masses[DEBUG_simFileIdx];
            BulletSharp.Math.Vector3 simInertia = m_inertias[DEBUG_simFileIdx];
            m_objFiles    = new string[1];
            m_objFiles[0] = simObjFile;
            m_masses      = new float[1];
            m_masses[0]   = simMass;
            m_inertias    = new List <BulletSharp.Math.Vector3>();
            m_inertias.Add(simInertia);
            Debug.Log("ONLY SIMULATING: " + simObjFile);
        }

        // create the ground, this will be the same for every sim
        BulletSharp.Math.Vector3 groundSize = new BulletSharp.Math.Vector3(50, 0.04f, 50);
        BoxShape groundShape = new BoxShape(groundSize);

        // groundShape.Margin = 0.07f;
        AddCollisionShape(groundShape);
        m_groundMargin = groundShape.Margin;
        // move down so surface is exactly y=0
        Debug.Log("GROUND MARGIN: " + m_groundMargin.ToString());
        // The 0.016 is dependent on the ground margin but idk why at this point
        m_groundInitTrans = Matrix.Translation(new BulletSharp.Math.Vector3(0, -((groundSize[1] / 2.0f) + 0.016f), 0));
        m_groundRb        = CreateRigidBody(0, m_groundInitTrans, groundShape, groundMat, groundFriction, viz: RENDER_MODE);

        // setup the camera
        SetEyeTarget(cameraLoc, cameraTarget);

        // Now load the first simulation object to start
        m_curObjIdx = startingObjIdx;
        if (m_objFiles.Length == 0)
        {
            ExitSimulation();
        }
        else
        {
            m_curDataOutDir = Path.Combine(dataOutDir, m_objFiles[m_curObjIdx].Replace(".obj", "") + "/");
            Directory.CreateDirectory(m_curDataOutDir);
            PrepareSimObj(m_baseDataDir + m_objFiles[m_curObjIdx], m_masses[m_curObjIdx], m_inertias[m_curObjIdx]);

            m_curVideoOutDir = Path.Combine(Application.dataPath, videoOutDir);
            m_curVideoOutDir = Path.Combine(m_curVideoOutDir, m_objFiles[m_curObjIdx].Replace(".obj", "") + "/");
            Directory.CreateDirectory(m_curVideoOutDir);
            string simOutDir = Path.Combine(m_curVideoOutDir, "sim_0");
            if (!Directory.Exists(simOutDir))
            {
                Directory.CreateDirectory(simOutDir);
            }
        }

        // so we can handle object collisions, only need to do this once
        GImpactCollisionAlgorithm.RegisterAlgorithm(m_colDispatcher);

        InitStateLists();

        // determine and apply the force for the first simulation
        SetupSim();
        // take note of inital rigid body state
        SaveInitState();
        SaveCurrentState();
        m_curSimNum   = 0;
        m_renderFrame = 1;
        // set up rotation tracking
        m_totalRot = new BulletSharp.Math.Vector3(0.0f, 0.0f, 0.0f);

        m_pclScale = UnityEngine.Vector3.one;

        m_fallenFiles = new List <string>();
        m_fallCount   = 0;
        m_stepCount   = 0;
        m_stuckCount  = 0;
        m_numPerturbs = 0;
    }
Esempio n. 5
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);
        }
        public void Init(String MediaDir)
        {
            #region Configuracion Basica de World

            //Creamos el mundo fisico por defecto.
            collisionConfiguration = new DefaultCollisionConfiguration();
            dispatcher             = new CollisionDispatcher(collisionConfiguration);
            GImpactCollisionAlgorithm.RegisterAlgorithm(dispatcher);
            constraintSolver      = new SequentialImpulseConstraintSolver();
            overlappingPairCache  = new DbvtBroadphase(); //AxisSweep3(new BsVector3(-5000f, -5000f, -5000f), new BsVector3(5000f, 5000f, 5000f), 8192);
            dynamicsWorld         = new DiscreteDynamicsWorld(dispatcher, overlappingPairCache, constraintSolver, collisionConfiguration);
            dynamicsWorld.Gravity = new TGCVector3(0, -100f, 0).ToBsVector;

            #endregion Configuracion Basica de World

            #region Capsula

            //Cuerpo rigido de una capsula basica
            capsuleRigidBody = BulletRigidBodyConstructor.CreateCapsule(10, 50, new TGCVector3(200, 500, 200), 10, false);

            //Valores que podemos modificar a partir del RigidBody base
            capsuleRigidBody.SetDamping(0.1f, 0f);
            capsuleRigidBody.Restitution = 0.1f;
            capsuleRigidBody.Friction    = 1;

            //Agregamos el RidigBody al World
            dynamicsWorld.AddRigidBody(capsuleRigidBody);

            #endregion Capsula

            #region Terreno

            //Creamos el RigidBody basico del Terreno
            var meshRigidBody = BulletRigidBodyConstructor.CreateSurfaceFromHeighMap(triangleDataVB);

            //Agregamos algo de friccion al RigidBody ya que este va a interactuar con objetos moviles
            //del World
            meshRigidBody.Friction = 0.5f;

            //Agregamos el RigidBody del terreno al World
            dynamicsWorld.AddRigidBody(meshRigidBody);

            #endregion Terreno

            #region Esfera

            //Creamos una esfera para interactuar
            pokeball = BulletRigidBodyConstructor.CreateBall(10f, 0.5f, new TGCVector3(100f, 500f, 100f));
            pokeball.SetDamping(0.1f, 0.5f);
            pokeball.Restitution = 1f;
            //Agregamos la pokebola al World
            dynamicsWorld.AddRigidBody(pokeball);

            //Textura de pokebola
            var texturePokeball = TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + @"Texturas\pokeball.jpg");

            //Se crea una esfera de tamaño 1 para escalarla luego (en render)
            sphereMesh = new TGCSphere(1, texturePokeball, TGCVector3.Empty);

            //Tgc no crea el vertex buffer hasta invocar a update values.
            sphereMesh.updateValues();

            #endregion Esfera

            #region Personaje

            //Cargamos personaje
            var skeletalLoader = new TgcSkeletalLoader();
            personaje = skeletalLoader.loadMeshAndAnimationsFromFile(
                MediaDir + "SkeletalAnimations\\Robot\\Robot-TgcSkeletalMesh.xml",
                MediaDir + "SkeletalAnimations\\Robot\\",
                new[]
            {
                MediaDir + "SkeletalAnimations\\Robot\\Caminando-TgcSkeletalAnim.xml",
                MediaDir + "SkeletalAnimations\\Robot\\Parado-TgcSkeletalAnim.xml"
            });

            //Le cambiamos la textura para diferenciarlo un poco
            personaje.changeDiffuseMaps(new[]
            {
                TgcTexture.createTexture(D3DDevice.Instance.Device,
                                         MediaDir + "SkeletalAnimations\\Robot\\Textures\\uvwGreen.jpg")
            });

            //Configurar animacion inicial
            personaje.playAnimation("Parado", true);

            #endregion Personaje

            #region Cajas

            var sizeBox = 20f;

            //Textura de caja
            var textureBox = TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + @"MeshCreator\Textures\Madera\cajaMadera2.jpg");

            box = BulletRigidBodyConstructor.CreateBox(new TGCVector3(sizeBox, sizeBox, sizeBox), 0, new TGCVector3(0, 12, 0), 0, 0, 0, 0.5f);
            dynamicsWorld.AddRigidBody(box);
            boxMesh = TGCBox.fromSize(new TGCVector3(40f, 40f, 40f), textureBox);
            boxMesh.updateValues();

            sizeBox = 40f;
            boxB    = BulletRigidBodyConstructor.CreateBox(new TGCVector3(sizeBox, sizeBox, sizeBox), 0, new TGCVector3(100, 40, 0), 0, 0, 0, 0.5f);
            dynamicsWorld.AddRigidBody(boxB);
            boxMeshB = TGCBox.fromSize(new TGCVector3(80f, 80f, 80f), textureBox);
            boxMeshB.updateValues();

            box45 = BulletRigidBodyConstructor.CreateBox(new TGCVector3(sizeBox, sizeBox, sizeBox), 0, new TGCVector3(200, 40, 0), BulletSharp.MathUtil.SIMD_QUARTER_PI, 0, 0, 0.5f);
            dynamicsWorld.AddRigidBody(box45);

            boxPush = BulletRigidBodyConstructor.CreateBox(new TGCVector3(sizeBox, sizeBox, sizeBox), 0.5f, new TGCVector3(-200, 60, 0), BulletSharp.MathUtil.SIMD_QUARTER_PI, 0, 0, 0.25f);
            dynamicsWorld.AddRigidBody(boxPush);

            boxMeshPush = TGCBox.fromSize(new TGCVector3(80f, 80f, 80f), textureBox);
            boxMeshPush.updateValues();

            #endregion Cajas

            #region Escalera

            var a             = 0;
            var textureStones = TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + @"Texturas\stones.bmp");

            //la altura de cualquier cubo que quiera subir una capsula debe ser menor a la mitad del radio
            var size = new TGCVector3(50, 4, 20);
            escalon = TGCBox.fromSize(size, textureStones);

            //Se crean 10 escalonescd d
            while (a < 10)
            {
                escalonRigidBody = BulletRigidBodyConstructor.CreateBox(size, 0, new TGCVector3(200, a * 4 + 10, a * 20 + 100), 0, 0, 0, 0.1f);

                escalonesRigidBodies.Add(escalonRigidBody);

                dynamicsWorld.AddRigidBody(escalonRigidBody);

                a++;
            }

            #endregion Escalera

            #region Plataforma

            textureStones       = TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + @"Texturas\cobblestone_quad.jpg");
            rigidBodyPlataforma = BulletRigidBodyConstructor.CreateBox(new TGCVector3(50f, 15f, 50f), 0, new TGCVector3(200, 42.5f, 315), 0, 0, 0, 0.5f);
            dynamicsWorld.AddRigidBody(rigidBodyPlataforma);
            plataforma = TGCBox.fromSize(new TGCVector3(50f, 15f, 50f), textureStones);
            plataforma.updateValues();

            #endregion Plataforma

            #region Columna

            columnaRigidBody = BulletRigidBodyConstructor.CreateCylinder(new TGCVector3(10, 50, 10), new TGCVector3(100, 50, 100), 0);
            dynamicsWorld.AddRigidBody(columnaRigidBody);
            var columnaLoader = new TgcSceneLoader();
            columnaMesh          = columnaLoader.loadSceneFromFile(MediaDir + @"MeshCreator\Meshes\Cimientos\PilarEgipcio\PilarEgipcio-TgcScene.xml", MediaDir + @"MeshCreator\Meshes\Cimientos\PilarEgipcio\").Meshes[0];
            columnaMesh.Position = new TGCVector3(100, 7.5f, 100);
            columnaMesh.UpdateMeshTransform();

            #endregion Columna

            director = new TGCVector3(0, 0, 1);
        }
        public SerializeDemoSimulation()
        {
            CollisionConfiguration = new DefaultCollisionConfiguration();
            Dispatcher             = new CollisionDispatcher(CollisionConfiguration);
            Broadphase             = new DbvtBroadphase();
            World = new DiscreteDynamicsWorld(Dispatcher, Broadphase, null, CollisionConfiguration);

            GImpactCollisionAlgorithm.RegisterAlgorithm(Dispatcher);

            string bulletFile;

            string[] args = Environment.GetCommandLineArgs();
            if (args.Length == 1)
            {
                bulletFile = "testFile.bullet";
            }
            else
            {
                bulletFile = args[1];
            }

            _fileLoader = new CustomBulletWorldImporter(World);
            if (!_fileLoader.LoadFile(bulletFile))
            {
                var groundShape = new BoxShape(50);
                _collisionShapes.Add(groundShape);
                RigidBody ground = PhysicsHelper.CreateStaticBody(Matrix.Translation(0, -50, 0), groundShape, World);
                ground.UserObject = "Ground";

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

                Vector3[] positions = new[] { new Vector3(0.1f, 0.2f, 0.3f), new Vector3(0.4f, 0.5f, 0.6f) };
                float[]   radi      = new float[2] {
                    0.3f, 0.4f
                };

                var colShape = new MultiSphereShape(positions, radi);

                //var colShape = new CapsuleShapeZ(1, 1);
                //var colShape = new CylinderShapeZ(1, 1, 1);
                //var colShape = new BoxShape(1);
                //var colShape = new SphereShape(1);
                _collisionShapes.Add(colShape);

                Vector3 localInertia = colShape.CalculateLocalInertia(mass);

                float startX = StartPosX - NumObjectsX / 2;
                float startY = StartPosY;
                float startZ = StartPosZ - NumObjectsZ / 2;

                for (int y = 0; y < NumObjectsY; y++)
                {
                    for (int x = 0; x < NumObjectsX; x++)
                    {
                        for (int z = 0; z < NumObjectsZ; z++)
                        {
                            Matrix startTransform = Matrix.Translation(
                                2 * x + startX,
                                2 * y + startY,
                                2 * z + startZ
                                );

                            // 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();

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

                            World.AddRigidBody(body);
                        }
                    }
                }

                using (var serializer = new DefaultSerializer())
                {
                    serializer.RegisterNameForObject(ground, "GroundName");

                    for (int i = 0; i < _collisionShapes.Count; i++)
                    {
                        serializer.RegisterNameForObject(_collisionShapes[i], "name" + i.ToString());
                    }

                    var p2p = new Point2PointConstraint((RigidBody)World.CollisionObjectArray[2],
                                                        new Vector3(0, 1, 0));
                    World.AddConstraint(p2p);
                    serializer.RegisterNameForObject(p2p, "constraintje");

                    World.Serialize(serializer);
                    byte[] dataBytes = new byte[serializer.CurrentBufferSize];
                    Marshal.Copy(serializer.BufferPointer, dataBytes, 0, dataBytes.Length);

                    using (var file = new FileStream("testFile.bullet", FileMode.Create))
                    {
                        file.Write(dataBytes, 0, dataBytes.Length);
                    }
                }
            }
        }
Esempio n. 8
0
 void Awake()
 {
     GImpactCollisionAlgorithm.RegisterAlgorithm((CollisionDispatcher)BPhysicsWorld.Get().world.Dispatcher);
     BPhysicsWorld.Get().DebugDrawMode = DebugDrawModes.DrawWireframe | DebugDrawModes.DrawConstraints | DebugDrawModes.DrawConstraintLimits;
     BPhysicsWorld.Get().DoDebugDraw   = true;
 }
Esempio n. 9
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);
            World.Gravity = new Vector3(0, -10, 0);

            GImpactCollisionAlgorithm.RegisterAlgorithm(Dispatcher);


            BulletWorldImporter fileLoader = new CustomBulletWorldImporter(World);

            if (!fileLoader.LoadFile("testFile.bullet"))
            {
                CollisionShape groundShape = new BoxShape(50);
                CollisionShapes.Add(groundShape);
                RigidBody ground = LocalCreateRigidBody(0, Matrix.Translation(0, -50, 0), groundShape);
                ground.UserObject = "Ground";

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

                Vector3[] positions = new Vector3[2] {
                    new Vector3(0.1f, 0.2f, 0.3f), new Vector3(0.4f, 0.5f, 0.6f)
                };
                float[] radi = new float[2] {
                    0.3f, 0.4f
                };

                CollisionShape colShape = new MultiSphereShape(positions, radi);

                //CollisionShape colShape = new CapsuleShapeZ(1, 1);
                //CollisionShape colShape = new CylinderShapeZ(1, 1, 1);
                //CollisionShape colShape = new BoxShape(1);
                //CollisionShape colShape = new SphereShape(1);
                CollisionShapes.Add(colShape);

                Vector3 localInertia = colShape.CalculateLocalInertia(mass);

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

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

                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);
                        }
                    }
                }

                DefaultSerializer serializer = new DefaultSerializer();

                serializer.RegisterNameForObject(ground, "GroundName");

                for (int i = 0; i < CollisionShapes.Count; i++)
                {
                    serializer.RegisterNameForObject(CollisionShapes[i], "name" + i.ToString());
                }

                Point2PointConstraint p2p = new Point2PointConstraint((RigidBody)World.CollisionObjectArray[2], new Vector3(0, 1, 0));
                World.AddConstraint(p2p);

                serializer.RegisterNameForObject(p2p, "constraintje");

                World.Serialize(serializer);

                BulletSharp.DataStream data = serializer.LockBuffer();
                byte[] dataBytes            = new byte[data.Length];
                data.Read(dataBytes, 0, dataBytes.Length);

                FileStream file = new FileStream("testFile.bullet", FileMode.Create);
                file.Write(dataBytes, 0, dataBytes.Length);
                file.Close();
            }
        }
Esempio n. 10
0
        public void Init(string MediaDir)
        {
            #region Configuracion Basica de World

            //Creamos el mundo fisico por defecto.
            collisionConfiguration = new DefaultCollisionConfiguration();
            dispatcher             = new CollisionDispatcher(collisionConfiguration);
            GImpactCollisionAlgorithm.RegisterAlgorithm(dispatcher);
            constraintSolver      = new SequentialImpulseConstraintSolver();
            overlappingPairCache  = new DbvtBroadphase(); //AxisSweep3(new BsVector3(-5000f, -5000f, -5000f), new BsVector3(5000f, 5000f, 5000f), 8192);
            dynamicsWorld         = new DiscreteDynamicsWorld(dispatcher, overlappingPairCache, constraintSolver, collisionConfiguration);
            dynamicsWorld.Gravity = new TGCVector3(0, -100f, 0).ToBulletVector3();

            #endregion Configuracion Basica de World

            strength = 5.8f;
            angle    = 0.5f;

            foreach (var mesh in meshes)
            {
                var childTriangleMesh = construirTriangleMeshShape(mesh);
                var buildingbody      = construirRigidBodyDeChildTriangleMeshShape(childTriangleMesh, mesh.Position, mesh.Scale);


                //buildingbody.Translate(mesh.Position.ToBulletVector3());
                dynamicsWorld.AddRigidBody(buildingbody);
            }

            //Se crea un plano ya que esta escena tiene problemas
            //con la definición de triangulos para el suelo
            var floorShape = new StaticPlaneShape(TGCVector3.Up.ToBulletVector3(), 10);
            floorShape.LocalScaling = new TGCVector3().ToBulletVector3();
            var floorMotionState = new DefaultMotionState();
            var floorInfo        = new RigidBodyConstructionInfo(0, floorMotionState, floorShape);
            floorBody                 = new RigidBody(floorInfo);
            floorBody.Friction        = 0.5f;
            floorBody.RollingFriction = 1;
            floorBody.Restitution     = 1f;
            floorBody.UserObject      = "floorBody";
            dynamicsWorld.AddRigidBody(floorBody);

            var meshRigidBody = BulletRigidBodyFactory.Instance.CreateSurfaceFromHeighMap(terreno.getData());
            dynamicsWorld.AddRigidBody(meshRigidBody);

            var loader = new TgcSceneLoader();

            //Se crea el cuerpo rígido de la caja, en la definicio de CreateBox el ultimo parametro representa si se quiere o no
            //calcular el momento de inercia del cuerpo. No calcularlo lo que va a hacer es que la caja que representa el personaje
            //no rote cuando colicione contra el mundo.
            personajeBody = BulletRigidBodyFactory.Instance.CreateCapsule(10, 10, personaje.Position, 2.55f, false);

            personajeBody.Gravity = new TGCVector3(0, -100, 0).ToBulletVector3();
            personajeBody.SetDamping(0.3f, 0f);
            personajeBody.Restitution     = 0.1f;
            personajeBody.Friction        = 1;
            personajeBody.ActivationState = ActivationState.IslandSleeping;

            dynamicsWorld.AddRigidBody(personajeBody);

            director = new TGCVector3(-1, 0, 0);
        }