Example #1
0
        /// <summary>
        /// Calculate and return a predicted LL from the specified A and B values.
        /// </summary>
        /// <param name="physical">The soil physical properties.</param>
        /// <param name="A">a.</param>
        /// <param name="B">The b.</param>
        /// <returns></returns>
        private static double[] PredictedLL(IPhysical physical, double[] A, double B)
        {
            double[] LL15 = Layers.LL15Mapped(physical, PredictedThickness);
            double[] DUL  = Layers.DULMapped(physical, PredictedThickness);
            double[] LL   = new double[PredictedThickness.Length];
            for (int i = 0; i != PredictedThickness.Length; i++)
            {
                double DULPercent = DUL[i] * 100.0;
                LL[i]  = DULPercent * (A[i] + B * DULPercent);
                LL[i] /= 100.0;

                // Bound the predicted LL values.
                LL[i] = Math.Max(LL[i], LL15[i]);
                LL[i] = Math.Min(LL[i], DUL[i]);
            }

            //  make the top 3 layers the same as the top 3 layers of LL15
            if (LL.Length >= 3)
            {
                LL[0] = LL15[0];
                LL[1] = LL15[1];
                LL[2] = LL15[2];
            }
            return(LL);
        }
Example #2
0
        public static void PhysicalDetails(Media physType)
        {
            IPhysical phys = (IPhysical)physType;

            if (physType.Type == "Video")
            {
                Console.WriteLine("7) Case: {0}", phys.Case);
                Console.WriteLine("8) Booklet: {0}", phys.Manual);
                Console.WriteLine("9) Condition: {0}", phys.Condition);
            }

            else if (physType.Type == "Music")
            {
                Console.WriteLine("6) Case: {0}", phys.Case);
                Console.WriteLine("7) Booklet: {0}", phys.Manual);
                Console.WriteLine("8) Condition: {0}", phys.Condition);
            }

            else if (physType.Type == "Video Game")
            {
                Console.WriteLine("8) Case: {0}", phys.Case);
                Console.WriteLine("8) Booklet: {0}", phys.Manual);
                Console.WriteLine("0) Condition: {0}", phys.Condition);
            }
        }
Example #3
0
 public Static(IPhysical p)
 {
     Material    = p.Material;
     MassData    = p.MassData;
     BoundingBox = p.BoundingBox;
     Position    = p.Position;
 }
Example #4
0
 public Link(IDecrypt decrypt, IEncrypt encrypt, IPhysical physical, int maxFrameSize)
 {
     _decrypt = decrypt;
     _encrypt = encrypt;
     _physical = physical;
     _maxFrameSize = maxFrameSize;
 }
Example #5
0
        public static void CheckCollision(ref IPhysical a, ref IPhysical b)
        {
            Manifold m = new Manifold();

            if (a is IDynamic)
            {
                m.A = (a as IDynamic);
            }
            else
            {
                m.A = new Static(a);
            }
            if (b is IDynamic)
            {
                m.B = (b as IDynamic);
            }
            else
            {
                m.B = new Static(b);
            }

            if (isCollision(ref m))
            {
                ResolveCollision(ref m);
            }
        }
Example #6
0
        private static void BodyPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            Body body = (Body)sender;

            if (!BodiesToPhysical.ContainsKey(body))
            {
                return;
            }

            IPhysical physical = BodiesToPhysical[body];

            if (physical.SuprressPropertyChangedEvents)
            {
                return;
            }

            switch (e.PropertyName)
            {
            case Body.MaterialPropertyName:
                physical.IsMaterial = body.IsMaterial;
                break;

            case Body.FrictionPropertyName:
                physical.FrictionCoefficient = body.FrictionCoefficient;
                break;

            case Body.VelocityPropertyName:
                physical.Velocity = body.Velocity;
                break;
            }
        }
Example #7
0
        public void ProcessEntityPhysics(IPhysical entity, float step)
        {
            entity.IsFalling = true;

            if (entity is ICollidable collidableEntity)
            {
                for (int index = 0; index < levelGeometries.Count; index++)
                {
                    LevelGeometry geom = levelGeometries[index];
                    CollisionSolver.SolveEntityAgainstGeometry(collidableEntity, geom);
                }
            }

            entity.Physics(step);

            if (entity is IEntityCollidable ec)
            {
                for (int index = 0; index < entities.Count; index++)
                {
                    ICollidable otherEntity = entities[index] as ICollidable;
                    if (!ec.Equals(otherEntity) && ec.GetType() != otherEntity.GetType())
                    {
                        CollisionSolver.SolveEntityAgainstEntity(ec, otherEntity);
                    }
                }
            }
        }
