// Used with soft bodies
        public void SetDynamicVertexBuffer(Device device, Vector3[] vectors)
        {
            if (VertexBuffer != null && VertexCount * 2 == vectors.Length)
            {
                DataBox db = device.ImmediateContext.MapSubresource(VertexBuffer, 0, MapMode.WriteDiscard, SharpDX.Direct3D11.MapFlags.None);
                SharpDX.Utilities.Write(db.DataPointer, vectors, 0, vectors.Length);
                device.ImmediateContext.UnmapSubresource(VertexBuffer, 0);
            }
            else
            {
                // Create new buffer
                if (VertexBuffer != null)
                    VertexBuffer.Dispose();

                BufferDescription vertexBufferDesc = new BufferDescription()
                {
                    SizeInBytes = Vector3.SizeInBytes * vectors.Length,
                    Usage = ResourceUsage.Dynamic,
                    BindFlags = BindFlags.VertexBuffer,
                    CpuAccessFlags = CpuAccessFlags.Write
                };

                using (var data = new DataStream(vertexBufferDesc.SizeInBytes, false, true))
                {
                    data.WriteRange(vectors);
                    data.Position = 0;
                    VertexBuffer = new Buffer(device, data, vertexBufferDesc);
                }

                VertexCount = vectors.Length / 2;
                BufferBindings[0] = new VertexBufferBinding(VertexBuffer, 24, 0);
            }
        }
        public override bool BuildSoftBody()
        {
            Mesh mesh = meshSettings.Build();

            GetComponent<MeshFilter>().sharedMesh = mesh;

            //convert the mesh data to Bullet data and create DoftBody
            BulletSharp.Math.Vector3[] bVerts = new BulletSharp.Math.Vector3[mesh.vertexCount];

            for (int i = 0; i < mesh.vertexCount; i++)
            {
                bVerts[i] = mesh.vertices[i].ToBullet();
            }

            m_BSoftBody = SoftBodyHelpers.CreateFromTriMesh(World.WorldInfo, bVerts, mesh.triangles);

            SoftBodySettings.ConfigureSoftBody(m_BSoftBody);         //Set SB settings

            //Set SB position to GO position
            m_BSoftBody.Rotate(transform.rotation.ToBullet());
            m_BSoftBody.Translate(transform.position.ToBullet());
            m_BSoftBody.Scale(transform.localScale.ToBullet());

            return true;
        }
 public void Rotate(float turnAmount)
 {
     BulletSharp.Math.Matrix xform = m_collisionObject.WorldTransform;
     BulletSharp.Math.Matrix orn = xform;
     BulletSharp.Math.Vector3 pos = xform.Origin;
     orn.Row4 = new BulletSharp.Math.Vector4(0, 0, 0, 1);
     BulletSharp.Math.Vector3 upDir = new BulletSharp.Math.Vector3(xform.M21, xform.M22, xform.M23);
     orn *= BulletSharp.Math.Matrix.RotationAxis(upDir, turnAmount);
     orn.Row4 = new BulletSharp.Math.Vector4(pos.X, pos.Y, pos.Z, 1);
     m_collisionObject.WorldTransform = orn;
 }
Example #4
0
 public IgnorableRayResultCallback(ref Vector3 rayFromWorld, ref Vector3 rayToWorld, List <object> ignore)
 {
     this.RayFromWorld = rayFromWorld;
     this.RayToWorld   = rayToWorld;
     this.ignoreList   = ignore;
     foreach (object obj in ignore)
     {
         if (obj is PhysicsEntity)
         {
             PhysicsEntity ent = obj as PhysicsEntity;
         }
     }
 }
 public override CollisionShape GetCollisionShape()
 {
     if (collisionShapePtr == null) {
         BulletSharp.Math.Vector3[] positions = new BulletSharp.Math.Vector3[spheres.Length];
         float[] radius = new float[spheres.Length];
         for (int i = 0; i < spheres.Length; i++) {
             positions[i] = spheres[i].position.ToBullet();
             radius[i] = spheres[i].radius;
         }
         collisionShapePtr = new MultiSphereShape(positions, radius);
     }
     return collisionShapePtr;
 }
Example #6
0
        void _UpdateFlipperMass(ref BulletPhysicsComponent bpc)
        {
            // Update params from ImGui menu
            float newMass = math.pow(10.0f, bpc.flipperMassMultiplierLog);

            if (newMass != _prevFlipperMassMultiplierLog)
            {
                _prevFlipperMassMultiplierLog = newMass;
                _usedFlipperMass = Mass * _prevFlipperMassMultiplierLog;
                Vector3 inertia = body.CollisionShape.CalculateLocalInertia(_usedFlipperMass);
                body.SetMassProps(_usedFlipperMass, inertia);
            }
        }
