private void SaveCode(ResultEnum result)
        {
            MyGuiScreenGamePlay.ActiveGameplayScreen    = MyGuiScreenGamePlay.TmpGameplayScreenHolder;
            MyGuiScreenGamePlay.TmpGameplayScreenHolder = null;
            SendCloseEditor();
            if (m_editorScreen.TextTooLong() == true)
            {
                var messageBox = MyGuiSandbox.CreateMessageBox(
                    messageCaption: MyTexts.Get(MySpaceTexts.ProgrammableBlock_CodeChanged),
                    messageText: MyTexts.Get(MySpaceTexts.ProgrammableBlock_Editor_TextTooLong),
                    buttonType: MyMessageBoxButtonsType.OK,
                    canHideOthers: false);
                MyScreenManager.AddScreen(messageBox);
                return;
            }

            DetailedInfo.Clear();
            RaisePropertiesChanged();
            if (result == ResultEnum.OK)
            {
                SaveCode();
            }
            else
            {
                string editorText = m_editorScreen.Description.Text.ToString();
                if (editorText != m_programData)
                {
                    var messageBox = MyGuiSandbox.CreateMessageBox(
                        messageCaption: MyTexts.Get(MySpaceTexts.ProgrammableBlock_CodeChanged),
                        messageText: MyTexts.Get(MySpaceTexts.ProgrammableBlock_SaveChanges),
                        buttonType: MyMessageBoxButtonsType.YES_NO,
                        canHideOthers: false);

                    messageBox.ResultCallback = delegate(MyGuiScreenMessageBox.ResultEnum result2)
                    {
                        if (result2 == MyGuiScreenMessageBox.ResultEnum.YES)
                        {
                            SaveCode(ResultEnum.OK);
                        }
                        else
                        {
                            m_editorData = m_programData;
                        }
                    };
                    MyScreenManager.AddScreen(messageBox);
                }
            }
        }
예제 #2
0
 private void UpdateText()
 {
     DetailedInfo.Clear();
     DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertiesText_Type));
     DetailedInfo.Append(BlockDefinition.DisplayNameText);
     DetailedInfo.Append("\n");
     DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertyProperties_CurrentMass));
     DetailedInfo.Append(IsWorking ? BlockDefinition.VirtualMass.ToString() : "0");
     DetailedInfo.Append(" kg\n");
     DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertiesText_RequiredInput));
     MyValueFormatter.AppendWorkInBestUnit(PowerReceiver.RequiredInput, DetailedInfo);
     DetailedInfo.Append("\n");
     DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertyProperties_CurrentInput));
     MyValueFormatter.AppendWorkInBestUnit(PowerReceiver.CurrentInput, DetailedInfo);
     RaisePropertiesChanged();
 }
예제 #3
0
        void UpdateText()
        {
            if (SafeConstraint != null)
            {
                DetailedInfo.Clear();
                DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertiesText_MotorCurrentAngle)).AppendDecimal(MathHelper.ToDegrees(m_currentAngle), 0).Append("°");

                if (!m_limitsActive && !(float.IsNegativeInfinity(m_minAngle) && float.IsPositiveInfinity(m_maxAngle)))
                {
                    DetailedInfo.Append(Environment.NewLine);
                    DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertiesText_MotorLimitsDisabled));
                }

                RaisePropertiesChanged();
            }
        }
예제 #4
0
 internal void UpdateText()
 {
     DetailedInfo.Clear();
     DetailedInfo.AppendStringBuilder(MyTexts.Get(MyCommonTexts.BlockPropertiesText_Type));
     DetailedInfo.Append(BlockDefinition.DisplayNameText);
     DetailedInfo.Append("\n");
     DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertiesText_MaxOutput));
     MyValueFormatter.AppendWorkInBestUnit(m_reactorDefinition.MaxPowerOutput * m_powerOutputMultiplier, DetailedInfo);
     DetailedInfo.Append("\n");
     if (IsFunctional)
     {
         DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertyProperties_CurrentOutput));
     }
     MyValueFormatter.AppendWorkInBestUnit(SourceComp.CurrentOutput, DetailedInfo);
     RaisePropertiesChanged();
 }
예제 #5
0
 public DetailedInfoModel(DetailedInfo info)
     : this()
 {
     if (info != null)
     {
         Manufacturer        = info.Manufacturer;
         Model               = info.Model;
         WindowsVersion      = info.WindowsVersion;
         WindowsVersionName  = info.WindowsVersionName;
         SystemType          = info.SystemType;
         Processors          = info.Processors;
         LogicalProcessors   = info.LogicalProcessors;
         TotalPhysicalMemory = (info.TotalPhysicalMemoryInMB * 1024 * 1024).ToPrettySize(2);
         HostUptime          = info.HostUptime;
     }
 }
예제 #6
0
 private void UpdateText()
 {
     DetailedInfo.Clear();
     DetailedInfo.AppendStringBuilder(MyTexts.Get(MyCommonTexts.BlockPropertiesText_Type));
     DetailedInfo.Append(BlockDefinition.DisplayNameText);
     DetailedInfo.Append("\n");
     DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertyProperties_CurrentMass));
     DetailedInfo.Append(IsWorking ? BlockDefinition.VirtualMass.ToString() : "0");
     DetailedInfo.Append(" kg\n");
     DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertiesText_RequiredInput));
     MyValueFormatter.AppendWorkInBestUnit(ResourceSink.RequiredInputByType(MyResourceDistributorComponent.ElectricityId), DetailedInfo);
     DetailedInfo.Append("\n");
     DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertyProperties_CurrentInput));
     MyValueFormatter.AppendWorkInBestUnit(ResourceSink.CurrentInputByType(MyResourceDistributorComponent.ElectricityId), DetailedInfo);
     RaisePropertiesChanged();
 }