Example #8
0
        //----------------------- Public methods -----------------------

        /// <summary>Initialise this root instance (and tissues).</summary>
        /// <param name="zone">The zone the roots belong to.</param>
        /// <param name="minimumLiveWt">Minimum live DM biomass for this organ (kg/ha).</param>
        public void Initialise(Zone zone, double minimumLiveWt)
        {
            // link to soil models parameters
            soil = zone.FindInScope <Soil>();
            if (soil == null)
            {
                throw new Exception($"Cannot find soil in zone {zone.Name}");
            }

            soilPhysical = soil.FindInScope <IPhysical>();
            if (soilPhysical == null)
            {
                throw new Exception($"Cannot find soil physical in soil {soil.Name}");
            }

            waterBalance = soil.FindInScope <ISoilWater>();
            if (waterBalance == null)
            {
                throw new Exception($"Cannot find a water balance model in soil {soil.Name}");
            }

            soilCropData = soil.FindDescendant <SoilCrop>(species.Name + "Soil");
            if (soilCropData == null)
            {
                throw new Exception($"Cannot find a soil crop parameterisation called {species.Name + "Soil"}");
            }

            nutrient = zone.FindInScope <INutrient>();
            if (nutrient == null)
            {
                throw new Exception($"Cannot find SoilNitrogen in zone {zone.Name}");
            }

            no3 = zone.FindInScope("NO3") as ISolute;
            if (no3 == null)
            {
                throw new Exception($"Cannot find NO3 solute in zone {zone.Name}");
            }

            nh4 = zone.FindInScope("NH4") as ISolute;
            if (nh4 == null)
            {
                throw new Exception($"Cannot find NH4 solute in zone {zone.Name}");
            }

            // initialise soil related variables
            zoneName             = soil.Parent.Name;
            nLayers              = soilPhysical.Thickness.Length;
            mySoilNH4Available   = new double[nLayers];
            mySoilNO3Available   = new double[nLayers];
            mySoilWaterAvailable = new double[nLayers];

            // save minimum DM and get target root distribution
            MinimumLiveDM      = minimumLiveWt;
            TargetDistribution = RootDistributionTarget();

            // initialise tissues
            Live.Initialise();
            Dead.Initialise();
        }
Example #9
0
        public void Visit(Box visitable)
        {
            IPhysical physical = PhysicalManager.MakeBox(visitable.XSize, visitable.YSize, visitable.ZSize);

            physical.Body = visitable;
            AfterCreating(visitable, physical);
        }
Example #10
0
        public void Visit(Ball visitable)
        {
            IPhysical physical = PhysicalManager.MakeCyllinder(visitable.Radius, visitable.Radius, visitable.Radius * 2);

            physical.Body = visitable;
            AfterCreating(visitable, physical);
        }
Example #11
0
        public void Visit(Cylinder visitable)
        {
            IPhysical physical = PhysicalManager.MakeCyllinder(visitable.RBottom, visitable.RTop, visitable.Height);

            physical.Body = visitable;
            AfterCreating(visitable, physical);
        }
Example #12
0
        /// <summary>
        /// Присоединит переданный объект, используя переданный Location.
        /// </summary>
        public void Attach(IPhysical body, Frame3D realLocation, bool joinWithFriction = true)
        {
            var bb = (BepuBody)body;
            var rb = bb.RealBody;

            BepuConverter.PutInFrame(rb, realLocation, bb.InitialOrientation);
            //bb.RealBody.Position = new Vector3(-bb.RealBody.Position.X, bb.RealBody.Position.Y, bb.RealBody.Position.Z);
            rb.Position    += RealBody.Position;
            rb.Orientation *= RealBody.Orientation;
            SolverGroup wj = BepuWorld.MakeWeldJoint(RealBody, rb);
            Connection  c;

            try            //есть connection
            {
                c = _connections.First(x => x.OtherBody == rb);
                c.Add(wj);
            }
            catch (Exception)            //нет connection
            {
                c = new Connection(rb);
                c.Add(wj);
                _connections.Add(c);                //connection добавляем для обоих тел! М.К.
                bb._connections.Add(c);
            }
        }
Example #13
0
 public void LinkFrontendSetup()
 {
     var decrypter = new DecryptStm();
     var encrypter = new EncryptStm();
     _fakePhysical = Substitute.For<IPhysical>();
     _uut = new Link(decrypter, encrypter, _fakePhysical, 1000);
 }
Example #14
0
 public void OnIntersect(IPhysical other)
 {
     if (other is Tile)
     {
         return;
     }
     Console.WriteLine(this.ToString() + "Collided with:" + other.ToString());
 }
Example #15
0
 private void OnSimulationCommencing(object sender, EventArgs e)
 {
     initial      = soil.FindChild <Sample>();
     soilPhysical = soil.FindChild <IPhysical>();
     if (!Name.Contains("PlantAvailable"))
     {
         Reset();
     }
 }
Example #16
0
 /// <summary>
 /// Настроит тело PhysicalModel в соответствии с телом PhysicalPrimitiveBody
 /// </summary>
 public static void SetSettings(Body body, IPhysical physical)
 {
     physical.IsStatic            = body.IsStatic;
     physical.Location            = body.Location;
     physical.Mass                = body.Volume / 1000 * ((body.Density == null) ? 1 : body.Density.Value);
     physical.FrictionCoefficient = body.FrictionCoefficient;
     physical.Id       = body.Id;
     physical.Velocity = body.Velocity;
 }
