Ejemplo n.º 1
0
        void Start()
        {
            gridSystem = GridTerminalSystem;
            gridId     = Me.CubeGrid.EntityId;
            if (string.IsNullOrWhiteSpace(turretGroup))
            {
                turrets = GetBlocks <IMyLargeTurretBase>(useSubgrids);
            }
            else
            {
                turrets = GetBlocks <IMyLargeTurretBase>(turretGroup, useSubgrids);
            }
            wcTurrets = new WcPbApi();
            if (string.IsNullOrWhiteSpace(rcName))
            {
                rc = GetBlock <IMyRemoteControl>();
            }
            else
            {
                rc = GetBlock <IMyRemoteControl>(rcName, useSubgrids);
            }
            if (rc == null)
            {
                throw new Exception("Remote control block not found.");
            }
            origin = rc.GetPosition();

            if (receiveHelpMsgs)
            {
                helpListener = IGC.RegisterBroadcastListener("AttackDrone_" + commsId);
                helpListener.SetMessageCallback("");
            }

            startRuntime = -1;
        }
Ejemplo n.º 2
0
    public void AddListener(string channel)
    {
        IMyBroadcastListener listener = this.p.IGC.RegisterBroadcastListener(channel);

        listener.SetMessageCallback(channel);
        this.listeners[channel] = listener;
    }
Ejemplo n.º 3
0
        string initDockingInfo()
        {
            string s = "";

            _BASE_IGCChannel = IGC.RegisterBroadcastListener("BASE?");
            _BASE_IGCChannel.SetMessageCallback(_BASE_IGCChannel.Tag);

            _CON_IGCChannel = IGC.RegisterBroadcastListener("CON?");
            _CON_IGCChannel.SetMessageCallback(_CON_IGCChannel.Tag);

            _COND_IGCChannel = IGC.RegisterBroadcastListener("COND?");
            _COND_IGCChannel.SetMessageCallback(_COND_IGCChannel.Tag);

            dockingInfo.Clear();
            dockingAlllights = GetBlocksContains <IMyLightingBlock>(sBaseConnector);
            //GetTargetBlocks<IMyLightingBlock>();

            if (localBaseConnectors.Count < 1)
            {
                s += connectorsInit();
            }

            Echo(localBaseConnectors.Count + " Base Connectors");
            for (int i = 0; i < localBaseConnectors.Count; i++)
            {
                //		IMyShipConnector connector = localBaseConnectors[i]  as IMyShipConnector;
                addDockingInfo(localBaseConnectors[i]);
            }
            // load from text panel...
            s += "DI:" + dockingInfo.Count;
//            Echo("EO:iDI()");
            return(s);
        }
        public Program()
        {
            Program.MyInstance      = this;
            Runtime.UpdateFrequency = UpdateFrequency.Update1;
            SetRadarController();
            SetShipController();
            SayMyName(MY_PREFIX);
            GetMeTheTurrets();
            int i = 0;

            try {
                string[] data = Storage.Split(';');
                AEGISUseRadarData    = bool.Parse(data[i++]);
                AEGISIsOnline        = bool.Parse(data[i++]);
                AEGISTargetsNeutrals = bool.Parse(data[i++]);
            }
            catch (Exception e) {
                e.ToString();
                int f = 0;
                if (++f >= i)
                {
                    AEGISUseRadarData = false;
                }
                if (++f >= i)
                {
                    AEGISIsOnline = true;
                }
                if (++f >= i)
                {
                    AEGISTargetsNeutrals = false;
                }
            }
            AEGISListener = IGC.RegisterBroadcastListener(MY_PREFIX);
            AEGISListener.SetMessageCallback();
        }
Ejemplo n.º 5
0
        public Program()
        {
            //gets all programmable blocks, where the block's name starts with "Dock"
            int hangarCount = GetAllHangars();

            Echo(String.Format("Found {0} Hangar Controllers", hangarCount));

            antenna = GridTerminalSystem.GetBlockWithName("Dock Request Antenna") as IMyRadioAntenna; //TODO: Remove specific name requrement
            if (antenna != null)
            {
                antenna.AttachedProgrammableBlock = Me.EntityId;
                listener = IGC.RegisterBroadcastListener(MESSAGE_TAG);
                listener.SetMessageCallback("REQUEST_WAITING");
            }
            logger = GridTerminalSystem.GetBlockWithName("LCD Logger") as IMyTextPanel;
            Echo(string.Format("ANTENNA FOUND: {0}", antenna != null));
            Echo(string.Format("LOGGER FOUND: {0}", logger != null));
            if (logger == null)
            {
                logger = Me.GetSurface(0);
            }
            logger.ContentType = ContentType.TEXT_AND_IMAGE;
            logger.FontSize    = FONT_SIZE;
            string loggerText = logger.GetText();

            if (!loggerText.Contains("DOCKING LOG"))
            {
                Echo("LOGGER TEXT DOES NOT INCLUDE HEADER. Only Found:\n" + loggerText);
                logger.WriteText(LOGGER_HEADER);
            }
        }
Ejemplo n.º 6
0
        public Program()
        {
            IMyTerminalBlock b = GridTerminalSystem.GetBlockWithName(ScreenName);

            Screen = (b as IMyTextSurface) ?? (b as IMyTextSurfaceProvider)?.GetSurface(0);
            if (Screen == null)
            {
                Screen = Me.GetSurface(0);
            }
            Screen.ContentType = VRage.Game.GUI.TextPanel.ContentType.TEXT_AND_IMAGE;
            Listener           = IGC.RegisterBroadcastListener(BroadcastTag);
            Listener.SetMessageCallback("incoming_message");
            if (Listener.IsActive)
            {
                Echo("Listener registered. Callback set.");
            }
            else
            {
                Echo("Listener not registered!");
            }
            if (!long.TryParse(Storage, out DroneID))
            {
                DroneID = 0;
            }
        }
Ejemplo n.º 7
0
        public Program()
        {
            drill  = GridTerminalSystem.GetBlockWithName(drill_name) as IMyShipDrill;
            piston = GridTerminalSystem.GetBlockWithName(piston_name) as IMyPistonBase;

            broadcast_listener = IGC.RegisterBroadcastListener(broadcast_tag);
            broadcast_listener.SetMessageCallback(broadcast_tag);
        }
Ejemplo n.º 8
0
 void BaseInitInfo()
 {
     baseList.Clear();
     // load from text panel
     BaseDeserialize();
     _BASEIGCChannel = IGC.RegisterBroadcastListener("BASE");
     _BASEIGCChannel.SetMessageCallback(_BASEIGCChannel.Tag);
 }
Ejemplo n.º 9
0
 public Program()
 {
     // подписываемся на канал
     listener = IGC.RegisterBroadcastListener(TAG);
     // указываем какой будет приходить argument в метод Main()
     listener.SetMessageCallback(TAG);
     Echo("Status: init ok");
 }
