public void AddContact(long id)
 {
     if (!this.listeContactId.Contains(id))
     {
         p.Echo("Add contact" + id);
         this.listeContactId.Add(id);
     }
 }
Beispiel #2
0
 private void showText(string text, int tick)
 {
     foreach (Display scr in getUpdatingDisplays(tick))
     {
         scr.display.WriteText(text + "\n", true);
         //scr.ShowPublicTextOnScreen();
     }
     caller.Echo(text);
 }
Beispiel #3
0
        // [License]
        // LicenseString = AKI-30000101
        // Key = 7729408826157419017
        private void ParseConfigs()
        {
            ErrorMsg = "";
            MyIni Parser = new MyIni();

            if (!Parser.TryParse(Program.Me.CustomData))
            {
                return;
            }

            var LicenseString = Parser.Get(LicenseHasher.GetLicenseField(), LicenseHasher.GetLicenseString()).ToString();
            var Key           = Parser.Get(LicenseHasher.GetLicenseField(), LicenseHasher.GetLicenseKeyString()).ToInt64();

            if (StringToNumber(LicenseString) != Key)
            {
                Crash(LicenseHasher.GetWrongKeyError());
                EchoError();
                LicenseOK = false;
                return;
            }

            string[] fields = LicenseString.Split('-');
            if (fields[0] != GetTagFunction(Program.Me)())
            {
                Crash(LicenseHasher.GetWrongOwnerError());
                EchoError();
                LicenseOK = false;
                return;
            }

            var year  = int.Parse(fields[1].Substring(0, 4));
            var month = int.Parse(fields[1].Substring(4, 2));
            var day   = int.Parse(fields[1].Substring(6, 2));

            if (new DateTime(year, month, day) < DateTime.Today)
            {
                Crash(LicenseHasher.GetElapsedError());
                EchoError();
                LicenseOK = false;
                return;
            }

            if (ErrorMsg == string.Empty)
            {
                stringBuilder.Clear();
                stringBuilder.AppendLine("<< Project Looking Glass >>");
                stringBuilder.AppendLine("<< V 1.01 >>");
                stringBuilder.AppendLine();
                stringBuilder.AppendLine("<< License Accepted >>");
                stringBuilder.AppendLine($"<< License Holder - {fields[0]} >>");
                stringBuilder.AppendLine($"<< License Valid Until - {year}/{month}/{day} >>");
                stringBuilder.AppendLine();
                stringBuilder.AppendLine("<< AKI thanks you for your business. >>");
                Program.Echo(stringBuilder.ToString());
            }
        }
Beispiel #4
0
        public void Print(List <IMyTextSurface> LogScreens)
        {
            string Output = Prefix + RunIndicator() + "\n"; //Add default massage

            _program.Echo("Detected screens: " + LogScreens.Count);
            foreach (string Line in Messages)
            {
                Output += Line + "\n";
            }

            Messages = new List <string>(); //reset lists

            if (Warnings.Count > 0)
            {
                Output += "\nWarnings:\n";
                foreach (string Line in Warnings)
                {
                    Output += Line + "\n";
                }
            }

            Warnings = new List <string>();

            if (Errors.Count > 0)
            {
                Output += "\nErrors:\n";
                foreach (string Line in Errors)
                {
                    Output += Line + "\n";
                }
            }

            Errors = new List <string>();

            if (LogScreens.Count <= 0)
            {
                Output += "No output screens detected.\n";
            }

            foreach (IMyTextSurface Screen in LogScreens)
            {
                try {
                    Screen.ContentType = ContentType.TEXT_AND_IMAGE;
                    Screen.WriteText(Output);
                } catch {
                    _program.Echo(Screen.Name + " is not a valid screen.");
                }
            }


            _program.Echo(Output);
        }