Example #17
0
        /// <summary>Convert the crop to the specified thickness. Ensures LL is between AirDry and DUL.</summary>
        /// <param name="crop">The crop to convert</param>
        /// <param name="thickness">The thicknesses to convert the crop to.</param>
        /// <param name="physical">The soil the crop belongs to.</param>
        private static void SetCropThickness(SoilCrop crop, double[] thickness, IPhysical physical)
        {
            if (!MathUtilities.AreEqual(thickness, physical.Thickness))
            {
                crop.LL = MapConcentration(crop.LL, physical.Thickness, thickness, MathUtilities.LastValue(crop.LL));
                crop.KL = MapConcentration(crop.KL, physical.Thickness, thickness, MathUtilities.LastValue(crop.KL));
                crop.XF = MapConcentration(crop.XF, physical.Thickness, thickness, MathUtilities.LastValue(crop.XF));

                crop.LL = MathUtilities.Constrain(crop.LL, AirDryMapped(physical, thickness), DULMapped(physical, thickness));
            }
        }
Example #18
0
 /// <summary>
 /// Свяжем тело и физическое тело
 /// </summary>
 internal static void SaveBody(Body body, IPhysical physical)
 {
     if (BodiesToPhysical.ContainsKey(body))
     {
         BodiesToPhysical[body] = physical;
     }
     else
     {
         BodiesToPhysical.Add(body, physical);
     }
 }
Example #19
0
        /// <summary>
        /// Change the axis of rotation for an entity
        /// </summary>
        /// <param name="sender">Calling object</param>
        /// <param name="entity">Entity to change the axis of rotation for</param>
        /// <param name="rotationAxis">New axis of rotation</param>
        public void EntitySetRotationAxis(object sender, IPhysical entity, Vector3 rotationAxis)
        {
            EventHandler <EntityRotationAxisArgs> callback = OnEntitySetRotationAxis;

            if (callback != null)
            {
                callback(sender, new EntityRotationAxisArgs {
                    Entity = entity, RotationAxis = rotationAxis
                });
            }

            // TODO: Implement this
        }
Example #20
0
        private void EntityRemoveHandler(object sender, EntityArgs e)
        {
            // Remove all entities with dynamics enabled from our dictionary
            if (e.Entity is IPhysical)
            {
                IPhysical physical = (IPhysical)e.Entity;

                if (!physical.DynamicsEnabled)
                {
                    m_activePhysicsEntities.Remove(physical.LocalID);
                }
            }
        }
Example #21
0
        /// <summary>
        /// Apply a physical angular force to an entity
        /// </summary>
        /// <param name="sender">Calling object</param>
        /// <param name="entity">Entity to apply the angular force to</param>
        /// <param name="impulse">Angular force to apply to the entity</param>
        public void EntityApplyRotationalImpulse(object sender, IPhysical entity, Vector3 impulse)
        {
            EventHandler <EntityImpulseArgs> callback = OnEntityApplyRotationalImpulse;

            if (callback != null)
            {
                callback(sender, new EntityImpulseArgs {
                    Entity = entity, Impulse = impulse
                });
            }

            // TODO: Implement this
        }
Example #22
0
        /// <summary>
        /// Set a constant angular velocity on an entity
        /// </summary>
        /// <param name="sender">Calling object</param>
        /// <param name="entity">Entity to set the angular velocity for</param>
        /// <param name="torque">Angular velocity to set on the entity</param>
        public void EntitySetTorque(object sender, IPhysical entity, Vector3 torque)
        {
            EventHandler <EntityTorqueArgs> callback = OnEntitySetTorque;

            if (callback != null)
            {
                callback(sender, new EntityTorqueArgs {
                    Entity = entity, Torque = torque
                });
            }

            // TODO: Implement this
        }
