Exemplo n.º 1
0
        private Vector3D GetSmartLosPosition(int i, ref Dummy.DummyInfo info, int degrees)
        {
            double   angle   = MathHelperD.ToRadians(degrees);
            var      perpDir = Vector3D.CalculatePerpendicularVector(info.Direction);
            Vector3D up;

            Vector3D.Normalize(ref perpDir, out up);
            Vector3D right;

            Vector3D.Cross(ref info.Direction, ref up, out right);
            var offset = Math.Tan(angle); // angle better be in radians

            var destPos = info.Position;

            switch (i)
            {
            case 0:
                return(destPos + (info.Direction * Comp.Ai.GridVolume.Radius));

            case 1:
                return(destPos + ((info.Direction + up * offset) * Comp.Ai.GridVolume.Radius));

            case 2:
                return(destPos + ((info.Direction - up * offset) * Comp.Ai.GridVolume.Radius));

            case 3:
                return(destPos + ((info.Direction + right * offset) * Comp.Ai.GridVolume.Radius));

            case 4:
                return(destPos + ((info.Direction - right * offset) * Comp.Ai.GridVolume.Radius));
            }

            return(Vector3D.Zero);
        }
Exemplo n.º 2
0
        public override void Draw()
        {
            base.Draw();

            ProfilerShort.Begin("Fireflies.Draw");
            var   scale  = 0.075f;
            float width  = scale / 1.66f;
            float height = scale;

            foreach (var particle in m_activeParticles)
            {
                if (!particle.Active)
                {
                    continue;
                }

                Vector4 drawColor = particle.Color;
                var     lifeRatio = (float)(MySandboxGame.TotalGamePlayTimeInMilliseconds - particle.BirthTime) / (float)particle.LifeTime;
                if (lifeRatio < 0.1f)
                {
                    drawColor = particle.Color * lifeRatio;
                }
                else if (lifeRatio > 0.9f)
                {
                    drawColor = particle.Color * (1.0f - lifeRatio);
                }

                var directionVector = Vector3D.CalculatePerpendicularVector(-Vector3D.Normalize(particle.Position - MySector.MainCamera.Position));

                MyTransparentGeometry.AddLineBillboard(particle.Material, drawColor, particle.Position, directionVector, height, width);
            }
            ProfilerShort.End();
        }
Exemplo n.º 3
0
        /// <summary>
        /// Returns a vector perpendicular to a vector, takes an angle
        /// </summary>
        public static Vector3D GetPerpendicularVector(Vector3D vector, double angle)
        {
            Vector3D perpVector = Vector3D.CalculatePerpendicularVector(Vector3.Normalize(vector));
            Vector3D bitangent; Vector3D.Cross(ref vector, ref perpVector, out bitangent);

            return(Vector3D.Normalize(Math.Cos(angle) * perpVector + Math.Sin(angle) * bitangent));
        }
