Beispiel #1
0
 public void UpdateBeforeSimulation100()
 {
     m_soundEmitters[(int)MySoundEmitterEnum.PrimaryState].Update();
     if (windSystem)
     {
         float oxygen = MyOxygenProviderSystem.GetOxygenInPoint(m_character.PositionComp.GetPosition());
         if (oxygen > 0f)
         {
             inAtmosphere = true;//in pressurized environment
         }
         else
         {
             Vector3 gravity = MyGravityProviderSystem.CalculateNaturalGravityInPoint(m_character.PositionComp.GetPosition());
             if (gravity.LengthSquared() > 0f)
             {
                 MyPlanet planet = MyGravityProviderSystem.GetNearestPlanet(m_character.PositionComp.GetPosition());
                 if (planet != null && planet.AtmosphereSettings.FogIntensity > 0f)
                 {
                     inAtmosphere = true;//in atmosphere without oxygen
                 }
                 else
                 {
                     inAtmosphere = false;
                 }
             }
             else
             {
                 inAtmosphere = false;
             }
         }
         windEmitter.Update();
     }
 }
Beispiel #2
0
        public override void UpdateAfterSimulation()
        {
            base.UpdateAfterSimulation();
            Vector3 vector = MyGravityProviderSystem.CalculateNaturalGravityInPoint(base.PositionComp.GetPosition());

            if (this.Physics.RigidBody.GetShape().ShapeType != HkShapeType.Sphere)
            {
                this.Physics.RigidBody.Gravity = vector;
            }
            else
            {
                this.m_smoothGravity    = (this.m_smoothGravity * 0.5f) + (vector * 0.5f);
                this.m_smoothGravityDir = this.m_smoothGravity;
                this.m_smoothGravityDir.Normalize();
                bool flag = false;
                foreach (Vector3 vector2 in this.m_supportNormals)
                {
                    if (vector2.Dot(this.m_smoothGravityDir) > 0.8f)
                    {
                        flag = true;
                        break;
                    }
                }
                this.m_supportNormals.Clear();
                if (!flag)
                {
                    this.Physics.RigidBody.Gravity = this.m_smoothGravity;
                }
                else if (this.Physics.RigidBody.Gravity.Length() > 0.01f)
                {
                    HkRigidBody rigidBody = this.Physics.RigidBody;
                    rigidBody.Gravity *= 0.99f;
                }
            }
        }
Beispiel #3
0
        private void InitializePath(MyEnvironmentalParticle particle)
        {
            var pathData = new PathData();

            if (pathData.PathPoints == null)
            {
                pathData.PathPoints = new Vector3D[PathData.PathPointCount + 2];
            }

            var gravity          = MyGravityProviderSystem.CalculateNaturalGravityInPoint(particle.Position);
            var gravityDirection = Vector3D.Normalize(gravity);

            pathData.PathPoints[1] = particle.Position - gravityDirection * MyRandom.Instance.NextFloat() * 2.5f;
            // TODO general direction of movement

            for (int index = 2; index < PathData.PathPointCount + 1; ++index)
            {
                var      pathLength   = 5.0f;
                Vector3D randomNormal = Vector3D.Normalize(new Vector3D(MyRandom.Instance.NextFloat(), MyRandom.Instance.NextFloat(), MyRandom.Instance.NextFloat()) * 2.0f - Vector3D.One - 0.25 * gravityDirection);
                pathData.PathPoints[index] = pathData.PathPoints[index - 1] + randomNormal * (MyRandom.Instance.NextFloat() + 1.0f) * pathLength - gravityDirection / (float)index * pathLength;
            }

            pathData.PathPoints[0] = pathData.PathPoints[1] - gravityDirection;
            pathData.PathPoints[PathData.PathPointCount + 1] = pathData.PathPoints[PathData.PathPointCount] + Vector3D.Normalize(pathData.PathPoints[PathData.PathPointCount] - pathData.PathPoints[PathData.PathPointCount - 1]);

            particle.UserData = pathData;
        }
Beispiel #4
0
        public override bool GetBotSpawnPosition(string behaviorType, out VRageMath.Vector3D spawnPosition)
        {
            // CH: TODO: Do this more generically, so that modders would be able to define their own bot types and the way they spawn
            if (behaviorType == "Spider")
            {
                MatrixD spawnMatrix;
                bool    success = GetSpiderSpawnPosition(out spawnMatrix, null);
                spawnPosition = spawnMatrix.Translation;
                return(success);
            }
            else if (MySession.Static.LocalCharacter != null)
            {
                var      pos = MySession.Static.LocalCharacter.PositionComp.GetPosition();
                Vector3  up;
                Vector3D right, forward;

                up = MyGravityProviderSystem.CalculateNaturalGravityInPoint(pos);
                if (up.LengthSquared() < 0.0001f)
                {
                    up = Vector3.Up;
                }
                else
                {
                    up = Vector3D.Normalize(up);
                }
                forward       = Vector3.CalculatePerpendicularVector(up);
                right         = Vector3.Cross(forward, up);
                spawnPosition = MyUtils.GetRandomDiscPosition(ref pos, 5.0f, ref forward, ref right);
                return(true);
            }

            spawnPosition = Vector3D.Zero;
            return(false);
        }