Example #23
0
        /// <summary>Sets the water thickness.</summary>
        /// <param name="physical">The water.</param>
        /// <param name="toThickness">To thickness.</param>
        /// <param name="soil">Soil</param>
        private static void SetPhysicalPropertiesThickness(IPhysical physical, double[] toThickness, Soil soil)
        {
            if (!MathUtilities.AreEqual(toThickness, physical.Thickness))
            {
                var crops = (physical as IModel).FindAllChildren <SoilCrop>();
                foreach (var crop in crops)
                {
                    crop.KL = MapConcentration(crop.KL, physical.Thickness, toThickness, MathUtilities.LastValue(crop.KL));
                    crop.XF = MapConcentration(crop.XF, physical.Thickness, toThickness, MathUtilities.LastValue(crop.XF));
                    crop.LL = MapConcentration(crop.LL, physical.Thickness, toThickness, MathUtilities.LastValue(crop.LL));
                }

                physical.BD     = MapConcentration(physical.BD, physical.Thickness, toThickness, MathUtilities.LastValue(physical.BD));
                physical.AirDry = MapConcentration(physical.AirDry, physical.Thickness, toThickness, MathUtilities.LastValue(physical.AirDry));
                physical.LL15   = MapConcentration(physical.LL15, physical.Thickness, toThickness, MathUtilities.LastValue(physical.LL15));
                physical.DUL    = MapConcentration(physical.DUL, physical.Thickness, toThickness, MathUtilities.LastValue(physical.DUL));
                physical.SAT    = MapConcentration(physical.SAT, physical.Thickness, toThickness, MathUtilities.LastValue(physical.SAT));
                physical.KS     = MapConcentration(physical.KS, physical.Thickness, toThickness, MathUtilities.LastValue(physical.KS));
                if (physical != null)
                {
                    if (physical.ParticleSizeClay != null && physical.ParticleSizeClay.Length > 0 && physical.ParticleSizeClay.Length != toThickness.Length)
                    {
                        physical.ParticleSizeClay = MapConcentration(physical.ParticleSizeClay, physical.Thickness, toThickness, MathUtilities.LastValue(physical.ParticleSizeClay));
                    }
                    if (physical.ParticleSizeSand != null && physical.ParticleSizeSand.Length > 0 && physical.ParticleSizeSand.Length != toThickness.Length)
                    {
                        physical.ParticleSizeSand = MapConcentration(physical.ParticleSizeSand, physical.Thickness, toThickness, MathUtilities.LastValue(physical.ParticleSizeSand));
                    }
                    if (physical.ParticleSizeSilt != null && physical.ParticleSizeSilt.Length > 0 && physical.ParticleSizeSilt.Length != toThickness.Length)
                    {
                        physical.ParticleSizeSilt = MapConcentration(physical.ParticleSizeSilt, physical.Thickness, toThickness, MathUtilities.LastValue(physical.ParticleSizeSilt));
                    }
                    if (physical.Rocks != null && physical.Rocks.Length > 0 && physical.Rocks.Length != toThickness.Length)
                    {
                        physical.Rocks = MapConcentration(physical.Rocks, physical.Thickness, toThickness, MathUtilities.LastValue(physical.Rocks));
                    }
                }
                physical.Thickness = toThickness;

                foreach (var crop in crops)
                {
                    var soilCrop = crop as SoilCrop;
                    // Ensure crop LL are between Airdry and DUL.
                    for (int i = 0; i < soilCrop.LL.Length; i++)
                    {
                        soilCrop.LL = MathUtilities.Constrain(soilCrop.LL, physical.AirDry, physical.DUL);
                    }
                }
            }
        }
Example #24
0
        public void GetPurchasables()
        {
            Messages.Add("Available to Buy");
            for (int i = 0; i < ForSale.Count; i++)
            {
                IPurchasable forSale = ForSale[i];
                Messages.Add($"{i + 1}");

                IPhysical carSale = forSale as IPhysical;
                if (carSale != null)
                {
                    carSale.Make;
                }
            }
            Messages.Add("Type a number to see details or Q to quit");
        }
Example #25
0
        private void EntityAddOrUpdateHandler(object sender, EntityAddOrUpdateArgs e)
        {
            // Add all entities with dynamics enabled to our dictionary
            if (e.UpdateFlags.HasFlag(UpdateFlags.PhysicalStatus) && !(e.Entity is IScenePresence) && e.Entity is IPhysical)
            {
                IPhysical physical = (IPhysical)e.Entity;

                if (physical.DynamicsEnabled)
                {
                    m_activePhysicsEntities.Add(physical.LocalID, physical);
                }
                else
                {
                    m_activePhysicsEntities.Remove(physical.LocalID);
                }
            }
        }
        /// <summary>
        /// Applies the physics vectors to a DrawableGameObject's velocity vector.
        /// </summary>
        /// <param name="velocity">The velocity vector to manipulate.</param>
        /// <returns>The updated velocity vector.</returns>
        public void ApplyPhysics(IPhysical physicalObject)
        {
            physicalObject.Velocity += (physicalObject.NetForce / physicalObject.Mass);

            // Prevent the physicalObject's speed from being greater than
            // the maxSpeed.
            if (physicalObject.Velocity.Length() > MaxSpeed)
            {
                physicalObject.Velocity /= physicalObject.Velocity.Length();
                physicalObject.Velocity *= MaxSpeed;
            }

            physicalObject.NetForce = Vector2.Zero;

            physicalObject.Position += physicalObject.Velocity;
               // Console.WriteLine("Handler Added VEL: " + physicalObject.Velocity);
        }
Example #27
0
        /// <summary>
        /// Отсоединит переданный объект, пересчитает его Location так, чтобы он был абсолютным.
        /// </summary>
        public void Detach(IPhysical body)
        {
            var bb = (BepuBody)body;
            var rb = bb.RealBody;

            foreach (var c in _connections.ToList().Where(c => c.OtherBody == rb))
            {
                try
                {
                    c.Disconnect();
                    _connections.Remove(c);
                    bb._connections.Remove(c);
                }
                catch
                {
                }
                break;
            }
        }