Ejemplo n.º 10
0
        // States
        // - OPEN
        // - OPENING
        // - CLOSED
        // - CLOSING
        // - UNKNOWN -> stopped in non-closed/open state, or moving to unknown state
        // - null -> default, requires init


        // Inputs
        // - CLOSE
        // - OPEN
        // - OBSERVE -> default, observes states, locks when available and change state accordingly
        // - RESTART -> reruns init

        public Program()
        {
            var config           = new Config(Me.CustomData);
            var blashDoorChannel = config.Get("blastDoorChannel", "BlastDoor");

            broadcastListener = IGC.RegisterBroadcastListener(blashDoorChannel);
            broadcastListener.SetMessageCallback("radioCommand");
        }
Ejemplo n.º 11
0
            public AntennaHandler(Program _program)
            {
                parent_program = _program;

                _myBroadcastListener = parent_program.IGC.RegisterBroadcastListener(_recallRequestTag);
                _myUnicastListener   = parent_program.IGC.UnicastListener;
                //_myUnicastListener = parent_program.IGC.RegisterBroadcastListener(_responseTag);
                _myUnicastListener.SetMessageCallback("UNICAST");
                _myBroadcastListener.SetMessageCallback(_recallRequestTag);
            }
Ejemplo n.º 12
0
        public Program()
        {
            settings = new Settings(Me);
            settings.Load();

            storage = new StorageData(this);
            storage.Load();

            transmitTag        += settings.followerSystemId.Value;
            transmitCommandTag += settings.followerSystemId.Value;

            // Prioritize the given cockpit name
            rc = GetBlock <IMyShipController>(settings.cockpitName.Value, true);
            if (rc == null) // Second priority cockpit
            {
                rc = GetBlock <IMyCockpit>();
            }
            if (rc == null) // Third priority remote control
            {
                rc = GetBlock <IMyRemoteControl>();
            }
            if (rc == null) // No cockpits found.
            {
                throw new Exception("No cockpit/remote control found. Set the cockpitName field in settings.");
            }

            thrust = new ThrusterControl(rc, settings.tickSpeed.Value, GetBlocks <IMyThrust>());
            gyros  = new GyroControl(rc, settings.tickSpeed.Value, GetBlocks <IMyGyro>());

            if (settings.enableCollisionAvoidence.Value)
            {
                cameras = GetBlocks <IMyCameraBlock>();
            }

            if (settings.tickSpeed.Value == UpdateFrequency.Update10)
            {
                echoFrequency = 10;
            }
            else if (settings.tickSpeed.Value == UpdateFrequency.Update100)
            {
                echoFrequency = 1;
            }

            leaderListener = IGC.RegisterBroadcastListener(transmitTag);
            leaderListener.SetMessageCallback("");
            commandListener = IGC.RegisterBroadcastListener(transmitCommandTag);
            commandListener.SetMessageCallback("");

            Echo("Ready.");
            if (!storage.IsDisabled)
            {
                Runtime.UpdateFrequency = settings.tickSpeed.Value;
            }
        }
            protected void AddListener(string subtag, bool withCallback = false)
            {
                string realTag         = ToRealTag(subtag);
                IMyBroadcastListener l = p.IGC.RegisterBroadcastListener(realTag);

                if (withCallback)
                {
                    l.SetMessageCallback(realTag);
                }
                listGroupListener.Add(l);
            }
Ejemplo n.º 14
0
        public Program()
        {
            // let them know we are alive
            Echo("Creator");

            // register a broadcast channel for our tag
            _myBroadcastListener = IGC.RegisterBroadcastListener(_broadCastTag);

            // Ask to be called back --to Main()-- when a message is received
            _myBroadcastListener.SetMessageCallback(_broadCastTag); // the callback agrument does NOT need to be the same as the tag
        }
Ejemplo n.º 15
0
        //grid map

        public Program()
        {
            //load program state
            if (alreadyRun & _ini.TryParse(Storage))
            {
                Vector3D.TryParse(_ini.Get("Basis", "A").ToString(), out _basisVecA);
                Vector3D.TryParse(_ini.Get("Basis", "B").ToString(), out _basisVecB);
                Vector3D.TryParse(_ini.Get("Basis", "Up").ToString(), out _basisVecUp);
                Vector3D.TryParse(_ini.Get("Basis", "Origin").ToString(), out _origin);
            }
            //load config
            else
            {
                MyIniParseResult result;
                if (!_ini.TryParse(Me.CustomData, out result))
                {
                    throw new Exception(result.ToString());
                }

                string           nameA  = _ini.Get("Basis", "A").ToString("A");
                IMyTerminalBlock blockA = GridTerminalSystem.GetBlockWithName(nameA);
                Vector3D         pointA = blockA.GetPosition();

                string           nameB  = _ini.Get("Basis", "B").ToString("B");
                IMyTerminalBlock blockB = GridTerminalSystem.GetBlockWithName(nameB);
                Vector3D         pointB = blockB.GetPosition();

                string           nameUp  = _ini.Get("Basis", "Up").ToString("Up");
                IMyTerminalBlock blockUp = GridTerminalSystem.GetBlockWithName(nameUp);
                Vector3D         pointUp = blockUp.GetPosition();

                string           nameOrigin  = _ini.Get("Basis", "Origin").ToString("Origin");
                IMyTerminalBlock blockOrigin = GridTerminalSystem.GetBlockWithName(nameOrigin);
                _origin = blockOrigin.GetPosition();


                _basisVecA  = Vector3D.Normalize(pointA - _origin);
                _basisVecB  = Vector3D.Normalize(pointB - _origin);
                _basisVecUp = Vector3D.Normalize(pointUp - _origin);

                _basisVecA  = Me.CubeGrid.WorldMatrix.Forward;
                _basisVecB  = Me.CubeGrid.WorldMatrix.Right;
                _basisVecUp = Me.CubeGrid.WorldMatrix.Up;

                alreadyRun = true;
            }

            //IGC
            _turtleListenerInit = IGC.RegisterBroadcastListener(_turtleInit);
            _turtleListenerInit.SetMessageCallback(_turtleInit);

            Runtime.UpdateFrequency |= UpdateFrequency.Update100;
        }
