Пример #1
0
    public void Enable(Base6Directions.Direction direction, bool enable,
                       Func <IMyThrust, bool> collect = null)
    {
        var thrusterList = GetThrusters(direction, collect, true);

        thrusterList.ForEach(thruster => thruster.Enabled = enable);
    }
Пример #2
0
        public static bool getDirFromOri(MyBlockOrientation orientation, Base6Directions.Direction direction, out Base6Directions.Direction?result)
        {
            switch (direction)
            {
            case Base6Directions.Direction.Left:
                result = orientation.Left;
                break;

            case Base6Directions.Direction.Up:
                result = orientation.Up;
                break;

            case Base6Directions.Direction.Forward:
                result = orientation.Forward;
                break;

            case Base6Directions.Direction.Right:
                result = Base6Directions.GetFlippedDirection(orientation.Left);
                break;

            case Base6Directions.Direction.Down:
                result = Base6Directions.GetFlippedDirection(orientation.Up);
                break;

            case Base6Directions.Direction.Backward:
                result = Base6Directions.GetFlippedDirection(orientation.Forward);
                break;

            default:
                result = null;
                return(false);
            }
            return(true);
        }
 public void Start(float targetSpeed, Base6Directions.Direction forward, double targetAltDescending = 0, double targetAltAcending = double.MaxValue, bool useSealevel = false, bool disableOnNaturalGravityExit = true)
 {
     Enabled             = true;
     TargetSpeed         = targetSpeed;
     AdaptiveTargetSpeed = targetSpeed;
     if (forward == Base6Directions.Direction.Left)
     {
         Forward = autoForward;
     }
     else
     {
         Forward = forward;
     }
     //EnableThrusters(reverse, false);
     if (targetSpeed < 0)
     {
         descending = true;
     }
     else
     {
         descending = false;
     }
     if (useSealevel)
     {
         elevationType = MyPlanetElevation.Sealevel;
     }
     else
     {
         elevationType = MyPlanetElevation.Surface;
     }
     TargetAltAcending           = targetAltAcending;
     TargetAltDescending         = targetAltDescending;
     DisableOnNaturalGravityExit = disableOnNaturalGravityExit;
     startedInNaturalGravity     = controller.GetNaturalGravity().Length() > 0;
 }
Пример #4
0
    public void Init(ShipControlCommons shipControl,
                     Base6Directions.Direction shipUp = Base6Directions.Direction.Up,
                     Base6Directions.Direction shipForward = Base6Directions.Direction.Forward)
    {
        ShipForward = shipForward;
        ShipUp = shipUp;
        ShipLeft = Base6Directions.GetLeft(ShipUp, ShipForward);

        var small = shipControl.Reference.CubeGrid.GridSize == 0.5f;

        yawPID.Kp = small ? SmallGyroKp : LargeGyroKp;
        yawPID.Ti = small ? SmallGyroTi : LargeGyroTi;
        yawPID.Td = small ? SmallGyroTd : LargeGyroTd;

        pitchPID.Kp = small ? SmallGyroKp : LargeGyroKp;
        pitchPID.Ti = small ? SmallGyroTi : LargeGyroTi;
        pitchPID.Td = small ? SmallGyroTd : LargeGyroTd;

        rollPID.Kp = small ? SmallGyroKp : LargeGyroKp;
        rollPID.Ti = small ? SmallGyroTi : LargeGyroTi;
        rollPID.Td = small ? SmallGyroTd : LargeGyroTd;

        yawPID.Reset();
        pitchPID.Reset();
        rollPID.Reset();
    }
Пример #5
0
 /// <summary>
 /// Adds Gravity Generator to list of Generators
 /// </summary>
 /// <param name="generator"></param>
 public void AddGenerator(IMyGravityGenerator generator)
 {
     grav.Add(generator);
     Base6Directions.Direction direction = core.Orientation.TransformDirectionInverse(generator.Orientation.Up); //transforms the "Up" direction of the generator into the direction of the corridor coordinates
     gravDirections.Add(direction);
     numberOfGeneratorsInDirection[((int)Base6Directions.GetAxis(direction) + 2) % 3]++;
 }
 internal Launcher(IMySmallMissileLauncher b, int timer, int offset)
 {
     tube        = b;
     cooldown    = timer;
     this.offset = offset;
     direction   = b.Orientation.Forward;
 }
Пример #7
0
    private Vector3D GetReferenceVector(ShipControlCommons shipControl,
                                        Base6Directions.Direction direction)
    {
        var offset = shipControl.Reference.Position + Base6Directions.GetIntVector(direction);

        return(Vector3D.Normalize(shipControl.Reference.CubeGrid.GridIntegerToWorld(offset) - shipControl.ReferencePoint));
    }
Пример #8
0
        /// <summary>
        /// Gets the closest face direction to worldDirection.
        /// </summary>
        public static Base6Directions.Direction ClosestFaceDirection(this IMyCubeBlock block, Vector3 worldDirection)
        {
            IEnumerable <Base6Directions.Direction> faceDirections = FaceDirections(block);

            worldDirection.Normalize();
            Base6Directions.Direction bestDirection = (Base6Directions.Direction) 255;
            double bestDirectionAngle = double.MinValue;

            foreach (Base6Directions.Direction direction in faceDirections)
            {
                Vector3 directionVector = block.WorldMatrix.GetDirectionVector(direction);
                double  cosAngle        = directionVector.Dot(worldDirection);

                //Log.DebugLog(cosAngle < -1 || cosAngle > 1, "cosAngle out of bounds: " + cosAngle, "GetFaceDirection()", Logger.severity.ERROR); // sometimes values are slightly out of range
                Logger.DebugLog("cosAngle invalid", Logger.severity.ERROR, condition: double.IsNaN(cosAngle) || double.IsInfinity(cosAngle));

                if (cosAngle > bestDirectionAngle)
                {
                    //Log.DebugLog("angle: " + angle + ", bestDirectionAngle: " + bestDirectionAngle + ", direction: " + direction, "GetFaceDirection()");
                    bestDirection      = direction;
                    bestDirectionAngle = cosAngle;
                }
            }

            if (bestDirectionAngle == double.MinValue)
            {
                throw new NullReferenceException("bestDirection");
            }

            return(bestDirection);
        }