Example #28
0
        public static bool CollisionTest(Ray ray, IPhysical obj, BasicMesh mesh, out float dist)
        {
            Vector3 start     = new Vector3(ray.X, ray.Y, ray.Z);
            Vector3 direction = new Vector3(ray.I, ray.J, ray.K);

            dist = Single.MaxValue;

            // Construct a matrix to transform to scene space
            Matrix4 transform = Matrix4.Identity;

            transform *= Matrix4.CreateScale(obj.Scale);
            transform *= Matrix4.CreateFromQuaternion(obj.RelativeRotation);
            transform *= Matrix4.CreateTranslation(obj.RelativePosition);

            ILinkable parent = obj.Parent;

            if (parent != null)
            {
                // Apply parent rotation and translation
                transform *= Matrix4.CreateFromQuaternion(parent.RelativeRotation);
                transform *= Matrix4.CreateTranslation(parent.RelativePosition);
            }

            // Iterate through all of the triangles in the mesh, doing a ray-triangle intersection
            for (int i = 0; i < mesh.Indices.Length; i += 3)
            {
                Vector3 point0 = mesh.Vertices[mesh.Indices[i + 0]] * transform;
                Vector3 point1 = mesh.Vertices[mesh.Indices[i + 1]] * transform;
                Vector3 point2 = mesh.Vertices[mesh.Indices[i + 2]] * transform;

                float thisDist;
                if (RayTriangle.CollisionTestCull(start, direction, point0, point1, point2, out thisDist))
                {
                    if (thisDist < dist)
                    {
                        dist = thisDist;
                    }
                }
            }

            return(dist < Single.MaxValue);
        }
Example #29
0
        /// <summary>
        /// Отсоединит переданный объект, пересчитает его Location так, чтобы он был абсолютным.
        /// </summary>
        public void Detach(IPhysical body)
        {
            //FarseerWorld.MakeWeldJoint(this.RealBody, (body as FarseerBody).RealBody);
            // Ищем в списке jointов

            var fb = (FarseerBody)body;

            fb.FloorFrictionEnabled = true;
            foreach (var j in _joints)             //ищем нужный joint
            {
                if ((j.BodyA == RealBody && j.BodyB == fb.RealBody) ||
                    (j.BodyB == RealBody && j.BodyA == fb.RealBody))
                {
                    j.Enabled = false;
                    FarseerWorld.RemoveJoint(j);
                    _joints.Remove(j);                     //Удалять joint из списка нужно у обоих тел! М.К.
                    fb._joints.Remove(j);
                    return;
                }
            }
        }
Example #30
0
        private void OnGameStateUpdate(SGameStateHeader header, List <SGameStateSlice> slices)
        {
            int physicsFrame = World.physicsFrameIter;

            World.physicsFrameIter = header.PhysicsStep;

            // grab each entity in the world
            // and make a dataslice for their physical state
            // send the batch off to clients to process
            foreach (SGameStateSlice slice in slices)
            {
                if (World.HasEntity(slice.EntityID))
                {
                    IPhysical ent = World.GetEntity(slice.EntityID) as IPhysical;

                    // if state implements Position, make sure to add here
                    ent.NextPosition = new Vector2(slice.NextX, slice.NextY);
                    ent.Velocity     = new Vector2(slice.VelocityX, slice.VelocityY);

                    for (int i = header.PhysicsStep; i < physicsFrame; i++)
                    {
                        if (ent is Player player)
                        {
                            player.Facing  = (Facing)slice.Flag0;
                            player.Looking = (Looking)slice.Flag1;
                            if (player.EntityID == ourPID)
                            {
                                var input = InputHistory.Get(i);
                                player.MovingLeft  = input.Left;
                                player.MovingRight = input.Right;
                                player.Jumping     = input.Jump;
                                player.LookingDown = input.Down;
                                player.LookingUp   = input.Up;
                            }
                        }
                        World.ProcessEntityPhysics(ent, PhysicsProperties.PHYSICS_TIMESTEP);
                    }
                }
            }
        }
 private static void CheckCollision()
 {
     for (int i = 0; i < physicalObjects.Count - 1; i++)
     {
         IPhysical physical1 = physicalObjects[i];
         if (physical1 != null)
         {
             for (int j = i + 1; j < physicalObjects.Count; j++)
             {
                 IPhysical physical2 = physicalObjects[j];
                 if (physical2 != null)
                 {
                     if (PhysicsManager.Intersect(physical1.BoxCollider, physical2.BoxCollider))
                     {
                         physical1.OnIntersect(physical2);
                         physical2.OnIntersect(physical1);
                     }
                 }
             }
         }
     }
 }