예제 #7
0
 public override void UpdateOnceBeforeFrame()
 {
     base.UpdateOnceBeforeFrame();
     IsCountingDown = false;
     if (Sync.IsServer)
     {
         for (int i = 0; i < Toolbar.ItemCount; ++i)
         {
             Toolbar.UpdateItem(i);
             Toolbar.ActivateItemAtIndex(i);
         }
     }
     UpdateEmissivity();
     DetailedInfo.Clear();
     RaisePropertiesChanged();
 }
예제 #8
0
        public DetailedInfo GetDetailedInfo(bool includeMoves)
        {
            lock (syncRoot)
            {
                if (!this.Started)
                {
                    throw new GameException("The game has not been started yet.");
                }

                var info = new DetailedInfo();
                info.Id = this.Id;
                info.CurrentPlayerNick = GetCurrentPlayer().NickName;
                info.GameOver = game.GameOver;
                info.GameType = this.gameType;

                var piecesQuery = this.game.GetPieces(this.state).Select(
                    kvp => new PieceAt {
                        Position = kvp.Key.ToInt32Array(),
                        PieceType = kvp.Value.Type,
                        Player = kvp.Value.Owner.ID
                    });
                // For now, only list the current players offboard pieces
                // TODO: fix it in BoardGameRules
                piecesQuery.Union(this.state.GetOffboard(state.CurrentPlayer).Select(
                    piece => new PieceAt {
                        Position = null,
                        PieceType = piece.Type,
                        Player = state.CurrentPlayerID
                    }));
                info.Pieces = piecesQuery.ToList(); // Enumerate it here before we release the lock

                info.Winners = game.Winners.Select(player => player.ID).ToList(); // Enumerate it

                if (includeMoves) {
                    var movesQuery = this.game.EnumeratePossibleMoves(state).Select(
                        move => new PossibleMove {
                            From = move.From != null ? move.From.ToInt32Array() : null,
                            To = move.To.ToInt32Array()
                        });
                    info.PossibleMoves = movesQuery.ToList(); // Enumerate it
                }

                return info;
            }
        }
예제 #9
0
        private void UpdateDisplay()
        {
            DetailedInfo.Clear();
            DetailedInfo.AppendStringBuilder(MyTexts.Get(MyCommonTexts.BlockPropertiesText_Type));
            DetailedInfo.Append(BlockDefinition.DisplayNameText);
            DetailedInfo.Append("\n");

            DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertiesText_MaxRequiredInput));
            MyValueFormatter.AppendWorkInBestUnit(ResourceSink.MaxRequiredInput, DetailedInfo);
            DetailedInfo.Append("\n");

            DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertiesText_OxygenOutput));
            DetailedInfo.Append((SourceComp.MaxOutputByType(BlockDefinition.ProducedGas) * 60).ToString("F"));
            DetailedInfo.Append(" L/min");

            RaisePropertiesChanged();
            UpdateEmissivity();
        }
예제 #10
0
        private void UpdateDisplay()
        {
            DetailedInfo.Clear();
            DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertiesText_Type));
            DetailedInfo.Append(BlockDefinition.DisplayNameText);
            DetailedInfo.Append("\n");

            DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertiesText_MaxRequiredInput));
            MyValueFormatter.AppendWorkInBestUnit(PowerReceiver.MaxRequiredInput, DetailedInfo);
            DetailedInfo.Append("\n");

            DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertiesText_OxygenOutput));
            DetailedInfo.Append((m_maxOxygenOutput * 100f).ToString("F"));
            DetailedInfo.Append("%");

            RaisePropertiesChanged();
            UpdateEmissivity();
        }
예제 #11
0
        private void UpdateText()
        {
            DetailedInfo.Clear();
            DetailedInfo.AppendStringBuilder(MyTexts.Get(MyCommonTexts.BlockPropertiesText_Type));
            DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BatteryBlock));
            DetailedInfo.Append("\n");
            DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertiesText_MaxOutput));
            MyValueFormatter.AppendWorkInBestUnit(BlockDefinition.MaxPowerOutput, DetailedInfo);
            DetailedInfo.Append("\n");
            DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertiesText_MaxRequiredInput));
            MyValueFormatter.AppendWorkInBestUnit(BlockDefinition.RequiredPowerInput, DetailedInfo);
            DetailedInfo.Append("\n");
            DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertiesText_MaxStoredPower));
            MyValueFormatter.AppendWorkHoursInBestUnit(MaxStoredPower, DetailedInfo);
            DetailedInfo.Append("\n");
            DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertyProperties_CurrentInput));
            MyValueFormatter.AppendWorkInBestUnit(ResourceSink.CurrentInput, DetailedInfo);
            DetailedInfo.Append("\n");
            DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertyProperties_CurrentOutput));
            MyValueFormatter.AppendWorkInBestUnit(SourceComp.CurrentOutput, DetailedInfo);
            DetailedInfo.Append("\n");
            DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertiesText_StoredPower));
            MyValueFormatter.AppendWorkHoursInBestUnit(CurrentStoredPower, DetailedInfo);
            DetailedInfo.Append("\n");
            float currentInput  = ResourceSink.CurrentInputByType(MyResourceDistributorComponent.ElectricityId);
            float currentOutput = SourceComp.CurrentOutputByType(MyResourceDistributorComponent.ElectricityId);

            if (currentInput > currentOutput)
            {
                DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertiesText_RechargedIn));
                MyValueFormatter.AppendTimeInBestUnit(m_timeRemaining, DetailedInfo);
            }
            else if (currentInput == currentOutput)
            {
                DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertiesText_DepletedIn));
                MyValueFormatter.AppendTimeInBestUnit(float.PositiveInfinity, DetailedInfo);
            }
            else
            {
                DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertiesText_DepletedIn));
                MyValueFormatter.AppendTimeInBestUnit(m_timeRemaining, DetailedInfo);
            }
            RaisePropertiesChanged();
        }