Beispiel #5
0
            internal AirlockState tick(float atmo, double tankFill)
            {
                AirlockState?ret = null;

                if (atmo < MAX_ATMOSPHERE)
                {
                    float air = getAtmo();

                    if (atmoLastTick > atmo)                       //accidentally left outside doors open? But only want to fire this once, not continuously, or it keeps closing airlocks
                    {
                        setAirlockState(AirlockState.CLOSED, false, air);
                    }

                    if (isDepressurized())
                    {
                        //show("Airlock '"+airlockID+"' is depressurized.");
                    }
                    else if (isBreached())
                    {
                        caller.Echo("Airlock '" + airlockID + "' is breached!");
                        setAirlockState(AirlockState.CLOSED, false, air);
                    }
                    else
                    {
                        //show("Airlock '"+airlockID+"' is pressurized.");
                    }

                    AirlockState s = getCurrentAirlockState();
                    setAirlockState(s, false, air, false);
                    if (s != AirlockState.CLOSED && s != AirlockState.OPEN)
                    {
                        preventAccidentalOpen(s);
                    }

                    if (atmo < MAX_ATMOSPHERE && air > 0.02 && !(allowOpenIfNoO2Space && isDepressurized() && tankFill > 0.99))
                    {
                        setDoorStates(outerDoors, false, false);
                    }

                    caller.Echo("Airlock '" + airlockID + "' is " + s + ".");

                    ret = s;
                }
                else
                {
                    setAirlockState(AirlockState.OPEN, true, atmo);                     //fresh air
                    ret = AirlockState.OPEN;
                }

                atmoLastTick = atmo;
                return(ret.Value);
            }
Beispiel #6
0
 public void add(string a, int b)
 {
     if (b <= this.k)
     {
         var c = n(a); if (b == ERROR)
         {
             i.Echo(c);
         }
         for (int d = 0; d < h.Count; d++)
         {
             if (autoscroll)
             {
                 List <string> e = new List <string>(); e.AddRange(h[d].GetPublicText().Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries)); StringBuilder f = new StringBuilder(); e.Add(c); if (!h[d].GetPrivateTitle().ToLower().Equals("nolinelimit"))
                 {
                     int g = m(h[d]); if (e.Count > g)
                     {
                         e.RemoveRange(0, e.Count - g);
                     }
                 }
                 h[d].WritePublicText(string.Join("\n", e));
             }
             else
             {
                 h[d].WritePublicText(c + '\n', true);
             }
         }
     }
 }
    private void Init()
    {
        List <IMyTerminalBlock> rotors = new List <IMyTerminalBlock>();

        grid.SearchBlocksOfName("Cell", rotors,
                                delegate(IMyTerminalBlock block) {
            return(block is IMyMotorStator && Util.NameRegex(block, CellPattern).Success);
        });

        program.Echo("initialized with " + rotors.Count + " rotors");
        for (int n = 0; n < rotors.Count; n++)
        {
            PrisonCell p = new PrisonCell(this, rotors[n] as IMyMotorStator);
            prisons[p.id] = p;
        }
    }
Beispiel #8
0
 void p(string a, int b)
 {
     if (b <= ERROR)
     {
         k.Echo(a);
     }
 }
Beispiel #9
0
 private void DisplayOnProgramableBlock(string msg, int verbosity)
 {
     if (verbosity <= ERROR)
     {
         GridProgram.Echo(msg);
     }
 }
 public static void Echo(string str)
 {
     if (Program != null)
     {
         Program.Echo(str);
     }
 }