Example #32
0
        public static bool CollisionTest(Ray ray, IPhysical obj, BasicMesh mesh, out float dist)
        {
            Vector3 start = new Vector3(ray.X, ray.Y, ray.Z);
            Vector3 direction = new Vector3(ray.I, ray.J, ray.K);
            dist = Single.MaxValue;

            // Construct a matrix to transform to scene space
            Matrix4 transform = Matrix4.Identity;

            transform *= Matrix4.CreateScale(obj.Scale);
            transform *= Matrix4.CreateFromQuaternion(obj.RelativeRotation);
            transform *= Matrix4.CreateTranslation(obj.RelativePosition);

            ILinkable parent = obj.Parent;
            if (parent != null)
            {
                // Apply parent rotation and translation
                transform *= Matrix4.CreateFromQuaternion(parent.RelativeRotation);
                transform *= Matrix4.CreateTranslation(parent.RelativePosition);
            }

            // Iterate through all of the triangles in the mesh, doing a ray-triangle intersection
            for (int i = 0; i < mesh.Indices.Length; i += 3)
            {
                Vector3 point0 = mesh.Vertices[mesh.Indices[i + 0]] * transform;
                Vector3 point1 = mesh.Vertices[mesh.Indices[i + 1]] * transform;
                Vector3 point2 = mesh.Vertices[mesh.Indices[i + 2]] * transform;

                float thisDist;
                if (RayTriangle.CollisionTestCull(start, direction, point0, point1, point2, out thisDist))
                {
                    if (thisDist < dist)
                        dist = thisDist;
                }
            }

            return dist < Single.MaxValue;
        }
Example #33
0
        /// <summary>
        /// Присоединит переданный объект, используя переданный Location.
        /// </summary>
        public void Attach(IPhysical body, Frame3D realLocation, bool joinWithFriction = true)
        {
            if (!joinWithFriction)
            {
                body.FloorFrictionEnabled = false;
            }

            var originalLocation = realLocation;
            var rotated          = FarseerConverter.Rotate2D(realLocation, this.Location.Yaw);

            // Передвинем тело к тому, к которому присоединяем. Без этого фарсир может переместить оба тела, будет косяк.
            body.Location = this.Location + new Frame3D(rotated.X, rotated.Y, rotated.Z);

            // Присоединяем с таким offset-ом, как если бы не передвигали, так как фарсиру нужно локальное смещение.
            // Пересчёт в юниты фарсира происходит внутри MakeWeldJoint.
            Joint j = FarseerWorld.MakeWeldJoint(RealBody, (body as FarseerBody).RealBody, originalLocation);

            //PhysicalManager.MakeIteration(1.0001, null);

            //j.CollideConnected = false;
            _joints.Add(j);
            (body as FarseerBody)._joints.Add(j);
        }
Example #34
0
		private void AfterCreating(Body body, IPhysical physical)
		{
			PhysicalManager.SetSettings(body, physical);
			PhysicalManager.SaveBody(body, physical);
		}
Example #35
0
 /// <summary>Drained upper limit - mapped to the specified layer structure. Units: mm/mm        /// </summary>
 /// <param name="physical">The soil physical properties.</param>
 /// <param name="ToThickness">To thickness.</param>
 /// <returns></returns>
 public static double[] DULMapped(IPhysical physical, double[] ToThickness)
 {
     return(MapConcentration(physical.DUL, physical.Thickness, ToThickness, physical.DUL.Last()));
 }
Example #36
0
		/// <summary>
		/// Отсоединит переданный объект, пересчитает его Location так, чтобы он был абсолютным.
		/// </summary>		
		public void Detach(IPhysical body)
		{
			var bb = (BepuBody) body;
			var rb = bb.RealBody;
			foreach (var c in _connections.ToList().Where(c => c.OtherBody == rb))
			{
				try
				{
					c.Disconnect();
					_connections.Remove(c);
					bb._connections.Remove(c);
				}
				catch
				{
				}
				break;
			}
		}
Example #37
0
		/// <summary>
		/// Присоединит переданный объект, используя его Location.
		/// </summary>		
		public void Attach(IPhysical body, bool joinWithFriction = true)
		{
			Attach(body, body.Location, joinWithFriction);
		}
Example #38
0
 /// <summary>
 /// Keep track of Physical objects, and add them to the physics engine.
 /// </summary>
 /// <param name="e"></param>
 public void TrackPhysical(IPhysical e)
 {
     if (e.Body != null)
     {
         Engine.Physics.AddBody(e.Body);
         PhysicalList.Add(e);
     }
 }
Example #39
0
 private void SetArrToBeVertical(out IPhysical<Vector2d>[] Arr, out int Comp)
 {
     Arr = ThingsCacheXAsc;
     Comp = 0;
 }
Example #40
0
 private void GetArrayCompAndDirFromAngle(double Angle, out IPhysical<Vector2d>[] Arr, out int Dir, out int Comp)
 {
     if (Angle < PiOverFour)
     {
         SetArrToBeHorazontal(out Arr, out Comp);
         Dir = 1;
     }
     else if (Angle < PiOverFour * 3)
     {
         SetArrToBeVertical(out Arr, out Comp);
         Dir = 1;
     }
     else if (Angle < PiOverFour * 5)
     {
         SetArrToBeHorazontal(out Arr, out Comp);
         Dir = -1;
     }
     else if (Angle < PiOverFour * 7 )
     {
         SetArrToBeVertical(out Arr, out Comp);
         Dir = -1;
     }
     else
     {
         SetArrToBeHorazontal(out Arr, out Comp);
         Dir = 1;
     }
 }