예제 #12
0
        protected override void UpdateText()
        {
            VRage.Profiler.ProfilerShort.Begin("UpdateText");
            DetailedInfo.Clear();
            DetailedInfo.AppendStringBuilder(MyTexts.Get(GetAttachState())).AppendLine();

            if (SafeConstraint != null)
            {
                float angle = m_limitsActive ? MyMath.Clamp(m_currentAngle, m_minAngle, m_maxAngle) : m_currentAngle;
                DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertiesText_MotorCurrentAngle)).AppendDecimal(MathHelper.ToDegrees(angle), 0).Append("°");

                if (!m_limitsActive && !(float.IsNegativeInfinity(m_minAngle) && float.IsPositiveInfinity(m_maxAngle)))
                {
                    DetailedInfo.Append(MyEnvironment.NewLine);
                    DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertiesText_MotorLimitsDisabled));
                }
            }
            RaisePropertiesChanged();
            VRage.Profiler.ProfilerShort.End();
        }
예제 #13
0
        private double getAverageLoadingState(List <IMyBatteryBlock> Batteries)
        {
            double allMax    = 0.0;
            double allStored = 0.0;
            double average   = 0;

            for (int i = 0; i < Batteries.Count; i++)
            {
                IMyBatteryBlock Battery = Batteries[i];
                DetailedInfo    DI      = new DetailedInfo(Battery);
                allMax    += parsePower(DI.getValue(BATTERY_VALUE_INDEX_MAX).getValue());
                allStored += parsePower(DI.getValue(BATTERY_VALUE_INDEX_STORED).getValue());
            }
            if (allMax > 0)
            {
                average = allStored / allMax;
            }

            return(average * 100);
        }
예제 #14
0
        private void UpdateText()
        {
            DetailedInfo.Clear();
            if (m_topBlockId.Value == 0)
            {
                DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertiesText_MotorDetached));
            }
            else if (m_constraint != null)
            {
                DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertiesText_MotorAttached));
            }
            else
            {
                DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertiesText_MotorAttachingSpecific));
            }
            DetailedInfo.AppendLine();

            DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertiesText_PistonCurrentPosition)).AppendDecimal(m_currentPos, 1).Append("m");
            RaisePropertiesChanged();
        }
예제 #15
0
        private void UdpateText()
        {
            DetailedInfo.Clear();
            DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertiesText_Type));
            DetailedInfo.Append(BlockDefinition.DisplayNameText);
            DetailedInfo.Append("\n");
            DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertiesText_MaxRequiredInput));
            MyValueFormatter.AppendWorkInBestUnit(ResourceSink.MaxRequiredInputByType(MyResourceDistributorComponent.ElectricityId), DetailedInfo);
            DetailedInfo.Append("\n");
            if (!(MySession.Static.Settings.EnableOxygen || BlockDefinition.StoredGasId != m_oxygenGasId))
            {
                DetailedInfo.Append("Oxygen disabled in world settings!");
            }
            else
            {
                DetailedInfo.Append("Filled: " + (FilledRatio * 100f).ToString("F4") + "%");
            }

            RaisePropertiesChanged();
        }
예제 #16
0
        private void UdpateText()
        {
            DetailedInfo.Clear();
            DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertiesText_Type));
            DetailedInfo.Append(BlockDefinition.DisplayNameText);
            DetailedInfo.Append("\n");
            DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertiesText_MaxRequiredInput));
            MyValueFormatter.AppendWorkInBestUnit(PowerReceiver.MaxRequiredInput, DetailedInfo);
            DetailedInfo.Append("\n");
            if (!MySession.Static.Settings.EnableOxygen)
            {
                DetailedInfo.Append("Oxygen disabled in world settigns!");
            }
            else
            {
                DetailedInfo.Append("Filled: " + (FilledRatio * 100f).ToString("F") + "%");
            }

            RaisePropertiesChanged();
        }
예제 #17
0
        public override void UpdateOnceBeforeFrame()
        {
            base.UpdateOnceBeforeFrame();
            IsCountingDown = false;
            if (Sync.IsServer)
            {
                for (int i = 0; i < Toolbar.ItemCount; ++i)
                {
                    Toolbar.UpdateItem(i);
                    Toolbar.ActivateItemAtIndex(i);
                }

                //Visual scripting action
                if (CubeGrid.Physics != null && MyVisualScriptLogicProvider.TimerBlockTriggered != null)
                {
                    MyVisualScriptLogicProvider.TimerBlockTriggered(CustomName.ToString());
                }
            }
            UpdateEmissivity();
            DetailedInfo.Clear();
            RaisePropertiesChanged();
        }