Beispiel #5
0
            public virtual void Start(MatrixD position, Vector3D initialVelocity, float scale, bool randomRotation = true)
            {
                MyDebug.AssertDebug(!m_isStarted);
                m_createdTime = MySandboxGame.TotalGamePlayTimeInMilliseconds;
                Container.Entity.PositionComp.Scale = RandomScale * scale;
                Container.Entity.WorldMatrix        = position;
                (Container.Entity.Physics as MyDebrisPhysics).ScalePhysicsShape(ref m_massProperties);
                Container.Entity.Physics.Clear();
                Container.Entity.Physics.LinearVelocity = initialVelocity;
                //apply random rotation impulse
                if (randomRotation)
                {
                    Container.Entity.Physics.AngularVelocity = new Vector3(MyUtils.GetRandomRadian(),
                                                                           MyUtils.GetRandomRadian(),
                                                                           MyUtils.GetRandomRadian());
                }
                MyEntities.Add(m_entity);
                Container.Entity.Physics.Enabled = true;
                float    simulationRatio = Sync.IsServer ? 1.0f : Sync.RelativeSimulationRatio * Sync.RelativeSimulationRatio;
                Vector3D gravity         = simulationRatio * MyGravityProviderSystem.CalculateNaturalGravityInPoint(position.Translation);

                ((MyPhysicsBody)Container.Entity.Physics).RigidBody.Gravity = gravity;
                (Container.Entity.Physics as MyPhysicsBody).HavokWorld.ActiveRigidBodies.Add((Container.Entity.Physics as MyPhysicsBody).RigidBody);
                m_isStarted = true;
            }
Beispiel #6
0
        private bool CheckGravity()
        {
            if (!Config.AllowInGravity)
            {
                if (!Vector3D.IsZero(MyGravityProviderSystem.CalculateNaturalGravityInPoint(PlayerPosition)))
                {
                    Chat?.Respond("Saving & Loading in gravity has been disabled!");
                    return(false);
                }
            }
            else
            {
                if (Config.MaxGravityAmount == 0)
                {
                    return(true);
                }

                float Gravity = MyGravityProviderSystem.CalculateNaturalGravityInPoint(PlayerPosition).Length() / 9.81f;
                if (Gravity > Config.MaxGravityAmount)
                {
                    //Log.Warn("Players gravity amount: " + Gravity);
                    Chat?.Respond("You are not permitted to Save/load in this gravity amount. Max amount: " + Config.MaxGravityAmount + "g");
                    return(false);
                }
            }

            return(true);
        }
Beispiel #7
0
        public override bool GetBotSpawnPosition(string behaviorType, out VRageMath.Vector3D spawnPosition)
        {
            if (MySession.LocalCharacter != null)
            {
                var      pos = MySession.LocalCharacter.PositionComp.GetPosition();
                Vector3  up;
                Vector3D right, forward;

                up = MyGravityProviderSystem.CalculateNaturalGravityInPoint(pos);
                if (up.LengthSquared() < 0.0001f)
                {
                    up = Vector3.Up;
                }
                else
                {
                    up = Vector3D.Normalize(up);
                }
                forward       = Vector3.CalculatePerpendicularVector(up);
                right         = Vector3.Cross(forward, up);
                spawnPosition = MyUtils.GetRandomDiscPosition(ref pos, 5.0f, ref forward, ref right);
                return(true);
            }

            spawnPosition = Vector3D.Zero;
            return(false);
        }
Beispiel #8
0
        public void UpdateAtmosphereStatus()
        {
            if (m_character != null && (m_localPlayer == false || (MySession.Static != null && m_character == MySession.Static.LocalCharacter)))
            {
                AtmosphereStatus original = m_atmosphereStatus;
                Vector3D         pos      = m_character.PositionComp.GetPosition();
                Vector3          gravity  = MyGravityProviderSystem.CalculateNaturalGravityInPoint(pos);
                if (gravity.LengthSquared() > 0f)
                {
                    MyPlanet planet = MyGamePruningStructure.GetClosestPlanet(pos);
                    if (planet != null && planet.HasAtmosphere && planet.GetAirDensity(pos) > 0.5f)
                    {
                        m_atmosphereStatus = AtmosphereStatus.Atmosphere;//in atmosphere
                    }
                    else
                    {
                        m_atmosphereStatus = AtmosphereStatus.Space;
                    }
                }
                else
                {
                    m_atmosphereStatus = AtmosphereStatus.Space;
                }

                if (m_atmosphereStatus == AtmosphereStatus.Space)
                {
                    float oxygen = 0f;
                    if (m_character.OxygenComponent != null)
                    {
                        if (m_localPlayer)
                        {
                            if (MySession.Static.ControlledEntity is MyCharacter)
                            {
                                //in suit
                                oxygen = m_character.OxygenComponent.EnvironmentOxygenLevel;
                            }
                            else
                            {
                                //in cockpit
                                oxygen = m_character.OxygenComponent.OxygenLevelAtCharacterLocation;
                            }
                        }
                        else
                        {
                            oxygen = m_character.OxygenComponent.EnvironmentOxygenLevel;
                        }
                    }
                    if (oxygen > 0.1f)
                    {
                        m_atmosphereStatus = AtmosphereStatus.ShipOrStation;//in pressurized environment
                    }
                }

                if (MyFakes.ENABLE_REALISTIC_LIMITER && MyFakes.ENABLE_NEW_SOUNDS && original != m_atmosphereStatus && MySession.Static != null && MySession.Static.Settings.RealisticSound)
                {
                    MyAudio.Static.EnableMasterLimiter(!(InAtmosphere || InShipOrStation));
                }
            }
        }