Ejemplo n.º 16
0
            public Spaceship(IMyGridTerminalSystem system, IMyIntergridCommunicationSystem igc)
            {
                this.system = system;
                this.igc    = igc;

                cpu = FindRunningPB(system);

                control   = FindBlockOfType <IMyRemoteControl>(system, this, Settings.TAG);
                connector = FindBlockOfType <IMyShipConnector>(system, this, Settings.TAG);
                debug     = FindBlockOfType <IMyTextPanel>(system, this, Settings.TAG);
                if (debug == null)
                {
                    IMyCockpit cockpit = FindBlockOfType <IMyCockpit>(system, this, Settings.TAG);
                    if (cockpit.SurfaceCount > 0)
                    {
                        debug = cockpit.GetSurface(0);
                    }
                }
                debug.Font        = "Monospace";
                debug.ContentType = ContentType.TEXT_AND_IMAGE;

                /*
                 *  screen = cockpit.GetSurface(0);
                 *  screen.ContentType = ContentType.SCRIPT;
                 *  MySpriteDrawFrame frame = screen.DrawFrame();
                 *
                 *
                 *  frame.Add(new MySprite(SpriteType.TEXTURE, "SquareSimple", new Vector2(0, 0), new Vector2(512, 512), Color.Black));
                 *  frame.Add(MySprite.CreateText("Ftiaxe Me!!!", "DEBUG", Color.White));
                 *  frame.Dispose();
                 */

                listener = igc.RegisterBroadcastListener(Settings.COMM_CHANNEL);
                listener = igc.RegisterBroadcastListener(Settings.COMM_CHANNEL);
                listener.SetMessageCallback(Settings.COMM_CHANNEL);
                thrusters = new ThrustersManager(this, control, system);

                autopilot = new Autopilot(this, control, FindBlockOfType <IMyGyro>(system, this));
                cas       = new CollisionAvoidanceSystem(this);
                fd        = new FlightDirector(this);

                if (connector.Status == MyShipConnectorStatus.Connected)
                {
                    flags = SpaceshipFlags.Dock;
                }
                else
                {
                    flags = SpaceshipFlags.Idle;
                }
            }
Ejemplo n.º 17
0
        public Program()
        {
            // Echo some information about 'me' when I'm compiled
            Echo("Creator.");
            Echo("Me=" + Me.EntityId.ToString());
            Echo(Me.CubeGrid.CustomName);

            // register a broadcast listener
            _bListener = IGC.RegisterBroadcastListener(BroadcastTag); // What it listens for
            _bListener.SetMessageCallback(BroadcastTag);              // What it will run the PB with once it has a message

            // save the unicast listener
            _uListener = IGC.UnicastListener;
            _uListener.SetMessageCallback(UnicastTag); // set PB callback argument to be used
        }
Ejemplo n.º 18
0
        public void setUp()
        {
            control    = GridTerminalSystem.GetBlockWithName("Targetting Ray/Remote") as IMyShipController;
            XROT       = GridTerminalSystem.GetBlockWithName("Targetting Ray/Yaw Rotor") as IMyMotorStator;
            YROT       = GridTerminalSystem.GetBlockWithName("Targetting Ray/Pitch Rotor") as IMyMotorStator;
            camera     = GridTerminalSystem.GetBlockWithName("Targetting Ray/Camera") as IMyCameraBlock;
            soundBlock = GridTerminalSystem.GetBlockWithName("Targetting Ray/Sound Block") as IMySoundBlock;
            if (camera != null && camera.EnableRaycast == false)
            {
                camera.EnableRaycast = true;
            }

            misCMDListener = IGC.RegisterBroadcastListener(misCMDTag);
            misCMDListener.SetMessageCallback();
        }
Ejemplo n.º 19
0
        void NavInitIGC()
        {
            _AddNavListener = IGC.RegisterBroadcastListener(WICOB_NAVADDTARGET);         // What it listens for
            _AddNavListener.SetMessageCallback(WICOB_NAVADDTARGET);                      // What it will run the PB with once it has a message

            _StartNavListener = IGC.RegisterBroadcastListener(WICOB_NAVSTART);           // What it listens for
            _StartNavListener.SetMessageCallback(WICOB_NAVSTART);                        // What it will run the PB with once it has a message

            _ResetNavListener = IGC.RegisterBroadcastListener(WICOB_NAVRESET);           // What it listens for
            _ResetNavListener.SetMessageCallback(WICOB_NAVRESET);                        // What it will run the PB with once it has a message

            _LaunchNavListener = IGC.RegisterBroadcastListener(WICOB_NAVLAUNCH);         // What it listens for
            _LaunchNavListener.SetMessageCallback(WICOB_NAVLAUNCH);                      // What it will run the PB with once it has a message

            _OrbitalNavListener = IGC.RegisterBroadcastListener(WICOB_NAVORBITALLAUNCH); // What it listens for
            _OrbitalNavListener.SetMessageCallback(WICOB_NAVORBITALLAUNCH);              // What it will run the PB with once it has a message
        }
Ejemplo n.º 20
0
        public Program()
        {
            // Prioritize the given cockpit name
            rc = GetBlock <IMyShipController>(cockpitName, true);
            if (rc == null) // Second priority cockpit
            {
                rc = GetBlock <IMyCockpit>();
            }
            if (rc == null) // Third priority remote control
            {
                rc = GetBlock <IMyRemoteControl>();
            }
            if (rc == null) // No cockpits found.
            {
                throw new Exception("No cockpit/remote control found. Set the cockpitName field in settings.");
            }

            wheels = new WheelControl(rc, tickSpeed, GetBlocks <IMyMotorSuspension>());

            leaderListener = IGC.RegisterBroadcastListener(transmitTag);
            leaderListener.SetMessageCallback("");
            commandListener = IGC.RegisterBroadcastListener(transmitCommandTag);
            commandListener.SetMessageCallback("");


            configurations["default"] = defaultOffset;
            offset = defaultOffset;
            LoadStorage();

            if (tickSpeed == UpdateFrequency.Update10)
            {
                echoFrequency = 10;
            }
            else if (tickSpeed == UpdateFrequency.Update100)
            {
                echoFrequency = 1;
            }
            Echo("Ready.");
        }
Ejemplo n.º 21
0
 public void Main(string argument, UpdateType updateSource)
 {
     if ((updateSource & UpdateType.IGC) > 0)
     {
         if (universalListener != null && universalListener.HasPendingMessage)
         {
             MyIGCMessage        message = universalListener.AcceptMessage();
             List <IMyTextPanel> panels  = new List <IMyTextPanel>();
             GridTerminalSystem.GetBlocksOfType(panels);
             if (panels.Count > 0)
             {
                 panels[0].WriteText(message.Tag + " " + message.Source + " " + message.Data + "\n", false);
             }
         }
     }
     else
     {
         universalListener = IGC.RegisterBroadcastListener(argument);
         universalListener.SetMessageCallback();
         Echo("CURRENT LISTENING CODE: " + argument);
     }
 }
Ejemplo n.º 22
0
        public Program()
        {
            //hardware
            _remote    = GridTerminalSystem.GetBlockWithName("Remote [t]") as IMyRemoteControl;
            _gyro      = GridTerminalSystem.GetBlockWithName("Gyroscope [t]") as IMyGyro;
            _connector = GridTerminalSystem.GetBlockWithName("Connector [t]") as IMyShipConnector;
            _messageBuilder.AppendLine("Hardware located.");
            //IGC
            IGC.UnicastListener.SetMessageCallback();
            _turtleListenerInit = IGC.RegisterBroadcastListener(_turtleInit);
            _turtleListenerInit.SetMessageCallback(_turtleInit);
            var op = GridTerminalSystem.GetBlockWithName("Operator [t]") as IMyProgrammableBlock;

            _turtleOperatorID = op.GetId();
            _messageBuilder.AppendLine("IGC loaded.");
            // load program state
            Load();
            // custom data reset - log info
            Me.CustomData            = "\t\tPROGRAM LOG:\n\n" + _messageBuilder;
            Runtime.UpdateFrequency |= UpdateFrequency.Once;
            _stateMachine            = Idle();
        }