예제 #18
0
        public override void UpdateAfterSimulation10()
        {
            base.UpdateAfterSimulation10();

            // If it is not working, than it cannot operate
            if (!this.IsWorking)
            {
                return;
            }

            var before = m_countdownMsCurrent % 1000;

            if (m_countdownMsCurrent > 0)
            {
                m_countdownMsCurrent -= (int)(1000 * 1f / 6f);
            }

            var after = m_countdownMsCurrent % 1000;

            if (before > 800 && after <= 800 || before <= 800 && after > 800)
            {
                UpdateEmissivity();
            }

            if (m_countdownMsCurrent <= 0)
            {
                NeedsUpdate         &= ~MyEntityUpdateEnum.EACH_10TH_FRAME;
                m_countdownMsCurrent = 0;
                NeedsUpdate         |= MyEntityUpdateEnum.BEFORE_NEXT_FRAME;
                if (m_beepEmitter != null && Silent == false)
                {
                    m_beepEmitter.PlaySound(m_beepEnd, true);
                }
            }
            DetailedInfo.Clear().AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertyTitle_TimerToTrigger));
            MyValueFormatter.AppendTimeExact(m_countdownMsCurrent / 1000, DetailedInfo);
            RaisePropertiesChanged();
        }
예제 #19
0
        private void UpdateDetailedInfo()
        {
            DetailedInfo.Clear();
            DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertiesText_Type));
            DetailedInfo.Append(BlockDefinition.DisplayNameText);
            DetailedInfo.AppendFormat("\n");
            DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertiesText_MaxRequiredInput));
            MyValueFormatter.AppendWorkInBestUnit(GetOperationalPowerConsumption(), DetailedInfo);
            DetailedInfo.AppendFormat("\n");
            DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertiesText_RequiredInput));
            MyValueFormatter.AppendWorkInBestUnit(PowerReceiver.RequiredInput, DetailedInfo);


            DetailedInfo.AppendFormat("\n\n");
            DetailedInfo.Append("Productivity: ");
            DetailedInfo.Append(((UpgradeValues["Productivity"] + 1f) * 100f).ToString("F0"));
            DetailedInfo.Append("%\n");
            DetailedInfo.Append("Power Efficinecy: ");
            DetailedInfo.Append(((UpgradeValues["PowerEfficiency"]) * 100f).ToString("F0"));
            DetailedInfo.Append("%\n");

            RaisePropertiesChanged();
        }
예제 #20
0
 private void UpdateText()
 {
     DetailedInfo.Clear();
     DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertiesText_Type));
     DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BatteryBlock));
     DetailedInfo.Append("\n");
     DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertiesText_MaxOutput));
     MyValueFormatter.AppendWorkInBestUnit(m_batteryBlockDefinition.MaxPowerOutput, DetailedInfo);
     DetailedInfo.Append("\n");
     DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertiesText_MaxRequiredInput));
     MyValueFormatter.AppendWorkInBestUnit(m_batteryBlockDefinition.RequiredPowerInput, DetailedInfo);
     DetailedInfo.Append("\n");
     DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertiesText_MaxStoredPower));
     MyValueFormatter.AppendWorkHoursInBestUnit(MaxStoredPower, DetailedInfo);
     DetailedInfo.Append("\n");
     DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertyProperties_CurrentInput));
     MyValueFormatter.AppendWorkInBestUnit(PowerReceiver.CurrentInput, DetailedInfo);
     DetailedInfo.Append("\n");
     DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertyProperties_CurrentOutput));
     MyValueFormatter.AppendWorkInBestUnit(CurrentPowerOutput, DetailedInfo);
     DetailedInfo.Append("\n");
     DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertiesText_StoredPower));
     MyValueFormatter.AppendWorkHoursInBestUnit(CurrentStoredPower, DetailedInfo);
     DetailedInfo.Append("\n");
     if (!ProducerEnabled)
     {
         DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertiesText_RechargedIn));
         MyValueFormatter.AppendTimeInBestUnit(m_timeRemaining, DetailedInfo);
     }
     else
     {
         DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertiesText_DepletedIn));
         MyValueFormatter.AppendTimeInBestUnit(m_timeRemaining, DetailedInfo);
     }
     RaisePropertiesChanged();
 }
예제 #21
0
        double getSolarpanelPowerWatt(IMySolarPanel SolarPanel)
        {
            DetailedInfo DI = new DetailedInfo(SolarPanel);

            return(parsePower(DI.getValue(1).getValue()));
        }