Example #7
0
        MultiSphereShape _CreateMultiSphereShape()
        {
            BulletSharp.Math.Vector3[] positions = new BulletSharp.Math.Vector3[spheres.Length];
            float[] radius = new float[spheres.Length];
            for (int i = 0; i < spheres.Length; i++)
            {
                positions[i] = spheres[i].position.ToBullet();
                radius[i]    = spheres[i].radius;
            }
            MultiSphereShape mss = new MultiSphereShape(positions, radius);

            mss.LocalScaling = m_localScaling.ToBullet();
            return(mss);
        }
Example #8
0
        /// <summary>
        /// Perform a raycast test and return colliding results.
        /// </summary>
        /// <param name="start">Start ray vector.</param>
        /// <param name="end">End ray vector.</param>
        /// <param name="returnNearest">If true, will only return the nearest object collided.</param>
        public RaycastResults Raycast(Vector3 start, Vector3 end, bool returnNearest = true)
        {
            // convert start and end vectors to bullet vectors
            BulletSharp.Math.Vector3 bStart = ToBullet.Vector(start);
            BulletSharp.Math.Vector3 bEnd   = ToBullet.Vector(end);

            // create class to hold results
            BulletSharp.RayResultCallback resultsCallback = returnNearest ?
                                                            new BulletSharp.ClosestRayResultCallback(ref bStart, ref bEnd) as BulletSharp.RayResultCallback :
                                                            new BulletSharp.AllHitsRayResultCallback(bStart, bEnd);

            // perform ray cast
            return(Raycast(bStart, bEnd, resultsCallback));
        }
Example #9
0
        /// <summary>
        /// Perform a raycast test and return colliding results, using native bullet objects.
        /// </summary>
        /// <param name="bStart">Start ray vector (bullet vector).</param>
        /// <param name="bEnd">End ray vector (bullet vector).</param>
        /// <param name="resultsCallback">BulletSharp results callback.</param>
        internal RaycastResults Raycast(BulletSharp.Math.Vector3 bStart, BulletSharp.Math.Vector3 bEnd, BulletSharp.RayResultCallback resultsCallback)
        {
            // perform the ray test
            _world.RayTestRef(ref bStart, ref bEnd, resultsCallback);

            // create results object to return
            RaycastResults results = new RaycastResults();

            // parse data based on type
            // closest result / closest but not me types:
            if (resultsCallback is BulletSharp.ClosestRayResultCallback)
            {
                // convert to closest results type
                BulletSharp.ClosestRayResultCallback closestReults = resultsCallback as BulletSharp.ClosestRayResultCallback;

                // set results data
                results.HasHit = closestReults.HasHit;
                if (results.HasHit)
                {
                    results.Collisions = new RaycastResults.SingleResult[1];
                    results.Collisions[0].HitFraction     = closestReults.ClosestHitFraction;
                    results.Collisions[0].CollisionNormal = ToMonoGame.Vector(closestReults.HitNormalWorld);
                    results.Collisions[0].CollisionPoint  = ToMonoGame.Vector(closestReults.HitPointWorld);
                    results.Collisions[0].CollisionBody   = (closestReults.CollisionObject.UserObject as BasicPhysicalBody).EcsComponent;
                }
            }
            // all results type
            else if (resultsCallback is BulletSharp.AllHitsRayResultCallback)
            {
                // convert to all results type
                BulletSharp.AllHitsRayResultCallback allResults = resultsCallback as BulletSharp.AllHitsRayResultCallback;

                // set results data
                results.HasHit = allResults.HasHit;
                if (results.HasHit)
                {
                    results.Collisions = new RaycastResults.SingleResult[allResults.CollisionObjects.Count];
                    for (int i = 0; i < allResults.CollisionObjects.Count; ++i)
                    {
                        results.Collisions[i].HitFraction     = allResults.HitFractions[i];
                        results.Collisions[i].CollisionNormal = ToMonoGame.Vector(allResults.HitNormalWorld[i]);
                        results.Collisions[i].CollisionPoint  = ToMonoGame.Vector(allResults.HitPointWorld[i]);
                        results.Collisions[i].CollisionBody   = (allResults.CollisionObjects[i].UserObject as BasicPhysicalBody).EcsComponent;
                    }
                }
            }

            // finally, return parsed results
            return(results);
        }
        List <List <int> > GetInstances(BulletSharp.Math.Vector3[] vec)
        {
            List <int> instances = new List <int>();
            int        pcount    = vec.Length;

            for (int x = 0; pcount > x; x++)
            {
                instances.Add(0);
            }

            for (int x = 0; pcount > x; x++)
            {
                BulletSharp.Math.Vector3 pos1 = vec[x];
                for (int i = 0; pcount > i; i++)
                {
                    BulletSharp.Math.Vector3 pos2 = vec[i];
                    if (pos1 == pos2)
                    {
                        instances[x] += 1;
                    }
                }
            }

            List <BulletSharp.Math.Vector3> unique = new List <BulletSharp.Math.Vector3>();

            for (int x = 0; instances.Count > x; x++)
            {
                if (instances[x] > 2)
                {
                    unique.Add(vec[x]);
                }
            }

            List <List <int> > pairs = new List <List <int> >();

            for (int x = 0; unique.Count > x; x++)
            {
                List <int> pindex = new List <int>();
                for (int i = 0; vec.Length > i; i++)
                {
                    if (unique[x] == vec[i])
                    {
                        pindex.Add(i);
                    }
                }
                pairs.Add(pindex);
            }

            return(pairs);
        }
    public void ExecuteBlastJump()
    {
        blastJumpToken   = false;
        handledThisFrame = true;

        if (!timer.CheckAndReset())
        {
            return;
        }

        BulletSharp.Math.Vector3 from = startRaycastFrom.position.ToBullet();
        BulletSharp.Math.Vector3 to   = (startRaycastFrom.position + startRaycastFrom.forward * maxBlastJumpRange).ToBullet();

        ClosestRayResultCallback callback = new ClosestRayResultCallback(ref from, ref to);

        BPhysicsWorld.Get().world.RayTest(from, to, callback);

        if (enableDebugMode)
        {
            Debug.DrawLine(from.ToUnity(), to.ToUnity(), Color.green, 2f);
        }

        if (callback.HasHit)
        {
            float force = 0;

            Vector3 meToGround = callback.HitPointWorld.ToUnity() - transform.position;
            float   dist       = meToGround.magnitude;
            if (dist < maxBlastJumpRange)
            {
                //Falloff curve visual: https://www.desmos.com/calculator/plvrrosegp
                var b = 1f / (Mathf.Pow(maxBlastJumpRange, 2) * smallestBlastForce);
                force = blastJumpForce / (1 * maxBlastJumpForce + (falloffStrength * Mathf.Abs(dist)) + (b * Mathf.Pow(Mathf.Abs(dist), 2)));
            }

            rigidBody.AddImpulse(-meToGround.normalized * force);

            #region Debug
            if (enableDebugMode)
            {
                Debug.Log("Blasting off with a force of: " + force);
                var s = GameObject.CreatePrimitive(PrimitiveType.Sphere);
                s.transform.localScale = Vector3.one * .1f;
                s.transform.position   = callback.HitPointWorld.ToUnity();
                s.GetComponent <MeshRenderer>().material.color = Color.green;
            }
            #endregion
        }
    }