Пример #9
0
 public MatrixI(Vector3I position, Base6Directions.Direction forward, Base6Directions.Direction up)
 {
     Translation = position;
     Right       = Base6Directions.GetFlippedDirection(Base6Directions.GetLeft(up, forward));
     Up          = up;
     Backward    = Base6Directions.GetFlippedDirection(forward);
 }
Пример #10
0
 bool sameThrusterDirection(Base6Directions.Direction orientation) =>
 (orientation == Base6Directions.Direction.Up && ((thrusterDirection_ & ThrusterDirection.Lower) != 0)) ||
 (orientation == Base6Directions.Direction.Down && ((thrusterDirection_ & ThrusterDirection.Lift) != 0)) ||
 (orientation == Base6Directions.Direction.Left && ((thrusterDirection_ & ThrusterDirection.Right) != 0)) ||
 (orientation == Base6Directions.Direction.Right && ((thrusterDirection_ & ThrusterDirection.Left) != 0)) ||
 (orientation == Base6Directions.Direction.Forward && ((thrusterDirection_ & ThrusterDirection.Break) != 0)) ||
 (orientation == Base6Directions.Direction.Backward && ((thrusterDirection_ & ThrusterDirection.Accelerate) != 0));
Пример #11
0
        private void SetAxisDetails(IMyGyro gyro, int axis,
                                    Base6Directions.Direction axisDirection)
        {
            switch (gyro.Orientation.TransformDirectionInverse(axisDirection))
            {
            case Base6Directions.Direction.Up:
                AxisDetails[axis] = new GyroAxisDetails(Yaw, -1);
                break;

            case Base6Directions.Direction.Down:
                AxisDetails[axis] = new GyroAxisDetails(Yaw, 1);
                break;

            case Base6Directions.Direction.Left:
                AxisDetails[axis] = new GyroAxisDetails(Pitch, -1);
                break;

            case Base6Directions.Direction.Right:
                AxisDetails[axis] = new GyroAxisDetails(Pitch, 1);
                break;

            case Base6Directions.Direction.Forward:
                AxisDetails[axis] = new GyroAxisDetails(Roll, 1);
                break;

            case Base6Directions.Direction.Backward:
                AxisDetails[axis] = new GyroAxisDetails(Roll, -1);
                break;
            }
        }
Пример #12
0
 void GetAxisAndDir(Base6Directions.Direction RefDir, out string Axis, out float sign)
 {
     Axis = "Yaw";
     sign = -1.0f;
     if (Base6Directions.GetAxis(YawAxisDir) == Base6Directions.GetAxis(RefDir))
     {
         if (YawAxisDir == RefDir)
         {
             sign = 1.0f;
         }
     }
     if (Base6Directions.GetAxis(PitchAxisDir) == Base6Directions.GetAxis(RefDir))
     {
         Axis = "Pitch";
         if (PitchAxisDir == RefDir)
         {
             sign = 1.0f;
         }
     }
     if (Base6Directions.GetAxis(RollAxisDir) == Base6Directions.GetAxis(RefDir))
     {
         Axis = "Roll";
         if (RollAxisDir == RefDir)
         {
         }
         else
         {
             sign = 1.0f;
         }
     }
 }
Пример #13
0
        private void LoadDummies()
        {
            var finalModel = VRage.Game.Models.MyModels.GetModelOnlyDummies(BlockDefinition.Model);

            foreach (var dummy in finalModel.Dummies)
            {
                if (dummy.Key.ToLower().Contains("merge"))
                {
                    var     matrix      = dummy.Value.Matrix;
                    Vector3 halfExtents = matrix.Scale / 2.0f;

                    Vector3 projectedPosition = Vector3.DominantAxisProjection(matrix.Translation / halfExtents);
                    projectedPosition.Normalize();
                    m_forward = Base6Directions.GetDirection(projectedPosition);
                    m_right   = Base6Directions.GetPerpendicular(m_forward);

                    var world = MatrixD.Normalize(matrix) * this.WorldMatrix;

                    var detectorShape = CreateFieldShape(halfExtents);
                    Physics           = new Sandbox.Engine.Physics.MyPhysicsBody(this, RigidBodyFlag.RBF_STATIC);
                    Physics.IsPhantom = true;
                    Physics.CreateFromCollisionObject(detectorShape, matrix.Translation, world, null, MyPhysics.CollisionLayers.ObjectDetectionCollisionLayer);
                    Physics.Enabled = IsWorking;
                    Physics.RigidBody.ContactPointCallbackEnabled = true;
                    detectorShape.Base.RemoveReference();

                    break;
                }
            }
        }
Пример #14
0
        /// <summary>
        /// gets the local position
        /// </summary>
        public Vector3 getLocal()
        {
            if (value__grid != null)
            {
                return((Vector3)value__grid);
            }

            if (value__world != null || value__worldAbsolute != null)
            {
                // create from world
                Vector3I gridInt = cubeGrid.WorldToGridInteger(getWorld() * precisionMultiplier + cubeGrid.GetPosition());
                value__grid = (gridInt * cubeGrid.GridSize) / precisionMultiplier;
                return((Vector3)value__grid);
            }

            // create from block
            // create from block
            // orient according to block
            Vector3D resultant     = Vector3D.Zero;
            Vector3D blockRelative = (Vector3D)value__block;

            Base6Directions.Direction RCdirection = cubeBlock.Orientation.Left;
            resultant  -= (Vector3D)Base6Directions.GetVector(RCdirection) * blockRelative.X;
            RCdirection = cubeBlock.Orientation.Up;
            resultant  += (Vector3D)Base6Directions.GetVector(RCdirection) * blockRelative.Y;
            RCdirection = cubeBlock.Orientation.Forward;
            resultant  -= (Vector3D)Base6Directions.GetVector(RCdirection) * blockRelative.Z;

            // add block position
            value__grid = resultant + cubeBlock.Position * cubeGrid.GridSize;
            return((Vector3D)value__grid);
        }