예제 #22
0
            private void initCommands(Environment env)
            {
                env.Debug.newScope("initCommands");

                //begin info command
                availableCommands.Add("info", new Command("info", "show short info of a command", env, (BaconArgs Args, Environment Env) => {
                    StringBuilder result = new StringBuilder();
                    if (Args.getArguments().Count > 0)
                    {
                        for (int i = 0; i < Args.getArguments().Count; i++)
                        {
                            string cmd = Args.getArguments()[i];
                            if (availableCommands.ContainsKey(cmd))
                            {
                                result.AppendLine(availableCommands[cmd].name + ": " + availableCommands[cmd].info);
                            }
                            else
                            {
                                result.AppendLine("unknown command: " + cmd);
                            }
                        }
                    }
                    else
                    {
                        List <Command> commands = new List <Command>(availableCommands.Values);
                        for (int i = 0; i < commands.Count; i++)
                        {
                            result.AppendLine(commands[i].name + ": " + commands[i].info);
                        }
                    }
                    return(result);
                }));
                availableCommands["info"].help.AppendLine("info [command [...]]");
                availableCommands["info"].help.AppendLine(availableCommands["info"].info);
                availableCommands["info"].help.AppendLine("no argument: info for all available commands");
                availableCommands["info"].help.AppendLine("give one ore more arguments to display info for these");
                //end info command
                //begin help command
                availableCommands.Add("help", new Command("help", "show help of a command", env, (BaconArgs Args, Environment Env) => {
                    StringBuilder result = new StringBuilder();
                    for (int i = 0; i < Args.getArguments().Count; i++)
                    {
                        if (availableCommands.ContainsKey(Args.getArguments()[i]))
                        {
                            result.Append(availableCommands[Args.getArguments()[i]].help.ToString());
                        }
                    }
                    return(result);
                }));
                availableCommands["help"].help.AppendLine("help command [...]");
                availableCommands["help"].help.AppendLine(availableCommands["help"].info);
                availableCommands["help"].help.AppendLine("shows help for the given command(s)");
                //end help commnd
                //begin details command
                availableCommands.Add("details",
                                      new Command("details", "show detailed info of a block", env, (BaconArgs Args, Environment Env) => {
                    StringBuilder result = new StringBuilder();
                    for (int i_arg = 0; i_arg < Args.getArguments().Count; i_arg++)
                    {
                        string tag = Args.getArguments()[i_arg];
                        List <IMyTerminalBlock> Blocks = new List <IMyTerminalBlock>();
                        Env.GridTerminalSystem.GetBlocksOfType <IMyTerminalBlock>(Blocks, (IMyTerminalBlock x) => x.CustomName.Contains(tag) && (!(Args.getFlag('t') == 0) || x.CubeGrid.Equals(Env.GridProgram.Me.CubeGrid)));
                        for (int i_blocks = 0; i_blocks < Blocks.Count; i_blocks++)
                        {
                            if (Args.getFlag('b') > 0)
                            {
                                result.AppendLine(Blocks[i_blocks].CustomName);
                            }
                            if (Args.getOption("line").Count > 0)
                            {
                                DetailedInfo info = new DetailedInfo(Blocks[i_blocks]);
                                for (int i = 0; i < Args.getOption("line").Count; i++)
                                {
                                    int line = 0;
                                    if (int.TryParse(Args.getOption("line")[i], out line))
                                    {
                                        DetailedInfo.DetailedInfoValue data = info.getValue(line);
                                        result.AppendLine((data != null)?data.k + ": " + data.v:"null");
                                    }
                                }
                            }
                            else
                            {
                                result.AppendLine(Blocks[i_blocks].DetailedInfo);
                            }
                        }
                    }
                    return(result);
                })
                                      );
                availableCommands["details"].help.AppendLine("details tag [tag [...]] [--line=N [...]] [-t] [-b]");
                availableCommands["details"].help.AppendLine(availableCommands["details"].info);
                availableCommands["details"].help.AppendLine("tag: filter block by a tag in it's name");
                availableCommands["details"].help.AppendLine("--line=N: show only detailed info from line N");
                availableCommands["details"].help.AppendLine("-t: find only blocks of same grid");
                availableCommands["details"].help.AppendLine("-b: add the Blockname on top of the info");
                //end details command

                env.Debug.leaveScope();
            }
예제 #23
0
        void UpdateText()
        {
            if (m_instantBuildingEnabled)
            {
                UpdateBaseText();
                if (m_clipboard.IsActive && ProjectedGrid != null)
                {
                    if (m_maxNumberOfBlocksPerProjection < MAX_NUMBER_OF_BLOCKS)
                    {
                        DetailedInfo.Append("\n");
                        DetailedInfo.Append("Ship blocks: " + (ProjectedGrid.BlocksCount) + "/" + m_maxNumberOfBlocksPerProjection);
                    }
                    if (m_maxNumberOfProjections < MAX_NUMBER_OF_PROJECTIONS)
                    {
                        DetailedInfo.Append("\n");
                        DetailedInfo.Append("Projections remaining: " + (m_projectionsRemaining) + "/" + m_maxNumberOfProjections);
                    }
                }
            }
            else
            {
                if (!m_statsDirty)
                {
                    return;
                }
                if (m_clipboard.IsActive)
                {
                    UpdateStats();
                }
                m_statsDirty = false;

                UpdateBaseText();

                if (m_clipboard.IsActive)
                {
                    DetailedInfo.Append("\n");
                    if (m_buildableBlocksCount > 0)
                    {
                        DetailedInfo.Append("\n");
                    }
                    else
                    {
                        DetailedInfo.Append("WARNING! Projection out of bounds!\n");
                    }
                    DetailedInfo.Append("Build progress: " + (m_totalBlocks - m_remainingBlocks) + "/" + m_totalBlocks);
                    if (m_remainingArmorBlocks > 0 || m_remainingBlocksPerType.Count != 0)
                    {
                        DetailedInfo.Append("\nBlocks remaining:\n");

                        DetailedInfo.Append("Armor blocks: " + m_remainingArmorBlocks);

                        foreach (var entry in m_remainingBlocksPerType)
                        {
                            DetailedInfo.Append("\n");
                            DetailedInfo.Append(entry.Key.DisplayNameText + ": " + entry.Value);
                        }
                    }
                    else
                    {
                        DetailedInfo.Append("\nComplete!");
                    }
                }

                RaisePropertiesChanged();
            }
        }