Example #12
0
 public void Update()
 {
     if (Time.frameCount == 10)
     {
         BulletSharp.Math.Vector3 fromP    = transform.position.ToBullet();
         BulletSharp.Math.Vector3 toP      = (transform.position + Vector3.down * 10f).ToBullet();
         ClosestRayResultCallback callback = new ClosestRayResultCallback(ref fromP, ref toP);
         BPhysicsWorld            world    = BPhysicsWorld.Get();
         world.world.RayTest(fromP, toP, callback);
         if (callback.HasHit)
         {
             Debug.LogFormat("Hit p={0} n={1} obj{2}", callback.HitPointWorld, callback.HitNormalWorld, callback.CollisionObject.UserObject);
         }
     }
 }
Example #13
0
        /// <summary>
        /// Teleports the specified target position.
        /// </summary>
        /// <param name="targetPosition">The target position.</param>
        public void Teleport(Vector3 targetPosition)
        {
            if (KinematicCharacter == null)
            {
                throw new InvalidOperationException("Attempted to call a Physics function that is avaliable only when the Entity has been already added to the Scene.");
            }

            //we assume that the user wants to teleport in world/entity space
            var entityPos = Entity.Transform.Position;
            var physPos   = PhysicsWorldTransform.TranslationVector;
            var diff      = physPos - entityPos;

            BulletSharp.Math.Vector3 bV3 = targetPosition + diff;
            KinematicCharacter.Warp(ref bV3);
        }
Example #14
0
 public override CollisionShape GetCollisionShape()
 {
     if (collisionShapePtr == null)
     {
         BulletSharp.Math.Vector3[] positions = new BulletSharp.Math.Vector3[spheres.Length];
         float[] radius = new float[spheres.Length];
         for (int i = 0; i < spheres.Length; i++)
         {
             positions[i] = spheres[i].position.ToBullet();
             radius[i]    = spheres[i].radius;
         }
         collisionShapePtr = new MultiSphereShape(positions, radius);
     }
     return(collisionShapePtr);
 }