Пример #15
0
    public List <IMyThrust> GetThrusters(Base6Directions.Direction direction,
                                         Func <IMyThrust, bool> collect = null,
                                         bool disable = false)
    {
        List <IMyThrust> thrusterList;

        if (!thrusters.TryGetValue(direction, out thrusterList))
        {
            thrusterList = new List <IMyThrust>();
            thrusters.Add(direction, thrusterList);
        }
        if (collect == null)
        {
            return(thrusterList);
        }
        else
        {
            var result = new List <IMyThrust>();
            foreach (var thruster in thrusterList)
            {
                if (collect(thruster))
                {
                    result.Add(thruster);
                }
                else if (disable)
                {
                    thruster.Enabled = false;
                }
            }
            return(result);
        }
    }
Пример #16
0
        public void SetDirection(Base6Directions.Direction dirToSet, Base6Directions.Direction newDirection)
        {
            switch (dirToSet)
            {
            case Base6Directions.Direction.Right:
                Right = newDirection;
                break;

            case Base6Directions.Direction.Left:
                Left = newDirection;
                break;

            case Base6Directions.Direction.Up:
                Up = newDirection;
                break;

            case Base6Directions.Direction.Down:
                Down = newDirection;
                break;

            case Base6Directions.Direction.Backward:
                Backward = newDirection;
                break;

            case Base6Directions.Direction.Forward:
                Forward = newDirection;
                break;
            }
        }
Пример #17
0
    public void Init(ZACommons commons, EventDriver eventDriver,
                     double maxError,
                     Base6Directions.Direction thrusterDirection = Base6Directions.Direction.Forward)
    {
        MaxError          = maxError;
        ThrusterDirection = thrusterDirection;

        var shipControl = (ShipControlCommons)commons;

        var forward = shipControl.ShipBlockOrientation.TransformDirection(ThrusterDirection);

        // Don't really care about "up," just pick a perpindicular direction
        seeker.Init(shipControl,
                    shipUp: Base6Directions.GetPerpendicular(forward),
                    shipForward: forward);

        var gyroControl = shipControl.GyroControl;

        gyroControl.Reset();
        gyroControl.EnableOverride(true);

        LastPosition = shipControl.ReferencePoint;

        Enabled = true;

        shipControl.ThrustControl.Enable(false);

        eventDriver.Schedule(SampleDelay, DetermineVelocity);
    }
        /// <summary>
        /// Converts the given block with the given matrix for static grid.
        /// </summary>
        private static void ConvertRotatedGridBlockToStatic(ref MatrixI transform, MyObjectBuilder_CubeBlock origBlock)
        {
            MyDefinitionId        defId = new MyDefinitionId(origBlock.TypeId, origBlock.SubtypeName);
            MyCubeBlockDefinition blockDefinition;

            MyDefinitionManager.Static.TryGetCubeBlockDefinition(defId, out blockDefinition);
            if (blockDefinition == null)
            {
                return;
            }

            // Orientation quaternion is not setup in origblock
            MyBlockOrientation origOrientation = origBlock.BlockOrientation;
            Vector3I           origMin         = origBlock.Min;
            Vector3I           origMax;

            MySlimBlock.ComputeMax(blockDefinition, origOrientation, ref origMin, out origMax);

            Vector3I tMin;
            Vector3I tMax;

            Vector3I.Transform(ref origMin, ref transform, out tMin);
            Vector3I.Transform(ref origMax, ref transform, out tMax);
            Base6Directions.Direction forward = transform.GetDirection(origOrientation.Forward);
            Base6Directions.Direction up      = transform.GetDirection(origOrientation.Up);

            // Write data
            MyBlockOrientation newBlockOrientation = new MyBlockOrientation(forward, up);
            Quaternion         rotationQuat;

            newBlockOrientation.GetQuaternion(out rotationQuat);
            origBlock.Orientation = rotationQuat;
            origBlock.Min         = Vector3I.Min(tMin, tMax);
        }
Пример #19
0
        /// <summary>
        /// Add or remove a thruster from thrustProfile, if appropriate.
        /// </summary>
        private void enableDisableThruster(ThrusterProperties properties, bool enable)
        {
            if (properties.isEnabled == enable)
            {
                if (enable)
                {
                    log("already enabled. " + properties, "enableDisableThruster()", Logger.severity.DEBUG);
                }
                else
                {
                    log("already disabled. " + properties, "enableDisableThruster()", Logger.severity.DEBUG);
                }
                return;
            }
            properties.isEnabled = enable;

            float change = properties.forceDamping;

            Base6Directions.Direction direction = properties.forceDirect;

            if (!enable)
            {
                change = -change;
            }

            thrustProfile[direction] += change;
            //log("thrust power change = " + change + ", total power = " + thrustProfile[direction] + ", direction = " + direction, "enableDisableThruster()", Logger.severity.TRACE);
        }
        /// <summary>
        /// Converts the given grid to static with the world matrix. Instead of grid (which must have identity rotation for static grid) we transform blocks in the grid.
        /// </summary>
        /// <param name="originalGrid">grid to be transformed</param>
        /// <param name="worldMatrix">target world transform</param>
        private static void ConvertGridBuilderToStatic(MyObjectBuilder_CubeGrid originalGrid, MatrixD worldMatrix)
        {
            originalGrid.IsStatic = true;
            originalGrid.PositionAndOrientation = new MyPositionAndOrientation(originalGrid.PositionAndOrientation.Value.Position, Vector3.Forward, Vector3.Up);

            Vector3 fw = (Vector3)worldMatrix.Forward;
            Vector3 up = (Vector3)worldMatrix.Up;

            Base6Directions.Direction fwDir = Base6Directions.GetClosestDirection(fw);
            Base6Directions.Direction upDir = Base6Directions.GetClosestDirection(up);
            if (upDir == fwDir)
            {
                upDir = Base6Directions.GetPerpendicular(fwDir);
            }
            MatrixI transform = new MatrixI(Vector3I.Zero, fwDir, upDir);

            // Blocks in static grid - must be recreated for static grid with different orientation and position
            foreach (var origBlock in originalGrid.CubeBlocks)
            {
                if (origBlock is MyObjectBuilder_CompoundCubeBlock)
                {
                    var origBlockCompound = origBlock as MyObjectBuilder_CompoundCubeBlock;
                    ConvertRotatedGridCompoundBlockToStatic(ref transform, origBlockCompound);
                    for (int i = 0; i < origBlockCompound.Blocks.Length; ++i)
                    {
                        var origBlockInCompound = origBlockCompound.Blocks[i];
                        ConvertRotatedGridBlockToStatic(ref transform, origBlockInCompound);
                    }
                }
                else
                {
                    ConvertRotatedGridBlockToStatic(ref transform, origBlock);
                }
            }
        }