Example #41
0
        private static int MoveIteratorToFirstRelevantObject(Vector2d Point, IPhysical<Vector2d>[] Arr, int Dir, int Comp, int i)
        {
            bool co = true;
            while (co)
            {
                if (Dir * (Dir * (Arr[i].Position.CoOrdinates[Comp])) < (Dir * (Point.CoOrdinates[Comp] - (80 * Dir))))
                {
                    i += Dir;
                }
                else
                {
                    co = false;
                }
            }

            return i;
        }
Example #42
0
        private static double FindPointsOnLine(Vector2d Point, double Angle, IPhysical<Vector2d>[] Arr, int Dir, int Comp, ref int i, ref ColourVector c)
        {
            double closest = 3600;
            while (Dir * (Dir * (Arr[i].Position.CoOrdinates[Comp])) < (Dir * (Point.CoOrdinates[Comp] - (80 * Dir))))
            {
                Vector2d diff = (Arr[i].Position - Point);
                double DistSquared = Vector2d.DistSquared(Arr[i].Position, Point);
                if (DistSquared != 0)
                {
                    double AngleFromPoin = Vector2d.AngleTowards(Arr[i].Position, Point);
                    double NormalisedDistPerpendicularToThing = Math.Tan(Angle - AngleFromPoin);
                    double q = DistSquared * NormalisedDistPerpendicularToThing * NormalisedDistPerpendicularToThing;
                    if (q < (Arr[i].Size * Arr[i].Size))
                    {
                        if (DistSquared < closest)
                        {
                            closest = DistSquared;
                            c = Arr[i].Colour;
                        }
                    }
                }
                i++;
            }

            return closest;
        }
Example #43
0
        private static int FindInitialIterator(IPhysical<Vector2d>[] Arr, int Dir)
        {
            int i = 0;
            if (Dir == 1)
            {
                i = 0;
            }
            else if (Dir == -1)
            {
                i = Arr.Count() - 1;
            }

            return i;
        }
Example #44
0
 public void UpdateThingChache(Field F)
 {
     List<IPhysical<Vector2d>> J = new List<IPhysical<Vector2d>>();
     J.AddRange(F.Bloops);
     foreach (Food B in Foods)
     {
         J.Add(B);
     }
     foreach (Poison B in Poisons)
     {
         J.Add(B);
     }
     foreach (Rock R in Rocks)
     {
         J.Add(R);
     }
     ThingsCache = J;
     ThingsCacheXAsc = J.OrderBy(t => t.Position.x).ToArray();
     ThingsCacheYAsc = J.OrderBy(t => t.Position.y).ToArray();
     FrameValid = F.Frame;
 }
Example #45
0
		/// <summary>
		/// Присоединит переданный объект, используя переданный Location.
		/// </summary>		
		public void Attach(IPhysical body, Frame3D realLocation, bool joinWithFriction = true)
		{
			if (!joinWithFriction)
			{
				body.FloorFrictionEnabled = false;
			}

			var originalLocation = realLocation;
			var rotated = FarseerConverter.Rotate2D(realLocation, this.Location.Yaw);

			// Передвинем тело к тому, к которому присоединяем. Без этого фарсир может переместить оба тела, будет косяк.
			body.Location = this.Location + new Frame3D(rotated.X, rotated.Y, rotated.Z);

			// Присоединяем с таким offset-ом, как если бы не передвигали, так как фарсиру нужно локальное смещение.
			// Пересчёт в юниты фарсира происходит внутри MakeWeldJoint.
			Joint j = fsworld.MakeWeldJoint(RealBody, (body as FarseerBody).RealBody, originalLocation);
			//PhysicalManager.MakeIteration(1.0001, null);

			//j.CollideConnected = false;
			_joints.Add(j);
			(body as FarseerBody)._joints.Add(j);
		}
Example #46
0
 /// <summary>
 /// If the given object is already Tracked "Physically",
 /// update which body should be in the Physics Engine.
 /// </summary>
 /// <param name="e">Given object</param>
 /// <param name="oldBody">
 /// The old objects Body can only be null if the object is not tracked
 /// by this tracker physically, in which case calling this method does nothing.
 /// </param>
 public void UpdatePhysicalTrack(IPhysical e, RigidBody oldBody)
 {
     if (PhysicalList.Contains(e)) { //only if it already tracked, which also means
         Engine.Physics.RemoveBody(oldBody); //it's in the physics engine, so remove it
         if (e.Body == null) //If the new body is null,
         {
             PhysicalList.Remove(e); //stop Physical tracking
         }
         else //otherwise
         {
             Engine.Physics.AddBody(e.Body); //add the new body to the physics engine
         }
     }
 }
Example #47
0
 /// <summary>
 /// Stop keep track of Physical objects, and remove them to the physics engine.
 /// </summary>
 /// <param name="e"></param>
 public void UntrackPhysical(IPhysical e)
 {
     Engine.Physics.RemoveBody(e.Body);
     PhysicalList.Remove(e);
 }