Example #15
0
 //------------------------------------------------------
 // Player Property Controls
 //------------------------------------------------------
 public void togglePhysical()
 {
     _physical = !_physical;
     if (_physical)
     {
         _previous_position = _character.spatial.position;
         BulletSharp.Math.Vector3 temp_position = -EngineHelper.otk2bullet(_character.spatial.position);
         _physics_character.character.Warp(ref temp_position);
     }
     else
     {
         _character.spatial.position = -_physics_character.getPosition();
         _camera.resetSmoothMovement();
     }
 }
Example #16
0
    public override float ReturnOutput()
    {
        //Raycasting begins, draw a ray from emitter to the receiver
        Ray ray = new Ray(Emitter.transform.position, Emitter.transform.forward);

        BulletSharp.Math.Vector3 fromUltra  = ray.origin.ToBullet();
        BulletSharp.Math.Vector3 toCollider = ray.GetPoint(10).ToBullet();

        Vector3 toColliderUnity = toCollider.ToUnity();

        //Callback returns all hit point results in order to avoid non colliders interfere with the ray test
        AllHitsRayResultCallback raysCallback = new AllHitsRayResultCallback(fromUltra, toCollider);

        //Retrieves bullet physics world and does a ray test with the given coordinates and updates the callback object
        BPhysicsWorld world = BPhysicsWorld.Get();

        world.world.RayTest(fromUltra, toCollider, raysCallback);
        List <BulletSharp.Math.Vector3> colliderPositions = raysCallback.HitPointWorld;

        BulletSharp.Math.Vector3 colliderPosition = BulletSharp.Math.Vector3.Zero;

        //Set the initial distance as the distance between emitter and receiver
        float distanceToCollider = sensorOffset;

        //Loop through all hitpoints (exclude the origin), if there is at least one hitpoint less than the distance between two sensors,
        //something should block the beam between emitter and receiver
        foreach (BulletSharp.Math.Vector3 pos in colliderPositions)
        {
            if ((pos - fromUltra).Length < distanceToCollider && !pos.Equals(BulletSharp.Math.Vector3.Zero))
            {
                distanceToCollider = (pos - fromUltra).Length;
                colliderPosition   = pos;
            }
        }
        //Again if the line connects to the middle of the field nothing is blocking the beam
        Debug.DrawLine(fromUltra.ToUnity(), colliderPosition.ToUnity(), Color.blue);

        if (distanceToCollider < sensorOffset)
        {
            //Something is there
            return(1);
        }
        else
        {
            //Nothing in between
            return(0);
        }
    }
Example #17
0
        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);
        }
Example #18
0
        ShapeData CreateShape(CollisionShape shape)
        {
            ShapeData shapeData = new ShapeData();

            if (shape.ShapeType == BroadphaseNativeType.SoftBodyShape)
            {
                // Soft body geometry is recreated each frame. Nothing to do here.
                return(shapeData);
            }

            uint[] indices;
            BulletSharp.Math.Vector3[] vertexBuffer = CreateShape(shape, out indices);

            if (vertexBuffer != null)
            {
                shapeData.VertexCount = vertexBuffer.Length / 2;

                Vector3[] vertices = new Vector3[shapeData.VertexCount];
                Vector3[] normals  = new Vector3[shapeData.VertexCount];

                int i;
                for (i = 0; i < shapeData.VertexCount; i++)
                {
                    vertices[i] = vertexBuffer[i * 2];
                    normals[i]  = vertexBuffer[i * 2 + 1];
                }

                shapeData.SetVertexBuffer(vertices);
                shapeData.SetNormalBuffer(normals);
            }

            if (indices != null)
            {
                ushort[] indices_s = CompactIndexBuffer(indices);
                if (indices_s != null)
                {
                    shapeData.SetIndexBuffer(indices_s);
                }
                else
                {
                    shapeData.SetIndexBuffer(indices);
                }
                shapeData.ElementCount = indices.Length;
            }

            return(shapeData);
        }