Beispiel #11
0
 private void show(string text)
 {
     foreach (IMyTextPanel scr in displays)
     {
         scr.WritePublicText(text + "\n", true);
     }
     caller.Echo(text);
 }
 public void Test()
 {
     foreach (UnitTest unit_test in unitTests)
     {
         try
         {
             gridProgram.Echo("Testing " + unit_test.UnitTestName + "...");
             unit_test.OnUnitTest();
             gridProgram.Echo("Test " + unit_test.UnitTestName + " was successful!");
         }
         catch (Exception e)
         {
             gridProgram.Echo("Test " + unit_test.UnitTestName + " failed!");
             gridProgram.Echo(e.ToString());
         }
     }
 }
            public HangarSystem(string hangar_prefix, Dictionary <string, string> block_names, MyGridProgram source, IMyTextSurface screen)
            {
                this.hangar_prefix = hangar_prefix;
                this.source        = source;
                this.screen        = screen;
                blocks             = new Dictionary <string, IMyTerminalBlock>();
                grouped_blocks     = new Dictionary <string, List <IMyTerminalBlock> >();
                GetBlocks(block_names);
                string saved_status = "";

                try
                {
                    saved_status = source.Me.CustomData.Split(',')[0];
                }
                catch (Exception e)
                {
                    source.Echo(string.Format("ERROR GETTING SAVED INFO: {0}", e.Message));
                }
                if (saved_status != "")
                {
                    source.Echo(string.Format("Saved Info:\n{0}", saved_status));
                    HangarStatus tmp_status;
                    Enum.TryParse(saved_status, out tmp_status);
                    SetHangarStatus(tmp_status);
                }
                else if (IsDocked())
                {
                    SetHangarStatus(HangarStatus.docked);
                }
                else
                {
                    SetHangarStatus(HangarStatus.free);
                }

                IMySensorBlock landing_sensor = (IMySensorBlock)blocks["landing_sensor"];
                IMySensorBlock exit_sensor    = (IMySensorBlock)blocks["exit_sensor"];

                landing_sensor.DetectSmallShips = true;
                landing_sensor.DetectSubgrids   = true;
                landing_sensor.DetectEnemy      = false;

                exit_sensor.DetectSmallShips = true;
                exit_sensor.DetectSubgrids   = true;
                exit_sensor.DetectEnemy      = false;
            }
Beispiel #14
0
            public void Log(string message)
            {
                // if (_lcd != null)
                // {
                //     _lcd.WriteText(message + '\n', true);
                // }

                _program.Echo(message);
            }
 private void show(string text)
 {
     foreach (IMyTextPanel scr in displays)
     {
         scr.WriteText(text + "\n", true);
         scr.FontSize = 0.707F;
         scr.ShowPublicTextOnScreen();
     }
     caller.Echo(text);
 }
Beispiel #16
0
 public Logger(IMyTextSurface s, MyGridProgram p = null)
 {
     this._surface = s;
     if (this._surface == null)
     {
         if (p != null)
         {
             p.Echo("No Logger found");
         }
         return;
     }
     else
     {
         if (p != null)
         {
             p.Echo("Logger surface found");
         }
     }
     this._surface.ContentType = VRage.Game.GUI.TextPanel.ContentType.TEXT_AND_IMAGE;
 }
Beispiel #17
0
            internal void tick(bool fullUpdate, float atmo, double tankFill, HashSet <IMyDoor> closedDoors, HashSet <IMyAirVent> depressurizing)
            {
                float f = getAirLevel();

                if (fullUpdate)
                {
                    bool open = isShipWaiting();
                    caller.Echo("Hangar '" + hangarID + "' Open Queued: " + open);
                    caller.Echo("Hangar '" + hangarID + "' Air Level: " + f + "%");
                    setHangarStatus(open, f, atmo, tankFill, closedDoors, depressurizing);
                }
                Color c = getColor(f);

                if (c != currentColor)
                {
                    setColor(c);
                }
                Color c2 = colorTick < COLOR_FADE_DURATION?Color.Lerp(lastColor, currentColor, colorTick / COLOR_FADE_DURATION) : currentColor;

                //Echo(lastColor+" > "+currentColor+" p="+colorTick/4F+" = "+c2);
                foreach (IMyLightingBlock light in spotlights)
                {
                    light.Color = c2;
                }
                foreach (IMyLightingBlock light in auxLights)
                {
                    light.Enabled = f >= AMBIENT_LIGHT_THRESHOLD;
                }
                float frac = f / 100F;

                foreach (IMyTextPanel scr in screens)
                {
                    setScreenContent(scr, frac);
                }
                colorTick++;
            }
Beispiel #18
0
        public void Show(MyGridProgram GS)
        {
            if (!Added)
            {
                Clear();
            }
            var text = string.Join("", buf);

            if (ToConsole || (Txt == null))
            {
                GS.Echo(text);
            }
            if (Txt != null)
            {
                Txt.WritePublicText(text); Txt.CustomData += "\n\n" + text;
            }
        }
 private void Echo(string str)
 {
     Program.Echo(str);
 }
Beispiel #20
0
 public void Echo(string s) => _root.Echo(s);