예제 #24
0
 public void WriteProgramResponse(string response)
 {
     DetailedInfo.Clear();
     DetailedInfo.Append(response);
     RaisePropertiesChanged();
 }
예제 #25
0
        public string ExecuteCode(string argument)
        {
            if (m_isRunning)
            {
                return(MyTexts.GetString(MySpaceTexts.ProgrammableBlock_Exception_AllreadyRunning));
            }
            if (m_wasTerminated == true)
            {
                return(DetailedInfo.ToString());
            }
            DetailedInfo.Clear();
            m_echoOutput.Clear();
            if (m_assembly == null)
            {
                return(MyTexts.GetString(MySpaceTexts.ProgrammableBlock_Exception_NoAssembly));
            }
            if (m_mainMethod == null)
            {
                return(MyTexts.GetString(MySpaceTexts.ProgrammableBlock_Exception_NoMain));
            }
            if (this.m_elapsedTimeField != null)
            {
                if (m_previousRunTimestamp == 0)
                {
                    m_previousRunTimestamp = Stopwatch.GetTimestamp();
                    m_elapsedTimeField.SetValue(m_instance, TimeSpan.Zero);
                }
                else
                {
                    var currentTimestamp = Stopwatch.GetTimestamp();
                    var elapsedTime      = (currentTimestamp - m_previousRunTimestamp) * Sync.RelativeSimulationRatio;
                    m_elapsedTimeField.SetValue(m_instance, TimeSpan.FromSeconds(elapsedTime * STOPWATCH_FREQUENCY));
                    m_previousRunTimestamp = currentTimestamp;
                }
            }
            if (m_programGridGroup != null)
            {
                var gridGroup      = MyCubeGridGroups.Static.Logical.GetGroup(CubeGrid);
                var terminalSystem = gridGroup.GroupData.TerminalSystem;
                terminalSystem.UpdateGridBlocksOwnership(this.OwnerId);
                m_programGridGroup.SetValue(m_instance, terminalSystem);
            }

            m_isRunning = true;
            string retVal = "";

            IlInjector.RestartCountingInstructions(MAX_NUM_EXECUTED_INSTRUCTIONS);
            try
            {
                if (m_mainMethodSupportsArgument)
                {
                    // Don't know if it's really necessary to predefine this argument array, I suspect not
                    // due to the cleverness of the compiler, but I do it this way just in case.
                    // Obviously if programmable block execution becomes asynchronous at some point this
                    // must be reworked.
                    m_argumentArray[0] = argument ?? string.Empty;
                    m_mainMethod.Invoke(m_instance, m_argumentArray);
                }
                else
                {
                    m_mainMethod.Invoke(m_instance, null);
                }
                if (m_echoOutput.Length > 0)
                {
                    retVal = m_echoOutput.ToString();
                }
            }
            catch (TargetInvocationException ex)
            {
                // Since we just had an exception I'm not fussed about using old
                // fashioned string concatenation here. We'll still want the echo
                // output, since its primary purpose is debugging.
                if (m_echoOutput.Length > 0)
                {
                    retVal = m_echoOutput.ToString();
                }
                OnProgramTermination();
                if (ex.InnerException is ScriptOutOfRangeException)
                {
                    retVal += MyTexts.GetString(MySpaceTexts.ProgrammableBlock_Exception_TooComplex);
                }
                else if (ex.InnerException != null)
                {
                    retVal += MyTexts.GetString(MySpaceTexts.ProgrammableBlock_Exception_ExceptionCaught) + ex.InnerException.Message;
                }
            }
            m_isRunning = false;
            return(retVal);
        }
예제 #26
0
 private void UpdateText()
 {
     DetailedInfo.Clear();
     DetailedInfo.AppendStringBuilder(MyTexts.Get(MySpaceTexts.BlockPropertiesText_PistonCurrentPosition)).AppendDecimal(m_currentPos, 1).Append("m");
     RaisePropertiesChanged();
 }