Exemplo n.º 4
0
        public MyNavmeshManager(MyRDPathfinding rdPathfinding, Vector3D center, Vector3D forwardDirection, int tileSize, int tileHeight, int tileLineCount, MyRecastOptions recastOptions)
        {
            Vector3 vector = new Vector3(ran.NextFloat(), ran.NextFloat(), ran.NextFloat());

            vector              -= Math.Min(vector.X, Math.Min(vector.Y, vector.Z));
            vector              /= Math.Max(vector.X, Math.Max(vector.Y, vector.Z));
            this.m_debugColor    = new Color(vector);
            this.m_tileSize      = tileSize;
            this.m_tileHeight    = tileHeight;
            this.m_tileLineCount = tileLineCount;
            this.Planet          = this.GetPlanet(center);
            this.m_heightCoordTransformationIncrease = 0.5f;
            float cellSize = 0.2f;

            this.m_recastOptions = recastOptions;
            float num2 = (this.m_tileSize * 0.5f) + (this.m_tileSize * ((float)Math.Floor((double)(this.m_tileLineCount * 0.5f))));
            float num3 = this.m_tileHeight * 0.5f;

            this.m_border = this.m_recastOptions.agentRadius + (3f * cellSize);
            float[] bMin = new float[] { -num2, -num3, -num2 };
            float[] bMax = new float[] { num2, num3, num2 };
            this.m_rdWrapper = new MyRDWrapper();
            this.m_rdWrapper.Init(cellSize, (float)this.m_tileSize, bMin, bMax);
            Vector3D vectord = Vector3D.CalculatePerpendicularVector(-Vector3D.Normalize(MyGravityProviderSystem.CalculateTotalGravityInPoint(center)));

            this.m_navmeshOBBs   = new MyNavmeshOBBs(this.Planet, center, vectord, this.m_tileLineCount, this.m_tileSize, this.m_tileHeight);
            this.m_debugTileSize = new int?[this.m_tileLineCount][];
            for (int i = 0; i < this.m_tileLineCount; i++)
            {
                this.m_debugTileSize[i] = new int?[this.m_tileLineCount];
            }
            this.m_extendedBaseOBB = new MyOrientedBoundingBoxD(this.m_navmeshOBBs.BaseOBB.Center, new Vector3D(this.m_navmeshOBBs.BaseOBB.HalfExtent.X, (double)this.m_tileHeight, this.m_navmeshOBBs.BaseOBB.HalfExtent.Z), this.m_navmeshOBBs.BaseOBB.Orientation);
            this.m_navInputMesh    = new MyNavigationInputMesh(rdPathfinding, this.Planet, center);
        }
        private static void SpawnEncounter(MyEncounterId encounterPosition, Vector3D placePosition, List <MySpawnGroupDefinition> candidates, int selectedEncounter)
        {
            var spawnGroup = candidates[selectedEncounter];

            long ownerId = 0; // 0 means that the owner won't be changed

            if (spawnGroup.IsPirate)
            {
                ownerId = MyPirateAntennas.GetPiratesId();
            }

            foreach (var selectedPrefab in spawnGroup.Prefabs)
            {
                List <MyCubeGrid> createdGrids = new List <MyCubeGrid>();
                Vector3D          direction    = Vector3D.Forward;
                Vector3D          upVector     = Vector3D.Up;

                var spawningOptions = spawnGroup.ReactorsOn ? VRage.Game.ModAPI.SpawningOptions.None : VRage.Game.ModAPI.SpawningOptions.TurnOffReactors;
                if (selectedPrefab.Speed > 0.0f)
                {
                    spawningOptions = VRage.Game.ModAPI.SpawningOptions.RotateFirstCockpitTowardsDirection |
                                      VRage.Game.ModAPI.SpawningOptions.SpawnRandomCargo |
                                      VRage.Game.ModAPI.SpawningOptions.DisableDampeners;

                    float centerArcRadius = (float)Math.Atan(MyNeutralShipSpawner.NEUTRAL_SHIP_FORBIDDEN_RADIUS / placePosition.Length());
                    direction = -Vector3D.Normalize(placePosition);
                    float    theta  = m_random.NextFloat(centerArcRadius, centerArcRadius + MyNeutralShipSpawner.NEUTRAL_SHIP_DIRECTION_SPREAD);
                    float    phi    = m_random.NextFloat(0, 2 * MathHelper.Pi);
                    Vector3D cosVec = Vector3D.CalculatePerpendicularVector(direction);
                    Vector3D sinVec = Vector3D.Cross(direction, cosVec);
                    cosVec   *= (Math.Sin(theta) * Math.Cos(phi));
                    sinVec   *= (Math.Sin(theta) * Math.Sin(phi));
                    direction = direction * Math.Cos(theta) + cosVec + sinVec;

                    upVector = Vector3D.CalculatePerpendicularVector(direction);
                }
                spawningOptions |= VRage.Game.ModAPI.SpawningOptions.DisableSave;

                if (selectedPrefab.PlaceToGridOrigin)
                {
                    spawningOptions |= SpawningOptions.UseGridOrigin;
                }

                Stack <Action> callback = new Stack <Action>();
                callback.Push(delegate() { ProcessCreatedGrids(ref encounterPosition, selectedPrefab.Speed, createdGrids); });

                MyPrefabManager.Static.SpawnPrefab(
                    resultList: createdGrids,
                    prefabName: selectedPrefab.SubtypeId,
                    position: placePosition + selectedPrefab.Position,
                    forward: direction,
                    up: upVector,
                    beaconName: selectedPrefab.BeaconText,
                    initialLinearVelocity: direction * selectedPrefab.Speed,
                    spawningOptions: spawningOptions | SpawningOptions.UseGridOrigin,
                    ownerId: ownerId,
                    updateSync: true,
                    callbacks: callback);
            }
        }
Exemplo n.º 6
0
        public static Vector3 GetRandomPerpendicularNormalToDirection(Random random, Vector3 direction)
        {
            direction.Normalize();
            var perp = Vector3D.CalculatePerpendicularVector(direction);

            perp.Normalize();
            var coperp = perp.Cross(direction);

            var theta = random.NextDouble() * Math.PI * 2;

            return(perp * Math.Sin(theta) + coperp * Math.Cos(theta));

            // Original Trickshot code
//             var perp = new Vector3D(1, 1, -(rangeVector.X + rangeVector.Y) / rangeVector.Z);
//             var coperp = perp.Cross(rangeVector);
//             perp.Normalize();
//             coperp.Normalize();
//
//             var rand = new Random();
//             var theta = rand.NextDouble() * Math.PI * 2;
//
//             //         var dist = -rangeVector;
//             //         dist.Normalize();
//             //         dist *= 1200;
//
//             TrickshotOffset = perp * Math.Sin(theta) + coperp * Math.Cos(theta);
        }