Beispiel #21
0
            /// <summary>
            /// Process all pending IGC messages.
            /// </summary>
            public void ProcessIGCMessages()
            {
                bool bFoundMessages = false;

                if (_debug)
                {
                    _gridProgram.Echo(_broadcastChannels.Count.ToString() + " broadcast channels");
                }
                if (_debug)
                {
                    _gridProgram.Echo(_broadcastMessageHandlers.Count.ToString() + " broadcast message handlers");
                }
                if (_debug)
                {
                    _gridProgram.Echo(_unicastMessageHandlers.Count.ToString() + " unicast message handlers");
                }


                // TODO: make this a yield return thing if processing takes too long
                do
                {
                    bFoundMessages = false;
                    foreach (var channel in _broadcastChannels)
                    {
                        if (channel.HasPendingMessage)
                        {
                            bFoundMessages = true;
                            var msg = channel.AcceptMessage();
                            if (_debug)
                            {
                                _gridProgram.Echo("Broadcast received. TAG:" + msg.Tag);
                                _debugTextPanel?.WriteText("IGC:" + msg.Tag + " SRC:" + msg.Source.ToString("X") + "\n", true);
                            }
                            foreach (var handler in _broadcastMessageHandlers)
                            {
                                if (_debug)
                                {
                                    _gridProgram.Echo("Calling handler");
                                }
                                handler(msg);
                            }
                            if (_debug)
                            {
                                _gridProgram.Echo("Broadcast Handlers completed");
                            }
                        }
                    }
                } while (bFoundMessages); // Process all pending messages

                if (_unicastListener != null)
                {
                    if (_debug)
                    {
                        _gridProgram.Echo("Unicast check");
                    }

                    // TODO: make this a yield return thing if processing takes too long
                    do
                    {
                        // since there's only one channel, we could just use .HasPendingMessages directly.. but this keeps the code loops the same
                        bFoundMessages = false;

                        if (_unicastListener.HasPendingMessage)
                        {
                            bFoundMessages = true;
                            var msg = _unicastListener.AcceptMessage();
                            if (_debug)
                            {
                                _gridProgram.Echo("Unicast received. TAG:" + msg.Tag);
                            }
                            foreach (var handler in _unicastMessageHandlers)
                            {
                                if (_debug)
                                {
                                    _gridProgram.Echo(" Unicast Handler");
                                }
                                // Call each handler
                                handler(msg);
                            }
                            if (_debug)
                            {
                                _gridProgram.Echo("Broadcast Handlers completed");
                            }
                        }
                    } while (bFoundMessages); // Process all pending messages
                    if (_debug)
                    {
                        _gridProgram.Echo("Unicast check completed");
                    }
                }
            }
Beispiel #22
0
    //

    public void Echo(string s)
    {
        pg.Echo(s);
    }