예제 #27
0
 public bool IsVoted(InGamePlayerInfo voter)
 {
     return(DetailedInfo.ContainsKey(voter.User.Id));
 }
        public ScriptTerminationReason ExecuteCode(string argument, out string response)
        {
            if (m_isRunning)
            {
                response = MyTexts.GetString(MySpaceTexts.ProgrammableBlock_Exception_AllreadyRunning);
                return(ScriptTerminationReason.AlreadyRunning);
            }
            if (m_terminationReason != ScriptTerminationReason.None)
            {
                response = DetailedInfo.ToString();
                return(m_terminationReason);
            }
            DetailedInfo.Clear();
            m_echoOutput.Clear();
            if (m_assembly == null)
            {
                response = MyTexts.GetString(MySpaceTexts.ProgrammableBlock_Exception_NoAssembly);
                return(ScriptTerminationReason.NoScript);
            }
            if (!m_instance.HasMainMethod)
            {
                response = MyTexts.GetString(MySpaceTexts.ProgrammableBlock_Exception_NoMain);
                return(ScriptTerminationReason.NoEntryPoint);
            }
            if (m_previousRunTimestamp == 0)
            {
                m_previousRunTimestamp = Stopwatch.GetTimestamp();
                m_instance.ElapsedTime = TimeSpan.Zero;
            }
            else
            {
                var currentTimestamp = Stopwatch.GetTimestamp();
                var elapsedTime      = (currentTimestamp - m_previousRunTimestamp) * Sync.RelativeSimulationRatio;
                m_instance.ElapsedTime = TimeSpan.FromSeconds(elapsedTime * STOPWATCH_FREQUENCY);
                m_previousRunTimestamp = currentTimestamp;
            }
            var gridGroup      = MyCubeGridGroups.Static.Logical.GetGroup(CubeGrid);
            var terminalSystem = gridGroup.GroupData.TerminalSystem;

            terminalSystem.UpdateGridBlocksOwnership(this.OwnerId);
            m_instance.GridTerminalSystem = terminalSystem;

            m_isRunning = true;
            response    = "";
            try
            {
                using (IlInjector.BeginRunBlock(MAX_NUM_EXECUTED_INSTRUCTIONS, MAX_NUM_METHOD_CALLS))
                {
                    m_instance.Main(argument);
                }
                if (m_echoOutput.Length > 0)
                {
                    response = m_echoOutput.ToString();
                }
            }
            catch (Exception ex)
            {
                // Since we just had an exception I'm not fussed about using old
                // fashioned string concatenation here. We'll still want the echo
                // output, since its primary purpose is debugging.
                if (m_echoOutput.Length > 0)
                {
                    response = m_echoOutput.ToString();
                }
                if (ex is ScriptOutOfRangeException)
                {
                    if (IlInjector.IsWithinRunBlock())
                    {
                        // If we're within a nested run, we don't reset the program, we just pass the error
                        response += MyTexts.GetString(MySpaceTexts.ProgrammableBlock_Exception_NestedTooComplex);
                        return(ScriptTerminationReason.InstructionOverflow);
                    }
                    else
                    {
                        response += MyTexts.GetString(MySpaceTexts.ProgrammableBlock_Exception_TooComplex);
                        OnProgramTermination(ScriptTerminationReason.InstructionOverflow);
                    }
                }
                else
                {
                    response += MyTexts.GetString(MySpaceTexts.ProgrammableBlock_Exception_ExceptionCaught) + ex.Message;
                    OnProgramTermination(ScriptTerminationReason.RuntimeException);
                }
            }
            finally
            {
                m_isRunning = false;
            }
            return(m_terminationReason);
        }
        public ScriptTerminationReason RunSandboxedProgramAction(Action <ModAPI.IMyGridProgram> action, out string response)
        {
            if (m_isRunning)
            {
                response = MyTexts.GetString(MySpaceTexts.ProgrammableBlock_Exception_AllreadyRunning);
                return(ScriptTerminationReason.AlreadyRunning);
            }
            if (m_terminationReason != ScriptTerminationReason.None)
            {
                response = DetailedInfo.ToString();
                return(m_terminationReason);
            }
            DetailedInfo.Clear();
            m_echoOutput.Clear();
            if (m_assembly == null)
            {
                response = MyTexts.GetString(MySpaceTexts.ProgrammableBlock_Exception_NoAssembly);
                return(ScriptTerminationReason.NoScript);
            }
            var gridGroup      = MyCubeGridGroups.Static.Logical.GetGroup(CubeGrid);
            var terminalSystem = gridGroup.GroupData.TerminalSystem;

            terminalSystem.UpdateGridBlocksOwnership(this.OwnerId);
            m_instance.GridTerminalSystem = terminalSystem;

            m_isRunning = true;
            response    = "";
#if !XB1 // XB1_NOILINJECTOR
            try {
                using (var handle = IlInjector.BeginRunBlock(MAX_NUM_EXECUTED_INSTRUCTIONS, MAX_NUM_METHOD_CALLS)) {
                    m_runtime.InjectorHandle = handle;
                    action(m_instance);
                }
                if (m_echoOutput.Length > 0)
                {
                    response = m_echoOutput.ToString();
                }
                return(m_terminationReason);
            } catch (Exception ex) {
                // Unwrap the exception if necessary
                if (ex is TargetInvocationException)
                {
                    ex = ex.InnerException;
                }

                // Since we just had an exception I'm not fussed about using old
                // fashioned string concatenation here. We'll still want the echo
                // output, since its primary purpose is debugging.
                if (m_echoOutput.Length > 0)
                {
                    response = m_echoOutput.ToString();
                }
                if (ex is ScriptOutOfRangeException)
                {
                    if (IlInjector.IsWithinRunBlock())
                    {
                        // If we're within a nested run, we don't reset the program, we just pass the error
                        response += MyTexts.GetString(MySpaceTexts.ProgrammableBlock_Exception_NestedTooComplex);
                        return(ScriptTerminationReason.InstructionOverflow);
                    }
                    else
                    {
                        response += MyTexts.GetString(MySpaceTexts.ProgrammableBlock_Exception_TooComplex);
                        OnProgramTermination(ScriptTerminationReason.InstructionOverflow);
                    }
                }
                else
                {
                    response += MyTexts.GetString(MySpaceTexts.ProgrammableBlock_Exception_ExceptionCaught) + ex.Message;
                    OnProgramTermination(ScriptTerminationReason.RuntimeException);
                }
                return(m_terminationReason);
            } finally {
                m_runtime.InjectorHandle = null;
                m_isRunning = false;
            }
#else // XB1
            System.Diagnostics.Debug.Assert(false, "No scripts on XB1!");
            return(m_terminationReason);
#endif // XB1
        }
