Exemple #1
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);
        }
        private void MarkExploredDirections(ref MyNavmeshComponents.ClosedCellInfo cellInfo)
        {
            foreach (var direction in Base6Directions.EnumDirections)
            {
                var dirFlag = Base6Directions.GetDirectionFlag(direction);
                if (cellInfo.ExploredDirections.HasFlag(dirFlag))
                {
                    continue;
                }

                Vector3I dirVec = Base6Directions.GetIntVector(direction);

                MyCellCoord otherCoord = new MyCellCoord();
                otherCoord.Lod        = MyVoxelNavigationMesh.NAVMESH_LOD;
                otherCoord.CoordInLod = m_currentCell + dirVec;
                if (otherCoord.CoordInLod.X == -1 || otherCoord.CoordInLod.Y == -1 || otherCoord.CoordInLod.Z == -1)
                {
                    continue;
                }

                ulong otherPackedCoord = otherCoord.PackId64();

                if (m_triangleLists.ContainsKey(otherPackedCoord))
                {
                    m_navmeshComponents.MarkExplored(otherPackedCoord, Base6Directions.GetFlippedDirection(direction));
                    cellInfo.ExploredDirections |= Base6Directions.GetDirectionFlag(direction);
                }
            }
            m_navmeshComponents.SetExplored(m_packedCoord, cellInfo.ExploredDirections);
        }
Exemple #3
0
 private unsafe void MarkExploredDirections(ref MyNavmeshComponents.ClosedCellInfo cellInfo)
 {
     foreach (Base6Directions.Direction direction in Base6Directions.EnumDirections)
     {
         Base6Directions.DirectionFlags directionFlag = Base6Directions.GetDirectionFlag(direction);
         if (!cellInfo.ExploredDirections.HasFlag(directionFlag))
         {
             Vector3I    intVector = Base6Directions.GetIntVector(direction);
             MyCellCoord coord     = new MyCellCoord {
                 Lod        = 0,
                 CoordInLod = (Vector3I)(this.m_currentCell + intVector)
             };
             if (((coord.CoordInLod.X != -1) && (coord.CoordInLod.Y != -1)) && (coord.CoordInLod.Z != -1))
             {
                 ulong key = coord.PackId64();
                 if (this.m_triangleLists.ContainsKey(key))
                 {
                     this.m_navmeshComponents.MarkExplored(key, Base6Directions.GetFlippedDirection(direction));
                     Base6Directions.DirectionFlags *flagsPtr1 = (Base6Directions.DirectionFlags *) ref cellInfo.ExploredDirections;
                     *((sbyte *)flagsPtr1) = *(((byte *)flagsPtr1)) | Base6Directions.GetDirectionFlag(direction);
                 }
             }
         }
     }
     this.m_navmeshComponents.SetExplored(this.m_packedCoord, cellInfo.ExploredDirections);
 }
        private void CheckEmissivity()
        {
            if (!InScene)
            {
                return;
            }

            EmissivityState state = EmissivityState.WORKING;

            var otherBlock = GetOtherMergeBlock();

            if (!IsWorking)
            {
                state = EmissivityState.NONE;
            }
            else if (otherBlock != null)
            {
                var dir1 = Base6Directions.GetFlippedDirection(otherBlock.Orientation.TransformDirection(otherBlock.m_forward));
                var dir2 = this.Orientation.TransformDirection(this.m_forward);
                if (dir1 == dir2)
                {
                    state = EmissivityState.LOCKED;
                }
            }
            else if (InConstraint)
            {
                state = EmissivityState.CONSTRAINED;
            }

            if (state != m_emissivityState)
            {
                UpdateEmissivity(state);
            }
        }
    private void UP()
    {
        PX = 0; NX = 0; PY = 0; NY = 0; PZ = 0; NZ = 0; bool a = false; var b = .0; double d; if (SC.TryGetPlanetElevation(MyPlanetElevation.Sealevel, out d))
        {
            a = d < AA; if (a)
            {
                b = PA(d);
            }
        }
        var c = SC.Orientation; foreach (var t in T)
        {
            var e = c.TransformDirectionInverse(Base6Directions.GetFlippedDirection(t.Orientation.Forward)); var f = TH.GetValueOrDefault(t.BlockDefinition.SubtypeId); if (f == null)
            {
                P.Echo("Unknown thruster type: " + t.BlockDefinition.SubtypeId); continue;
            }
            var g = f.GetPower(a, b); switch (e)
            {
            case Base6Directions.Direction.Right: PX += g; break;

            case Base6Directions.Direction.Left: NX += g; break;

            case Base6Directions.Direction.Up: PY += g; break;

            case Base6Directions.Direction.Down: NY += g; break;

            case Base6Directions.Direction.Backward: PZ += g; break;

            case Base6Directions.Direction.Forward: NZ += g; break;
            }
        }
    }
Exemple #6
0
    public void Init(ShipControlCommons shipControl,
                     Base6Directions.Direction localForward = Base6Directions.Direction.Forward)
    {
        LocalForward  = localForward;
        LocalBackward = Base6Directions.GetFlippedDirection(LocalForward);

        thrustPID.Reset();
    }
Exemple #7
0
            // Finds the grid direction for left (x) and down (y)
            private void GetAxis(IMyTextPanel panel, out Vector3I xAxis, out Vector3I yAxis)
            {
                Base6Directions.Direction xAxisDir = Base6Directions.GetFlippedDirection(panel.Orientation.Left);
                xAxis = Vector3I.Round(Base6Directions.GetVector(xAxisDir));

                Base6Directions.Direction yAxisDir = Base6Directions.GetFlippedDirection(panel.Orientation.Up);
                yAxis = Vector3I.Round(Base6Directions.GetVector(yAxisDir));
            }