Пример #21
0
    public void Init(ShipControlCommons shipControl,
                     Base6Directions.Direction shipUp      = Base6Directions.Direction.Up,
                     Base6Directions.Direction shipForward = Base6Directions.Direction.Forward)
    {
        ShipForward = shipForward;
        ShipUp      = shipUp;
        ShipLeft    = Base6Directions.GetLeft(ShipUp, ShipForward);

        var small = shipControl.Reference.CubeGrid.GridSize == 0.5f;

        yawPID.Kp = small ? SmallGyroKp : LargeGyroKp;
        yawPID.Ti = small ? SmallGyroTi : LargeGyroTi;
        yawPID.Td = small ? SmallGyroTd : LargeGyroTd;

        pitchPID.Kp = small ? SmallGyroKp : LargeGyroKp;
        pitchPID.Ti = small ? SmallGyroTi : LargeGyroTi;
        pitchPID.Td = small ? SmallGyroTd : LargeGyroTd;

        rollPID.Kp = small ? SmallGyroKp : LargeGyroKp;
        rollPID.Ti = small ? SmallGyroTi : LargeGyroTi;
        rollPID.Td = small ? SmallGyroTd : LargeGyroTd;

        yawPID.Reset();
        pitchPID.Reset();
        rollPID.Reset();
    }
Пример #22
0
            public ThrusterGroup(Program _parent_program, Base6Directions.Direction direction,
                                 IMyTerminalBlock _directionReferenceBlock)
            {
                parent_program          = _parent_program;
                directionReferenceBlock = _directionReferenceBlock;
                thrusters            = new List <IMyThrust>();
                MaxThrust            = 0;
                LocalThrustDirection = direction;
                UpdateWorldDirection();
                ANS = new double[3];
                finalThrustForces   = new Vector3D();
                finalThrusterGroups = new ThrusterGroup[6];
                matrixM             = new double[3, 3];

                if (LocalThrustDirection == Base6Directions.Direction.Down ||
                    LocalThrustDirection == Base6Directions.Direction.Right ||
                    LocalThrustDirection == Base6Directions.Direction.Backward)
                {
                    directionSign = -1;
                }
                else
                {
                    directionSign = 1;
                }
            }
Пример #23
0
        public void SetDirectionVector(Base6Directions.Direction direction, Vector3 newValue)
        {
            switch (direction)
            {
            case Base6Directions.Direction.Forward:
                this.Forward = newValue;
                return;

            case Base6Directions.Direction.Backward:
                this.Backward = newValue;
                return;

            case Base6Directions.Direction.Left:
                this.Left = newValue;
                return;

            case Base6Directions.Direction.Right:
                this.Right = newValue;
                return;

            case Base6Directions.Direction.Up:
                this.Up = newValue;
                return;

            case Base6Directions.Direction.Down:
                this.Down = newValue;
                return;
            }
        }
Пример #24
0
 public Base6Directions.Direction TransformDirectionInverse(Base6Directions.Direction baseDirection)
 {
     Base6Directions.Axis axis = Base6Directions.GetAxis(baseDirection);
     if (axis == Base6Directions.GetAxis(this.Forward))
     {
         if (baseDirection != this.Forward)
         {
             return(Base6Directions.Direction.Backward);
         }
         return(Base6Directions.Direction.Forward);
     }
     if (axis == Base6Directions.GetAxis(this.Left))
     {
         if (baseDirection != this.Left)
         {
             return(Base6Directions.Direction.Right);
         }
         return(Base6Directions.Direction.Left);
     }
     if (baseDirection != this.Up)
     {
         return(Base6Directions.Direction.Down);
     }
     return(Base6Directions.Direction.Up);
 }
Пример #25
0
            public static Vector3D GetDirection(MatrixD m, string dirStr)
            {
                Base6Directions.Direction d = GetDirection(dirStr);
                string   upperDir           = dirStr == null ? "F" : dirStr.ToUpper();
                Vector3D r;

                switch (d)
                {
                case Base6Directions.Direction.Backward:
                    r = m.Backward;
                    break;

                case Base6Directions.Direction.Up:
                    r = m.Up;
                    break;

                case Base6Directions.Direction.Down:
                    r = m.Down;
                    break;

                case Base6Directions.Direction.Left:
                    r = m.Left;
                    break;

                case Base6Directions.Direction.Right:
                    r = m.Right;
                    break;

                case Base6Directions.Direction.Forward:
                default:
                    r = m.Forward;
                    break;
                }
                return(r);
            }