Example #48
0
		/// <summary>
		/// Свяжем тело и физическое тело
		/// </summary>
		internal void SaveBody(Body body, IPhysical physical)
		{
			if (BodiesToPhysical.ContainsKey(body))
				BodiesToPhysical[body] = physical;
			else
				BodiesToPhysical.Add(body, physical);
		}
Example #49
0
 public bool CheckMove(IPhysical physical, BoundingBox thisBB, GameTime gameTime)
 {
     throw new NotImplementedException();
 }
Example #50
0
 public bool EntityCollisionTest(Ray ray, IPhysical obj, out float distance)
 {
     float unused;
     return RayAABB.CollisionTestSmits(obj.SceneAABB, ray, out distance, out unused);
 }
Example #51
0
		/// <summary>
		/// Присоединит переданный объект, используя переданный Location.
		/// </summary>		
		public void Attach(IPhysical body, Frame3D realLocation, bool joinWithFriction = true)
		{
			var bb = (BepuBody) body;
			var rb = bb.RealBody;
			BepuConverter.PutInFrame(rb, realLocation, bb.InitialOrientation);
			//bb.RealBody.Position = new Vector3(-bb.RealBody.Position.X, bb.RealBody.Position.Y, bb.RealBody.Position.Z);
			rb.Position += RealBody.Position;
			rb.Orientation *= RealBody.Orientation;
			SolverGroup wj = BepuWorld.MakeWeldJoint(RealBody, rb);
			Connection c;
			try//есть connection
			{
				c = _connections.First(x => x.OtherBody == rb);
				c.Add(wj);
			}
			catch (Exception)//нет connection
			{
				c = new Connection(rb);
				c.Add(wj);
				_connections.Add(c);//connection добавляем для обоих тел! М.К.
				bb._connections.Add(c);
			}
		}
Example #52
0
        /// <summary>
        /// Change the axis of rotation for an entity
        /// </summary>
        /// <param name="sender">Calling object</param>
        /// <param name="entity">Entity to change the axis of rotation for</param>
        /// <param name="rotationAxis">New axis of rotation</param>
        public void EntitySetRotationAxis(object sender, IPhysical entity, Vector3 rotationAxis)
        {
            EventHandler<EntityRotationAxisArgs> callback = OnEntitySetRotationAxis;
            if (callback != null)
                callback(sender, new EntityRotationAxisArgs { Entity = entity, RotationAxis = rotationAxis });

            // TODO: Implement this
        }
Example #53
0
		/// <summary>
		/// Настроит тело PhysicalModel в соответствии с телом PhysicalPrimitiveBody
		/// </summary>	
		public void SetSettings(Body body, IPhysical physical)
		{
			physical.IsStatic = body.IsStatic;
			physical.Location = body.Location;
			physical.Mass = body.Volume / 1000 * ((body.Density == null) ? 1 : body.Density.Value);
			physical.FrictionCoefficient = body.FrictionCoefficient;
			physical.Id = body.Id;
			physical.Velocity = body.Velocity;
		}
Example #54
0
        /// <summary>
        /// Set a constant angular velocity on an entity
        /// </summary>
        /// <param name="sender">Calling object</param>
        /// <param name="entity">Entity to set the angular velocity for</param>
        /// <param name="torque">Angular velocity to set on the entity</param>
        public void EntitySetTorque(object sender, IPhysical entity, Vector3 torque)
        {
            EventHandler<EntityTorqueArgs> callback = OnEntitySetTorque;
            if (callback != null)
                callback(sender, new EntityTorqueArgs { Entity = entity, Torque = torque });

            // TODO: Implement this
        }
Example #55
0
        /// <summary>
        /// Apply a physical angular force to an entity
        /// </summary>
        /// <param name="sender">Calling object</param>
        /// <param name="entity">Entity to apply the angular force to</param>
        /// <param name="impulse">Angular force to apply to the entity</param>
        public void EntityApplyRotationalImpulse(object sender, IPhysical entity, Vector3 impulse)
        {
            EventHandler<EntityImpulseArgs> callback = OnEntityApplyRotationalImpulse;
            if (callback != null)
                callback(sender, new EntityImpulseArgs { Entity = entity, Impulse = impulse });

            // TODO: Implement this
        }
Example #56
0
		/// <summary>
		/// Отсоединит переданный объект, пересчитает его Location так, чтобы он был абсолютным.
		/// </summary>		
		public void Detach(IPhysical body)
		{
			//FarseerWorld.MakeWeldJoint(this.RealBody, (body as FarseerBody).RealBody);
			// Ищем в списке jointов

			var fb = (FarseerBody) body;
			fb.FloorFrictionEnabled = true;
			foreach (var j in _joints) //ищем нужный joint
			{
				if ((j.BodyA == RealBody && j.BodyB == fb.RealBody) ||
					(j.BodyB == RealBody && j.BodyA == fb.RealBody))
				{
					j.Enabled = false;
					fsworld.RemoveJoint(j);
					_joints.Remove(j); //Удалять joint из списка нужно у обоих тел! М.К.
					fb._joints.Remove(j);
					return;
				}
			}
		}