Beispiel #9
0
        private void SpawnBot(SpawnInfo spawnInfo, MyPlanet planet, MyPlanetAnimalSpawnInfo animalSpawnInfo)
        {
            PlanetAIInfo planetInfo = null;

            if (!m_planets.TryGetValue(planet.EntityId, out planetInfo))
            {
                Debug.Assert(false, "Could not get planet info!");
                return;
            }

            if (planetInfo.BotNumber >= MAX_BOTS_PER_PLANET)
            {
                return;
            }

            Debug.Assert(animalSpawnInfo != null);
            double   spawnDistMin     = animalSpawnInfo.SpawnDistMin;
            double   spawnDistMax     = animalSpawnInfo.SpawnDistMax;
            Vector3D center           = spawnInfo.Position;
            Vector3D planetGravityVec = MyGravityProviderSystem.CalculateNaturalGravityInPoint(center);

            //GR: if gravity is zero provide a random Vector to normalize
            if (planetGravityVec == Vector3D.Zero)
            {
                planetGravityVec = Vector3D.Up;
            }
            planetGravityVec.Normalize();
            Vector3D planetTangent   = Vector3D.CalculatePerpendicularVector(planetGravityVec);
            Vector3D planetBitangent = Vector3D.Cross(planetGravityVec, planetTangent);

            planetTangent.Normalize();
            planetBitangent.Normalize();
            Vector3D spawnPos = MyUtils.GetRandomDiscPosition(ref center, spawnDistMin, spawnDistMax, ref planetTangent, ref planetBitangent);

            spawnPos = planet.GetClosestSurfacePointGlobal(ref spawnPos);
            Vector3D?spawnPosCorrected = MyEntities.FindFreePlace(spawnPos, 2.0f);

            if (spawnPosCorrected.HasValue)
            {
                spawnPos = spawnPosCorrected.Value;
            }

            planet.CorrectSpawnLocation(ref spawnPos, 2.0f);

            MyAgentDefinition botBehavior = GetAnimalDefinition(animalSpawnInfo) as MyAgentDefinition;

            if (botBehavior != null)
            {
                if (botBehavior.Id.SubtypeName == Wolf_SUBTYPE_ID && MySession.Static.EnableWolfs)
                {
                    MyAIComponent.Static.SpawnNewBot(botBehavior, spawnPos);
                }
                else if (botBehavior.Id.SubtypeName != Wolf_SUBTYPE_ID && MySession.Static.EnableSpiders)
                {
                    MyAIComponent.Static.SpawnNewBot(botBehavior, spawnPos);
                }
            }
        }
Beispiel #10
0
        private bool IsNearPlanet()
        {
            if (ControlledEntity == null)
            {
                return(false);
            }

            return(!Vector3.IsZero(MyGravityProviderSystem.CalculateNaturalGravityInPoint(ControlledEntity.PositionComp.GetPosition())));
        }
        public override void UpdateAfterSimulation()
        {
            base.UpdateAfterSimulation();
            // DA: Consider using havok fields (buoyancy demo) for gravity of planets.
            //<ib.floating>
            //Physics.RigidBody.Gravity = MyGravityProviderSystem.CalculateNaturalGravityInPoint(PositionComp.GetPosition());
            Vector3 gravity = MyGravityProviderSystem.CalculateNaturalGravityInPoint(PositionComp.GetPosition());


            if (Physics.RigidBody.GetShape().ShapeType == HkShapeType.Sphere)
            {
                const float w = 0.5f;
                m_smoothGravity    = m_smoothGravity * w + gravity * (1 - w);
                m_smoothGravityDir = m_smoothGravity;
                m_smoothGravityDir.Normalize();

                bool anySupport = false;
                foreach (var supportNormal in m_supportNormals)
                {
                    float       cosalpha      = supportNormal.Dot(m_smoothGravityDir);
                    const float cosalphaLimit = 0.8f; // +/- 12 Degrees
                    if (cosalpha > cosalphaLimit)
                    {
                        anySupport = true;
                        break;
                    }
                }
                m_supportNormals.Clear();

                if (anySupport)
                {
                    //Physics.RigidBody.Gravity = Vector3.Zero;
                    const float limitGravity = 0.01f;
                    if ((Physics.RigidBody.Gravity.Length() > limitGravity))
                    {
                        Physics.RigidBody.Gravity *= 0.99f; // Decay gravity
                    }
                }
                else
                {
                    Physics.RigidBody.Gravity = m_smoothGravity;
                }
            }
            else
            {
                Physics.RigidBody.Gravity = gravity;
            }


            if (m_massChangeForCollisions < 1f)
            {
                if ((MySession.Static.ElapsedPlayTime.TotalMilliseconds - m_timeFromSpawn.TotalMilliseconds) >= 2000)
                {
                    m_massChangeForCollisions = 1f;
                }
            }
        }
        public bool UpdatePhysicalMovement()
        {
            if (!Running)
            {
                return(false);
            }

            var characterPhysics = Character.Physics;

            var characterProxy = characterPhysics.CharacterProxy;

            if (characterProxy != null)
            {
                if (characterProxy.LinearVelocity.Length() < MyCharacter.MINIMAL_SPEED)
                {
                    characterProxy.LinearVelocity = Vector3.Zero;
                }
            }

            var rigidBody = characterPhysics.RigidBody;

            if (rigidBody != null)
            {
                rigidBody.Gravity = Vector3.Zero;

                if (MySession.Static.SurvivalMode || MyFakes.ENABLE_PLANETS_JETPACK_LIMIT_IN_CREATIVE)
                {
                    Vector3 planetGravity = MyGravityProviderSystem.CalculateNaturalGravityInPoint(Character.PositionComp.WorldAABB.Center);

                    if (planetGravity != Vector3.Zero)
                    {
                        rigidBody.Gravity = planetGravity * MyPerGameSettings.CharacterGravityMultiplier;
                    }
                }

                return(true);
            }
            else if (characterProxy != null)
            {
                characterProxy.Gravity = Vector3.Zero;

                if (MySession.Static.SurvivalMode || MyFakes.ENABLE_PLANETS_JETPACK_LIMIT_IN_CREATIVE)
                {
                    Vector3 planetGravity = MyGravityProviderSystem.CalculateNaturalGravityInPoint(Character.PositionComp.WorldAABB.Center);

                    if (planetGravity != Vector3.Zero)
                    {
                        characterProxy.Gravity = planetGravity * MyPerGameSettings.CharacterGravityMultiplier;
                    }
                }

                return(true);
            }

            return(false);
        }