Пример #26
0
        public Base6Directions.Direction TransformDirection(Base6Directions.Direction baseDirection)
        {
            Base6Directions.Axis axis = Base6Directions.GetAxis(baseDirection);
            int num = (int)(baseDirection % Base6Directions.Direction.Left);

            switch (axis)
            {
            case Base6Directions.Axis.ForwardBackward:
                if (num != 1)
                {
                    return(this.Forward);
                }
                return(Base6Directions.GetFlippedDirection(this.Forward));

            case Base6Directions.Axis.LeftRight:
                if (num != 1)
                {
                    return(this.Left);
                }
                return(Base6Directions.GetFlippedDirection(this.Left));
            }
            if (num != 1)
            {
                return(this.Up);
            }
            return(Base6Directions.GetFlippedDirection(this.Up));
        }
        private void EraseFaceTriangles(Vector3I pos, Base6Directions.Direction direction)
        {
            m_tmpTriangleList.Clear();

            Vector3I directionVec = Base6Directions.GetIntVector((int)direction);

            List <int> triList = null;

            if (m_smallTriangleRegistry.TryGetValue(pos, out triList))
            {
                foreach (var index in triList)
                {
                    var triangle = GetTriangle(index);
                    if (IsFaceTriangle(triangle, pos, directionVec))
                    {
                        m_tmpTriangleList.Add(new KeyValuePair <MyNavigationTriangle, Vector3I>(triangle, pos));
                    }
                }
            }

            foreach (var triangle in m_tmpTriangleList)
            {
                RemoveTriangle(triangle.Key, triangle.Value);
            }
            m_tmpTriangleList.Clear();
        }
Пример #28
0
    public List <IMyThrust> GetThrusters(Base6Directions.Direction direction,
                                         Func <IMyThrust, bool> collect = null,
                                         bool disable = false)
    {
        List <IMyThrust> thrusterList;

        if (!thrusters.TryGetValue(direction, out thrusterList))
        {
            thrusterList = new List <IMyThrust>();
            thrusters.Add(direction, thrusterList);
        }
        if (collect == null)
        {
            return(thrusterList);
        }
        else
        {
            var result = new List <IMyThrust>();
            for (var e = thrusterList.GetEnumerator(); e.MoveNext();)
            {
                var thruster = (IMyThrust)e.Current;
                if (collect(thruster))
                {
                    result.Add(thruster);
                }
                else if (disable)
                {
                    thruster.SetValue <bool>("OnOff", false);
                }
            }
            return(result);
        }
    }
Пример #29
0
    public void Init(ZACommons commons, EventDriver eventDriver,
                     double maxError,
                     Base6Directions.Direction thrusterDirection = Base6Directions.Direction.Forward)
    {
        MaxError = maxError;
        ThrusterDirection = thrusterDirection;
        
        var shipControl = (ShipControlCommons)commons;

        var forward = shipControl.ShipBlockOrientation.TransformDirection(ThrusterDirection);
        // Don't really care about "up," just pick a perpindicular direction
        seeker.Init(shipControl,
                    shipUp: Base6Directions.GetPerpendicular(forward),
                    shipForward: forward);

        var gyroControl = shipControl.GyroControl;
        gyroControl.Reset();
        gyroControl.EnableOverride(true);

        LastPosition = shipControl.ReferencePoint;

        Enabled = true;

        shipControl.ThrustControl.Enable(false);

        eventDriver.Schedule(SampleDelay, DetermineVelocity);
    }
Пример #30
0
            public void SetYawPitchRoll(float yaw, float pitch, float roll)
            {
                for (int i = 0; i < Gyros.Count; i++)
                {
                    string  Axis;
                    float   sign;
                    Vector3 RotatedVector = Base6Directions.GetVector(Forward);
                    Vector3.TransformNormal(ref RotatedVector, Gyros[i].Orientation, out RotatedVector);
                    RollAxisDir   = Base6Directions.GetDirection(ref RotatedVector);
                    RotatedVector = Base6Directions.GetVector(Left);
                    Vector3.TransformNormal(ref RotatedVector, Gyros[i].Orientation, out RotatedVector);
                    PitchAxisDir  = Base6Directions.GetDirection(ref RotatedVector);
                    RotatedVector = Base6Directions.GetVector(Up);
                    Vector3.TransformNormal(ref RotatedVector, Gyros[i].Orientation, out RotatedVector);
                    YawAxisDir = Base6Directions.GetDirection(ref RotatedVector);
                    GetAxisAndDir(RefUp, out Axis, out sign);
                    SetAxis(Gyros[i], Axis, sign * yaw);
//                    Gyros[i].SetValueFloat(Axis, sign * yaw);

                    GetAxisAndDir(RefLeft, out Axis, out sign);
                    SetAxis(Gyros[i], Axis, sign * pitch);
//                    Gyros[i].SetValueFloat(Axis, sign * pitch);

                    GetAxisAndDir(RefForward, out Axis, out sign);
                    SetAxis(Gyros[i], Axis, sign * roll);
//                    Gyros[i].SetValueFloat(Axis, sign * roll);
                }
            }
Пример #31
0
        private bool IsRotationValid(MyBlockOrientation refOrientation, MyBlockOrientation orientation, MyBlockOrientation[] validRotations)
        {
            Debug.Assert(validRotations != null);

            // Ref matrix
            MatrixI localMatrix = new MatrixI(Vector3I.Zero, refOrientation.Forward, refOrientation.Up);
            MatrixI inverseMatrix;

            MatrixI.Invert(ref localMatrix, out inverseMatrix);
            Matrix inverseMatrixF = inverseMatrix.GetFloatMatrix();

            // Transform orientation to ref
            Base6Directions.Direction forward = Base6Directions.GetClosestDirection(Vector3.TransformNormal((Vector3)Base6Directions.GetIntVector(orientation.Forward), inverseMatrixF));
            Base6Directions.Direction up      = Base6Directions.GetClosestDirection(Vector3.TransformNormal((Vector3)Base6Directions.GetIntVector(orientation.Up), inverseMatrixF));

            foreach (var validRotation in validRotations)
            {
                if (validRotation.Forward == forward && validRotation.Up == up)
                {
                    return(true);
                }
            }

            return(false);
        }