Exemple #8
0
        private float CalcForceInDirection(Base6Directions.Direction direction)
        {
            float force = 0;

            using (lock_thrustersInDirection.AcquireSharedUsing())
                foreach (MyThrust thruster in m_thrustersInDirection[(int)direction])
                {
                    if (!thruster.Closed && thruster.IsWorking)
                    {
                        force += GetThrusterMaxForce(thruster);
                    }
                }

            m_totalThrustForce[(int)direction] = force;

            if (direction == m_primaryForce.Direction)
            {
                //Log.DebugLog("updating primary force, direction: " + direction + ", force: " + force, "CalcForceInDirection()");
                m_primaryForce.Force = force;
            }
            else if (force > m_primaryForce.Force * 1.1f)
            {
                Log.DebugLog("stronger than primary force, direction: " + direction + ", force: " + force + ", acceleration: " + force / myGrid.Physics.Mass + ", primary: " + m_primaryForce, Logger.severity.DEBUG);
                m_secondaryForce         = m_primaryForce;
                m_primaryForce.Direction = direction;
                m_primaryForce.Force     = force;

                if (m_secondaryForce.Direction == Base6Directions.GetFlippedDirection(m_primaryForce.Direction))
                {
                    m_secondaryForce = new ForceInDirection()
                    {
                        Direction = Base6Directions.GetPerpendicular(m_primaryForce.Direction)
                    }
                }
                ;

                Log.DebugLog("secondary: " + m_secondaryForce);

                Standard.SetMatrixOrientation(m_primaryForce.Direction, m_secondaryForce.Direction);
                Gravity.SetMatrixOrientation(m_secondaryForce.Direction, m_primaryForce.Direction);
            }
            else if (direction == m_secondaryForce.Direction)
            {
                //Log.DebugLog("updating secondary force, direction: " + direction + ", force: " + force, "CalcForceInDirection()");
                m_secondaryForce.Force = force;
            }
            else if (force > m_secondaryForce.Force * 1.1f && direction != Base6Directions.GetFlippedDirection(m_primaryForce.Direction))
            {
                Log.DebugLog("stronger than secondary force, direction: " + direction + ", force: " + force + ", acceleration: " + force / myGrid.Physics.Mass + ", secondary: " + m_secondaryForce, Logger.severity.DEBUG);
                m_secondaryForce.Direction = direction;
                m_secondaryForce.Force     = force;
                Standard.SetMatrixOrientation(m_primaryForce.Direction, m_secondaryForce.Direction);
                Gravity.SetMatrixOrientation(m_secondaryForce.Direction, m_primaryForce.Direction);
            }

            //Log.DebugLog("direction: " + direction + "(" + (int)direction + ")" + ", force: " + force);
            return(force);
        }
    public void Run(ZACommons commons, EventDriver eventDriver)
    {
        var shipControl = (ShipControlCommons)commons;

        ResetIfNotLive(commons, eventDriver);
        if (!Active)
        {
            return;
        }

        // Determine velocity
        var velocity = shipControl.LinearVelocity;

        // If we have no velocity, we have no ship controllers.
        // In theory, ResetIfNotLive should have caught it above
        if (velocity != null)
        {
            var cruiseDirectionFlipped = Base6Directions.GetFlippedDirection(CruiseDirection);
            // Determine forward vector
            var forward3I = shipControl.Reference.Position + Base6Directions.GetIntVector(shipControl.ShipBlockOrientation.TransformDirection(CruiseDirection));
            var forward   = Vector3D.Normalize(shipControl.Reference.CubeGrid.GridIntegerToWorld(forward3I) - shipControl.ReferencePoint);

            CurrentSpeed = Vector3D.Dot((Vector3D)velocity, forward);
            var error = TargetSpeed - CurrentSpeed;

            var force = thrustPID.Compute(error);
            //commons.Echo("Force: " + force);

            var thrustControl = shipControl.ThrustControl;
            var collect       = ParseCruiseFlags();
            if (Math.Abs(error) < CRUISE_CONTROL_DEAD_ZONE * TargetSpeed)
            {
                // Close enough, just disable both sets of thrusters
                thrustControl.Enable(CruiseDirection, false, collect);
                thrustControl.Enable(cruiseDirectionFlipped, false, collect);
            }
            else if (force > 0.0)
            {
                // Thrust forward
                thrustControl.Enable(CruiseDirection, true, collect);
                thrustControl.SetOverride(CruiseDirection, force, collect);
                thrustControl.Enable(cruiseDirectionFlipped, false, collect);
            }
            else
            {
                thrustControl.Enable(CruiseDirection, false, collect);
                thrustControl.Enable(cruiseDirectionFlipped, true, collect);
                thrustControl.SetOverride(cruiseDirectionFlipped, -force, collect);
            }
        }

        eventDriver.Schedule(FramesPerRun, Run);
    }
 void SetupThrusters()
 {
     //add all backward facing thrusters to backwardThruster list.
     thrusters = new List <IMyThrust>();
     GridTerminalSystem.GetBlocksOfType(thrusters);
     foreach (IMyThrust thruster in thrusters)
     {
         if (Base6Directions.GetFlippedDirection(rc.Orientation.Forward) == Base6Directions.GetFlippedDirection(thruster.Orientation.Forward))
         {
             backwardThrusters.Add(thruster);
         }
     }
 }