Beispiel #13
0
        public void UpdateAtmosphereStatus()
        {
            if (m_character != null && (m_localPlayer == false || (MySession.Static != null && m_character == MySession.Static.LocalCharacter)))
            {
                Vector3D pos     = m_character.PositionComp.GetPosition();
                Vector3  gravity = MyGravityProviderSystem.CalculateNaturalGravityInPoint(pos);
                if (gravity.LengthSquared() > 0f)
                {
                    MyPlanet planet = MyGravityProviderSystem.GetNearestPlanet(pos);
                    float    d      = (float)Vector3D.DistanceSquared(planet.PositionComp.GetPosition(), pos);
                    if (planet != null && planet.HasAtmosphere && Vector3D.DistanceSquared(planet.PositionComp.GetPosition(), pos) < planet.AtmosphereRadius * planet.AtmosphereRadius)
                    {
                        m_atmosphereStatus = AtmosphereStatus.Atmosphere;//in atmosphere
                    }
                    else
                    {
                        m_atmosphereStatus = AtmosphereStatus.Space;
                    }
                }
                else
                {
                    m_atmosphereStatus = AtmosphereStatus.Space;
                }

                if (m_atmosphereStatus == AtmosphereStatus.Space)
                {
                    float oxygen = 0f;
                    if (m_character.OxygenComponent != null)
                    {
                        if (m_localPlayer)
                        {
                            if (MySession.Static.ControlledEntity is MyCharacter)
                            {
                                //in suit
                                oxygen = m_character.OxygenComponent.EnvironmentOxygenLevel;
                            }
                            else
                            {
                                //in cockpit
                                oxygen = m_character.OxygenComponent.OxygenLevelAtCharacterLocation;
                            }
                        }
                        else
                        {
                            oxygen = m_character.OxygenComponent.EnvironmentOxygenLevel;
                        }
                    }
                    if (oxygen > 0.1f)
                    {
                        m_atmosphereStatus = AtmosphereStatus.ShipOrStation;//in pressurized environment
                    }
                }
            }
        }
Beispiel #14
0
        public bool Contains(ref Vector3D point)
        {
            Vector3D vectord;

            List <BoundingBox> .Enumerator enumerator;
            Vector3D.Transform(ref point, ref this.m_worldInv, out vectord);
            Vector3 vector = Vector3.TransformNormal(MyGravityProviderSystem.CalculateNaturalGravityInPoint(this.m_grid.PositionComp.WorldAABB.Center), this.m_worldInv);

            if (!Vector3.IsZero(vector))
            {
                vector = Vector3.Normalize(vector);
                Ray ray = new Ray((Vector3)vectord, -vector * 2f);
                using (enumerator = this.m_segments.GetEnumerator())
                {
                    bool flag;
                    while (true)
                    {
                        if (enumerator.MoveNext())
                        {
                            float?nullable = enumerator.Current.Intersects(ray);
                            if (nullable == null)
                            {
                                continue;
                            }
                            flag = true;
                        }
                        else
                        {
                            goto TR_0000;
                        }
                        break;
                    }
                    return(flag);
                }
            }
            using (enumerator = this.m_segments.GetEnumerator())
            {
                while (true)
                {
                    if (!enumerator.MoveNext())
                    {
                        break;
                    }
                    BoundingBox current = enumerator.Current;
                    if (current.Contains(vectord) == ContainmentType.Contains)
                    {
                        return(true);
                    }
                }
            }
TR_0000:
            return(false);
        }
        private void CalculateGridPosition(Vector3D Target)
        {
            List <MyObjectBuilder_CubeGrid> TotalGrids = new List <MyObjectBuilder_CubeGrid>();
            List <MyObjectBuilder_Cockpit>  cockpits   = new List <MyObjectBuilder_Cockpit>();
            Vector3D forwardVector = Vector3D.Zero;


            Hangar.Debug("Total Grids to be pasted: " + _grids.Count());

            //Attempt to get gravity/Artificial gravity to align the grids to


            //Here you can adjust the offset from the surface and rotation.
            //Unfortunatley we move the grid again after this to find a free space around the character. Perhaps later i can incorporate that into
            //LordTylus's existing grid checkplament method
            float gravityRotation = 0f;

            Vector3 gravityDirectionalVector = MyGravityProviderSystem.CalculateNaturalGravityInPoint(Target);

            if (gravityDirectionalVector == Vector3.Zero)
            {
                gravityDirectionalVector = MyGravityProviderSystem.CalculateArtificialGravityInPoint(Target);
            }
            Vector3D upDirectionalVector;

            if (gravityDirectionalVector != Vector3.Zero)
            {
                Hangar.Debug("Attempting to correct grid orientation!");
                gravityDirectionalVector.Normalize();
                upDirectionalVector = -gravityDirectionalVector;

                if (forwardVector == Vector3D.Zero)
                {
                    forwardVector = Vector3D.CalculatePerpendicularVector(gravityDirectionalVector);
                    if (gravityRotation != 0f)
                    {
                        MatrixD matrixa = MatrixD.CreateFromAxisAngle(upDirectionalVector, gravityRotation);
                        forwardVector = Vector3D.Transform(forwardVector, matrixa);
                    }
                }
            }
            else if (forwardVector == Vector3D.Zero)
            {
                forwardVector       = Vector3D.Right;
                upDirectionalVector = Vector3D.Up;
            }
            else
            {
                upDirectionalVector = Vector3D.CalculatePerpendicularVector(-forwardVector);
            }

            BeginAlignToGravity(_grids, Target, forwardVector, upDirectionalVector);
        }
        public static void GetSpawnPosition(float collisionRadius, out Vector3 direction, out Vector3D position)
        {
            float distance = 0;

            foreach (var entity in MyEntities.GetEntities())
            {
                // Include only voxels
                if (entity is MyVoxelMap)
                {
                    distance = (float)MathHelper.Max(distance, entity.PositionComp.WorldVolume.Center.Length() + entity.PositionComp.WorldVolume.Radius);
                }
            }

            // 500 - 650m from last voxel
            distance += MyUtils.GetRandomFloat(500, 650);

            if (MyEntities.IsWorldLimited())
            {
                distance = Math.Min(distance, MyEntities.WorldSafeHalfExtent());
            }
            else
            {
                distance = Math.Min(distance, 20000); // limited spawn area in infinite worlds
            }
            direction = MyUtils.GetRandomVector3Normalized();
            var searchPosition = MyEntities.FindFreePlace((Vector3D)(direction * distance), collisionRadius);

            if (!searchPosition.HasValue)
            {
                searchPosition = (Vector3D)(direction * distance); // Spawn in existing place (better than crash)
            }
            Vector3D globalPoint = (Vector3D)searchPosition;

            position = globalPoint;

            if (MyGravityProviderSystem.CalculateNaturalGravityInPoint(globalPoint) != null && MyGravityProviderSystem.CalculateNaturalGravityInPoint(globalPoint).Length() != 0)
            {
                MyPlanet planet     = MyGravityProviderSystem.GetStrongestGravityWell(globalPoint);
                double   multiplier = planet.MaximumRadius / globalPoint.Length();
                globalPoint *= multiplier;
                Vector3D closestPoint = planet.GetClosestSurfacePointGlobal(ref globalPoint) * 1.25;
                searchPosition = MyEntities.FindFreePlace(closestPoint, collisionRadius);
                if (searchPosition.HasValue)
                {
                    position = searchPosition.Value;
                }
            }
            else
            {
                position = searchPosition.Value;
            }
        }