예제 #30
0
        private void CompileAndCreateInstance(string program, string storage)
        {
            if (MySession.Static.EnableIngameScripts == false)
            {
                return;
            }
            m_wasTerminated = false;
            m_mainMethod    = null;
            Assembly temp = null;

            MyGuiScreenEditor.CompileProgram(program, m_compilerErrors, ref temp);
            if (temp != null)
            {
                try
                {
                    m_assembly = IlInjector.InjectCodeToAssembly("IngameScript_safe", temp, typeof(IlInjector).GetMethod("CountInstructions", BindingFlags.Public | BindingFlags.Static));

                    var type = m_assembly.GetType("Program");
                    if (type != null)
                    {
                        IlInjector.RestartCountingInstructions(MAX_NUM_EXECUTED_INSTRUCTIONS);
                        try
                        {
                            m_instance         = Activator.CreateInstance(type);
                            m_programGridGroup = type.GetField("GridTerminalSystem", BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance);
                            m_storageField     = type.GetField("Storage", BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance);
                            m_meField          = type.GetField("Me", BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance);
                            m_echoField        = type.GetField("Echo", BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance);
                            m_elapsedTimeField = type.GetField("ElapsedTime", BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance);
                            if (m_programGridGroup != null)
                            {
                                // First try to get the main method with a string argument. If this fails, try to get one without.
                                m_mainMethod = type.GetMethod("Main", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, new[] { typeof(string) }, null);
                                m_mainMethodSupportsArgument = m_mainMethod != null;
                                if (m_mainMethod == null)
                                {
                                    m_mainMethod = type.GetMethod("Main", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
                                }
                            }
                            if (m_storageField != null)
                            {
                                m_storageField.SetValue(m_instance, storage);
                            }
                            if (m_meField != null)
                            {
                                m_meField.SetValue(m_instance, this);
                            }
                            if (m_echoField != null)
                            {
                                m_echoField.SetValue(m_instance, new Action <string>(EchoTextToDetailInfo));
                            }
                        }
                        catch (TargetInvocationException ex)
                        {
                            if (ex.InnerException != null)
                            {
                                string response = MyTexts.GetString(MySpaceTexts.ProgrammableBlock_Exception_ExceptionCaught) + ex.InnerException.Message;
                                if (DetailedInfo.ToString() != response)
                                {
                                    SyncObject.SendProgramResponseMessage(response);
                                    WriteProgramResponse(response);
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    string response = MyTexts.GetString(MySpaceTexts.ProgrammableBlock_Exception_ExceptionCaught) + ex.Message;
                    if (DetailedInfo.ToString() != response)
                    {
                        SyncObject.SendProgramResponseMessage(response);
                        WriteProgramResponse(response);
                    }
                }
            }
        }
예제 #31
0
        public string ExecuteCode(string argument)
        {
            if (m_isRunning)
            {
                return(MyTexts.GetString(MySpaceTexts.ProgrammableBlock_Exception_AllreadyRunning));
            }
            if (m_wasTerminated == true)
            {
                return(DetailedInfo.ToString());
            }
            DetailedInfo.Clear();
            m_echoOutput.Clear();
            if (m_assembly == null)
            {
                return(MyTexts.GetString(MySpaceTexts.ProgrammableBlock_Exception_NoAssembly));
            }
            if (!m_instance.HasMainMethod)
            {
                return(MyTexts.GetString(MySpaceTexts.ProgrammableBlock_Exception_NoMain));
            }
            if (m_previousRunTimestamp == 0)
            {
                m_previousRunTimestamp = Stopwatch.GetTimestamp();
                m_instance.ElapsedTime = TimeSpan.Zero;
            }
            else
            {
                var currentTimestamp = Stopwatch.GetTimestamp();
                var elapsedTime      = (currentTimestamp - m_previousRunTimestamp) * Sync.RelativeSimulationRatio;
                m_instance.ElapsedTime = TimeSpan.FromSeconds(elapsedTime * STOPWATCH_FREQUENCY);
                m_previousRunTimestamp = currentTimestamp;
            }
            var gridGroup      = MyCubeGridGroups.Static.Logical.GetGroup(CubeGrid);
            var terminalSystem = gridGroup.GroupData.TerminalSystem;

            terminalSystem.UpdateGridBlocksOwnership(this.OwnerId);
            m_instance.GridTerminalSystem = terminalSystem;

            m_isRunning = true;
            string retVal = "";

            IlInjector.RestartCountingInstructions(MAX_NUM_EXECUTED_INSTRUCTIONS);
            try
            {
                m_instance.Main(argument);
                if (m_echoOutput.Length > 0)
                {
                    retVal = m_echoOutput.ToString();
                }
            }
            catch (Exception ex)
            {
                // Since we just had an exception I'm not fussed about using old
                // fashioned string concatenation here. We'll still want the echo
                // output, since its primary purpose is debugging.
                if (m_echoOutput.Length > 0)
                {
                    retVal = m_echoOutput.ToString();
                }
                OnProgramTermination();
                if (ex is ScriptOutOfRangeException)
                {
                    retVal += MyTexts.GetString(MySpaceTexts.ProgrammableBlock_Exception_TooComplex);
                }
                else
                {
                    retVal += MyTexts.GetString(MySpaceTexts.ProgrammableBlock_Exception_ExceptionCaught) + ex.Message;
                }
            }
            m_isRunning = false;
            return(retVal);
        }