Exemple #11
0
        /// <summary>
        /// Creates properties for a thruster and adds it to allMyThrusters. If the thruster is working, calls enableDisableThruster(true).
        /// </summary>
        /// <param name="thruster">The new thruster</param>
        private void newThruster(IMySlimBlock thruster)
        {
            float dampingForce            = 10 * (MyDefinitionManager.Static.GetCubeBlockDefinition(thruster.GetObjectBuilder()) as MyThrustDefinition).ForceMagnitude;
            ThrusterProperties properties = new ThrusterProperties(dampingForce, Base6Directions.GetFlippedDirection(thruster.FatBlock.Orientation.Forward));

            allMyThrusters.Add(thruster.FatBlock, properties);
            thruster.FatBlock.IsWorkingChanged += block_IsWorkingChanged;
            if (thruster.FatBlock.IsWorking)
            {
                enableDisableThruster(properties, true);
            }
            return;
        }
Exemple #12
0
    public void Burn(ZACommons commons, EventDriver eventDriver)
    {
        if (ShouldAbort(commons, eventDriver, Modes.Burning, false))
        {
            return;
        }

        var shipControl = (ShipControlCommons)commons;

        var controller = GetShipController(shipControl);

        if (controller == null)
        {
            return;
        }
        var gravity = controller.GetNaturalGravity();

        if (gravity.LengthSquared() > 0.0)
        {
            // Override gyro, disable "bottom" thrusters
            shipControl.Reset(gyroOverride: true, thrusterEnable: true,
                              thrusterCondition: ThrusterCondition);
            shipControl.ThrustControl.Enable(Base6Directions.GetFlippedDirection(BrakeDirection), false);

            var down = shipControl.ShipBlockOrientation.TransformDirection(BrakeDirection);
            seeker.Init(shipControl,
                        shipUp: Base6Directions.GetPerpendicular(down),
                        shipForward: down);

            if (Autodrop)
            {
                // "forward" & "right"
                var forward = Base6Directions.GetPerpendicular(BrakeDirection);
                var right   = Base6Directions.GetCross(forward, BrakeDirection);
                // Actual orientations don't matter
                // Just as long as they're planar & perpendicular to down
                LongCruiser.Init(shipControl, localForward: forward);
                LatCruiser.Init(shipControl, localForward: right);
            }

            Mode = Modes.Gliding;
            eventDriver.Schedule(FramesPerRun, Glide);
        }
        else
        {
            cruiser.Cruise(shipControl, VTVLHELPER_BURN_SPEED,
                           condition: ThrusterCondition);

            eventDriver.Schedule(FramesPerRun, Burn);
        }
    }
Exemple #13
0
        private void calcOrientationFromBlockDirection(IMyCubeBlock block)
        {
            if (CNS.match_direction != null)
            {
                log("already have an orientation: " + CNS.match_direction + ":" + CNS.match_roll, "calcOrientationFromBlockDirection()", Logger.severity.TRACE);
                return;
            }

            Base6Directions.Direction?landDirLocal;
            if (!landingDirectionLocal(block, out landDirLocal))
            {
                log("could not get landing direction from block: " + block.DefinitionDisplayNameText, "calcOrientationFromBlockDirection()", Logger.severity.INFO);
                return;
            }
            Base6Directions.Direction?blockDirection;
            direction_RCfromGrid(landDirLocal, out blockDirection);

            switch (blockDirection)
            {
            case Base6Directions.Direction.Forward:
                CNS.match_direction = Base6Directions.GetFlippedDirection((Base6Directions.Direction)CNS.landDirection);                         //CNS.match_direction = Base6Directions.Direction.Backward;
                // roll is irrelevant
                break;

            case Base6Directions.Direction.Backward:
                CNS.match_direction = CNS.landDirection;                         //CNS.match_direction = Base6Directions.Direction.Forward;
                // roll is irrelevant
                break;

            case Base6Directions.Direction.Up:
                CNS.match_direction = Base6Directions.GetPerpendicular((Base6Directions.Direction)CNS.landDirection);                       //CNS.match_direction = Base6Directions.Direction.Up;
                CNS.match_roll      = Base6Directions.GetFlippedDirection((Base6Directions.Direction)CNS.landDirection);                    //CNS.match_roll = Base6Directions.Direction.Backward;
                break;

            case Base6Directions.Direction.Down:
                CNS.match_direction = Base6Directions.GetPerpendicular((Base6Directions.Direction)CNS.landDirection); //CNS.match_direction = Base6Directions.Direction.Down;
                CNS.match_roll      = CNS.landDirection;                                                              //CNS.match_direction = Base6Directions.Direction.Forward;
                break;

            case Base6Directions.Direction.Left:
                CNS.match_direction = Base6Directions.GetPerpendicular((Base6Directions.Direction)CNS.landDirection);                                                                              //CNS.match_roll = Base6Directions.Direction.Up;
                CNS.match_roll      = Base6Directions.GetFlippedDirection(Base6Directions.GetCross((Base6Directions.Direction)CNS.match_direction, (Base6Directions.Direction)CNS.landDirection)); //CNS.match_direction = Base6Directions.Direction.Left;
                break;

            case Base6Directions.Direction.Right:
                CNS.match_direction = Base6Directions.GetPerpendicular((Base6Directions.Direction)CNS.landDirection);                                         //CNS.match_roll = Base6Directions.Direction.Up;
                CNS.match_roll      = Base6Directions.GetCross((Base6Directions.Direction)CNS.match_direction, (Base6Directions.Direction)CNS.landDirection); //CNS.match_direction = Base6Directions.Direction.Right;
                break;
            }
            log("landDirection = " + landDirLocal + ", blockDirection = " + blockDirection + ", match_direction = " + CNS.match_direction + ", match_roll = " + CNS.match_roll, "calcOrientationFromBlockDirection()", Logger.severity.DEBUG);
        }
            public void update(IMyGridTerminalSystem terminal, IMyShipController cockpit)
            {
                _cockpit = cockpit;

                Base6Directions.Direction cockpitForward = _cockpit.Orientation.TransformDirection(Base6Directions.Direction.Forward);
                for (int i = 0; i < 6; ++i)
                {
                    _thrust[i].Clear();
                    terminal.GetBlocksOfType(_thrust[i], b =>
                                             // The desired direction, transformed by the cockpit, is equal to the direction of thrust
                                             _cockpit.Orientation.TransformDirection(GRID_THRUST_DIRECTIONS[i])
                                             == Base6Directions.GetFlippedDirection(b.Orientation.Forward));
                    _effectiveThrust[i] = computeTotalEffectiveThrust(_thrust[i]);
                }
            }