Beispiel #17
0
        private Vector3D?FindPastePosition(Vector3D Target)
        {
            //Log.info($"BoundingSphereD: {SphereD.Center}, {SphereD.Radius}");
            //Log.info($"MyOrientedBoundingBoxD: {BoxD.Center}, {BoxD.GetAABB()}");
            MyGravityProviderSystem.CalculateNaturalGravityInPoint(Target, out float val);
            if (val == 0)
            {
                //following method is what SEworldgen uses. We only really need to use this in space
                return(FindSuitableJumpLocationSpace(Target));
            }

            return(MyEntities.FindFreePlaceCustom(Target, (float)SphereD.Radius, 90, 10, 1.5f, 10));
        }
Beispiel #18
0
        public override void UpdateAfterSimulation()
        {
            base.UpdateAfterSimulation();
            // DA: Consider using havok fields (buoyancy demo) for gravity of planets.
            Physics.RigidBody.Gravity = MyGravityProviderSystem.CalculateNaturalGravityInPoint(PositionComp.GetPosition());

            if (m_massChangeForCollisions < 1f)
            {
                if ((MySession.Static.ElapsedPlayTime.TotalMilliseconds - m_timeFromSpawn.TotalMilliseconds) >= 2000)
                {
                    m_massChangeForCollisions = 1f;
                }
            }
        }
        private static void StartWave()
        {
            if (!m_currentTarget.HasValue)
            {
                return;
            }

            var sunDir = GetCorrectedDirection(MySector.DirectionToSunNormalized);

            SetupDirVectors(sunDir);
            var waveMeteorCount = MyUtils.GetRandomFloat(Math.Min(2, m_meteorcount - 3), m_meteorcount + 3);

            var      randCircle          = MyUtils.GetRandomVector3CircleNormalized();
            var      rand                = MyUtils.GetRandomFloat(0, 1);
            Vector3D randomCircleInPlain = randCircle.X * m_rightVector + randCircle.Z * m_downVector;
            var      hitPosition         = m_currentTarget.Value.Center + Math.Pow(rand, 0.7f) * m_currentTarget.Value.Radius * randomCircleInPlain * METEOR_BLUR_KOEF;
            //Cast Ray for sure

            var antigravityDir = -Vector3D.Normalize(MyGravityProviderSystem.CalculateNaturalGravityInPoint(hitPosition));

            if (antigravityDir != Vector3D.Zero)
            {
                var hi = MyPhysics.CastRay(hitPosition + antigravityDir * (3000), hitPosition, MyPhysics.CollisionLayers.DefaultCollisionLayer);
                if (hi != null)
                {
                    hitPosition = hi.Value.Position;
                }
            }
            m_meteorHitPos = hitPosition;
            for (int i = 0; i < waveMeteorCount; i++)
            {
                // hit
                randCircle          = MyUtils.GetRandomVector3CircleNormalized();
                rand                = MyUtils.GetRandomFloat(0, 1);
                randomCircleInPlain = randCircle.X * m_rightVector + randCircle.Z * m_downVector;
                hitPosition         = hitPosition + Math.Pow(rand, 0.7f) * m_currentTarget.Value.Radius * randomCircleInPlain;


                // start
                var toSun = sunDir * (2000 + 100 * i);
                randCircle          = MyUtils.GetRandomVector3CircleNormalized();
                randomCircleInPlain = randCircle.X * m_rightVector + randCircle.Z * m_downVector;
                var realPosition = hitPosition + toSun + (float)Math.Tan(MyUtils.GetRandomFloat(0, (float)Math.PI / 18)) * randomCircleInPlain;

                m_meteorList.Add(MyMeteor.SpawnRandom(realPosition, Vector3.Normalize(hitPosition - realPosition)));
            }
            m_rightVector = Vector3.Zero;
        }