Exemplo n.º 7
0
        public bool CreateEffectForGate(GateDataMessage gate, bool enable = false)
        {
            var effectName = gate.ParticleId;
            var size       = gate.Size;

            var centerMatrix = MatrixD.CreateWorld(gate.Position, Vector3D.CalculatePerpendicularVector(gate.Forward), -gate.Forward);

            if (effectName.Contains("end"))
            {
                size        *= 0.4f;
                centerMatrix = MatrixD.CreateWorld(gate.Position, Vector3D.CalculatePerpendicularVector(gate.Forward), gate.Forward);
            }

            var initialMatrix = centerMatrix;

            initialMatrix.Translation += initialMatrix.Right * size;
            var wmPos            = initialMatrix.Translation;
            var rotatingParticle = new RotatingParticle(0, initialMatrix, centerMatrix, size, gate.ParticleId);

            _allEffects[gate.Id] = rotatingParticle;
            if (enable)
            {
                _enabledEffects[gate.Id] = rotatingParticle;
                return(true);
            }
            return(true);
        }
Exemplo n.º 8
0
            void moveTo(Vector3D ROID_START, Vector3D ROID_END)
            {
                //Setup Of Common Variables
                Vector3D DronePosition   = RC.GetPosition();
                Vector3D Drone_To_Target = Vector3D.Normalize(ROID_END - DronePosition);
                //Generates XYZ Vectors
                Vector3D X_ADD = Vector3D.Normalize(ROID_END - ROID_START);    //Characteristic 'Forward' vector
                Vector3D Y_ADD = Vector3D.CalculatePerpendicularVector(X_ADD); //Characteristic 'Left' vector
                Vector3D Z_ADD = Vector3D.Cross(X_ADD, Y_ADD);                 //Characteristic 'Up' vector

                //设置起点
                Vector3D CurrentVectorStart = ROID_START;
                //设置终点
                Vector3D CurrentVectorEnd = ROID_END; //Accounts for small input
                double   dis = Vector3D.Distance(CurrentVectorStart, DronePosition);
                //Inputs To Autopilot Function
                double RollReqt = (float)(0.6 * (Vector3D.Dot(Z_ADD, RC.WorldMatrix.Down)));

                GyroTurn6(X_ADD * 999999999999999999, RotationalSensitvity, GYRO, RC, RollReqt, PrecisionMaxAngularVel);
                if (dis > 20 && isAutoPilot)
                {
                    RC_Manager(CurrentVectorStart, RC, false);
                    if (dis < 30)
                    {
                        isAutoPilot = false;
                    }
                    print("方式:自动驾驶");
                }
                else
                {
                    print("方式:程序控制");
                    Vector_Thrust_Manager(CurrentVectorStart, CurrentVectorEnd, RC.GetPosition(), 1, 0.5, RC);
                }
            }
Exemplo n.º 9
0
        public static void ScorePlanetFlatness(Vector3D startPos, double radius, out double score, out Vector3D groundPos)
        {
            var planet = MyGamePruningStructure.GetClosestPlanet(startPos);

            groundPos = planet.GetClosestSurfacePointGlobal(ref startPos);
            var center = planet.PositionComp.WorldVolume.Center;

            var normal = groundPos - center;

            normal.Normalize();
            // Sample two points _radius_ away perp. to normal
            var otherDir = Vector3D.CalculatePerpendicularVector(normal);

            otherDir.Normalize();
            var otherWorld = groundPos + otherDir * radius;
            var other1Surf = planet.GetClosestSurfacePointGlobal(ref otherWorld);

            Vector3D.Cross(ref normal, ref otherDir, out otherDir);
            otherDir.Normalize();
            otherWorld = groundPos + otherDir * radius;
            var other2Surf = planet.GetClosestSurfacePointGlobal(ref otherWorld);

            var surfNorm = Vector3D.Cross(other2Surf - groundPos, other1Surf - groundPos);

            surfNorm.Normalize();
            score = Math.Abs(Vector3D.Dot(surfNorm, normal));
        }
Exemplo n.º 10
0
        private static Vector3D GetPerpendicularVector(ref Vector3D axis, double angle)
        {
            var      tangent = Vector3D.CalculatePerpendicularVector(axis);
            Vector3D bitangent;

            Vector3D.Cross(ref axis, ref tangent, out bitangent);
            return(Math.Cos(angle) * tangent + Math.Sin(angle) * bitangent);
        }
Exemplo n.º 11
0
        private bool SpawnDrone(long antennaEntityId, long ownerId, Vector3D position, MySpawnGroupDefinition spawnGroup)
        {
            Vector3D direction    = MyUtils.GetRandomVector3Normalized();
            Vector3D upVector     = Vector3D.CalculatePerpendicularVector(direction);
            MatrixD  originMatrix = MatrixD.CreateWorld(position, direction, upVector);

            foreach (var shipPrefab in spawnGroup.Prefabs)
            {
                Vector3D shipPosition = Vector3D.Transform((Vector3D)shipPrefab.Position, originMatrix);

                m_tmpGridList.Clear();

                MyPrefabManager.Static.SpawnPrefab(
                    resultList: m_tmpGridList,
                    prefabName: shipPrefab.SubtypeId,
                    position: shipPosition,
                    forward: direction,
                    up: upVector,
                    initialLinearVelocity: default(Vector3),
                    beaconName: null,
                    spawningOptions: Sandbox.ModAPI.SpawningOptions.None,
                    ownerId: ownerId,
                    updateSync: true);

                foreach (var grid in m_tmpGridList)
                {
                    grid.ChangeGridOwnership(ownerId, MyOwnershipShareModeEnum.None);

                    MyRemoteControl firstRemote = null;

                    foreach (var block in grid.CubeBlocks)
                    {
                        if (block.FatBlock == null)
                        {
                            continue;
                        }

                        var pb = block.FatBlock as MyProgrammableBlock;
                        if (pb != null)
                        {
                            pb.SendRecompile();
                        }

                        var remote = block.FatBlock as MyRemoteControl;
                        if (firstRemote == null)
                        {
                            firstRemote = remote;
                        }
                    }

                    // If there's no remote control on the grid, we have to register it as is
                    RegisterDrone(antennaEntityId, (MyEntity)firstRemote ?? (MyEntity)grid);
                }

                m_tmpGridList.Clear();
            }
            return(true);
        }