Exemple #15
0
        public void SetMatrixOrientation(Base6Directions.Direction forward, Base6Directions.Direction up)
        {
            if (forward == up || forward == Base6Directions.GetFlippedDirection(up))
            {
                Log.AlwaysLog("incompatible directions, for2: " + forward + ", up2: " + up, Logger.severity.FATAL);
                throw new ArgumentException("forward is not perpendicular to up");
            }

            Matrix localMatrix = LocalMatrix;

            localMatrix.Forward = Base6Directions.GetVector(forward);
            localMatrix.Up      = Base6Directions.GetVector(up);
            localMatrix.Right   = Base6Directions.GetVector(Base6Directions.GetCross(forward, up));

            this.LocalMatrix = localMatrix;
        }
Exemple #16
0
        /// <summary>
        /// Adds thruster to thrustersInDirection
        /// </summary>
        /// <param name="thruster">The new thruster</param>
        private void newThruster(MyThrust thruster)
        {
            Log.DebugLog("thruster == null", Logger.severity.ERROR, condition: thruster == null);

            if (TP_ThrustOverride == null)
            {
                TP_ThrustOverride = thruster.GetProperty("Override") as ITerminalProperty <float>;
            }

            using (lock_thrustersInDirection.AcquireExclusiveUsing())
                m_thrustersInDirection[(int)Base6Directions.GetFlippedDirection(thruster.Orientation.Forward)].Add(thruster);
            if (TP_ThrustOverride.GetValue(thruster) != 0f)
            {
                TP_ThrustOverride.SetValue(thruster, 0f);
            }
        }
Exemple #17
0
        private bool direction_RCfromGrid(Base6Directions.Direction?gridDirection, out Base6Directions.Direction?result)
        {
            if (gridDirection == null)
            {
                result = null;
                return(false);
            }

            IMyCubeBlock myRC = myNav.currentRCblock;

            if (myRC.Orientation.Left == gridDirection)
            {
                result = Base6Directions.Direction.Left;
                return(true);
            }
            if (Base6Directions.GetFlippedDirection(myRC.Orientation.Left) == gridDirection)
            {
                result = Base6Directions.Direction.Right;
                return(true);
            }
            if (myRC.Orientation.Up == gridDirection)
            {
                result = Base6Directions.Direction.Up;
                return(true);
            }
            if (Base6Directions.GetFlippedDirection(myRC.Orientation.Up) == gridDirection)
            {
                result = Base6Directions.Direction.Down;
                return(true);
            }
            if (myRC.Orientation.Forward == gridDirection)
            {
                result = Base6Directions.Direction.Forward;
                return(true);
            }
            if (Base6Directions.GetFlippedDirection(myRC.Orientation.Forward) == gridDirection)
            {
                result = Base6Directions.Direction.Backward;
                return(true);
            }

            myLogger.log(Logger.severity.ERROR, "direction_RCfromGrid", "failed to match direction: " + gridDirection);
            result = null;
            return(false);
        }
Exemple #18
0
    private void StartReverse(ShipControlCommons shipControl, EventDriver eventDriver)
    {
        shipControl.Reset(gyroOverride: true);

        var shipBackward = Base6Directions.GetFlippedDirection(shipControl.ShipForward);

        seeker.Init(shipControl,
                    shipUp: shipControl.ShipUp,
                    shipForward: shipBackward);
        cruiser.Init(shipControl,
                     localForward: Base6Directions.Direction.Backward);

        if (Mode != REVERSING)
        {
            Mode = REVERSING;
            eventDriver.Schedule(0, Reverse);
        }
    }