Example #19
0
        CollisionShape _AddFlipperCylinders(FlipperBehavior flipper)
        {
            float r1 = flipper.data.BaseRadius;
            float r2 = flipper.data.EndRadius;
            float h  = flipper.data.Height;
            float l  = flipper.data.FlipperRadius;

            var hh = h * 0.5f; // half height
            var cs = new BulletSharp.CompoundShape();

            cs.AddChildShape(
                Matrix.Translation(0, 0, hh),
                new CylinderShapeZ(r1, r1, hh));

            cs.AddChildShape(
                Matrix.Translation(0, -l, hh),
                new CylinderShapeZ(r2, r2, hh));

            // we can't add Triangle Mesh Shape to Compound Shape. Add one or two boxes
            float   hbl   = new Vector2(l, r1 - r2).magnitude * 0.5f;
            Vector3 n     = new Vector3(l, r1 - r2, 0); n.Normalize();
            Vector3 beg   = new Vector3(0, 0, hh) + n * (r1 - r2);
            Vector3 beg2  = new Vector3(-beg.X, beg.Y, beg.Z);
            Vector3 end   = new Vector3(0, -l, hh);
            float   angle = math.atan2(n.Y, n.X);

            bool onlyFront = true;
            bool rev       = (flipper.data.StartAngle < 0 | flipper.data.StartAngle > 180);

            if (!onlyFront || rev)
            {
                cs.AddChildShape(
                    Matrix.RotationZ(-angle) *
                    Matrix.Translation((beg + end) * 0.5f),
                    new BoxShape(Mathf.Min(r1, r2), hbl, hh));
            }

            if (!onlyFront || !rev)
            {
                cs.AddChildShape(
                    Matrix.RotationZ(angle) *
                    Matrix.Translation((beg2 + end) * 0.5f),
                    new BoxShape(Mathf.Min(r1, r2), hbl, hh));
            }

            return(cs);
        }
Example #20
0
        internal void Initialize()
        {
            // Build the broadphase
            broadphase = new DbvtBroadphase();

            // Set up the collision configuration and dispatcher
            collisionConfiguration = new DefaultCollisionConfiguration();
            dispatcher             = new CollisionDispatcher(collisionConfiguration);

            // The actual physics solver
            solver = new SequentialImpulseConstraintSolver();

            // The world
            dynamicsWorld = new DiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration);
            BulletSharp.Math.Vector3 grav = Gravity;
            dynamicsWorld.SetGravity(ref grav);
            collisionWorld = new CollisionWorld(dispatcher, broadphase, collisionConfiguration);
        }
Example #21
0
        public void updatePhysicalPosition()
        {
            if (_physical)
            {
                BulletSharp.Math.Vector3 walk_direction = -EngineHelper.otk2bullet((character.spatial.position - _previous_position));

                _physics_character.character.SetWalkDirection(ref walk_direction);


                _character.spatial.position = -_physics_character.getPosition();
                _previous_position          = character.spatial.position;
            }
            else
            {
                BulletSharp.Math.Vector3 temp_position = -EngineHelper.otk2bullet(_character.spatial.position);
                _physics_character.character.Warp(ref temp_position);
            }
        }
        public void SetVertexBuffer(Device device, Vector3[] vectors)
        {
            BufferDescription vertexBufferDesc = new BufferDescription()
            {
                SizeInBytes = Vector3.SizeInBytes * vectors.Length,
                Usage = ResourceUsage.Default,
                BindFlags = BindFlags.VertexBuffer
            };

            using (var data = new DataStream(vertexBufferDesc.SizeInBytes, false, true))
            {
                data.WriteRange(vectors);
                data.Position = 0;
                VertexBuffer = new Buffer(device, data, vertexBufferDesc);
            }

            BufferBindings[0] = new VertexBufferBinding(VertexBuffer, 24, 0);
        }
Example #23
0
        public override float AddSingleResult(LocalRayResult rayResult, bool normalInWorldSpace)
        {
            Debug.Assert(rayResult.HitFraction <= this.ClosestHitFraction, "invalid ray hit fraction");
            this.ClosestHitFraction = rayResult.HitFraction;
            this.CollisionObject    = rayResult.CollisionObject;
            if (normalInWorldSpace)
            {
                HitNormalWorld = rayResult.HitNormalLocal;
            }
            else
            {
                BulletSharp.Math.Matrix om;
                this.CollisionObject.GetWorldTransform(out om);
                //this.HitNormalWorld = om.Basis * rayResult.HitNormalLocal;
            }

            return(0f);
        }