Exemplo n.º 12
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);
                }
            }
        }
Exemplo n.º 13
0
        public static Vector3D GetRandomPerpendicularVector(ref Vector3D axis)
        {
            Debug.Assert(Vector3D.IsUnit(ref axis));
            Vector3D tangent = Vector3D.CalculatePerpendicularVector(axis);
            Vector3D bitangent; Vector3D.Cross(ref axis, ref tangent, out bitangent);
            double   angle = GetRandomDouble(0, 2 * MathHelper.Pi);

            return(Math.Cos(angle) * tangent + Math.Sin(angle) * bitangent);
        }
Exemplo n.º 14
0
        private static void SpawnEncouter(MyEncounterId encounterPosition, Vector3D placePosition, List <MySpawnGroupDefinition> candidates, int selectedEncounter)
        {
            foreach (var selectedPrefab in candidates[selectedEncounter].Prefabs)
            {
                m_createdGrids.Clear();
                Vector3D direction = Vector3D.Forward;
                Vector3D upVector  = Vector3D.Up;

                var spawningOptions = Sandbox.ModAPI.SpawningOptions.TurnOffReactors;
                if (selectedPrefab.Speed > 0.0f)
                {
                    spawningOptions = Sandbox.ModAPI.SpawningOptions.RotateFirstCockpitTowardsDirection |
                                      Sandbox.ModAPI.SpawningOptions.SpawnRandomCargo |
                                      Sandbox.ModAPI.SpawningOptions.DisableDampeners;



                    float centerArcRadius = (float)Math.Atan(MyNeutralShipSpawner.NEUTRAL_SHIP_FORBIDDEN_RADIUS / placePosition.Length());
                    direction = -Vector3D.Normalize(placePosition);
                    float    theta  = m_random.NextFloat(centerArcRadius, centerArcRadius + MyNeutralShipSpawner.NEUTRAL_SHIP_DIRECTION_SPREAD);
                    float    phi    = m_random.NextFloat(0, 2 * MathHelper.Pi);
                    Vector3D cosVec = Vector3D.CalculatePerpendicularVector(direction);
                    Vector3D sinVec = Vector3D.Cross(direction, cosVec);
                    cosVec   *= (Math.Sin(theta) * Math.Cos(phi));
                    sinVec   *= (Math.Sin(theta) * Math.Sin(phi));
                    direction = direction * Math.Cos(theta) + cosVec + sinVec;

                    upVector = Vector3D.CalculatePerpendicularVector(direction);
                }
                spawningOptions |= Sandbox.ModAPI.SpawningOptions.DisableSave;

                var      prefabDefinition    = MyDefinitionManager.Static.GetPrefabDefinition(selectedPrefab.SubtypeId);
                Vector3D prefabPosDeltaValue = Vector3D.Zero;
                if (prefabDefinition.CubeGrids.Length > 0)
                {
                    if (prefabDefinition.CubeGrids[0].PositionAndOrientation.HasValue)
                    {
                        prefabPosDeltaValue = prefabDefinition.CubeGrids[0].PositionAndOrientation.Value.Position;
                    }
                }
                prefabPosDeltaValue -= prefabDefinition.BoundingSphere.Center;

                MyPrefabManager.Static.SpawnPrefab(
                    resultList: m_createdGrids,
                    prefabName: selectedPrefab.SubtypeId,
                    position: placePosition + selectedPrefab.Position - prefabPosDeltaValue,
                    forward: direction,
                    up: upVector,
                    beaconName: selectedPrefab.BeaconText,
                    initialLinearVelocity: direction * selectedPrefab.Speed,
                    spawningOptions: spawningOptions,
                    updateSync: true);

                ProcessCreatedGrids(ref encounterPosition, selectedPrefab.Speed);
            }
        }
Exemplo n.º 15
0
        private MatrixD LocalNavmeshPositionToWorldPositionTransform(MyOrientedBoundingBoxD obb, Vector3D center)
        {
            // TODO: should use the obb?

            Vector3D   gravityVector = -Vector3D.Normalize(GameSystems.MyGravityProviderSystem.CalculateTotalGravityInPoint(center));
            var        fwd           = Vector3D.CalculatePerpendicularVector(gravityVector);
            Quaternion quaternion    = Quaternion.CreateFromForwardUp(fwd, gravityVector);

            return(MatrixD.CreateFromQuaternion(quaternion));
        }