Beispiel #23
0
    Vector3D _getApplyVal()
    {
        if (_checkOrInitRc())
        {
            return(zero);
        }
        Vector3D v       = targetVelocity;
        Vector3D gravity = _gravity();

        if (gravity.Length() == 0)
        {
            gravity = zero;
        }
        Vector3D velocity = _velocity();
        double   mass     = (double)rc.CalculateShipMass().BaseMass + (
            (rc.CalculateShipMass().TotalMass -
             // rc.CalculateShipMass().BaseMass) /10);
             rc.CalculateShipMass().BaseMass));

        Vector3D vn                   = Vector3D.Normalize(v);
        Vector3D accAlongVector       = tm.GetThrustAlongVector(vn);
        double   accAlongVectorLength = accAlongVector.Length();

        pg.Echo("accAlongVectorLength = \n" + accAlongVectorLength);

        Vector3D velocityProjection       = velocity * (velocity.Dot(vn) / velocity.Length());
        double   velocityProjectionLength = velocityProjection.Length();

        pg.Echo("velocityProjectionLength = \n" + velocityProjectionLength);

        double breakingTime = velocityProjectionLength / accAlongVectorLength;

        pg.Echo("breakingTime = \n" + breakingTime);
        double breakingDistance = 1.1 * breakingTime * velocityProjectionLength / 2;

        pg.Echo("breakingDistance = \n" + breakingDistance);

        if (v.Length() < breakingDistance)
        {
            // v = -v;
            v = vn * (velocityProjectionLength - accAlongVectorLength);
        }

        // if (tm.unobtainable (velocityProjection)) {
        //     vn = velocityProjection - velocity;
        // }

        // Vector3D correction = velocity+gravity;
        // double corrLen = 100-correction.Length();
        // double vLen = v.Length();
        // if (vLen > corrLen) {
        //     v *= (corrLen/vLen);
        // }
        Vector3D tv = Vector3D.TransformNormal(
            v - velocity - gravity,
            MatrixD.Transpose(pg.Me.CubeGrid.WorldMatrix)
            );

        refVelocity = v - velocity - gravity;
        return(tv * mass);
    }
        public void PreencherLCDPanelOUEcho(int index, ref IMyTextPanel infoLayoutLCD, string assemblerKey, int qtdAssemblersNotFound, ref List <ControlObject> controlObjectList)
        {
            switch (index)
            {
            case 1: {
                if (infoLayoutLCD != null)
                {
                    infoLayoutLCD.WriteText("----- Produção Automática -----", true);
                    infoLayoutLCD.WriteText("-------------------------------", true);
                    infoLayoutLCD.WriteText("", true);
                    infoLayoutLCD.WriteText("", true);
                    infoLayoutLCD.WriteText("O(s) Container(s) Final(is) não existem, por favor verifique o(s) nome(s) do(s) container(s) e tente novamente!", true);
                }
                else
                {
                    myProgram.Echo("----- Produção Automática -----");
                    myProgram.Echo("-------------------------------");
                    myProgram.Echo("");
                    myProgram.Echo("");
                    myProgram.Echo("O(s) Container(s) Final(is) não existem, por favor verifique o(s) nome(s) do(s) container(s) e tente novamente!");
                }
                break;
            }

            case 2: {
                if (infoLayoutLCD != null)
                {
                    if (qtdAssemblersNotFound == 1)
                    {
                        infoLayoutLCD.WriteText("----- Produção Automática -----", true);
                        infoLayoutLCD.WriteText("-------------------------------", true);
                        infoLayoutLCD.WriteText("", true);
                        infoLayoutLCD.WriteText("", true);
                        infoLayoutLCD.WriteText("O assembler: " + assemblerKey + ", não foi encontrado!", true);
                    }
                    else
                    {
                        infoLayoutLCD.WriteText(infoLayoutLCD.GetText(), true);
                        infoLayoutLCD.WriteText("O assembler: " + assemblerKey + ", não foi encontrado!", true);
                    }
                }
                else
                {
                    if (qtdAssemblersNotFound == 1)
                    {
                        myProgram.Echo("----- Produção Automática -----");
                        myProgram.Echo("-------------------------------");
                        myProgram.Echo("");
                        myProgram.Echo("");
                        myProgram.Echo("O assembler: " + assemblerKey + ", não foi encontrado!");
                    }
                    else
                    {
                        myProgram.Echo("O assembler: " + assemblerKey + ", não foi encontrado!");
                    }
                }
                break;
            }

            case 3: {
                // --------------------------------------------------
                // CRIANDO O CABEÇALHO DA TELA
                // --------------------------------------------------
                infoLayoutLCD.WriteText("----- Produção Automática -----", true);
                infoLayoutLCD.WriteText("-------------------------------", true);
                infoLayoutLCD.WriteText("", true);
                infoLayoutLCD.WriteText("", true);
                infoLayoutLCD.WriteText("Componente - Qtd Produzida/Qtd Produzir/Qtd Manter/Assemblers Informados/Assemblers Encontrados", true);

                // --------------------------------------------------
                // CRIANDO O CORPO DA TELA
                // --------------------------------------------------
                StringBuilder linhaLCD = new StringBuilder();
                foreach (var controlObject in controlObjectList)
                {
                    linhaLCD.AppendLine(controlObject.getAssemblerKey() +
                                        controlObject.getComponentsAmountProduced() +
                                        controlObject.getComponentsAmountToProduce() +
                                        controlObject.getComponetAmountKeepStorage() +
                                        controlObject.getFoundAllAssemblers() +
                                        controlObject.getQtdyOfAssemblersFound());
                    infoLayoutLCD.WriteText(linhaLCD, true);
                }
                break;
            }

            default:
                break;
            }
        }
            /// <summary>
            /// Open the hangar door and prepare the hangar for a ship to dock.
            /// </summary>
            public void StartDockingProcedure()
            {
                if (status == HangarStatus.free)
                {
                    SetHangarStatus(HangarStatus.docking);
                    //change graphic of external LCDs to arrow
                    SetExternalScreens(DisplayTextures.arrowTexture);

                    //open door
                    OpenCloseHangarDoor(true);
                    source.Echo("OPENING BIG DOOR");
                    PowerLights(false, "group_int_lights");
                    PowerLights(true, "group_ext_lights");
                    PowerLights(true, "group_warn_lights");
                    source.Echo("LIGHTS SET");

                    //WAIT for sensor to detect ship landing
                    source.Echo("WAITING FOR SENSOR TO DETECT SHIP");
                }
            }
            public void write(string msg)
            {
                string arg = "[" + program.ElapsedTime.TotalMilliseconds.ToString() + "] " + msg;

                program.Echo(arg);
            }
    public void Update(double Seconds)
    {
        Program.Echo('\n' + "Update()");

        LeftLock  = (Left.Status == LegStatus.Lowered);
        RightLock = (Right.Status == LegStatus.Lowered);

        if (LastCommand != Command)
        {
            switch (Command)
            {
            case LegCommand.Stop:
                Left.Stop();
                Right.Stop();
                break;

            case LegCommand.Forward:
                Left.Forward();
                Right.Forward();
                break;

            case LegCommand.Backward:
                Left.Backward();
                Right.Backward();
                break;

            case LegCommand.Left:
                Left.Backward();
                Right.Forward();
                break;

            case LegCommand.Right:
                Left.Forward();
                Right.Backward();
                break;
            }
        }

        if (MovingLeg == null || LockedLeg == null)
        {
            if (LeftLock && RightLock)
            {
                if (NextUnlockRight || (Left.StridePercent < Right.StridePercent && !NextUnlockLeft))
                {
                    MovingLeg = Right;
                    LockedLeg = Left;
                }
                else
                {
                    MovingLeg = Left;
                    LockedLeg = Right;
                }
                MovingLeg.Raise();
            }
            else if (LeftLock)
            {
                MovingLeg = Right;
                LockedLeg = Left;
            }
            else if (RightLock)
            {
                MovingLeg = Left;
                LockedLeg = Right;
            }
            else
            {
                if (Preferance == Base6Directions.Direction.Left)
                {
                    MovingLeg = Right;
                    LockedLeg = Left;
                }
                else
                {
                    MovingLeg = Left;
                    LockedLeg = Right;
                }
            }
        }


        if (MovingLeg == Left)
        {
            Program.Echo("ML, SR");
        }
        else
        {
            Program.Echo("MR, SL");
        }
        if (NextLockLeft)
        {
            Program.Echo("NextLockLeft");
        }
        else if (NextLockRight)
        {
            Program.Echo("NextLockRight");
        }
        else
        {
            Program.Echo("NextLockNone");
        }
        if (Command != LegCommand.Stop)
        {
            //MovingLeg.Continue();
            if (LockedLeg.State != LegState.Pushing)
            {
                LockedLeg.Push();
            }
            if (MovingLeg.State != LegState.Returning && MovingLeg.State != LegState.Lowering)
            {
                MovingLeg.Return();
            }
            else
            {
                if (MovingLeg.StridePercent < 50)
                {
                    if (MovingLeg.State != LegState.Returning)
                    {
                        MovingLeg.Return();
                        if (MovingLeg == Left)
                        {
                            NextLockLeft = true;
                        }
                        else
                        {
                            NextLockRight = true;
                        }
                    }
                }
                else if (MovingLeg.StridePercent >= 50)
                {
                    if (MovingLeg.State != LegState.Lowering)
                    {
                        MovingLeg.Drop();
                        if (MovingLeg == Left)
                        {
                            NextUnlockRight = true;
                        }
                        else
                        {
                            NextUnlockLeft = true;
                        }
                    }
                }
                if (MovingLeg.Status == LegStatus.Raised)
                {
                    MovingLeg.Lower();
                }
            }
            LastSwitch += Seconds;
        }
        else
        {
            MovingLeg.Stop();
            LockedLeg.Stop();
        }
        LockedLeg.Update();
        MovingLeg.Update();
        LastCommand = Command;
        if (LeftLock && RightLock && LastSwitch > 0.5 || LastSwitch > 5)
        {
            Leg temp = MovingLeg;
            MovingLeg = LockedLeg;
            LockedLeg = temp;
            MovingLeg.Raise();
            LastSwitch = 0;
        }
    }