Example #24
0
    /// <summary>
    /// Updates constraint information for the active object, if applicable.
    /// </summary>
    private void Update()
    {
        if (Input.GetMouseButtonDown(0) && (Input.GetKey(KeyCode.LeftAlt) || Input.GetKey(KeyCode.RightAlt)) && constraint == null)
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            BulletSharp.Math.Vector3 start = ray.origin.ToBullet();
            BulletSharp.Math.Vector3 end   = ray.GetPoint(100).ToBullet();

            ClosestRayResultCallback callback = new ClosestRayResultCallback(ref start, ref end);
            BPhysicsWorld.Get().world.RayTest(start, end, callback);

            rayDistance = (start - callback.HitPointWorld).Length;

            if (callback.CollisionObject != null)
            {
                BRigidBody rigidBody = callback.CollisionObject.UserObject as BRigidBody;

                if (rigidBody != null && rigidBody.mass > 0f)
                {
                    initialState = rigidBody.GetCollisionObject().ActivationState;
                    rigidBody.GetCollisionObject().ActivationState = ActivationState.DisableDeactivation;
                    initialDamping           = rigidBody.angularDamping;
                    rigidBody.angularDamping = 0.9f;

                    constraint                = rigidBody.gameObject.AddComponent <BBallSocketConstraintEx>();
                    constraint.PivotInA       = rigidBody.transform.InverseTransformPoint(callback.HitPointWorld.ToUnity()).ToBullet();
                    constraint.constraintType = BTypedConstraint.ConstraintType.constrainToPointInSpace;
                }
            }
        }
        else if (Input.GetMouseButtonUp(0) && constraint != null)
        {
            constraint.thisRigidBody.GetCollisionObject().ActivationState = initialState;
            constraint.GetComponent <BRigidBody>().angularDamping = initialDamping;

            Destroy(constraint);
            constraint = null;
        }
        else if (constraint != null)
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            constraint.PivotInB = ray.GetPoint(rayDistance).ToBullet();
        }
    }
        /// <summary>
        /// Performs an un-filtered raycast.
        /// </summary>
        /// <param name="ray">The ray to perform the cast on.</param>
        /// <param name="maxLength">The maximum length of the ray.</param>
        /// <returns></returns>
        internal RayCastResult FindPartOnRay(Ray ray, float maxLength = 3000)
        {
            lock (Locker)
            {
                var     from = ray.Origin;
                Vector3 to;

                Vector3.Multiply(ref ray.Direction, maxLength, out to);
                Vector3.Add(ref to, ref from, out to);

                var bulletFrom = new BulletSharp.Math.Vector3(from.x, from.y, from.z);
                var bulletTo   = new BulletSharp.Math.Vector3(to.x, to.y, to.z);

                var resultCallback = new ClosestRayResultCallback(ref bulletFrom, ref bulletTo);
                World.RayTest(bulletFrom, bulletTo, resultCallback);

                return(new RayCastResult(ref resultCallback));
            }
        }
        internal override bool _BuildCollisionObject()
        {
            Mesh mesh = meshSettings.Build();

            if (mesh == null)
            {
                Debug.LogError("Could not build mesh from meshSettings for " + this, transform);
                return(false);
            }

            GetComponent <MeshFilter>().sharedMesh = mesh;

                        #if UNITY_EDITOR
            if (!UnityEditor.EditorApplication.isPlaying)
            {
                return(false);
            }
                        #endif

            if (World == null)
            {
                return(false);
            }

            //convert the mesh data to Bullet data and create SoftBody
            BulletSharp.Math.Vector3[] bVerts = new BulletSharp.Math.Vector3[mesh.vertexCount];
            Vector3[] verts = mesh.vertices;
            for (int i = 0; i < mesh.vertexCount; i++)
            {
                bVerts[i] = verts[i].ToBullet();
            }

            softBody        = SoftBodyHelpers.CreateFromTriMesh(World.WorldInfo, bVerts, mesh.triangles);
            collisionObject = softBody;
            SoftBodySettings.ConfigureSoftBody(softBody);//Set SB settings

            //Set SB position to GO position
            softBody.Rotate(transform.rotation.ToBullet());
            softBody.Translate(transform.position.ToBullet());
            softBody.Scale(transform.localScale.ToBullet());

            return(true);
        }
        public RigidBody LocalCreateRigidBody(float mass, BulletSharp.Math.Matrix startTransform, CollisionShape shape)
        {
            bool isDynamic = (mass != 0.0f);

            Vector3 localInertia = Vector3.Zero;

            if (isDynamic)
            {
                shape.CalculateLocalInertia(mass, out localInertia);
            }

            DefaultMotionState myMotionState = new DefaultMotionState(startTransform);

            RigidBodyConstructionInfo rbInfo = new RigidBodyConstructionInfo(mass, myMotionState, shape, localInertia);
            RigidBody body = new RigidBody(rbInfo);

            World.AddRigidBody(body);

            return(body);
        }