Пример #32
0
        private void CreateConstraint(MyCubeGrid other, MyShipMergeBlock block)
        {
            var data = new HkPrismaticConstraintData();

            data.MaximumLinearLimit = 0;
            data.MinimumLinearLimit = 0;
            var posA      = ConstraintPositionInGridSpace();
            var posB      = block.ConstraintPositionInGridSpace();
            var axisA     = PositionComp.LocalMatrix.GetDirectionVector(m_forward);
            var axisAPerp = PositionComp.LocalMatrix.GetDirectionVector(m_right);
            var axisB     = -block.PositionComp.LocalMatrix.GetDirectionVector(m_forward);

            Base6Directions.Direction thisRightForOther = block.WorldMatrix.GetClosestDirection(WorldMatrix.GetDirectionVector(m_right));
            Base6Directions.Direction otherRight        = WorldMatrix.GetClosestDirection(block.WorldMatrix.GetDirectionVector(block.m_right));

            var axisBPerp = block.PositionComp.LocalMatrix.GetDirectionVector(thisRightForOther);

            data.SetInBodySpace(posA, posB, axisA, axisB, axisAPerp, axisBPerp, CubeGrid.Physics, other.Physics);
            var data2 = new HkMalleableConstraintData();

            data2.SetData(data);
            data.ClearHandle();
            data           = null;
            data2.Strength = 0.00001f;

            var constraint = new HkConstraint(CubeGrid.Physics.RigidBody, other.Physics.RigidBody, data2);

            AddConstraint(constraint);

            SetConstraint(block, constraint, otherRight);
            m_other.SetConstraint(this, constraint, thisRightForOther);
        }
Пример #33
0
    public void Init(ShipControlCommons shipControl,
                     Base6Directions.Direction localForward = Base6Directions.Direction.Forward)
    {
        LocalForward = localForward;
        LocalBackward = Base6Directions.GetFlippedDirection(LocalForward);

        thrustPID.Reset();
    }
Пример #34
0
        public void SetLocalPosition(Vector3I sectionStart, int sectionStartPosition, float cubeSize, Base6Directions.Direction forward, Base6Directions.Direction offset)
        {
            int segmentPosition = LinePosition - sectionStartPosition;

            Matrix localMatrix = PositionComp.LocalMatrix;
            Vector3 offsetVector = PositionComp.LocalMatrix.GetDirectionVector(forward) * segmentPosition + PositionComp.LocalMatrix.GetDirectionVector(offset) * 0.10f;
            localMatrix.Translation = (sectionStart + offsetVector / PositionComp.Scale.Value) * cubeSize;
            PositionComp.LocalMatrix = localMatrix;

            m_segmentDirection = forward;
        }
Пример #35
0
 public void Init(ZACommons commons, EventDriver eventDriver,
                  Vector3D target, double speed,
                  double delay = 1.0,
                  Action<ZACommons, EventDriver> doneAction = null,
                  Base6Directions.Direction localForward = Base6Directions.Direction.Forward)
 {
     if (!AutopilotEngaged)
     {
         AutopilotTarget = target;
         AutopilotSpeed = speed;
         AutopilotEngaged = true;
         DoneAction = doneAction;
         LocalForward = localForward;
         eventDriver.Schedule(delay, Start);
     }
 }
Пример #36
0
 public void SetDirection(Base6Directions.Direction dirToSet, Base6Directions.Direction newDirection)
 {
     switch (dirToSet)
     {
         case Base6Directions.Direction.Right:
             Right = newDirection;
             break;
         case Base6Directions.Direction.Left:
             Left = newDirection;
             break;
         case Base6Directions.Direction.Up:
             Up = newDirection;
             break;
         case Base6Directions.Direction.Down:
             Down = newDirection;
             break;
         case Base6Directions.Direction.Backward:
             Backward = newDirection;
             break;
         case Base6Directions.Direction.Forward:
             Forward = newDirection;
             break;
     }
 }
Пример #37
0
        private void OnPasteAutopilotSetup(MyObjectBuilder_AutopilotClipboard clipboard)
        {
            m_currentDirection = (Base6Directions.Direction)clipboard.Direction;
            m_currentFlightMode = (FlightMode)clipboard.FlightMode;
            m_dockingModeEnabled = clipboard.DockingModeEnabled;
            if (clipboard.Waypoints != null)
            {
                m_waypoints = new List<MyAutopilotWaypoint>(clipboard.Waypoints.Count);
                foreach (var waypoint in clipboard.Waypoints)
                {
                    if (waypoint.Actions != null)
                    {
                        foreach (var action in waypoint.Actions)
                        {
                            var blockAction = action as MyObjectBuilder_ToolbarItemTerminalBlock;
                            //Swith from old entity to the new one
                            if (blockAction != null && blockAction.BlockEntityId == clipboard.RemoteEntityId)
                            {
                                blockAction.BlockEntityId = EntityId;
                            }
                        }
                    }
                    m_waypoints.Add(new MyAutopilotWaypoint(waypoint, this));
                }
            }

            m_selectedWaypoints.Clear();

            RaisePropertiesChangedRemote();
        }
Пример #38
0
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            SyncFlag = true;
            base.Init(objectBuilder, cubeGrid);
            NeedsUpdate = MyEntityUpdateEnum.BEFORE_NEXT_FRAME | MyEntityUpdateEnum.EACH_FRAME | MyEntityUpdateEnum.EACH_10TH_FRAME;

            var remoteOb = (MyObjectBuilder_RemoteControl)objectBuilder;
            m_savedPreviousControlledEntityId = remoteOb.PreviousControlledEntityId;


            PowerReceiver = new MyPowerReceiver(
                MyConsumerGroupEnum.Utility,
                false,
                m_powerNeeded,
                this.CalculateRequiredPowerInput);

            PowerReceiver.IsPoweredChanged += Receiver_IsPoweredChanged;
            PowerReceiver.RequiredInputChanged += Receiver_RequiredInputChanged;
            PowerReceiver.Update();

            m_autoPilotEnabled = remoteOb.AutoPilotEnabled;
            m_dockingModeEnabled = remoteOb.DockingModeEnabled;
            m_currentFlightMode = (FlightMode)remoteOb.FlightMode;
            m_currentDirection = (Base6Directions.Direction)remoteOb.Direction;

            if (remoteOb.Coords == null || remoteOb.Coords.Count == 0)
            {
                if (remoteOb.Waypoints == null)
                {
                    m_waypoints = new List<MyAutopilotWaypoint>();
                    CurrentWaypoint = null;
                }
                else
                {
                    m_waypoints = new List<MyAutopilotWaypoint>(remoteOb.Waypoints.Count);
                    for (int i = 0; i < remoteOb.Waypoints.Count; i++)
                    {
                        m_waypoints.Add(new MyAutopilotWaypoint(remoteOb.Waypoints[i], this));
                    }
                }
            }
            else
            {
                m_waypoints = new List<MyAutopilotWaypoint>(remoteOb.Coords.Count);
                for (int i = 0; i < remoteOb.Coords.Count; i++)
                {
                    m_waypoints.Add(new MyAutopilotWaypoint(remoteOb.Coords[i], remoteOb.Names[i], this));
                }

                if (remoteOb.AutoPilotToolbar != null && m_currentFlightMode == FlightMode.OneWay)
                {
                    m_waypoints[m_waypoints.Count - 1].SetActions(remoteOb.AutoPilotToolbar.Slots);
                }
            }

            if (remoteOb.CurrentWaypointIndex == -1 || remoteOb.CurrentWaypointIndex >= m_waypoints.Count)
            {
                CurrentWaypoint = null;
            }
            else
            {
                CurrentWaypoint = m_waypoints[remoteOb.CurrentWaypointIndex];
            }

            m_actionToolbar = new MyToolbar(MyToolbarType.ButtonPanel, pageCount: 1);
            m_actionToolbar.DrawNumbers = false;
            m_actionToolbar.Init(null, this);

            m_selectedGpsLocations = new List<IMyGps>();
            m_selectedWaypoints = new List<MyAutopilotWaypoint>();
            UpdateText();
        }