Exemplo n.º 16
0
        private static Vector3D GetRandomPerpendicularVector(ref Vector3D axis)
        {
            Vector3D vectord2;
            Vector3D vectord = Vector3D.CalculatePerpendicularVector((Vector3D)axis);

            Vector3D.Cross(ref axis, ref vectord, out vectord2);
            double randomDouble = MyUtils.GetRandomDouble(0.0, 6.2831859588623047);

            return((Vector3D)((Math.Cos(randomDouble) * vectord) + (Math.Sin(randomDouble) * vectord2)));
        }
Exemplo n.º 17
0
        private static void SpawningParallelChecks()
        {
            if (_currentSpawn.SpawningType != SpawnTypeEnum.CustomSpawn)
            {
                _spawnMatrix = _currentSpawn.CurrentPositionMatrix;
                return;
            }

            if (_currentSpawn.UseRelativeSpawnPosition)
            {
                var spawnCoords = Vector3D.Transform(_currentSpawn.RelativeSpawnOffset, _currentSpawn.CurrentPositionMatrix);
                _spawnMatrix = MatrixD.CreateWorld(spawnCoords, _currentSpawn.CurrentPositionMatrix.Forward, _currentSpawn.CurrentPositionMatrix.Up);
            }
            else
            {
                var upDir      = VectorHelper.GetPlanetUpDirection(_currentSpawn.CurrentPositionMatrix.Translation);
                var playerList = new List <IMyPlayer>();
                MyAPIGateway.Players.GetPlayers(playerList);

                for (int i = 0; i < 15; i++)
                {
                    if (upDir == Vector3D.Zero)
                    {
                        var spawnCoords = VectorHelper.RandomDirection() * VectorHelper.RandomDistance(_currentSpawn.MinDistance, _currentSpawn.MaxDistance) + _currentSpawn.CurrentPositionMatrix.Translation;
                        var forwardDir  = Vector3D.Normalize(spawnCoords - _currentSpawn.CurrentPositionMatrix.Translation);
                        var upPerpDir   = Vector3D.CalculatePerpendicularVector(forwardDir);
                        _spawnMatrix = MatrixD.CreateWorld(spawnCoords, forwardDir, upPerpDir);
                    }
                    else
                    {
                        _spawnMatrix = VectorHelper.GetPlanetRandomSpawnMatrix(_currentSpawn.CurrentPositionMatrix.Translation, _currentSpawn.MinDistance, _currentSpawn.MaxDistance, _currentSpawn.MinAltitude, _currentSpawn.MaxAltitude, _currentSpawn.InheritNpcAltitude);
                    }

                    foreach (var player in playerList)
                    {
                        if (player.IsBot || player.Controller?.ControlledEntity?.Entity == null)
                        {
                            continue;
                        }

                        if (Vector3D.Distance(_spawnMatrix.Translation, player.GetPosition()) < 100)
                        {
                            Logger.MsgDebug(_currentSpawn.ProfileSubtypeId + ": Player Too Close To Possible Spawn Coords. Attempt " + (i + 1).ToString(), DebugTypeEnum.Spawn);
                            _spawnMatrix = MatrixD.Identity;
                            break;
                        }
                    }

                    if (_spawnMatrix != MatrixD.Identity)
                    {
                        break;
                    }
                }
            }
        }
Exemplo n.º 18
0
        public static void CalculateHavok(List <Vector3I> result, float gridSize, Vector3D lineStart, Vector3D lineEnd, Vector3I min, Vector3I max)
        {
            var dir   = Vector3D.Normalize(lineEnd - lineStart);
            var up    = Vector3D.Normalize(Vector3D.CalculatePerpendicularVector(dir)) * 0.06f;
            var right = Vector3D.Normalize(Vector3D.Cross(dir, up)) * 0.06;

            Calculate(result, gridSize, lineStart + up, lineEnd + up, min, max);
            Calculate(result, gridSize, lineStart - up, lineEnd - up, min, max);
            Calculate(result, gridSize, lineStart + right, lineEnd + right, min, max);
            Calculate(result, gridSize, lineStart - right, lineEnd - right, min, max);
        }
Exemplo n.º 19
0
        public static void CalculateHavok(List <Vector3I> result, float gridSize, Vector3D lineStart, Vector3D lineEnd, Vector3I min, Vector3I max)
        {
            Vector3D v        = Vector3D.Normalize(lineEnd - lineStart);
            Vector3D vectord  = Vector3D.Normalize(Vector3D.CalculatePerpendicularVector(v)) * 0.059999998658895493;
            Vector3D vectord2 = Vector3D.Normalize(Vector3D.Cross(v, vectord)) * 0.06;

            Calculate(result, gridSize, lineStart + vectord, lineEnd + vectord, min, max);
            Calculate(result, gridSize, lineStart - vectord, lineEnd - vectord, min, max);
            Calculate(result, gridSize, lineStart + vectord2, lineEnd + vectord2, min, max);
            Calculate(result, gridSize, lineStart - vectord2, lineEnd - vectord2, min, max);
        }
        public MyNavigationInputMesh(MyRDPathfinding rdPathfinding, MyPlanet planet, Vector3D center)
        {
            m_rdPathfinding = rdPathfinding;
            m_planet        = planet;
            m_center        = center;

            Vector3D gravityVector = -Vector3D.Normalize(GameSystems.MyGravityProviderSystem.CalculateTotalGravityInPoint(m_center));
            Vector3D fwd           = Vector3D.CalculatePerpendicularVector(gravityVector);

            rdWorldQuaternion = Quaternion.Inverse(Quaternion.CreateFromForwardUp(fwd, gravityVector));
        }