Beispiel #20
0
            public virtual void Start(MatrixD position, Vector3D initialVelocity, bool randomRotation = true)
            {
                this.m_createdTime = MySandboxGame.TotalGamePlayTimeInMilliseconds;
                base.Container.Entity.WorldMatrix = position;
                base.Container.Entity.Physics.Clear();
                base.Container.Entity.Physics.LinearVelocity = (Vector3)initialVelocity;
                if (randomRotation)
                {
                    base.Container.Entity.Physics.AngularVelocity = new Vector3(MyUtils.GetRandomRadian(), MyUtils.GetRandomRadian(), MyUtils.GetRandomRadian());
                }
                MyEntities.Add(base.m_entity, true);
                base.Container.Entity.Physics.Enabled = true;
                Vector3 vector = MyGravityProviderSystem.CalculateNaturalGravityInPoint(position.Translation);

                ((MyPhysicsBody)base.Container.Entity.Physics).RigidBody.Gravity = vector;
                this.m_isStarted = true;
            }
        public float GetAirDensity(IMyCubeGrid grid)
        {
            Vector3D pos     = grid.PositionComp.GetPosition();
            Vector3  gravity = MyGravityProviderSystem.CalculateNaturalGravityInPoint(pos);

            if (gravity.LengthSquared() > 0f)
            {
                var planet = MyGamePruningStructure.GetClosestPlanet(pos);
                if (planet != null && planet.HasAtmosphere)
                {
                    return(-(planet.GetAirDensity(pos)));
                }
            }

            // Probably in space.
            return(0);
        }
Beispiel #22
0
        public static MyPlanetNamesData GetPlanetNames(Vector3D position)
        {
            MyPlanetNamesData data          = new MyPlanetNamesData();
            MyPlanet          closestPlanet = MyGamePruningStructure.GetClosestPlanet(position);
            Vector3           vector        = MyGravityProviderSystem.CalculateNaturalGravityInPoint(position);

            if ((closestPlanet == null) || (vector.LengthSquared() <= 0f))
            {
                data.planetName = "";
                data.planetType = "";
            }
            else
            {
                data.planetName = closestPlanet.StorageName;
                data.planetType = closestPlanet.Generator.FolderName;
            }
            return(data);
        }
Beispiel #23
0
        public bool UpdatePhysicalMovement()
        {
            if (!this.Running)
            {
                return(false);
            }
            MyPhysicsBody    physics        = base.Character.Physics;
            MyCharacterProxy characterProxy = physics.CharacterProxy;

            if ((characterProxy != null) && (characterProxy.LinearVelocity.Length() < 0.001f))
            {
                characterProxy.LinearVelocity = Vector3.Zero;
            }
            float       num       = 1f;
            HkRigidBody rigidBody = physics.RigidBody;

            if (rigidBody != null)
            {
                rigidBody.Gravity = Vector3.Zero;
                if (MySession.Static.SurvivalMode || MyFakes.ENABLE_PLANETS_JETPACK_LIMIT_IN_CREATIVE)
                {
                    Vector3 vector2 = (Vector3)(num * MyGravityProviderSystem.CalculateNaturalGravityInPoint(base.Character.PositionComp.WorldAABB.Center));
                    if (vector2 != Vector3.Zero)
                    {
                        rigidBody.Gravity = vector2 * MyPerGameSettings.CharacterGravityMultiplier;
                    }
                }
                return(true);
            }
            if (characterProxy == null)
            {
                return(false);
            }
            characterProxy.Gravity = Vector3.Zero;
            if (MySession.Static.SurvivalMode || MyFakes.ENABLE_PLANETS_JETPACK_LIMIT_IN_CREATIVE)
            {
                Vector3 vector3 = (Vector3)(num * MyGravityProviderSystem.CalculateNaturalGravityInPoint(base.Character.PositionComp.WorldAABB.Center));
                if (vector3 != Vector3.Zero)
                {
                    characterProxy.Gravity = vector3 * MyPerGameSettings.CharacterGravityMultiplier;
                }
            }
            return(true);
        }
        /// <summary>
        /// Calculate propper direction for meteorits. Everytime above horizon.
        /// </summary>
        /// <param name="direction"></param>
        /// <returns></returns>
        private static Vector3 GetCorrectedDirection(Vector3 direction)
        {
            var currDir = direction;

            if (m_currentTarget == null)
            {
                return(currDir);
            }

            var tgtPos = m_currentTarget.Value.Center;

            MyMeteorShower.m_tgtPos = tgtPos;

            if (!MyGravityProviderSystem.IsPositionInNaturalGravity(tgtPos))
            {
                return(currDir);
            }

            var pltTgtDir = -Vector3D.Normalize(MyGravityProviderSystem.CalculateNaturalGravityInPoint(tgtPos));
            var tmpVec    = Vector3D.Normalize(Vector3D.Cross(pltTgtDir, currDir));
            var mirror    = Vector3D.Normalize(Vector3D.Cross(tmpVec, pltTgtDir));

            MyMeteorShower.m_mirrorDir = mirror;
            MyMeteorShower.m_pltTgtDir = pltTgtDir;
            MyMeteorShower.m_normalSun = tmpVec;

            double horizonRatio = pltTgtDir.Dot(currDir);

            //below down horizon
            if (horizonRatio < -HORIZON_ANGLE_FROM_ZENITH_RATIO)
            {
                return(Vector3D.Reflect(-currDir, mirror));
            }

            // between below and above horizon (prohi
            if (horizonRatio < HORIZON_ANGLE_FROM_ZENITH_RATIO)
            {
                MatrixD tmpMat = MatrixD.CreateFromAxisAngle(tmpVec, -Math.Asin(HORIZON_ANGLE_FROM_ZENITH_RATIO));
                return(Vector3D.Transform(mirror, tmpMat));
            }

            // above 20 Degree above horizon
            return(currDir);
        }