Пример #39
0
        protected void SetConstraint(MyShipMergeBlock otherBlock, HkConstraint constraint, Base6Directions.Direction otherRight)
        {
            Debug.Assert(m_constraint == null && m_other == null);
            if (m_constraint != null || m_other != null) return;

            m_constraint = constraint;
            m_other = otherBlock;
            m_otherRight = otherRight;
            CheckEmissivity();

            NeedsUpdate |= MyEntityUpdateEnum.EACH_FRAME;
        }
Пример #40
0
        private void LoadDummies()
        {
            var finalModel = VRage.Game.Models.MyModels.GetModelOnlyDummies(BlockDefinition.Model);
            foreach (var dummy in finalModel.Dummies)
            {
                if (dummy.Key.ToLower().Contains("merge"))
                {
                    var matrix = dummy.Value.Matrix;
                    Vector3 halfExtents = matrix.Scale / 2.0f;

                    Vector3 projectedPosition = Vector3.DominantAxisProjection(matrix.Translation / halfExtents);
                    projectedPosition.Normalize();
                    m_forward = Base6Directions.GetDirection(projectedPosition);
                    m_right = Base6Directions.GetPerpendicular(m_forward);

                    var world = MatrixD.Normalize(matrix) * this.WorldMatrix;

                    var detectorShape = CreateFieldShape(halfExtents);
                    Physics = new Sandbox.Engine.Physics.MyPhysicsBody(this, RigidBodyFlag.RBF_STATIC);
                    Physics.IsPhantom = true;
                    Physics.CreateFromCollisionObject(detectorShape, matrix.Translation, world, null, MyPhysics.CollisionLayers.ObjectDetectionCollisionLayer);
                    Physics.Enabled = IsWorking;
                    Physics.RigidBody.ContactPointCallbackEnabled = true;
                    detectorShape.Base.RemoveReference();

                    break;
                }
            }
        }
Пример #41
0
 private void OnChangeDirection(Base6Directions.Direction direction)
 {
     m_currentDirection = direction;
     RaisePropertiesChangedRemote();
 }
Пример #42
0
 public MatrixI(Vector3I position, Base6Directions.Direction forward, Base6Directions.Direction up)
 {
     Translation = position;
     Right = Base6Directions.GetFlippedDirection(Base6Directions.GetLeft(up, forward));
     Up = up;
     Backward = Base6Directions.GetFlippedDirection(forward);
 }
 public SerializableBlockOrientation(ref Quaternion q)
 {
     Forward = Base6Directions.GetForward(q);
     Up = Base6Directions.GetUp(q);
 }
 public SerializableBlockOrientation(Base6Directions.Direction forward, Base6Directions.Direction up)
 {
     Forward = forward;
     Up = up;
 }
Пример #45
0
 public MyBlockOrientation(Base6Directions.Direction forward, Base6Directions.Direction up)
 {
     Forward = forward;
     Up = up;
     Debug.Assert(IsValid);
 }
Пример #46
0
 public MyBlockOrientation(ref Quaternion q)
 {
     Forward = Base6Directions.GetForward(q);
     Up      = Base6Directions.GetUp(q);
     Debug.Assert(IsValid);
 }
Пример #47
0
            public ThrusterProperties(IMyThrust thruster)
            {
                thruster.throwIfNull_argument("thruster");

                this.thruster = thruster;
                this.force = (DefinitionCache.GetCubeBlockDefinition(thruster) as MyThrustDefinition).ForceMagnitude;
                //this.dampingForce = force * 10;
                this.forceDirect = Base6Directions.GetFlippedDirection(thruster.Orientation.Forward);
            }
        public void ShipOrientation()
        {
            if (_shipControls != null)
            {
                var Origin = ((IMyCubeBlock) _shipControls).GetPosition();
                var Up = Origin + (((IMyCubeBlock) _shipControls).LocalMatrix.Up);
                var Forward = Origin + (((IMyCubeBlock) _shipControls).LocalMatrix.Forward);
                var Left = Origin + (((IMyCubeBlock) _shipControls).LocalMatrix.Left);

                Vector3D forwardVector = Forward - Origin;
                Vector3D upVector = Up - Origin;
                Vector3D leftVector = Left - Origin;

                leftVector.Normalize();
                forwardVector.Normalize();
                upVector.Normalize();

                _shipUp = Base6Directions.GetDirection(upVector);
                _shipLeft = Base6Directions.GetDirection(leftVector);
            }
        }