Exemplo n.º 21
0
            private void TargetLosCheck()
            {
                var to   = MyAi.GridVolume.Center;
                var from = TargetPos;

                var perpDir  = Vector3D.CalculatePerpendicularVector(to - from);
                var fromPerp = from + (perpDir * TargetRadius);
                var toPerp   = to + (perpDir * MyAi.GridVolume.Radius);

                MyAi.Session.Physics.CastRayParallel(ref from, ref to, CollisionLayers.VoxelCollisionLayer, TargetLostCallBack);
                MyAi.Session.Physics.CastRayParallel(ref fromPerp, ref toPerp, CollisionLayers.VoxelCollisionLayer, TargetLostCallBack);
            }
Exemplo n.º 22
0
        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);
        }
Exemplo n.º 23
0
 //vector pointing tword enemy
 public void EvasiveManeuvering(Vector3D enemysVector)
 {
     enemysVector.CalculatePerpendicularVector(out enemysVector);
     if (enemysVector.Normalize() > 10)
     {
         ThrustTwordsDirection(enemysVector, false, true);
     }
     else
     {
         ThrustTwordsDirection(enemysVector, false, true);
     }
 }
Exemplo n.º 24
0
        /// <summary>
        /// Returns a position 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="planetSpawnHeightRatio">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>
        public static void GetSpawnPosition(float collisionRadius, ref Vector3D position, out Vector3D forward, out Vector3D up, float planetSpawnHeightRatio = 0.3f, float randomRangeMin = 500, float randomRangeMax = 650)
        {
            // Are we spawning near a planet?
            MyPlanet planet = MyGamePruningStructure.GetClosestPlanet(position);

            if (planet != null)
            {
                GetSpawnPositionNearPlanet(planet, collisionRadius, ref position, out forward, out up, planetSpawnHeightRatio, randomRangeMin, randomRangeMax);
                return;
            }

            // Old logic, testing for asteroids and other objects
            double distance = 0;

            foreach (var entity in MyEntities.GetEntities())
            {
                MyVoxelMap voxelMap = entity as MyVoxelMap;

                // Only test against voxels
                if (entity == null)
                {
                    continue;
                }

                distance = MathHelper.Max(distance, entity.PositionComp.WorldVolume.Center.Length() + entity.PositionComp.WorldVolume.Radius);
            }

            // Random range from last voxel
            distance += MyUtils.GetRandomFloat(randomRangeMin, randomRangeMax);

            if (MyEntities.IsWorldLimited())
            {
                distance = Math.Min(distance, MyEntities.WorldSafeHalfExtent());
            }
            else
            {
                distance = Math.Min(distance, 20000); // limited spawn area in infinite worlds
            }
            // Compute random position
            forward = MyUtils.GetRandomVector3Normalized();
            up      = Vector3D.CalculatePerpendicularVector(forward);
            Vector3D randomizedPosition = position + (forward * distance);

            // Test if we can spawn here
            Vector3D?searchPosition = MyEntities.FindFreePlace(randomizedPosition, collisionRadius);

            if (searchPosition.HasValue)
            {
                randomizedPosition = searchPosition.Value;
            }

            position = randomizedPosition;
        }
Exemplo n.º 25
0
        public void DebugDraw(MatrixD worldMatrix)
        {
            Vector3D translation = worldMatrix.Translation;

            MyRenderProxy.DebugDrawSphere(translation, this.m_minRadius, Color.Red, 0.2f, true, true, true, false);
            MyRenderProxy.DebugDrawSphere(translation, this.m_maxRadius, Color.Red, 0.2f, true, true, true, false);
            float   num = this.m_lastUpdatePosition.Length();
            Vector3 v   = this.m_lastUpdatePosition / num;

            MyRenderProxy.DebugDrawLine3D(translation, translation + (this.OcclusionDistance * v), Color.Green, Color.Green, true, false);
            Vector3D baseVec = Vector3D.CalculatePerpendicularVector(v) * this.m_baseRadius;

            MyRenderProxy.DebugDrawCone(translation + (v * (num - this.OcclusionDistance)), v * this.OcclusionDistance, baseVec, Color.Blue, true, false);
        }