Beispiel #25
0
        private void CutTree(int itemInstanceId, Vector3D hitWorldPosition, Vector3 hitNormal, float forceMultiplier = 1.0f)
        {
            HkStaticCompoundShape shape = (HkStaticCompoundShape)Physics.RigidBody.GetShape();
            int physicsInstanceId;

            if (m_localIdToPhysicsShapeInstanceId.TryGetValue(itemInstanceId, out physicsInstanceId))
            {
                //Remove static tree
                MyEnvironmentItemData itemData = m_itemsData[itemInstanceId];

                RemoveItem(itemInstanceId, physicsInstanceId, sync: true, immediateUpdate: true);

                //Create fractured tree
                MyDefinitionId id             = new MyDefinitionId(Definition.ItemDefinitionType, itemData.SubtypeId);
                var            itemDefinition = MyDefinitionManager.Static.GetEnvironmentItemDefinition(id);
                if (MyModels.GetModelOnlyData(itemDefinition.Model).HavokBreakableShapes != null)
                {
                    CreateBreakableShape(itemDefinition, ref itemData, ref hitWorldPosition, hitNormal, forceMultiplier);
                }
                else
                {
                    ProfilerShort.Begin("Spawning tree");
                    // This is for SE when you hit a tree, it will create a floating object with the same model. In case it affects ME, it may be changed. Contact DusanA for it.
                    Debug.Assert(MyPerGameSettings.Game == GameEnum.SE_GAME);
                    MyPhysicalInventoryItem Item = new MyPhysicalInventoryItem()
                    {
                        Amount = 1, Content = new MyObjectBuilder_TreeObject()
                        {
                            SubtypeName = itemData.SubtypeId.ToString()
                        }
                    };
                    Vector3D pos     = itemData.Transform.Position;
                    Vector3D gravity = -MyGravityProviderSystem.CalculateNaturalGravityInPoint(pos);
                    gravity.Normalize();

                    MyFloatingObjects.Spawn(Item, pos + gravity, MyUtils.GetRandomPerpendicularVector(ref gravity), gravity);
                    ProfilerShort.End();
                }
            }
        }
        public bool Contains(ref Vector3D point)
        {
            Vector3D localPoint;

            Vector3D.Transform(ref point, ref m_worldInv, out localPoint);

            // Testing a point against extrusion of the BB along gravity is the same as
            // testing extrusion of the point (i.e. a ray going in the opposite direction) against the original BB.
            Vector3D testPoint = m_grid.PositionComp.WorldAABB.Center;
            Vector3  gravity   = MyGravityProviderSystem.CalculateNaturalGravityInPoint(testPoint);

            gravity = Vector3.TransformNormal(gravity, m_worldInv);
            if (!Vector3.IsZero(gravity))
            {
                gravity = Vector3.Normalize(gravity);
                Ray ray = new Ray(localPoint, -gravity * 2.0f); // 2.0f = height of the character

                foreach (var segment in m_segments)
                {
                    if (segment.Intersects(ray).HasValue)
                    {
                        return(true);
                    }
                }
            }
            else
            {
                // CH: Use some kind of a tree or something better than a list here!
                foreach (var segment in m_segments)
                {
                    if (segment.Contains(localPoint) == ContainmentType.Contains)
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
Beispiel #27
0
        /// <summary>
        /// Returns a position adjusted for planets that should be safe to spawn at given the radius and position.
        /// </summary>
        /// <param name="collisionRadius">The radius of the object that is trying to spawn.</param>
        /// <param name="position">The position the object would like to spawn at.</param>
        /// <param name="forward">(Out) The forward vector the object should spawn with.</param>
        /// <param name="up">(Out) The up vector the object should spawn with.</param>
        /// <param name="planetAtmosphereRatio">The ratio within the planet's max radius and atmosphere radius you are positioned in.</param>
        /// <param name="randomRangeMin">The minimum randomized distance that is added.</param>
        /// <param name="randomRangeMax">The minimum randomized distance that is added.</param>
        private static void GetSpawnPositionNearPlanet(MyPlanet planet, float collisionRadius, ref Vector3D position, out Vector3D forward, out Vector3D up, float planetAtmosphereRatio = 0.3f, float randomRangeMin = 500, float randomRangeMax = 650)
        {
            // Position us at a desirable height on the planet
            // Roughl halfway the planet's upper atmosphere and outer radius
            float randomHeightAdjustment = MyUtils.GetRandomFloat(randomRangeMin, randomRangeMax);
            float height = planet.MaximumRadius + planetAtmosphereRatio * (planet.AtmosphereRadius - planet.MaximumRadius) + randomHeightAdjustment;

            // Compute random position
            position = planet.PositionComp.WorldVolume.Center + MyUtils.GetRandomVector3Normalized() * height;
            Vector3D?freePlace   = MyEntities.FindFreePlace(position, collisionRadius);
            int      numAttempts = 1;

            // While we have no valid spawn position, try again 3 more times
            while (!freePlace.HasValue && numAttempts <= 3)
            {
                position     = planet.PositionComp.WorldVolume.Center + MyUtils.GetRandomVector3Normalized() * height;
                freePlace    = MyEntities.FindFreePlace(position, collisionRadius);
                numAttempts += 1;
            }

            // If we have a valid position, use it
            if (freePlace.HasValue)
            {
                position = freePlace.Value;
            }

            // Return orientation perpendicular to planet surface
            Vector3 gravityAtPosition = MyGravityProviderSystem.CalculateNaturalGravityInPoint(position);

            if (Vector3.IsZero(gravityAtPosition)) // If we are somehow randomized outside of gravity range, make sure some orientation is used
            {
                gravityAtPosition = Vector3.Up;
            }

            Vector3D normalizedGravityVector = Vector3D.Normalize(gravityAtPosition);

            forward = Vector3.CalculatePerpendicularVector(-normalizedGravityVector);
            up      = -normalizedGravityVector;
        }
        private EdgePlacerSystem.AnnotatedNode CreateVertex(Vector3D worldPos)
        {
            var      node = Graph.GetNode(worldPos);
            Vector3D up;

            if (node != null)
            {
                up       = node.Up;
                worldPos = node.Position;
            }
            else
            {
                up = Vector3D.Normalize(-MyGravityProviderSystem.CalculateNaturalGravityInPoint(worldPos));
                if (!up.IsValid() || up.LengthSquared() < 1e-3f)
                {
                    up = Vector3D.Up;
                }
            }

            return(new EdgePlacerSystem.AnnotatedNode {
                Position = worldPos, Up = (Vector3)up, Existing = node, Tangent = node?.Tangent ?? Vector3.Zero
            });
        }
Beispiel #29
0
        public Node GetOrCreateNode(Vector3D pos, Vector3D?up = null, bool desirePin = false)
        {
            var nearest = NearestNode(pos);

            if (nearest != null && Vector3D.DistanceSquared(nearest.Position, pos) < RailConstants.NodeMergeDistanceSq)
            {
                if (!desirePin || Vector3D.DistanceSquared(nearest.Position, pos) < .05f * .05f)
                {
                    return(nearest);
                }
            }

            // ReSharper disable once InvertIf
            if (!up.HasValue)
            {
                up = Vector3D.Normalize(-MyGravityProviderSystem.CalculateNaturalGravityInPoint(pos));
                if (!up.Value.IsValid() || up.Value.LengthSquared() < 1e-3f)
                {
                    up = Vector3D.Up;
                }
            }

            return(new Node(this, pos, up.Value));
        }
Beispiel #30
0
        protected MyBehaviorTreeState RunAway([BTParam] float distance)
        {
            if (!runAwayPos.HasValue)
            {
                Vector3D currentPosition  = Bot.Player.Character.PositionComp.GetPosition();
                Vector3D planetGravityVec = MyGravityProviderSystem.CalculateNaturalGravityInPoint(currentPosition);

                var planet = MyGravityProviderSystem.GetNearestPlanet(currentPosition);
                if (planet == null)
                {
                    return(MyBehaviorTreeState.FAILURE);
                }

                if (lastTargetedEntityPosition.HasValue)
                {
                    Vector3D lastTargetedEntityPositionProjected = lastTargetedEntityPosition.Value;
                    lastTargetedEntityPositionProjected = planet.GetClosestSurfacePointGlobal(ref lastTargetedEntityPositionProjected);

                    Vector3D direction           = currentPosition - lastTargetedEntityPositionProjected;
                    Vector3D runAwayPosCandidate = currentPosition + Vector3D.Normalize(direction) * distance;
                    runAwayPos = planet.GetClosestSurfacePointGlobal(ref runAwayPosCandidate);
                }
                else
                {
                    planetGravityVec.Normalize();
                    Vector3D planetTangent   = Vector3D.CalculatePerpendicularVector(planetGravityVec);
                    Vector3D planetBitangent = Vector3D.Cross(planetGravityVec, planetTangent);
                    planetTangent.Normalize();
                    planetBitangent.Normalize();
                    Vector3D runAwayPosCandidate = MyUtils.GetRandomDiscPosition(ref currentPosition, distance, distance, ref planetTangent, ref planetBitangent);
                    if (planet != null)
                    {
                        runAwayPos = planet.GetClosestSurfacePointGlobal(ref runAwayPosCandidate);
                    }
                    else
                    {
                        runAwayPos = runAwayPosCandidate;
                    }
                }
                AiTargetBase.SetTargetPosition(runAwayPos.Value);
                AimWithMovement();
            }
            else
            {
                if (Bot.Navigation.Stuck)
                {
                    return(MyBehaviorTreeState.FAILURE);
                }
            }

            AiTargetBase.GotoTargetNoPath(1.0f, false);

            if (Vector3D.DistanceSquared(runAwayPos.Value, Bot.Player.Character.PositionComp.GetPosition()) < 10.0f * 10.0f)
            {
                CyberhoundLogic.Remove();
                return(MyBehaviorTreeState.SUCCESS);
            }
            else
            {
                return(MyBehaviorTreeState.RUNNING);
            }
        }