Пример #49
0
    public void HandleCommand(ZACommons commons, EventDriver eventDriver,
                              string argument)
    {
        argument = argument.Trim().ToLower();
        var parts = argument.Split(new char[] { ' ' }, 4);
        if (parts.Length < 2) return;
        var command = parts[0];
        var speed = parts[1];

        if (command == "cruise")
        {
            if (speed == "reset")
            {
                CruiseFlags = null;
                if (parts.Length >= 3) CruiseFlags = parts[2];
                Reset(commons);
                ThrusterStates.Clear();
                Active = false;
                SaveLastCommand(commons, null);
            }
            else if (speed == "stop")
            {
                RestoreThrusterStates(commons);
                Active = false;
                SaveLastCommand(commons, null);
            }
            else
            {
                CruiseDirection = Base6Directions.Direction.Forward;
                if (parts.Length >= 3)
                {
                    switch (parts[2])
                    {
                        case "forward":
                        case "forwards":
                        default:
                            break;

                        case "backward":
                        case "backwards":
                        case "reverse":
                            CruiseDirection = Base6Directions.Direction.Backward;
                            break;

                        case "left":
                            CruiseDirection = Base6Directions.Direction.Left;
                            break;

                        case "right":
                            CruiseDirection = Base6Directions.Direction.Right;
                            break;

                        case "up":
                            CruiseDirection = Base6Directions.Direction.Up;
                            break;

                        case "down":
                            CruiseDirection = Base6Directions.Direction.Down;
                            break;
                    }
                }

                CruiseFlags = null;
                if (parts.Length == 4) CruiseFlags = parts[3];

                double desiredSpeed;
                if (double.TryParse(speed, out desiredSpeed))
                {
                    TargetSpeed = Math.Max(desiredSpeed, 0.0);

                    thrustPID.Reset();

                    if (!Active)
                    {
                        SaveThrusterStates(commons);
                        Active = true;
                        eventDriver.Schedule(0, Run);
                    }

                    SaveLastCommand(commons, argument);
                }
            }
        }
    }
Пример #50
0
 public MyBlockOrientation(ref Matrix m)
 {
     Forward = Base6Directions.GetForward(ref m);
     Up      = Base6Directions.GetUp(ref m);
     //Debug.Assert(IsValid);
 }
Пример #51
0
		public FlyToGrid(Mover mover, AllNavigationSettings navSet, string targetGrid,
			AttachedGrid.AttachmentKind allowedAttachment = AttachedGrid.AttachmentKind.Permanent)
			: base(mover, navSet)
		{
			this.m_logger = new Logger(GetType().Name, m_controlBlock.CubeBlock, () => m_landingState.ToString());
			this.m_targetBlock = m_navSet.Settings_Current.DestinationBlock;
			string blockName = m_targetBlock == null ? null : m_targetBlock.BlockName;
			this.m_gridFinder = new GridFinder(m_navSet, m_mover.Block, targetGrid, blockName, allowedAttachment);
			this.m_contBlock = m_navSet.Settings_Commands.NavigationBlock;

			PseudoBlock landingBlock = m_navSet.Settings_Current.LandingBlock;
			m_navBlock = landingBlock ?? m_navSet.Settings_Current.NavigationBlock;

			if (landingBlock != null)
			{
				if (landingBlock.Block is IMyFunctionalBlock)
					m_landingState = LandingState.Approach;
				else
				{
					m_logger.debugLog("landingBlock is not functional, player error? : " + landingBlock.Block.DisplayNameText, "FlyToGrid()", Logger.severity.INFO);
					m_landingState = LandingState.None;
				}

				if (m_targetBlock == null)
				{
					if (!(landingBlock.Block is IMyLandingGear))
					{
						m_logger.debugLog("cannot land block without a target", "FlyToGrid()", Logger.severity.INFO);
						m_landingState = LandingState.None;
					}
					else
					{
						m_logger.debugLog("golden retriever mode enabled", "FlyToGrid()", Logger.severity.INFO);
						m_landGearWithoutTargetBlock = true;
					}
				}
				else if (landingBlock.Block is Ingame.IMyShipConnector)
				{
					m_gridFinder.BlockCondition = block => {
						Ingame.IMyShipConnector connector = block as Ingame.IMyShipConnector;
						return connector != null && (!connector.IsConnected || connector.OtherConnector == m_navBlock.Block);
					};
					m_landingDirection = m_targetBlock.Forward ?? Base6Directions.GetFlippedDirection(landingBlock.Block.GetFaceDirection()[0]);
				}
				else if (landingBlock.Block is IMyShipMergeBlock)
				{
					m_gridFinder.BlockCondition = block => block is IMyShipMergeBlock;
					m_landingDirection = m_targetBlock.Forward ?? Base6Directions.GetFlippedDirection(landingBlock.Block.GetFaceDirection()[0]);
					(landingBlock.Block as IMyShipMergeBlock).BeforeMerge += MergeBlock_BeforeMerge;
				}
				else if (m_targetBlock.Forward.HasValue)
					m_landingDirection = m_targetBlock.Forward.Value;
				else
				{
					m_logger.debugLog("Player failed to specify landing direction and it could not be determined.", "FlyToGrid()", Logger.severity.INFO);
					m_landingState = LandingState.None;
				}

				if (m_landingState != LandingState.None)
				{
					float minDestRadius = m_controlBlock.CubeGrid.GetLongestDim() * 5f;
					if (m_navSet.Settings_Current.DestinationRadius < minDestRadius)
					{
						m_logger.debugLog("Increasing DestinationRadius from " + m_navSet.Settings_Current.DestinationRadius + " to " + minDestRadius, "FlyToGrid()", Logger.severity.DEBUG);
						m_navSet.Settings_Task_NavRot.DestinationRadius = minDestRadius;
					}

					new UnLander(mover, navSet, landingBlock);

					m_landingHalfSize = landingBlock.Block.GetLengthInDirection(landingBlock.Block.LocalMatrix.GetClosestDirection(landingBlock.LocalMatrix.Forward)) * 0.5f;
					m_logger.debugLog("m_landing direction: " + m_landingDirection + ", m_landingBlockSize: " + m_landingHalfSize, "FlyToGrid()");
				}
			}

			m_navSet.Settings_Task_NavMove.NavigatorMover = this;
		}