Example #28
0
        public bool RayPick(OpenTK.Vector3 from, OpenTK.Vector3 to, out OpenTK.Vector3 col)
        {
            var bfrom = ToBulletVector3(from);
            var bto   = ToBulletVector3(to);

            var cfrom = new BulletSharp.Math.Vector3();
            var cto   = new BulletSharp.Math.Vector3();

            ClosestRayResultCallback rayCb = new ClosestRayResultCallback(ref cfrom, ref cto);

            world.RayTest(bfrom, bto, rayCb);

            // Lerp로 보간해야 결과가 나온다.

            var p = BulletSharp.Math.Vector3.Lerp(bfrom, bto, rayCb.ClosestHitFraction);

            col = ToOpenVector3(p);

            return(rayCb.HasHit);
        }
Example #29
0
        public BulletTest()
        {
            InitializeWorld();
            RigidBody fallRigidBody = AddFallingRigidBody();

            AddGroundRigidBody();

            for (int i = 0; i < 300; i++)
            {
                dynamicsWorld.StepSimulation(1 / 60f, 10);
                BulletSharp.Math.Vector3 myValue = new BulletSharp.Math.Vector3();
                fallRigidBody.GetVelocityInLocalPoint(myValue);
                float a = fallRigidBody.WorldTransform.Origin.Y;
                //dynamicsWorld.GetGravity()
                //Console.Write(myValue);
                //Console.WriteLine(a);

                //fallRigidBody.WorldTransform.set
            }
        }
Example #30
0
        ShapeData CreateShape(CollisionShape shape)
        {
            ShapeData shapeData = new ShapeData();

            uint[] indices;
            BulletSharp.Math.Vector3[] vertexBuffer = CreateShape(shape, out indices);

            if (vertexBuffer != null)
            {
                shapeData.VertexCount = vertexBuffer.Length / 2;

                Vector3[] vertices = new Vector3[shapeData.VertexCount];
                Vector3[] normals  = new Vector3[shapeData.VertexCount];

                int i;
                for (i = 0; i < shapeData.VertexCount; i++)
                {
                    vertices[i] = vertexBuffer[i * 2];
                    normals[i]  = vertexBuffer[i * 2 + 1];
                }

                shapeData.SetVertexBuffer(vertices);
                shapeData.SetNormalBuffer(normals);
            }

            if (indices != null)
            {
                ushort[] indices_s = CompactIndexBuffer(indices);
                if (indices_s != null)
                {
                    shapeData.SetIndexBuffer(indices_s);
                }
                else
                {
                    shapeData.SetIndexBuffer(indices);
                }
                shapeData.ElementCount = indices.Length;
            }

            return(shapeData);
        }
Example #31
0
        public RayResult FindEntityOnRay(Ray ray, PhysicsEntity ignore = null)
        {
            RayResult result = new RayResult();

            if (collisionWorld != null)
            {
                BulletSharp.Math.Vector3 start = ray.Origin;
                BulletSharp.Math.Vector3 end   = ray.Origin + ray.Direction;

                ClosestRayResultCallback callback = new ClosestRayResultCallback(ref start, ref end);
                collisionWorld.RayTest(start, end, callback);

                if (callback.HasHit && callback.CollisionObject != ignore.Rigidbody)
                {
                    result.Position = callback.HitPointWorld;
                    result.Normal   = callback.HitNormalWorld;
                    //result.Hit = callback.CollisionObject;
                }
            }
            return(result);
        }
        public override bool Raycast(GameSystem.GameCore.SerializableMath.Vector3 startPoint, GameSystem.GameCore.SerializableMath.Vector3 endPoint, out GameSystem.GameCore.SerializableMath.Vector3[] hitPoint, out CollisionProxy[] hitObject, int mask = -1)
        {
            // transfer serializable math position to bullet math position
            BulletSharp.Math.Vector3 start = startPoint.ToBullet(), end = endPoint.ToBullet();
            var callback = new AllHitsRayResultCallback(start, end);

            // set group mask filter
            callback.CollisionFilterMask = (short)mask;
            world.RayTest(start, end, callback);
            if (callback.HasHit)
            {
                hitPoint  = callback.HitPointWorld.ToSerializableArray();
                hitObject = callback.CollisionObjects.SelectToArray(colObj => (CollisionProxy)colObj.UserObject);
            }
            else
            {
                hitPoint  = new GameSystem.GameCore.SerializableMath.Vector3[0];
                hitObject = new CollisionProxy[0];
            }
            return(callback.HasHit);
        }