Beispiel #28
0
    public void Update()
    {
        //如果主控未设置则寻找主控,如果主控有变化,则重新初始化
        if (SettedMain == null)
        {
            List <IMyShipController> list = new List <IMyShipController>();
            MGP.GridTerminalSystem.GetBlocksOfType <IMyShipController> (list);
            IMyShipController MainFound = null;
            foreach (IMyShipController sc in list)
            {
                if (sc.IsUnderControl)
                {
                    MainFound = sc;
                }
            }
            if (Main != MainFound && MainFound != null)
            {
                Main = MainFound; Init();
            }
            else if (Main == null)
            {
                return;
            }
        }
        else
        {
            Main = SettedMain;
        }
        //TODO	更新当前速度、加速度、旋转状态,更新当前操作状态
        MyPos       = Main.GetPosition();
        MyVelocity  = Main.GetShipVelocities().LinearVelocity;
        InertiaDump = (ManualControl)?InertiaDump:Main.DampenersOverride;
        Vector3  MoveIndicator   = Main.MoveIndicator;
        MatrixD  refLookAtMatrix = MatrixD.CreateLookAt(new Vector3D(0, 0, 0), Main.WorldMatrix.Forward, Main.WorldMatrix.Up);
        Vector3D rotation        = (ManualControl)?Gyro(faceToDir):new Vector3D(Main.RotationIndicator.Y, -Main.RotationIndicator.X, -Main.RollIndicator * 100);        //陀螺仪方向
        //控制陀螺仪惯性
        Vector3D AngularVectorToMe = Vector3D.TransformNormal(Main.GetShipVelocities().AngularVelocity, refLookAtMatrix);

        CalcumRotation = (CalcumRotation * 4 + new Vector3D(AngularVectorToMe.Y, -AngularVectorToMe.X, -AngularVectorToMe.Z)) / 5;
        rotation       = rotation - new Vector3D(AngularVectorToMe.Y, -AngularVectorToMe.X, -AngularVectorToMe.Z) * 0.6 - CalcumRotation * 0.4;
        SetGyroYPR(rotation);
        //将飞船速度转换坐标系为相对速度

        Vector3D relativeVelocity = new Vector3D(0);

        if (MyVelocity.Length() > 0)
        {
            relativeVelocity = Vector3D.TransformNormal(MyVelocity, refLookAtMatrix);                                   //坐标系转换后的相对速度
        }
        Vector3D relativeCruiseVelocity = new Vector3D(0);

        if (CruiseVelocity.Length() > 0)
        {
            relativeCruiseVelocity = Vector3D.TransformNormal(CruiseVelocity, refLookAtMatrix);
        }
        //判断惯性控制输出
        Vector3D output         = (ManualControl)?OutputVector:new Vector3D(MoveIndicator.X * -100f, MoveIndicator.Y * -100f, MoveIndicator.Z * -100f);// 从控制到出力转换
        Vector3D expectVelocity = (output.Length() > 0)?Vector3D.Normalize(output) * -100:Vector3D.Zero;

        if (InertiaDump)
        {
            output.X = CalcInertiaDump(relativeVelocity.X - expectVelocity.X);
            output.Y = CalcInertiaDump(relativeVelocity.Y - expectVelocity.Y);
            output.Z = CalcInertiaDump(relativeVelocity.Z - expectVelocity.Z);
            //output=(output.Length()>0)?Vector3D.Normalize(output)*100:Vector3D.Zero;
        }
        else
        {
            output = -expectVelocity;
        }
        MGP.Echo(output.ToString());
        GEngine(output);
        TEngine(output);
        SEngine(output);
    }
Beispiel #29
0
 protected void Echo(string str)
 {
     Program.Echo(str);
 }