Exemple #19
0
        private Vector3I CalculateOtherGridOffset()
        {
            Debug.Assert(m_other != null);

            Vector3 myConstraint    = ConstraintPositionInGridSpace() / this.CubeGrid.GridSize;
            Vector3 otherConstraint = -m_other.ConstraintPositionInGridSpace() / m_other.CubeGrid.GridSize;

            Base6Directions.Direction thisRight   = Orientation.TransformDirection(m_right);   // Where does this block's right point to
            Base6Directions.Direction thisForward = Orientation.TransformDirection(m_forward); // Where does this block's forward point to

            Base6Directions.Direction otherBackward = Base6Directions.GetFlippedDirection(m_other.Orientation.TransformDirection(m_other.m_forward));
            Base6Directions.Direction otherRight    = m_other.CubeGrid.WorldMatrix.GetClosestDirection(CubeGrid.WorldMatrix.GetDirectionVector(thisRight));

            Vector3 toOtherOrigin;
            MatrixI rotation = MatrixI.CreateRotation(otherRight, otherBackward, thisRight, thisForward);

            Vector3.Transform(ref otherConstraint, ref rotation, out toOtherOrigin);

            return(Vector3I.Round(myConstraint + toOtherOrigin));
        }
    private void TO(Vector3D o)
    {
        TS = false; var a = SC.Orientation; foreach (var t in T)
        {
            var d = a.TransformDirectionInverse(Base6Directions.GetFlippedDirection(t.Orientation.Forward)); switch (d)
            {
            case Base6Directions.Direction.Right: t.SetValueFloat("Override", Math.Max(0, (float)o.X)); break;

            case Base6Directions.Direction.Left: t.SetValueFloat("Override", Math.Max(0, (float)-o.X)); break;

            case Base6Directions.Direction.Up: t.SetValueFloat("Override", Math.Max(0, (float)o.Y)); break;

            case Base6Directions.Direction.Down: t.SetValueFloat("Override", Math.Max(0, (float)-o.Y)); break;

            case Base6Directions.Direction.Backward: t.SetValueFloat("Override", Math.Max(0, (float)o.Z)); break;

            case Base6Directions.Direction.Forward: t.SetValueFloat("Override", Math.Max(0, (float)-o.Z)); break;
            }
        }
    }
            internal Light(IMyLightingBlock b, Base6Directions.Direction dir)
            {
                light = b;

                isSpotlight = b.BlockDefinition.SubtypeName.ToLowerInvariant().Contains("frontlight");
                isExitLight = isSpotlight && b.Orientation.Forward == Base6Directions.GetFlippedDirection(dir);

                b.Intensity = 20;
                b.Radius    = 200;
                b.Falloff   = 4;

                maxIntensity = b.Intensity;
                maxRadius    = b.Radius;

                switch (dir)
                {
                case Base6Directions.Direction.Backward:                         //+Z
                    positionValue = b.Position.Z;
                    break;

                case Base6Directions.Direction.Forward:
                    positionValue = -b.Position.Z;
                    break;

                case Base6Directions.Direction.Right:                         //+X
                    positionValue = b.Position.X;
                    break;

                case Base6Directions.Direction.Left:
                    positionValue = -b.Position.X;
                    break;

                case Base6Directions.Direction.Down:
                    positionValue = -b.Position.Y;
                    break;

                case Base6Directions.Direction.Up:                         //+Y
                    positionValue = b.Position.Y;
                    break;
                }
            }
Exemple #22
0
        private void setArtificialGravity(float gnat, float g)
        {
            float eff = getAGravEfficacy(gnat);
            float f   = eff <= 0 ? 0 : 1F / eff;

            if (SPLIT_GRAVITY)
            {
                f /= gravGens.Count;
            }
            if (gravDriveOn())
            {
                Echo("Gravity Drive is working, all other gravity disabled.");
                f = 0;
            }
            else
            {
                Echo("Setting gravity generator level to " + f * 100 + "% in direction " + upDirection.ToString());
            }
            foreach (IMyGravityGenerator gen in gravGens)
            {
                if (f <= 0 || g <= 0)
                {
                    gen.Enabled = false;
                }
                else
                {
                    float sign = 0;
                    if (gen.Orientation.Up == upDirection)
                    {
                        sign = 1;
                    }
                    else if (gen.Orientation.Up == Base6Directions.GetFlippedDirection(upDirection))
                    {
                        sign = -1;
                    }
                    float amt = g * 9.81F * f * sign;
                    gen.Enabled             = Math.Abs(amt) > 0;
                    gen.GravityAcceleration = amt;
                }
            }
        }
Exemple #23
0
    public void Init(IEnumerable <IMyTerminalBlock> blocks,
                     Func <IMyThrust, bool> collect        = null,
                     Base6Directions.Direction shipUp      = Base6Directions.Direction.Up,
                     Base6Directions.Direction shipForward = Base6Directions.Direction.Forward)
    {
        MyBlockOrientation shipOrientation = new MyBlockOrientation(shipForward, shipUp);

        thrusters.Clear();
        foreach (var block in blocks)
        {
            var thruster = block as IMyThrust;
            if (thruster != null && thruster.IsFunctional &&
                (collect == null || collect(thruster)))
            {
                var facing          = thruster.Orientation.TransformDirection(Base6Directions.Direction.Forward); // Exhaust goes this way
                var thrustDirection = Base6Directions.GetFlippedDirection(facing);
                var shipDirection   = shipOrientation.TransformDirectionInverse(thrustDirection);
                AddThruster(shipDirection, thruster);
            }
        }
    }
Exemple #24
0
        public static Vector3I CalculateOffset(IMyCubeBlock pad1, IMyCubeBlock pad2)
        {
            Vector3 pad1local = pad1.Position;  // ConstraintPositionInGridSpace(pad1) / pad1.CubeGrid.GridSize;
            Vector3 pad2local = -pad2.Position; // -ConstraintPositionInGridSpace(pad2) / pad2.CubeGrid.GridSize;

            // I dunno why it works but it seems to do in the tests I made xD
            pad1local += Base6Directions.GetVector(pad1.Orientation.TransformDirection(Base6Directions.GetOppositeDirection(WeldPad.DirForward)));
            //pad2local += Base6Directions.GetVector(pad2.Orientation.TransformDirection(Base6Directions.GetOppositeDirection(WeldPad.DIR_FORWARD)));

            Base6Directions.Direction direction = pad1.Orientation.TransformDirection(WeldPad.DirRight);

            MatrixI matrix = MatrixI.CreateRotation(
                newB: pad1.Orientation.TransformDirection(WeldPad.DirForward),
                oldB: Base6Directions.GetFlippedDirection(pad2.Orientation.TransformDirection(WeldPad.DirForward)),
                oldA: pad2.CubeGrid.WorldMatrix.GetClosestDirection(pad1.CubeGrid.WorldMatrix.GetDirectionVector(direction)),
                newA: direction);

            Vector3 offset;

            Vector3.Transform(ref pad2local, ref matrix, out offset);
            return(Vector3I.Round(pad1local + offset));
        }