Ejemplo n.º 23
0
        private void UpdateSettings()
        {
            var parser = new MyIni();

            if (!parser.TryParse(Me.CustomData))
            {
                throw new InvalidOperationException("Couldn't parse CustomData as INI!");
            }
            this.tag       = parser.Get(SETTINGS_SECTION, "tag").ToString(MissileCommons.DEFAULT_TAG);
            this.statusTag = parser.Get(SETTINGS_SECTION, "statusTag").ToString(MissileCommons.STATUS_TAG);
            this.directing = parser.Get(SETTINGS_SECTION, "directing").ToBoolean(true);
            if (this.directing)
            {
                this.directorTurret = GridTerminalSystem.GetBlockOfType <IMyLargeTurretBase>(t => MyIni.HasSection(t.CustomData, DIRECTOR_TURRET_SECTION));
                if (this.directorTurret != null)
                {
                    LogLine($"Director mode on, found director turret {directorTurret.CustomName}");
                }
                else
                {
                    LogLine($"No director turret was found. If you have one, add the [{DIRECTOR_TURRET_SECTION}] line to its Custom Data. Disabling director mode.");
                    this.directing = false;
                }
            }
            if (missileMsgListener != null)
            {
                missileMsgListener.DisableMessageCallback();
            }
            missileMsgListener = IGC.RegisterBroadcastListener(this.tag);
            missileMsgListener.SetMessageCallback();

            if (missileStatusListener != null)
            {
                missileStatusListener.DisableMessageCallback();
            }
            missileStatusListener = IGC.RegisterBroadcastListener(MissileCommons.STATUS_TAG);
            missileStatusListener.SetMessageCallback();
        }
Ejemplo n.º 24
0
        void Initalize()
        {
            var controls = new List <IMyRemoteControl>();

            GridTerminalSystem.GetBlocksOfType(controls);

            mainControl = controls.Find(control => {
                try { return(JSON.Parse(control.CustomData).jsonObject["type"].jsonString == "mainControl"); }
                catch { return(false); }
            });
            name              = $"Greedle ID {new Random().Next()}";
            target            = Vector3.Zero;
            directiveListener = IGC.RegisterBroadcastListener("greedle_directive");
            directiveListener.SetMessageCallback();

            var antennas = new List <IMyRadioAntenna>();

            GridTerminalSystem.GetBlocksOfType(antennas);
            foreach (var antenna in antennas)
            {
                antenna.HudText = name;
            }
            Me.GetSurface(0).ContentType = ContentType.TEXT_AND_IMAGE;
        }
Ejemplo n.º 25
0
        void Start()
        {
            gridSystem = GridTerminalSystem;
            gridId     = Me.CubeGrid.EntityId;
            turrets    = GetBlocks <IMyLargeTurretBase>(turretGroup, useSubgrids);

            wcTurrets = new WcPbApi();
            try
            {
                if (!wcTurrets.Activate(Me))
                {
                    wcTurrets = null;
                }
            }
            catch
            {
                wcTurrets = null;
            }

            if (string.IsNullOrWhiteSpace(rcName))
            {
                rc = GetBlock <IMyRemoteControl>();
            }
            else
            {
                rc = GetBlock <IMyRemoteControl>(rcName, useSubgrids);
            }
            if (rc == null)
            {
                throw new Exception("Remote control block not found.");
            }
            gyros  = new GyroControl(rc);
            origin = rc.GetPosition();

            this.guns = new List <IMyUserControllableGun>();
            List <IMyUserControllableGun> guns = GetBlocks <IMyUserControllableGun>(gunsGroup, useSubgrids);

            foreach (IMyUserControllableGun g in guns)
            {
                if (!(g is IMyLargeTurretBase))
                {
                    g.SetValueBool("Shoot", false);
                    if (rocketMode != RocketMode.None)
                    {
                        IMySmallMissileLauncher m = g as IMySmallMissileLauncher;
                        if (m != null)
                        {
                            rockets.Add(m);
                            continue;
                        }
                    }
                    this.guns.Add(g);
                }
            }

            if (receiveHelpMsgs)
            {
                helpListener = IGC.RegisterBroadcastListener("AttackDrone_" + commsId);
                helpListener.SetMessageCallback("");
            }


            thrust       = new ThrusterControl(rc, GetBlocks <IMyThrust>(thrustGroup));
            maxAngle    *= Math.PI / 180;
            startRuntime = -1;
        }