Exemplo n.º 26
0
        //  This method will start sun wind. Or if there is one coming, this will reset it so it will start again.
        public static void Start()
        {
            //  Activate sun wind
            IsActive = true;

            m_smallBillboardsStarted = false;

            m_timeLastUpdate = MySandboxGame.TotalGamePlayTimeInMilliseconds;

            //  Place sun wind at farest possible negative Z position
            //Vector3 directionToSunNormalized = MyMwcUtils.Normalize(MyGuiScreenGameBase.Static.SunPosition - MyCamera.Position); MyMwcSectorGroups.Get(MyGuiScreenGameBase.Static.Sector.SectorGroup).GetDirectionToSunNormalized();
            Vector3D directionToSunNormalized = MySector.DirectionToSunNormalized;

            m_initialSunWindPosition     = /*MySession.Player.PlayerEntity.Entity.WorldMatrix.Translation +*/ directionToSunNormalized * MySunWindConstants.SUN_WIND_LENGTH_HALF / 2;
            m_directionFromSunNormalized = -directionToSunNormalized;

            //  Start the sound of burning (looping)
            StopCue();
            //m_burningCue = MyAudio.Static.AddCue3D(MySoundCuesEnum.SfxSolarWind, m_initialSunWindPosition, m_directionFromSunNormalized, Vector3.Up, Vector3.Zero);
            //MySounds.UpdateCuePitch(m_burningCue, MyMwcUtils.GetRandomFloat(-1, +1));

            m_speed = MyUtils.GetRandomFloat(MySunWindConstants.SPEED_MIN, MySunWindConstants.SPEED_MAX);

            m_strength = MyUtils.GetRandomFloat(0, 1);

            m_directionFromSunNormalized.CalculatePerpendicularVector(out m_rightVector);
            m_downVector = MyUtils.Normalize(Vector3D.Cross(m_directionFromSunNormalized, m_rightVector));

            StartBillboards();

            // Reinit computed max distances, they'll be computed in update
            m_computedMaxDistances = 0;

            m_deltaTime = 0;

            // Collect entities
            m_sunwindEntities.Clear();
            //foreach (var entity in MyEntities.GetEntities())
            //{
            //    /*if (!(entity is MySmallShip)) continue;

            //    // Do not move with indestructibles (NPCs etc)
            //    if (!entity.IsDestructible)
            //        continue;*/

            //    m_sunwindEntities.Add(entity);
            //}
        }
Exemplo n.º 27
0
        private MyNavmeshManager CreateManager(Vector3D center, Vector3D?forwardDirection = new Vector3D?())
        {
            if (forwardDirection == null)
            {
                Vector3D v = -Vector3D.Normalize(MyGravityProviderSystem.CalculateTotalGravityInPoint(center));
                forwardDirection = new Vector3D?(Vector3D.CalculatePerpendicularVector(v));
            }
            int tileSize          = 0x10;
            MyNavmeshManager item = new MyNavmeshManager(this, center, forwardDirection.Value, tileSize, 70, 0x19, this.GetRecastOptions(null))
            {
                DrawNavmesh = this.m_drawNavmesh
            };

            this.m_planetManagers[item.Planet].Add(item);
            return(item);
        }
Exemplo n.º 28
0
 public static void Start()
 {
     IsActive = true;
     m_smallBillboardsStarted     = false;
     m_timeLastUpdate             = MySandboxGame.TotalGamePlayTimeInMilliseconds;
     m_initialSunWindPosition     = (MySector.DirectionToSunNormalized * 30000.0) / 2.0;
     m_directionFromSunNormalized = -MySector.DirectionToSunNormalized;
     StopCue();
     m_speed    = MyUtils.GetRandomFloat(1300f, 1500f);
     m_strength = MyUtils.GetRandomFloat(0f, 1f);
     m_directionFromSunNormalized.CalculatePerpendicularVector(out m_rightVector);
     m_downVector = MyUtils.Normalize(Vector3D.Cross(m_directionFromSunNormalized, m_rightVector));
     StartBillboards();
     m_computedMaxDistances = 0;
     m_deltaTime            = 0f;
     m_sunwindEntities.Clear();
 }