Exemple #25
0
        /// <summary>
        /// if removed is a thruster, remove it from thrustersInDirection
        /// </summary>
        /// <remarks>
        /// if a working block is destroyed, block_IsWorkingChange() is called first
        /// </remarks>
        /// <param name="removed">block that was removed</param>
        private void grid_OnBlockRemoved(IMySlimBlock removed)
        {
            try
            {
                if (removed.FatBlock == null)
                {
                    return;
                }

                MyThrust asThrust = removed.FatBlock as MyThrust;
                if (asThrust == null)
                {
                    return;
                }

                using (lock_thrustersInDirection.AcquireExclusiveUsing())
                    m_thrustersInDirection[(int)Base6Directions.GetFlippedDirection(asThrust.Orientation.Forward)].Remove(asThrust);
                Log.DebugLog("removed thruster = " + removed.FatBlock.DefinitionDisplayNameText + "/" + asThrust.DisplayNameText, Logger.severity.DEBUG);
                return;
            }
            catch (Exception e)
            { Log.AlwaysLog("Exception: " + e, Logger.severity.ERROR); }
        }
Exemple #26
0
    private void SetThrustersOverride(Vector3D overrides)
    {
        thrustersStopped = false;

        MyBlockOrientation orientation = shipController.Orientation;

        foreach (IMyThrust thruster in thrusters)
        {
            Base6Directions.Direction direction = Base6Directions.GetFlippedDirection(thruster.Orientation.Forward);
            switch (direction)
            {
            case Base6Directions.Direction.Right:
                thruster.SetValueFloat("Override", Math.Max(0, (float)overrides.X));
                break;

            case Base6Directions.Direction.Left:
                thruster.SetValueFloat("Override", Math.Max(0, (float)-overrides.X));
                break;

            case Base6Directions.Direction.Up:
                thruster.SetValueFloat("Override", Math.Max(0, (float)overrides.Y));
                break;

            case Base6Directions.Direction.Down:
                thruster.SetValueFloat("Override", Math.Max(0, (float)-overrides.Y));
                break;

            case Base6Directions.Direction.Backward:
                thruster.SetValueFloat("Override", Math.Max(0, (float)overrides.Z));
                break;

            case Base6Directions.Direction.Forward:
                thruster.SetValueFloat("Override", Math.Max(0, (float)-overrides.Z));
                break;
            }
        }
    }