Ejemplo n.º 26
0
        void doModeDocking()
        {
            StatusLog("clear", textPanelReport);
            StatusLog(moduleName + ":DOCKING!", textPanelReport);
//            StatusLog(moduleName + ":Docking: current_state=" + current_state, textPanelReport);
//            StatusLog(moduleName + ":Docking: current_state=" + current_state, textLongStatus, true);
//           bWantFast = true;
            Echo("DOCKING: state=" + current_state);

            bWantSlow = true;

            IMySensorBlock sb;

            if (dockingConnector == null)
            {
                current_state = 0;
            }

//            sInitResults += "DOCKING: state=" + current_state+"\n";

            if (current_state == 0)
            {
//                sInitResults = "DOCKING: state=" + current_state+"\n";
                if (AnyConnectorIsConnected())
                {
                    setMode(MODE_DOCKED);
                    return;
                }

                // these will replace any existing channel
                _CONDIGCChannel = IGC.RegisterBroadcastListener("COND");   // What it listens for
                _CONDIGCChannel.SetMessageCallback("COND");                // What it will run the PB with once it has a message
                _ACONDIGCChannel = IGC.RegisterBroadcastListener("ACOND"); // What it listens for
                _ACONDIGCChannel.SetMessageCallback("ACOND");              // What it will run the PB with once it has a message
                _CONAIGCChannel = IGC.RegisterBroadcastListener("CONA");   // What it listens for
                _CONAIGCChannel.SetMessageCallback("CONA");                // What it will run the PB with once it has a message

                doSubModuleTimerTriggers("[DOCKING]");
                dockingConnector = getDockingConnector();
                if (dockingConnector == null)// || getAvailableRemoteConnector(out targetConnector))
                {
                    Echo("No local connector for docking");
                    StatusLog(moduleName + ":No local Docking Connector Available!", textLongStatus, true);
                    // we could check for merge blocks.. or landing gears..
                    sStartupError += "\nNo local Docking Connector Available!";
                    setMode(MODE_ATTENTION);
                    bWantFast = false;
                    return;
                }
                else
                {
                    ResetMotion();
                    turnDrillsOff();

                    thrustersInit(dockingConnector, ref thrustDockForwardList, ref thrustDockBackwardList,
                                  ref thrustDockDownList, ref thrustDockUpList,
                                  ref thrustDockLeftList, ref thrustDockRightList);
                    current_state = 100;
                }
                lTargetBase = 0;// iTargetBase = -1;
            }
            Vector3D vPos = dockingConnector.GetPosition();

            if (!AnyConnectorIsConnected() && AnyConnectorIsLocked())
            {
                ConnectAnyConnectors();
                ResetMotion();
                setMode(MODE_DOCKED);
                powerDownThrusters(thrustAllList, thrustAll, true);
                return;
            }
            if (current_state == 100)
            {
                // TODO: allow for relay ships that are NOT bases..
                // TODO: if memory docking, don't need to adjust antenna
                // TODO: if stealth mode, don't mess with antenna
                float range = RangeToNearestBase() + 100f + (float)velocityShip * 5f;
                antennaMaxPower(false, range);
                if (sensorsList.Count > 0)
                {
                    sb = sensorsList[0];
                    //			setSensorShip(sb, 1, 1, 1, 1, 50, 1);
                }
                current_state = 110;
            }
            else if (current_state == 110)
            { // wait for slow
                if (velocityShip < 10)
                {
                    if (lTargetBase <= 0)
                    {
                        lTargetBase = BaseFindBest();
                    }
                    //                    sInitResults += "110: Base=" + iTargetBase;
                    dtDockingActionStart = DateTime.Now;
                    if (lTargetBase > 0)
                    {
                        calculateGridBBPosition(dockingConnector);
                        Vector3D[] points = new Vector3D[4];
                        _obbf.GetFaceCorners(5, points); // 5 = front
                                                         // front output order is BL, BR, TL, TR
                        double width  = (points[0] - points[1]).Length();
                        double height = (points[0] - points[2]).Length();
                        _obbf.GetFaceCorners(0, points);
                        // face 0=right output order is  BL, TL, BR, TR ???
                        double length = (points[0] - points[2]).Length();

                        string sMessage = "";// = "WICO:CON?:";
                        string sTag     = "CON?";
                        sMessage += lTargetBase.ToString() + ":";
                        //$"{height:N1},{width:N1},{length:N1}:";
                        sMessage += height.ToString("0.0") + "," + width.ToString("0.0") + "," + length.ToString("0.0") + ":";
                        //                    sMessage += shipDim.HeightInMeters() + "," + shipDim.WidthInMeters() + "," + shipDim.LengthInMeters() + ":";
                        sMessage += shipOrientationBlock.CubeGrid.CustomName + ":";
                        sMessage += SaveFile.EntityId.ToString() + ":";
                        sMessage += Vector3DToString(shipOrientationBlock.GetPosition());
                        antSend(sTag, sMessage); // antSend(sMessage);
                                                 //                        antSend("WICO:CON?:" + baseIdOf(iTargetBase).ToString() + ":" + "mini" + ":" + shipOrientationBlock.CubeGrid.CustomName + ":" + SaveFile.EntityId.ToString() + ":" + Vector3DToString(shipOrientationBlock.GetPosition()));
                        current_state = 120;
                    }
                    else // No available base
                    {
                        // try to get a base to respond
                        checkBases(true);
                        current_state = 130;
                        //                        setMode(MODE_ATTENTION);
                    }
                }
                else
                {
                    ResetMotion();
                }
            }
            else if (current_state == 120)
            { // wait for reply from base
                StatusLog("Awaiting Response from Base", textPanelReport);

                bWantFast = false;
                DateTime dtMaxWait = dtDockingActionStart.AddSeconds(5.0f);
                DateTime dtNow     = DateTime.Now;
                if (DateTime.Compare(dtNow, dtMaxWait) > 0)
                {
                    sStartupError += "\nTime out awaiting CONA";
                    current_state  = 125;
                    return;
                }
                //                if (sReceivedMessage != "")
                if (_CONAIGCChannel.HasPendingMessage)
                {
                    var    igcMessage = _CONAIGCChannel.AcceptMessage();
                    string sMessage   = (string)igcMessage.Data;
//                    Echo("Received Message=\n" + sMessage);
                    string[] aMessage = sMessage.Trim().Split(':');
                    Echo(aMessage.Length + ": Length");
                    for (int i = 0; i < aMessage.Length; i++)
                    {
                        Echo(i + ":" + aMessage[i]);
                    }
                    if (aMessage.Length > 1)
                    {
                        /*
                         * if (aMessage[0] != "WICO")
                         * {
                         *  Echo("not wico system message");
                         *  return;
                         * }
                         * if (aMessage.Length > 2)
                         * {
                         *  if (aMessage[1] == "CONA")
                         *  {
                         */
                        Echo("Approach answer!");
                        //antSend("WICO:CONA:" + droneId +":" + SaveFile.EntityId.ToString(), +":"+Vector3DToString(vApproachPosition))
                        int iOffset = 0;

                        long id = 0;
                        long.TryParse(aMessage[iOffset++], out id);
                        if (id == SaveFile.EntityId)
                        {
                            // it's a message for us.
//                                    sReceivedMessage = ""; // we processed it.
                            long.TryParse(aMessage[iOffset++], out id);
                            double x, y, z;
//                                    int iOff = iOffset++;
                            x = Convert.ToDouble(aMessage[iOffset++]);
                            y = Convert.ToDouble(aMessage[iOffset++]);
                            z = Convert.ToDouble(aMessage[iOffset++]);
                            Vector3D vPosition = new Vector3D(x, y, z);

                            vHome      = vPosition;
                            bValidHome = true;
                            //                                        StatusLog("clear", gpsPanel);
                            //                                        debugGPSOutput("Home", vHome);

                            current_state = 150;
                        }
                    }
                    // TODO: need to process CONF

                    /*
                     * }
                     * }
                     */
                }
                else
                { // uses timeout from above
                    Echo("Awaiting reply message");
                }
            }
            else if (current_state == 125)
            { // timeout waiting for reply from base..
                // move closer to the chosen base's last known position.
                if (lTargetBase <= 0)
                {
                    // TODO: remove base from list and try again.  ATTENTION if no remaining bases
                    sStartupError += "\nNo Base in range";
                    setMode(MODE_ATTENTION);
                    return;
                }
                else if (RangeToNearestBase() < 3000)
                {
                    // we think we are close enough
                    // force recheck
//                    sStartupError += "\nForce Recheck";
                    lTargetBase = -1;
                    checkBases(true);
                    current_state = 110;
                }
                else
                {
                    // get closer
//                    sStartupError += "\nGet Closer";
                    NavGoTarget(BasePositionOf(lTargetBase), iMode, 110, 3100, "DOCK Base Proximity");
                    current_state = 126;
                }
                //                doTravelMovement(BasePositionOf(lTargetBase), 3100, 110, 106);
            }
            else if (current_state == 126)
            {
                // we are waiting for NAV module to get message and start
                Echo("Waiting for NAV to start");
            }
            else if (current_state == 130)
            {
                // no known bases. requested response. wait for a while to see if we get one
                StatusLog("Trying to find a base", textPanelReport);
                bWantFast = false;
                DateTime dtMaxWait = dtDockingActionStart.AddSeconds(2.0f);
                DateTime dtNow     = DateTime.Now;
                if (DateTime.Compare(dtNow, dtMaxWait) > 0)
                {
                    sStartupError += "\nTimeout finding base";
                    setMode(MODE_ATTENTION);
                    return;
                }
                if (BaseFindBest() >= 0)
                {
                    current_state = 110;
                }
            }

            else if (current_state == 150)
            { //150	Move to 'approach' location (or current location) ?request 'wait' location?
                current_state = 175;

                /*
                 * if (bValidHome)
                 * {
                 *  double distancesqHome = Vector3D.DistanceSquared(vHome, shipOrientationBlock.GetPosition());
                 *  if (distancesqHome > 25000) // max SG antenna range //TODO: get max from antenna module
                 *  {
                 *      current_state = 175;
                 *  }
                 *  else current_state = 200;
                 * }
                 * else current_state = 200;
                 */
            }
            else if (current_state == 175)
            { // get closer to approach location
                NavGoTarget(vHome, iMode, 200, 5, "DOCK Base Approach");
                current_state = 176;
            }
            else if (current_state == 176)
            {
                // we are waiting for NAV module to get message and start
                Echo("Waiting for NAV to start");
            }
            else if (current_state == 200)
            {//200	Arrived at approach location
                // request available docking connector
                StatusLog("Requsting Docking Connector", textPanelReport);
                if (velocityShip < 1)
                {
                    calculateGridBBPosition(dockingConnector);
                    Vector3D[] points = new Vector3D[4];
                    _obbf.GetFaceCorners(5, points); // 5 = front
                                                     // front output order is BL, BR, TL, TR
                    double width  = (points[0] - points[1]).Length();
                    double height = (points[0] - points[2]).Length();
                    _obbf.GetFaceCorners(0, points);
                    // face 0=right output order is  BL, TL, BR, TR ???
                    double length = (points[0] - points[2]).Length();

                    string sMessage = "";// "WICO:COND?:";
                    string sTag     = "COND?";
                    sMessage += lTargetBase.ToString() + ":";
                    sMessage += height.ToString("0.0") + "," + width.ToString("0.0") + "," + length.ToString("0.0") + ":";
                    //                    sMessage += shipDim.HeightInMeters() + "," + shipDim.WidthInMeters() + "," + shipDim.LengthInMeters() + ":";
                    sMessage += shipOrientationBlock.CubeGrid.CustomName + ":";
                    sMessage += SaveFile.EntityId.ToString() + ":";
                    sMessage += Vector3DToString(shipOrientationBlock.GetPosition());
                    antSend(sTag, sMessage);// antSend(sMessage);

                    //                    antSend("WICO:COND?:" + baseIdOf(iTargetBase) + ":" + "mini" + ":" + shipOrientationBlock.CubeGrid.CustomName + ":" + SaveFile.EntityId.ToString() + ":" + Vector3DToString(shipOrientationBlock.GetPosition()));
                    {
                        dtDockingActionStart = DateTime.Now;
                        current_state        = 210;
                    }
                }
                else
                {
                    ResetMotion();
                }
            }
            else if (current_state == 210)
            { //210	wait for available connector
                StatusLog("Awaiting reply with Docking Connector", textPanelReport);
                bWantFast = false;
                DateTime dtMaxWait = dtDockingActionStart.AddSeconds(5.0f);
                DateTime dtNow     = DateTime.Now;
                if (DateTime.Compare(dtNow, dtMaxWait) > 0)
                {
                    sStartupError += "\nTime out awaiting COND";
                    current_state  = 100;
                    return;
                }
                if (getAvailableRemoteConnector(out targetConnector))
                {
                    current_state = 250;
                }
                else
                {
                    if (_CONDIGCChannel.HasPendingMessage || _ACONDIGCChannel.HasPendingMessage)
//                        if (sReceivedMessage != "")
                    {
//                        sStartupError += "\nCOND received:";
                        string sMessage      = "";
                        bool   bAlignMessage = false;
                        if (_CONDIGCChannel.HasPendingMessage)
                        {
                            var igcMessage = _CONDIGCChannel.AcceptMessage();
                            sMessage = (string)igcMessage.Data;
                        }
                        else
                        {
                            var igcMessage = _ACONDIGCChannel.AcceptMessage();
                            sMessage      = (string)igcMessage.Data;
                            bAlignMessage = true;
                        }
                        //                       Echo("Received Message=\n" + sReceivedMessage);
                        string[] aMessage = sMessage.Trim().Split(':');
                        Echo(aMessage.Length + ": Length");
                        for (int i = 0; i < aMessage.Length; i++)
                        {
                            Echo(i + ":" + aMessage[i]);
                        }
                        int iOffset = 0;

                        /*
                         * if (aMessage.Length > 1)
                         * {
                         *  if (aMessage[0] != "WICO")
                         *  {
                         *      Echo("not wico system message");
                         *      return;
                         *  }
                         *  if (aMessage.Length > 2)
                         *  {
                         */
                        //                                if (aMessage[1] == "DOCK" || aMessage[1] == "ADOCK")
                        //                               if (aMessage[1] == "COND" || aMessage[1] == "ACOND")
                        {
                            Echo("Docking answer!");
                            // FORMAT:	antSend("WICO:DOCK:" + aMessage[3] + ":" + connector.EntityId + ":" + connector.CustomName + ":" + Vector3DToString(vPosition) + ":" + Vector3DToString(vVec));
                            //	antSend("WICO:ADOCK:" + incomingID + ":" + connector.EntityId + ":" + connector.CustomName  + ":" + Vector3DToString(vPosition) + ":" + Vector3DToString(vVec)+":" + Vector3DToString(vAlign));

                            long id = 0;
                            long.TryParse(aMessage[iOffset++], out id);
                            if (id == SaveFile.EntityId)
                            {
                                // it's a message for us.
//                                sReceivedMessage = ""; // we processed it.
                                long.TryParse(aMessage[iOffset++], out id);
                                string sName = aMessage[iOffset++];
                                double x, y, z;
                                //                                        int iOff = 5;
                                x = Convert.ToDouble(aMessage[iOffset++]);
                                y = Convert.ToDouble(aMessage[iOffset++]);
                                z = Convert.ToDouble(aMessage[iOffset++]);
                                Vector3D vPosition = new Vector3D(x, y, z);

                                x = Convert.ToDouble(aMessage[iOffset++]);
                                y = Convert.ToDouble(aMessage[iOffset++]);
                                z = Convert.ToDouble(aMessage[iOffset++]);
                                Vector3D vVec = new Vector3D(x, y, z);

                                //                                        if (aMessage[1] == "ACOND")
                                if (bAlignMessage)
                                {
                                    x            = Convert.ToDouble(aMessage[iOffset++]);
                                    y            = Convert.ToDouble(aMessage[iOffset++]);
                                    z            = Convert.ToDouble(aMessage[iOffset++]);
                                    vDockAlign   = new Vector3D(x, y, z);
                                    bDoDockAlign = true;
                                }
                                vDock         = vPosition;
                                vLaunch1      = vDock + vVec * (shipDim.LengthInMeters() * 1.5);
                                vHome         = vDock + vVec * (shipDim.LengthInMeters() * 3);
                                bValidDock    = true;
                                bValidLaunch1 = true;
                                bValidHome    = true;
                                StatusLog("clear", gpsPanel);
                                debugGPSOutput("dock", vDock);
                                debugGPSOutput("launch1", vLaunch1);
                                debugGPSOutput("Home", vHome);

                                current_state = 300;
                            }
//                            else sStartupError += "\nCOND, but not my boat";
                        }
                        // TODO handle CONF

                        /*
                         * }
                         * }
                         */
                    }
                    else
                    { // uses timeout from above
                        Echo("Awaiting reply message");
                    }
                }
            }
            else if (current_state == 250)
            { //250	when available, calculate approach locations from a saved targetconnector
                vDock         = targetConnector.vPosition;
                vLaunch1      = vDock + targetConnector.vVector * (shipDim.LengthInMeters() * 1.5);
                vHome         = vDock + targetConnector.vVector * (shipDim.LengthInMeters() * 3);
                bValidDock    = true;
                bValidLaunch1 = true;
                bValidHome    = true;
                current_state = 300;
                StatusLog("clear", gpsPanel);
                debugGPSOutput("dock", vDock);
                debugGPSOutput("launch1", vLaunch1);
                debugGPSOutput("Home", vHome);
                MoveForwardSlowReset();
                bWantFast = true;
            }
            else if (current_state == 300)
            { //300  Start:	Move through locations
                current_state = 310;
                MoveForwardSlowReset();
//                iDockingPushCount = 0;
                bWantFast = true;
            }
            else if (current_state == 310)
            { //	310 move to home
                Echo("Moving to Home");
                //		if(iPushCount<60) iPushCount++;
                //		else

                NavGoTarget(vHome, iMode, 340, 3, "DOCK Approach");
                //               doTravelMovement(vHome, 3.0f, 350, 161);
                current_state = 311;
            }
            else if (current_state == 311)
            {
                // we are waiting for NAV module to get message and start
                Echo("Waiting for NAV to start");
            }
            else if (current_state == 340)
            { // arrived at 'home' from NAV
                ResetMotion();
                Echo("Waiting for ship to stop");
                turnEjectorsOff();
                MoveForwardSlowReset();
//                iDockingPushCount = 0;
                if (velocityShip < 0.1f)
                {
                    bWantFast     = true;
                    current_state = 350;
                }
                else
                {
                    bWantMedium = true;
                    //                    bWantFast = false;
                }
            }
            else if (current_state == 350)
            {
                // move connector closer to home
                double distanceSQ = (vHome - ((IMyShipController)shipOrientationBlock).CenterOfMass).LengthSquared();
                Echo("DistanceSQ=" + distanceSQ.ToString("0.0"));
                double stoppingDistance = calculateStoppingDistance(thrustBackwardList, velocityShip, 0);
                if (distanceSQ > shipDim.BlockMultiplier() * 3)
                {
                    MoveForwardSlow(3, 5, thrustForwardList, thrustBackwardList);
                    bWantMedium = true;
                }
                else
                {
                    ResetMotion();
                    doSubModuleTimerTriggers("[DOCKING:APPROACH]");
                    MoveForwardSlowReset();
                    current_state = 400;
                    bWantFast     = true;
                }
            }
            else if (current_state == 400)
            {
                // move to Launch1
                Echo("Moving to Launch1");

                NavGoTarget(vLaunch1, iMode, 410, 3, "DOCK Connector Entry");
                current_state = 401;
            }
            else if (current_state == 401)
            {
                // we are waiting for NAV module to get message and start
                Echo("Waiting for NAV to start");
            }
            else if (current_state == 410)
            {
                // move closer to Launch1
                double distanceSQ = (vLaunch1 - ((IMyShipController)shipOrientationBlock).CenterOfMass).LengthSquared();
                Echo("DistanceSQ=" + distanceSQ.ToString("0.0"));
                double stoppingDistance = calculateStoppingDistance(thrustBackwardList, velocityShip, 0);
                if (distanceSQ > shipDim.BlockMultiplier() * 3)
                {
                    MoveForwardSlow(3, 5, thrustForwardList, thrustBackwardList);
                    bWantMedium = true;
                }
                else
                {
                    ResetMotion();
                    MoveForwardSlowReset();
                    current_state = 430;
                    bWantFast     = true;
                }
            }
            else if (current_state == 430)
            {
                // arrived at launch1
                bWantFast           = true;
                dockingLastDistance = -1;
                current_state       = 450;
                // TODO: do/waitfor mechanical changes needed for docking
            }
            else if (current_state == 450 || current_state == 452)
            { //450 452 'reverse' to dock, aiming connector at dock location
              // align to docking alignment if needed
                StatusLog("Align Up to Docking Connector", textPanelReport);
                bWantFast = true;
                //                turnEjectorsOff();
                if (!bDoDockAlign)
                {
                    current_state = 500;
                    return;
                }
                Echo("Aligning to dock");
                bool bAimed = false;
                minAngleRad = 0.03f;

                // TODO: need to change direction if non- 'back' connector
                bAimed    = GyroMain("up", vDockAlign, shipOrientationBlock);
                bWantFast = true;
                if (current_state == 452)
                {
                    current_state = 500;
                }
                else if (bAimed)
                {
                    current_state++;              // 450->451
                }
            }
            else if (current_state == 451)
            { //451 align to dock
                StatusLog("Align to Docking Connector", textPanelReport);
                bWantFast = true;
                Vector3D vTargetLocation = vDock;
                Vector3D vVec            = vTargetLocation - dockingConnector.GetPosition();

                if (!bDoDockAlign)
                {
                    current_state = 452;
                }

                //		Vector3D vTargetLocation = shipOrientationBlock.GetPosition() +vDockAlign;
                //		Vector3D vVec = vTargetLocation - shipOrientationBlock.GetPosition();
                Echo("Aligning to dock");
                bool bAimed = false;
                minAngleRad = 0.03f;
                bAimed      = GyroMain("forward", vVec, dockingConnector);
                if (bAimed)
                {
                    current_state = 452;
                }
                else
                {
                    bWantFast = true;
                }
            }
            else if (current_state == 500)
            { //500 'reverse' to dock, aiming connector at dock location (really it's connector-forward)
              // TODO: needs a time-out for when misaligned or base connector moves.
              //               bWantFast = true;
                StatusLog("Reversing to Docking Connector", textPanelReport);
                Echo("bDoDockAlign=" + bDoDockAlign);
                //                StatusLog(moduleName + ":Docking: Reversing to dock! Velocity=" + velocityShip.ToString("0.00"), textPanelReport);
                Echo("Reversing to Dock");
                CTRL_COEFF  = 0.75;
                minAngleRad = 0.01f;

                Vector3D vTargetLocation = vDock;
                Vector3D vVec            = vTargetLocation - dockingConnector.GetPosition();
                double   distance        = vVec.Length();
                Echo("distance=" + niceDoubleMeters(distance));
                Echo("velocity=" + velocityShip.ToString("0.00"));
                StatusLog("Distance=" + niceDoubleMeters(distance), textPanelReport);
                StatusLog("Velocity=" + niceDoubleMeters(velocityShip) + "/s", textPanelReport);

                if (dockingLastDistance < 0)
                {
                    dockingLastDistance = distance;
                }
                if (dockingLastDistance < distance)
                {
                    // we are farther away than last time... something is wrong..
//                    sStartupError += "\nLast=" + niceDoubleMeters(dockingLastDistance) + " Cur=" + niceDoubleMeters(distance);
                    current_state = 590;
                }
                if (distance > 10)
                {
                    minAngleRad = 0.03f;
                }
                else
                {
                    minAngleRad = 0.05f;
                }

                //                debugGPSOutput("DockLocation", vTargetLocation);

                bool bAimed = false;

                /*
                 *      if ((craft_operation & CRAFT_MODE_SLED) > 0)
                 *      {
                 *          double yawangle = CalculateYaw(vTargetLocation, dockingConnector);
                 *          DoRotate(yawangle, "Yaw");
                 *          if (Math.Abs(yawangle) < .05) bAimed = true;
                 *      }
                 *      else
                 */
                if (distance > 15)
                {
                    bAimed = BeamRider(vLaunch1, vDock, dockingConnector);
                }
                else
                {
                    bAimed = GyroMain("forward", vVec, dockingConnector);
                }

                /*
                 * double maxThrust = calculateMaxThrust(thrustDockForwardList);
                 * MyShipMass myMass;
                 * myMass = ((IMyShipController)shipOrientationBlock).CalculateShipMass();
                 * double effectiveMass = myMass.PhysicalMass;
                 * double maxDeltaV = (maxThrust) / effectiveMass;
                 * if (iDockingPushCount < 1)
                 * {
                 *  if (maxDeltaV < 2)
                 *      iDockingPushCount = 75;
                 *  else if (maxDeltaV < 5)
                 *      iDockingPushCount = 25;
                 * }
                 */
                //               Echo("dockingPushCount=" + iDockingPushCount);
                // TODO: if we aren't moving and dockingpushcount>100, then we need to wiggle.

                if (bAimed)
                {
                    // we are aimed at location
                    Echo("Aimed");
                    if (distance > 15)
                    {
                        bWantMedium = true;
                        Echo(">15");
                        MoveForwardSlow(5, 10, thrustDockForwardList, thrustDockBackwardList);

                        /*
                         * if (velocityShip < .5)
                         * {
                         *  iDockingPushCount++;
                         *  powerUpThrusters(thrustDockForwardList, 25 + iDockingPushCount);
                         * }
                         * else if (velocityShip < 5)
                         * {
                         *  powerUpThrusters(thrustDockForwardList, 1);
                         * }
                         * else
                         *  powerDownThrusters(thrustAllList);
                         */
                    }
                    else
                    {
                        Echo("<=15");
                        bWantFast = true;
                        MoveForwardSlow(.5f, 1.5f, thrustDockForwardList, thrustDockBackwardList);

                        /*
                         * if (velocityShip < .5)
                         * {
                         *  iDockingPushCount++;
                         *  powerUpThrusters(thrustDockForwardList, 25 + iDockingPushCount);
                         * }
                         * else if (velocityShip < 1.4)
                         * {
                         *  powerUpThrusters(thrustDockForwardList, 1);
                         *  if (iDockingPushCount > 0) iDockingPushCount--;
                         * }
                         * else
                         *  powerDownThrusters(thrustAllList);
                         */
                    }
                }
                else
                {
                    Echo("Aiming");
                    powerDownThrusters(thrustAllList);
                    bWantFast = true;
                }
            }
            else if (current_state == 590)
            {
                // abort dock and try again
                ResetMotion();
                Vector3D vVec     = vDock - dockingConnector.GetPosition();
                double   distance = vVec.Length();
                if (distance > shipDim.LengthInMeters() * 1.25)
                {
                    // we are far enough away.  Try again
                    current_state = 0;
                    bWantFast     = true;
                    return;
                }
                bool bAimed = GyroMain("forward", vVec, dockingConnector);
                if (!bAimed)
                {
                    bWantFast = true;
                }
                else
                {
                    bWantMedium = true;
                }
                MoveForwardSlow(5, 10, thrustDockBackwardList, thrustDockForwardList);
            }
        }