Example #33
0
 void PlaneSpace1(BulletSharp.Math.Vector3 n, out BulletSharp.Math.Vector3 p, out BulletSharp.Math.Vector3 q)
 {
     if (Math.Abs(n[2]) > (Math.Sqrt(2) / 2))
     {
         // choose p in y-z plane
         float a = n[1] * n[1] + n[2] * n[2];
         float k = 1.0f / (float)Math.Sqrt(a);
         p = new BulletSharp.Math.Vector3(0, -n[2] * k, n[1] * k);
         // set q = n x p
         q = BulletSharp.Math.Vector3.Cross(n, p);
     }
     else
     {
         // choose p in x-y plane
         float a = n[0] * n[0] + n[1] * n[1];
         float k = 1.0f / (float)Math.Sqrt(a);
         p = new BulletSharp.Math.Vector3(-n[1] * k, n[0] * k, 0);
         // set q = n x p
         q = BulletSharp.Math.Vector3.Cross(n, p);
     }
 }
Example #34
0
    public static BulletSharp.Math.Vector3 ToEuler(this BulletSharp.Math.Quaternion quat)
    {
        var eulers = new BulletSharp.Math.Vector3
        {
            X = (float)Math.Atan2(2 * (quat.W * quat.X + quat.Y * quat.Z), 1 - 2 * (quat.X * quat.X + quat.Y * quat.Y)),
            Z = (float)Math.Atan2(2 * (quat.W * quat.Z + quat.X * quat.Y), 1 - 2 * (quat.Y * quat.Y + quat.Z * quat.Z))
        };

        var expr = 2 * (quat.W * quat.Y - quat.Z * quat.X);

        if (Math.Abs(expr) >= 1)
        {
            eulers.Y = (float)(Math.Sign(expr) * Math.PI / 2);
        }
        else
        {
            eulers.Y = (float)Math.Asin(expr);
        }

        return(eulers);
    }
        public override bool Raycast(GameSystem.GameCore.SerializableMath.Vector3 startPoint, GameSystem.GameCore.SerializableMath.Vector3 endPoint, out GameSystem.GameCore.SerializableMath.Vector3 hitPoint, out CollisionProxy hitObject, int mask = -1)
        {
            // transfer serializable math position to bullet math position
            BulletSharp.Math.Vector3 start = startPoint.ToBullet(), end = endPoint.ToBullet();
            var callback = new ClosestRayResultCallback(ref start, ref end);

            // set group mask filter
            callback.CollisionFilterMask = (short)mask;
            world.RayTest(start, end, callback);
            if (callback.HasHit)
            {
                hitPoint  = callback.HitPointWorld.ToSerializable();
                hitObject = (CollisionProxy)callback.CollisionObject.UserObject;
            }
            else
            {
                hitPoint  = GameSystem.GameCore.SerializableMath.Vector3.Zero;
                hitObject = null;
            }
            return(callback.HasHit);
        }
        // Used with soft bodies
        public void SetDynamicVertexBuffer(Device device, Vector3[] vectors)
        {
            if (VertexBuffer != null && VertexCount * 2 == vectors.Length)
            {
                // Update existing buffer
                using (var data = VertexBuffer.Map(MapMode.WriteDiscard))
                {
                    data.WriteRange(vectors, 0, vectors.Length);
                    VertexBuffer.Unmap();
                }
            }
            else
            {
                // Create new buffer
                if (VertexBuffer != null)
                    VertexBuffer.Dispose();

                BufferDescription vertexBufferDesc = new BufferDescription()
                {
                    SizeInBytes = Vector3.SizeInBytes * vectors.Length,
                    Usage = ResourceUsage.Dynamic,
                    BindFlags = BindFlags.VertexBuffer,
                    CpuAccessFlags = CpuAccessFlags.Write
                };

                using (var data = new DataStream(vertexBufferDesc.SizeInBytes, false, true))
                {
                    data.WriteRange(vectors);
                    data.Position = 0;
                    VertexBuffer = new Buffer(device, data, vertexBufferDesc);
                }

                VertexCount = vectors.Length / 2;
                BufferBindings[0] = new VertexBufferBinding(VertexBuffer, 24, 0);
            }
        }
 void PlaneSpace1(BulletSharp.Math.Vector3 n, out BulletSharp.Math.Vector3 p, out BulletSharp.Math.Vector3 q)
 {
     if (Math.Abs(n[2]) > (Math.Sqrt(2) / 2))
     {
         // choose p in y-z plane
         float a = n[1] * n[1] + n[2] * n[2];
         float k = 1.0f / (float)Math.Sqrt(a);
         p = new BulletSharp.Math.Vector3(0, -n[2] * k, n[1] * k);
         // set q = n x p
         q = BulletSharp.Math.Vector3.Cross(n, p);
     }
     else
     {
         // choose p in x-y plane
         float a = n[0] * n[0] + n[1] * n[1];
         float k = 1.0f / (float)Math.Sqrt(a);
         p = new BulletSharp.Math.Vector3(-n[1] * k, n[0] * k, 0);
         // set q = n x p
         q = BulletSharp.Math.Vector3.Cross(n, p);
     }
 }