Exemplo n.º 29
0
        public MyNavmeshManager(MyRDPathfinding rdPathfinding, Vector3D center, Vector3D forwardDirection, int tileSize, int tileHeight, int tileLineCount, MyRecastOptions recastOptions)
        {
            m_tileSize      = tileSize;
            m_tileHeight    = tileHeight;
            m_tileLineCount = tileLineCount;
            Planet          = GetPlanet(center);

            m_heightCoordTransformationIncrease = 0.5f;

            float cellSize = RECAST_CELL_SIZE;

            m_recastOptions = recastOptions;

            float horizontalOrigin = (m_tileSize * 0.5f + m_tileSize * (float)Math.Floor(m_tileLineCount * 0.5f));
            var   verticalOrigin   = m_tileHeight * 0.5f;

            m_border = m_recastOptions.agentRadius + 3 * cellSize;

            float[] bmin = new float[3] {
                -horizontalOrigin, -verticalOrigin, -horizontalOrigin
            };
            float[] bmax = new float[3] {
                horizontalOrigin, verticalOrigin, horizontalOrigin
            };

            m_rdWrapper = new MyRDWrapper();
            m_rdWrapper.Init(cellSize, m_tileSize, bmin, bmax);

            Vector3D gravityVector = -Vector3D.Normalize(GameSystems.MyGravityProviderSystem.CalculateTotalGravityInPoint(center));
            var      direction     = Vector3D.CalculatePerpendicularVector(gravityVector);

            m_navmeshOBBs   = new MyNavmeshOBBs(Planet, center, direction, m_tileLineCount, m_tileSize, m_tileHeight);
            m_debugTileSize = new int?[m_tileLineCount][];
            for (int i = 0; i < m_tileLineCount; i++)
            {
                m_debugTileSize[i] = new int?[m_tileLineCount];
            }

            m_extendedBaseOBB = new MyOrientedBoundingBoxD(m_navmeshOBBs.BaseOBB.Center,
                                                           new Vector3D(m_navmeshOBBs.BaseOBB.HalfExtent.X, m_tileHeight, m_navmeshOBBs.BaseOBB.HalfExtent.Z),
                                                           m_navmeshOBBs.BaseOBB.Orientation);

            m_navInputMesh = new MyNavigationInputMesh(rdPathfinding, Planet, center);
        }
Exemplo n.º 30
0
        public virtual void Start(Vector3D position, Vector3D initialVelocity, Vector3D direction, long owner)
        {
            System.Diagnostics.Debug.Assert(Closed);
            System.Diagnostics.Debug.Assert(this.EntityId == 0);

            Closed = false;
            GuidedInMultiplayer = false;

            this.EntityId = MyEntityIdentifier.AllocateId();

            m_isExploded            = false;
            m_cascadeExplosionLevel = 0;
            m_origin           = position + direction * m_ammoOffsetSize;
            m_previousPosition = m_origin;
            m_initialVelocity  = initialVelocity;

            m_elapsedMiliseconds = 0;
            MarkedToDestroy      = false;

            MatrixD ammoWorld = MatrixD.CreateWorld(m_origin, direction, Vector3D.CalculatePerpendicularVector(direction));

            PositionComp.SetWorldMatrix(ammoWorld);

            this.Physics.Clear();
            this.Physics.Enabled = true;

            MyEntities.Add(this);

            //if (owner.Physics != null)
            //    this.Physics.GroupMask = owner.Physics.GroupMask;
            //else
            //    this.Physics.GroupMask = MyGroupMask.Empty;

            //this.Physics.Enabled = true;

            this.Physics.LinearVelocity = initialVelocity;
            NeedsUpdate = MyEntityUpdateEnum.EACH_FRAME;

            //this.Physics.ApplyImpulse(direction * this.Physics.Mass * impulseMultiplier, position);
        }
Exemplo n.º 31
0
        //  This method will start sun wind. Or if there is one coming, this will reset it so it will start again.
        public static void Start()
        {
            //  Activate sun wind
            IsActive = true;

            m_smallBillboardsStarted = false;

            m_timeLastUpdate = MySandboxGame.TotalGamePlayTimeInMilliseconds;

            //  Place sun wind at farest possible negative Z position
            //Vector3 directionToSunNormalized = MyMwcUtils.Normalize(MyGuiScreenGameBase.Static.SunPosition - MyCamera.Position); MyMwcSectorGroups.Get(MyGuiScreenGameBase.Static.Sector.SectorGroup).GetDirectionToSunNormalized();
            Vector3D directionToSunNormalized = MySector.DirectionToSunNormalized;
            m_initialSunWindPosition = /*MySession.Static.Player.PlayerEntity.Entity.WorldMatrix.Translation +*/ directionToSunNormalized * MySunWindConstants.SUN_WIND_LENGTH_HALF / 2;
            m_directionFromSunNormalized = -directionToSunNormalized;

            //  Start the sound of burning (looping)
            StopCue();
            //m_burningCue = MyAudio.Static.AddCue3D(MySoundCuesEnum.SfxSolarWind, m_initialSunWindPosition, m_directionFromSunNormalized, Vector3.Up, Vector3.Zero);
            //MySounds.UpdateCuePitch(m_burningCue, MyMwcUtils.GetRandomFloat(-1, +1));

            m_speed = MyUtils.GetRandomFloat(MySunWindConstants.SPEED_MIN, MySunWindConstants.SPEED_MAX);

            m_strength = MyUtils.GetRandomFloat(0, 1);

            m_directionFromSunNormalized.CalculatePerpendicularVector(out m_rightVector);
            m_downVector = MyUtils.Normalize(Vector3D.Cross(m_directionFromSunNormalized, m_rightVector));

            StartBillboards();
            
            // Reinit computed max distances, they'll be computed in update
            m_computedMaxDistances = 0;

            m_deltaTime = 0;

            // Collect entities
            m_sunwindEntities.Clear();
            //foreach (var entity in MyEntities.GetEntities())
            //{
            //    /*if (!(entity is MySmallShip)) continue;

            //    // Do not move with indestructibles (NPCs etc)
            //    if (!entity.IsDestructible)
            //        continue;*/

            //    m_sunwindEntities.Add(entity);
            //}
        }