Ejemplo n.º 27
0
 public Program()
 {
     universalListener = IGC.RegisterBroadcastListener("CODE");
     universalListener.SetMessageCallback();
 }
        public Program()
        {
            Runtime.UpdateFrequency = UpdateFrequency.Update1;
            SayMyName(MY_PREFIX);
            ErrorOutput("", false);
            GetRadars();
            GetControllingBlock();
            GetTurretController();
            int i = 0;

            try {
                string[] args = Storage.Split(';');
                currExt = float.Parse(args[i++]);
                currRPM = float.Parse(args[i++]);

                DetectPlayers         = bool.Parse(args[i++]);
                DetectFloatingObjects = bool.Parse(args[i++]);
                DetectSmallShips      = bool.Parse(args[i++]);
                DetectLargeShips      = bool.Parse(args[i++]);
                DetectStations        = bool.Parse(args[i++]);
                DetectSubgrids        = bool.Parse(args[i++]);
                DetectAsteroids       = bool.Parse(args[i++]);

                DetectOwner    = bool.Parse(args[i++]);
                DetectFriendly = bool.Parse(args[i++]);
                DetectNeutral  = bool.Parse(args[i++]);
                DetectEnemy    = bool.Parse(args[i++]);

                AEGIS = bool.Parse(args[i++]);
            }
            catch (Exception e) {
                e.ToString();
                int f = 0;

                if (++f >= i)
                {
                    currExt = 8000f;
                }
                if (++f >= i)
                {
                    currRPM = 3f;
                }

                if (++f >= i)
                {
                    DetectPlayers = false;
                }
                if (++f >= i)
                {
                    DetectFloatingObjects = false;
                }
                if (++f >= i)
                {
                    DetectSmallShips = true;
                }
                if (++f >= i)
                {
                    DetectLargeShips = true;
                }
                if (++f >= i)
                {
                    DetectStations = true;
                }
                if (++f >= i)
                {
                    DetectSubgrids = false;
                }
                if (++f >= i)
                {
                    DetectAsteroids = false;
                }

                if (++f >= i)
                {
                    DetectOwner = false;
                }
                if (++f >= i)
                {
                    DetectFriendly = false;
                }
                if (++f >= i)
                {
                    DetectNeutral = true;
                }
                if (++f >= i)
                {
                    DetectEnemy = true;
                }

                if (++f >= i)
                {
                    AEGIS = true;
                }
            }
            SetRadars(currExt, currRPM);
            GetScreens();
            misCMDListener = IGC.RegisterBroadcastListener(misCMDTag);
            misCMDListener.SetMessageCallback();
        }