Exemple #27
0
        /// <summary>
        /// Creates a PseudoBlock from a block and an orientation.
        /// </summary>
        /// <param name="block">The block to calculate the local matrix from.</param>
        /// <param name="forward">The direction the block should face towards the target.</param>
        /// <param name="up">A direction perpendicular to forward.</param>
        public PseudoBlock(IMyCubeBlock block, Base6Directions.Direction?forward, Base6Directions.Direction?up)
            : this(block)
        {
            Base6Directions.Direction for2 = forward ?? block.FirstFaceDirection();
            Base6Directions.Direction up2  = up ??
                                             (for2 == Base6Directions.Direction.Forward ? Base6Directions.Direction.Up : Base6Directions.GetPerpendicular(for2));

            if (for2 == up2 || for2 == Base6Directions.GetFlippedDirection(up2))
            {
                Log.DebugLog("incompatible directions, for2: " + for2 + ", up2: " + up2);
                up2 = Base6Directions.GetPerpendicular(for2);
            }

            this.LocalMatrix = new Matrix()
            {
                Forward = block.LocalMatrix.GetDirectionVector(for2),
                Up      = block.LocalMatrix.GetDirectionVector(up2),
                Right   = block.LocalMatrix.GetDirectionVector(Base6Directions.GetCross(for2, up2)),
                M41     = block.LocalMatrix.M41,
                M42     = block.LocalMatrix.M42,
                M43     = block.LocalMatrix.M43,
                M44     = block.LocalMatrix.M44
            };
        }
        public void Main(string argument, UpdateType updateSource)
        {
            string[] argInfo = argument.Split(new string[] { "," }, StringSplitOptions.None);
            if (argument == "RUN")
            {
                //Check if can scan, and scan if can.
                if (cam.CanScan(rayCastDistance))
                {
                    detectedInfo = cam.Raycast(rayCastDistance);
                }
                else
                {
                    Echo("Can't scan yet!");
                }

                Echo("INITIATING");

                coordinate = Vector3D.Zero; //initating to zero value.

                Boolean found = false;
                if (detectedInfo.HitPosition != null)
                {
                    coordinate = detectedInfo.HitPosition.Value;
                    found      = true;
                }

                if (found)
                {
                    Vector3D currentCoords = rc.GetPosition();

                    //creating unit vector
                    double denominator = Math.Sqrt(Math.Pow(coordinate.X - currentCoords.X, 2)
                                                   + Math.Pow(coordinate.Y - currentCoords.Y, 2)
                                                   + Math.Pow(coordinate.Z - currentCoords.Z, 2));
                    double xMultiplier = (coordinate.X - currentCoords.X) / denominator;
                    double yMultiplier = (coordinate.Y - currentCoords.Y) / denominator;
                    double zMultiplier = (coordinate.Z - currentCoords.Z) / denominator;

                    //manipulating target coordinate with unit vector
                    coordinate.X -= finalDistFromTarget * xMultiplier;
                    coordinate.Y -= finalDistFromTarget * yMultiplier;
                    coordinate.Z -= finalDistFromTarget * zMultiplier;

                    //Setting up backward thrusters list
                    backwardThrusters = new List <IMyThrust>();

                    //Obtaining each thruster pointing backward
                    foreach (IMyThrust thruster in thrusters)
                    {
                        if (Base6Directions.GetFlippedDirection(rc.Orientation.Forward) == Base6Directions.GetFlippedDirection(thruster.Orientation.Forward))
                        {
                            backwardThrusters.Add(thruster);
                        }
                    }

                    //Obtaining max backward acceleration
                    MyShipMass myShipMass = rc.CalculateShipMass();
                    backwardsAcceleration = CalculateAcceleration(myShipMass.TotalMass, backwardThrusters);

                    //autopilot settings
                    rc.ClearWaypoints();
                    rc.AddWaypoint(coordinate, "AUTO DYNAMIC BRAKING SCRIPT COORDINATE");
                    rc.SetAutoPilotEnabled(true);
                    rc.SetCollisionAvoidance(false);
                    rc.SetDockingMode(false); //CHANGE??? or dont?
                    rc.FlightMode = FlightMode.OneWay;
                    rc.Direction  = Base6Directions.Direction.Forward;
                    blindMode     = false;
                }
            }
            else if (argInfo[0] == "blind".ToLower())
            {
                int     dist   = 0;
                Boolean passed = Int32.TryParse(argInfo[1], out dist);

                if (passed)
                {
                    Vector3D dir = rc.WorldMatrix.Forward;
                    coordinate    = rc.GetPosition();
                    coordinate.X += dir.X * dist;
                    coordinate.Y += dir.Y * dist;
                    coordinate.Z += dir.Z * dist;

                    Vector3D currentCoords = rc.GetPosition();

                    //Setting up backward thrusters list
                    backwardThrusters = new List <IMyThrust>();

                    //Obtaining each thruster pointing backward
                    foreach (IMyThrust thruster in thrusters)
                    {
                        if (Base6Directions.GetFlippedDirection(rc.Orientation.Forward) == Base6Directions.GetFlippedDirection(thruster.Orientation.Forward))
                        {
                            backwardThrusters.Add(thruster);
                        }
                    }

                    //Obtaining max backward acceleration
                    MyShipMass myShipMass = rc.CalculateShipMass();
                    backwardsAcceleration = CalculateAcceleration(myShipMass.TotalMass, backwardThrusters);

                    //autopilot settings
                    rc.ClearWaypoints();
                    rc.AddWaypoint(coordinate, "CAPTXAN'S SCRIPT COORDINATE");
                    rc.SetAutoPilotEnabled(true);
                    rc.SetCollisionAvoidance(false);
                    rc.SetDockingMode(false); //CHANGE??? or dont?
                    rc.FlightMode = FlightMode.OneWay;
                    rc.Direction  = Base6Directions.Direction.Forward;
                    blindMode     = true;
                    blindCounter  = 0;
                }
                else
                {
                    Echo("2nd parameter is not a number!");
                }
            }
            else
            {
                //User Feedback
                if (!cam.CanScan(rayCastDistance))
                {
                    float percentage = ((cam.TimeUntilScan(rayCastDistance) / 1000) / (rayCastDistance / 2000));
                    percentage = (1 - percentage) * 100;
                    Echo("Raycast is recharging " + percentage + "%");
                    if (!cam.EnableRaycast)
                    {
                        cam.EnableRaycast = true;
                    }
                }
                else
                {
                    Echo("Ready to Scan");
                    cam.EnableRaycast = false;
                }

                //Travelling CHANGE HERE FOR ENABLE / DISABLE AUTOPILOT
                if (rc.IsAutoPilotEnabled)
                {
                    travelling = true;
                    double currentDistanceFromTarget = Vector3D.Distance(coordinate, rc.GetPosition());
                    Echo("Travelling, ETA: " + (int)(currentDistanceFromTarget / rc.GetShipSpeed()) + "s");

                    //Calculating stopping distance to determine if thrusters need to be enabled.
                    Echo("Current Speed: " + (int)rc.GetShipSpeed() + "m/s");
                    Echo("Ship Speed Limit: " + rc.SpeedLimit + "m/s");
                    if (rc.GetShipSpeed() > rc.SpeedLimit - 1) //If ship at max speed
                    {
                        Vector3D currentTrajectory = Vector3D.Normalize(rc.GetPosition() - prevPosition);
                        prevPosition = rc.GetPosition();
                        Vector3D calculatedTrajectory = Vector3D.Normalize(rc.GetPosition() - coordinate);

                        double accuracyAmount;
                        if (currentDistanceFromTarget > 15000)
                        {
                            accuracyAmount = .99999;
                        }
                        else if (currentDistanceFromTarget > 5000)
                        {
                            accuracyAmount = .9999;
                        }
                        else
                        {
                            accuracyAmount = .999;
                        }

                        if (currentDistanceFromTarget * .90 > (Math.Pow(rc.GetShipSpeed(), 2) / (2 * backwardsAcceleration)) &&
                            Math.Abs(currentTrajectory.Dot(calculatedTrajectory)) > accuracyAmount)
                        {
                            foreach (IMyThrust thruster in thrusters)
                            {
                                thruster.ApplyAction("OnOff_Off");
                            }
                        }
                        else //Curr < stopp
                        {
                            foreach (IMyThrust thruster in thrusters)
                            {
                                thruster.ApplyAction("OnOff_On");
                            }
                        }
                    }

                    Echo("Blind Mode: " + blindMode);

                    if (blindMode)
                    {
                        Echo("Blind Counter: " + blindCounter);
                        Echo("Coll Avoid: " + rc.);
                        if (cam.CanScan(((Math.Pow(rc.GetShipSpeed(), 2) / (2 * backwardsAcceleration)) * 2)))
                        {
                            detectedInfo = cam.Raycast((Math.Pow(maxSpeed, 2) / (2 * backwardsAcceleration)) * 2);
                            if (detectedInfo.HitPosition != null)
                            {
                                rc.SpeedLimit = 3;
                                rc.SetCollisionAvoidance(true);
                                blindCounter = 0;
                            }
                            else
                            {
                                if (blindCounter > 500)
                                {
                                    rc.SpeedLimit = maxSpeed;
                                    rc.SetCollisionAvoidance(false);
                                    blindCounter = 0;
                                }
                                else
                                {
                                    blindCounter++;
                                }
                            }
                        }
                    }
                }
                else if (travelling)
                {
                    foreach (IMyThrust thruster in thrusters)
                    {
                        thruster.ApplyAction("OnOff_On");
                    }
                    travelling = false;
                    blindMode  = false;
                }
            }
            //Additional Arugment Commands
            if (argument == "ABORT")
            {
                rc.SetAutoPilotEnabled(false);
                rc.DampenersOverride = true;
            }
        }
        private void MergeFromAnotherMesh(MyGridNavigationMesh otherMesh, ref MatrixI transform)
        {
            ProfilerShort.Begin("MergeFromAnotherMesh");
            m_mergeHelper.Clear();

            // Save the cubes from the other mesh that are touching cubes of this mesh into a helper set.
            // Also put the touched cubes from this mesh into the set.
            foreach (var position in otherMesh.m_smallTriangleRegistry.Keys)
            {
                bool add = false;
                foreach (var direction in Base6Directions.IntDirections)
                {
                    // CH: TODO: We query the grid so far, but in the future, we should make sure that the access is thread-safe
                    Vector3I pos = Vector3I.Transform(position + direction, transform);
                    if (m_cubeSet.Contains(ref pos))             // Test the transformed position...
                    {
                        m_mergeHelper.Add(position + direction); // ... but add the original one
                        add = true;
                    }
                }
                if (add)
                {
                    m_mergeHelper.Add(position);
                }
            }

            foreach (var entry in otherMesh.m_smallTriangleRegistry)
            {
                Vector3I originalCube = entry.Key;
                Vector3I tformedCube; Vector3I.Transform(ref originalCube, ref transform, out tformedCube);

                // If the cube is one of the touching cubes, we have to intersect the touching triangles
                if (m_mergeHelper.Contains(originalCube))
                {
                    // Take the touching pairs one by one and calculate triangulation of the disjoint union of the opposing faces
                    // Remove the opposing faces from the old block
                    // Add the triangulation to the mesh
                    // Add the rest of the navmesh from this block to the mesh

                    m_tmpTriangleList.Clear();

                    // CH: TODO. Just remove the triangles now
                    foreach (var direction in Base6Directions.EnumDirections)
                    {
                        Vector3I directionVec = Base6Directions.GetIntVector((int)direction);
                        Base6Directions.Direction tformedDirection = transform.GetDirection(direction);
                        Vector3I tformedFlippedVec = Base6Directions.GetIntVector((int)Base6Directions.GetFlippedDirection(tformedDirection));

                        // Remove face triangles from this mesh
                        if (m_mergeHelper.Contains(originalCube + directionVec))
                        {
                            List <int> triList = null;
                            if (m_smallTriangleRegistry.TryGetValue(tformedCube - tformedFlippedVec, out triList))
                            {
                                foreach (var index in triList)
                                {
                                    var triangle = GetTriangle(index);
                                    // CH: TODO: This will probably be expensive. Could we precalculate it?
                                    if (IsFaceTriangle(triangle, tformedCube - tformedFlippedVec, tformedFlippedVec))
                                    {
                                        m_tmpTriangleList.Add(new KeyValuePair <MyNavigationTriangle, Vector3I>(triangle, tformedCube - tformedFlippedVec));
                                    }
                                }
                            }
                        }
                    }

                    foreach (var triangle in m_tmpTriangleList)
                    {
                        RemoveTriangle(triangle.Key, triangle.Value);
                    }
                    m_tmpTriangleList.Clear();

                    int debugCounter = 0;

                    // CH: TODO: optimize this (actually whole this method)
                    foreach (var triangleIndex in entry.Value)
                    {
                        var      triangle    = otherMesh.GetTriangle(triangleIndex);
                        Vector3I pos         = entry.Key;
                        bool     addTriangle = true;
                        foreach (var direction in Base6Directions.EnumDirections)
                        {
                            Vector3I dirvec = Base6Directions.GetIntVector((int)direction);
                            if (m_mergeHelper.Contains(pos + dirvec) && IsFaceTriangle(triangle, pos, dirvec))
                            {
                                addTriangle = false;
                                break;
                            }
                        }

                        if (addTriangle)
                        {
                            if (debugCounter == 5)
                            {
                            }
                            CopyTriangle(triangle, pos, ref transform);
                            debugCounter++;
                        }
                    }
                }
                // Otherwise, we just transform the triangles from the other mesh and add them to this mesh
                else
                {
                    foreach (var triangleIndex in entry.Value)
                    {
                        var triangle = otherMesh.GetTriangle(triangleIndex);
                        CopyTriangle(triangle, entry.Key, ref transform);
                        //if (triangleIndex > 1) break;
                    }
                }
            }

            m_mergeHelper.Clear();
            ProfilerShort.End();
        }
Exemple #30
0
 // Returns a position with the same position and with a flipped direction
 // .-------.    .-------.
 // |       |    |       |
 // |   o-->| ~> |<--o   |
 // |       |    |       |
 // '-------*    .-------.
 public ConveyorLinePosition GetFlippedPosition()
 {
     return(new ConveyorLinePosition(LocalGridPosition, Base6Directions.GetFlippedDirection(Direction)));
 }