Esempio n. 1
0
 public static void Error(string message)
 {
     PopupDialog.SpawnPopupDialog("Error", message, "Close", true, HighLogic.Skin);
 }
Esempio n. 2
0
        public void Start()
        {
            //Checkers are identified by the type name and _version field name.
            FieldInfo[] fields =
                GetAllTypes()
                .Where(t => t.Name == "CompatibilityChecker")
                .Select(t => t.GetField("_version", BindingFlags.Static | BindingFlags.NonPublic))
                .Where(f => f != null)
                .Where(f => f.FieldType == typeof(int))
                .ToArray();

            //Let the latest version of the checker execute.
            if (_version != fields.Max(f => (int)f.GetValue(null)))
            {
                return;
            }

            Debug.Log($"[CompatibilityChecker] Running checker version {_version} from '{Assembly.GetExecutingAssembly().GetName().Name}'");

            //Other checkers will see this version and not run.
            //This accomplishes the same as an explicit "ran" flag with fewer moving parts.
            _version = int.MaxValue;

            //A mod is incompatible if its compatibility checker has an IsCompatible method which returns false.
            string[] incompatible =
                fields
                .Select(f => f.DeclaringType.GetMethod("IsCompatible", Type.EmptyTypes))
                .Where(m => m.IsStatic)
                .Where(m => m.ReturnType == typeof(bool))
                .Where(m =>
            {
                try
                {
                    return(!(bool)m.Invoke(null, new object[0]));
                }
                catch (Exception e)
                {
                    //If a mod throws an exception from IsCompatible, it's not compatible.
                    Debug.LogWarning($"[CompatibilityChecker] Exception while invoking IsCompatible() from '{m.DeclaringType.Assembly.GetName().Name}':\n\n{e}");
                    return(true);
                }
            })
                .Select(m => m.DeclaringType.Assembly.GetName().Name)
                .ToArray();

            //A mod is incompatible with Unity if its compatibility checker has an IsUnityCompatible method which returns false.
            string[] incompatibleUnity =
                fields
                .Select(f => f.DeclaringType.GetMethod("IsUnityCompatible", Type.EmptyTypes))
                .Where(m => m != null)  //Mods without IsUnityCompatible() are assumed to be compatible.
                .Where(m => m.IsStatic)
                .Where(m => m.ReturnType == typeof(bool))
                .Where(m =>
            {
                try
                {
                    return(!(bool)m.Invoke(null, new object[0]));
                }
                catch (Exception e)
                {
                    //If a mod throws an exception from IsUnityCompatible, it's not compatible.
                    Debug.LogWarning($"[CompatibilityChecker] Exception while invoking IsUnityCompatible() from '{m.DeclaringType.Assembly.GetName().Name}':\n\n{e}");
                    return(true);
                }
            })
                .Select(m => m.DeclaringType.Assembly.GetName().Name)
                .ToArray();

            Array.Sort(incompatible);
            Array.Sort(incompatibleUnity);

            string message = string.Empty;

            if (incompatible.Length > 0 || incompatibleUnity.Length > 0)
            {
                message += (message == string.Empty ? "Some" : "\n\nAdditionally, some") + " installed mods may be incompatible with this version of Kerbal Space Program. Features may be broken or disabled. Please check for updates to the listed mods.";

                if (incompatible.Length > 0)
                {
                    Debug.LogWarning("[CompatibilityChecker] Incompatible mods detected: " + string.Join(", ", incompatible));
                    message += $"\n\nThese mods are incompatible with KSP {Versioning.version_major}.{Versioning.version_minor}.{Versioning.Revision}:\n\n";
                    message += string.Join("\n", incompatible);
                }

                if (incompatibleUnity.Length > 0)
                {
                    Debug.LogWarning("[CompatibilityChecker] Incompatible mods (Unity) detected: " + string.Join(", ", incompatibleUnity));
                    message += $"\n\nThese mods are incompatible with Unity {Application.unityVersion}:\n\n";
                    message += string.Join("\n", incompatibleUnity);
                }
            }

            if (incompatible.Length > 0 || incompatibleUnity.Length > 0)
            {
                PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), "CompatibilityChecker", "Incompatible Mods Detected", message, "OK", true, HighLogic.UISkin);
            }
        }
Esempio n. 3
0
        public void Display()
        {
            //stabDerivHelp = GUILayout.Toggle(stabDerivHelp, "?", ButtonStyle, GUILayout.Width(200));

            GUILayout.Label("Flight Condition:");
            GUILayout.BeginHorizontal();
            GUILayout.Label("Planet:");
            _bodySettingDropdown.GUIDropDownDisplay();

            GUILayout.Label("Altitude (km):");
            altitude = GUILayout.TextField(altitude, GUILayout.ExpandWidth(true));

            GUILayout.Label("Mach Number: ");
            machNumber = GUILayout.TextField(machNumber, GUILayout.ExpandWidth(true));

            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            GUILayout.Label("Flap Setting: ");
            _flapSettingDropdown.GUIDropDownDisplay();
            GUILayout.Label("Spoilers:");
            spoilersDeployed = GUILayout.Toggle(spoilersDeployed, spoilersDeployed ? "Deployed" : "Retracted", GUILayout.Width(100));
            GUILayout.EndHorizontal();

            if (GUILayout.Button("Calculate Stability Derivatives", GUILayout.Width(250.0F), GUILayout.Height(25.0F)))
            {
                CelestialBody body = _bodySettingDropdown.ActiveSelection;
                FARAeroUtil.UpdateCurrentActiveBody(body);
                //atm_temp_str = Regex.Replace(atm_temp_str, @"[^-?[0-9]*(\.[0-9]*)?]", "");
                //rho_str = Regex.Replace(rho_str, @"[^-?[0-9]*(\.[0-9]*)?]", "");
                machNumber = Regex.Replace(machNumber, @"[^-?[0-9]*(\.[0-9]*)?]", "");

                altitude = Regex.Replace(altitude, @"[^-?[0-9]*(\.[0-9]*)?]", "");
                double altitudeDouble = Convert.ToDouble(altitude);
                altitudeDouble *= 1000;


                double temp     = body.GetTemperature(altitudeDouble);
                double pressure = body.GetPressure(altitudeDouble);
                if (pressure > 0)
                {
                    //double temp = Convert.ToSingle(atm_temp_str);
                    double machDouble = Convert.ToSingle(machNumber);
                    machDouble = FARMathUtil.Clamp(machDouble, 0.001, float.PositiveInfinity);

                    double density = body.GetDensity(pressure, temp);

                    double sspeed = body.GetSpeedOfSound(pressure, density);
                    double vel    = sspeed * machDouble;

                    //UpdateControlSettings();

                    double q = vel * vel * density * 0.5f;

                    stabDerivOutput        = simManager.StabDerivCalculator.CalculateStabilityDerivs(vel, q, machDouble, 0, 0, 0, _flapSettingDropdown.ActiveSelection, spoilersDeployed, body, altitudeDouble);
                    simManager.vehicleData = stabDerivOutput;
                    SetAngleVectors(stabDerivOutput.stableAoA);
                }
                else
                {
                    PopupDialog.SpawnPopupDialog(new Vector2(0, 0), new Vector2(0, 0), "Error!", "Altitude was above atmosphere", "OK", true, HighLogic.UISkin);
                }
            }
            GUILayout.BeginHorizontal();
            GUILayout.Label("Aircraft Properties", GUILayout.Width(180));
            GUILayout.Label("Moments of Inertia", GUILayout.Width(160));
            GUILayout.Label("Products of Inertia", GUILayout.Width(160));
            GUILayout.Label("Level Flight", GUILayout.Width(140));
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            GUILayout.BeginVertical(GUILayout.Width(180));
            GUILayout.Label("Ref Area: " + stabDerivOutput.area.ToString("G3") + " m²");
            GUILayout.Label("Scaled Chord: " + stabDerivOutput.MAC.ToString("G3") + " m");
            GUILayout.Label("Scaled Span: " + stabDerivOutput.b.ToString("G3") + " m");
            GUILayout.EndVertical();


            GUILayout.BeginVertical(GUILayout.Width(160));
            GUILayout.Label(new GUIContent("Ixx: " + stabDerivOutput.stabDerivs[0].ToString("G6") + " kg * m²", "Inertia about X-axis due to rotation about X-axis"));
            GUILayout.Label(new GUIContent("Iyy: " + stabDerivOutput.stabDerivs[1].ToString("G6") + " kg * m²", "Inertia about Y-axis due to rotation about Y-axis"));
            GUILayout.Label(new GUIContent("Izz: " + stabDerivOutput.stabDerivs[2].ToString("G6") + " kg * m²", "Inertia about Z-axis due to rotation about Z-axis"));
            GUILayout.EndVertical();

            GUILayout.BeginVertical(GUILayout.Width(160));
            GUILayout.Label(new GUIContent("Ixy: " + stabDerivOutput.stabDerivs[24].ToString("G6") + " kg * m²", "Inertia about X-axis due to rotation about Y-axis; is equal to inertia about Y-axis due to rotation about X-axis"));
            GUILayout.Label(new GUIContent("Iyz: " + stabDerivOutput.stabDerivs[25].ToString("G6") + " kg * m²", "Inertia about Y-axis due to rotation about Z-axis; is equal to inertia about Z-axis due to rotation about Y-axis"));
            GUILayout.Label(new GUIContent("Ixz: " + stabDerivOutput.stabDerivs[26].ToString("G6") + " kg * m²", "Inertia about X-axis due to rotation about Z-axis; is equal to inertia about Z-axis due to rotation about X-axis"));
            GUILayout.EndVertical();

            GUILayout.BeginVertical(GUILayout.Width(140));
            GUILayout.Label(new GUIContent("u0: " + stabDerivOutput.nominalVelocity.ToString("G6") + " m/s", "Air speed based on this mach number and temperature."));
            GUILayout.BeginHorizontal();
            GUILayout.Label(new GUIContent("Cl: " + stabDerivOutput.stableCl.ToString("G3"), "Required lift coefficient at this mass, speed and air density."));
            GUILayout.Label(new GUIContent("Cd: " + stabDerivOutput.stableCd.ToString("G3"), "Resulting drag coefficient at this mass, speed and air density."));
            GUILayout.EndHorizontal();
            GUILayout.Label(new GUIContent("AoA: " + stabDerivOutput.stableAoAState + stabDerivOutput.stableAoA.ToString("G6") + " deg", "Angle of attack required to achieve the necessary lift force."));
            GUILayout.EndVertical();

            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            GUILayout.Label("Longitudinal Derivatives", GUILayout.Width(160));
            GUILayout.EndHorizontal();

            GUIStyle BackgroundStyle = new GUIStyle(GUI.skin.box);

            BackgroundStyle.hover = BackgroundStyle.active = BackgroundStyle.normal;

            GUILayout.BeginVertical(BackgroundStyle);
            GUILayout.BeginHorizontal();
            GUILayout.Label("Down Vel Derivatives", GUILayout.Width(160));
            GUILayout.Label("Fwd Vel Derivatives", GUILayout.Width(160));
            GUILayout.Label("Pitch Rate Derivatives", GUILayout.Width(160));
            GUILayout.Label("Pitch Ctrl Derivatives", GUILayout.Width(160));
            GUILayout.EndHorizontal();
            GUILayout.BeginHorizontal();
            StabilityLabel("Zw: ", stabDerivOutput.stabDerivs[3], " s⁻¹", "Change in Z-direction acceleration with respect to Z-direction velocity; should be negative", 160, -1);
            StabilityLabel("Zu: ", stabDerivOutput.stabDerivs[6], " s⁻¹", "Change in Z-direction acceleration with respect to X-direction velocity; should be negative", 160, -1);
            StabilityLabel("Zq: ", stabDerivOutput.stabDerivs[9], " m/s", "Change in Z-direction acceleration with respect to pitch-up rate; sign unimportant", 160, 0);
            StabilityLabel("Zδe: ", stabDerivOutput.stabDerivs[12], " m/s²", "Change in Z-direction acceleration with respect to pitch control input; should be negative", 160, 0);
            GUILayout.EndHorizontal();
            GUILayout.BeginHorizontal();
            StabilityLabel("Xw: ", stabDerivOutput.stabDerivs[4], " s⁻¹", "Change in X-direction acceleration with respect to Z-direction velocity; sign unimportant", 160, 0);
            StabilityLabel("Xu: ", stabDerivOutput.stabDerivs[7], " s⁻¹", "Change in X-direction acceleration with respect to X-direction velocity; should be negative", 160, -1);
            StabilityLabel("Xq: ", stabDerivOutput.stabDerivs[10], " m/s", "Change in X-direction acceleration with respect to pitch-up rate; sign unimportant", 160, 0);
            StabilityLabel("Xδe: ", stabDerivOutput.stabDerivs[13], " m/s²", "Change in X-direction acceleration with respect to pitch control input; sign unimportant", 160, 0);
            GUILayout.EndHorizontal();
            GUILayout.BeginHorizontal();
            StabilityLabel("Mw: ", stabDerivOutput.stabDerivs[5], " (m * s)⁻¹", "Change in pitch-up angular acceleration with respect to Z-direction velocity; should be negative", 160, -1);
            StabilityLabel("Mu: ", stabDerivOutput.stabDerivs[8], " (m * s)⁻¹", "Change in pitch-up angular acceleration acceleration with respect to X-direction velocity; sign unimportant", 160, 0);
            StabilityLabel("Mq: ", stabDerivOutput.stabDerivs[11], " s⁻¹", "Change in pitch-up angular acceleration acceleration with respect to pitch-up rate; should be negative", 160, -1);
            StabilityLabel("Mδe: ", stabDerivOutput.stabDerivs[14], " s⁻²", "Change in pitch-up angular acceleration acceleration with respect to pitch control input; should be positive", 160, 1);
            GUILayout.EndHorizontal();
            GUILayout.EndVertical();

            GUILayout.BeginHorizontal();
            GUILayout.Label("Lateral Derivatives", GUILayout.Width(160));
            GUILayout.EndHorizontal();
            GUILayout.BeginHorizontal();
            GUILayout.Label("Sideslip Derivatives", GUILayout.Width(160));
            GUILayout.Label("Roll Rate Derivatives", GUILayout.Width(160));
            GUILayout.Label("Yaw Rate Derivatives", GUILayout.Width(160));
            GUILayout.EndHorizontal();
            GUILayout.BeginVertical(BackgroundStyle);
            GUILayout.BeginHorizontal();
            StabilityLabel("Yβ: ", stabDerivOutput.stabDerivs[15], " m/s²", "Change in Y-direction acceleration with respect to sideslip angle β; should be negative", 160, -1);
            StabilityLabel("Yp: ", stabDerivOutput.stabDerivs[18], " m/s", "Change in Y-direction acceleration with respect to roll-right rate; sign unimportant", 160, 0);
            StabilityLabel("Yr: ", stabDerivOutput.stabDerivs[21], " m/s", "Change in Y-direction acceleration with respect to yaw-right rate; should be positive", 160, 1);
            GUILayout.EndHorizontal();
            GUILayout.BeginHorizontal();
            StabilityLabel("Lβ: ", stabDerivOutput.stabDerivs[16], " s⁻²", "Change in roll-right angular acceleration with respect to sideslip angle β; should be negative", 160, -1);
            StabilityLabel("Lp: ", stabDerivOutput.stabDerivs[19], " s⁻¹", "Change in roll-right angular acceleration with respect to roll-right rate; should be negative", 160, -1);
            StabilityLabel("Lr: ", stabDerivOutput.stabDerivs[22], " s⁻¹", "Change in roll-right angular acceleration with respect to yaw-right rate; should be positive", 160, 1);
            GUILayout.EndHorizontal();
            GUILayout.BeginHorizontal();
            StabilityLabel("Nβ: ", stabDerivOutput.stabDerivs[17], " s⁻²", "Change in yaw-right angular acceleration with respect to sideslip angle β; should be positive", 160, 1);
            StabilityLabel("Np: ", stabDerivOutput.stabDerivs[20], " s⁻¹", "Change in yaw-right angular acceleration with respect to roll-right rate; sign unimportant", 160, 0);
            StabilityLabel("Nr: ", stabDerivOutput.stabDerivs[23], " s⁻¹", "Change in yaw-right angular acceleration with respect to yaw-right rate; should be negative", 160, -1);
            GUILayout.EndHorizontal();
            GUILayout.EndVertical();

            DrawTooltip();
        }
Esempio n. 4
0
        public static void DrawPresetWindow(int windowID)
        {
            GUIStyle yellowText = new GUIStyle(GUI.skin.label);

            yellowText.normal.textColor = Color.yellow;

            if (WorkingPreset == null)
            {
                SetNewWorkingPreset(new KCT_Preset(KCT_PresetManager.Instance.ActivePreset), false); //might need to copy instead of assign here
                presetIndex = KCT_PresetManager.Instance.GetIndex(WorkingPreset);
            }

            GUILayout.BeginVertical();
            GUILayout.BeginHorizontal();

            //preset selector
            GUILayout.BeginVertical();
            GUILayout.Label("Presets", yellowText, GUILayout.ExpandHeight(false));
            //preset toolbar in a scrollview
            presetScrollView = GUILayout.BeginScrollView(presetScrollView, GUILayout.Width(presetPosition.width / 6.0f)); //TODO: update HighLogic.Skin.textArea
            string[] presetShortNames = KCT_PresetManager.Instance.PresetShortNames(true);
            if (presetIndex == -1)
            {
                SetNewWorkingPreset(null, true);
            }
            if (changed && presetIndex < presetShortNames.Length - 1 && !KCT_Utilities.ConfigNodesAreEquivalent(WorkingPreset.AsConfigNode(), KCT_PresetManager.Instance.Presets[presetIndex].AsConfigNode())) //!KCT_PresetManager.Instance.PresetsEqual(WorkingPreset, KCT_PresetManager.Instance.Presets[presetIndex], true)
            {
                SetNewWorkingPreset(null, true);
            }

            int prev = presetIndex;

            presetIndex = GUILayout.SelectionGrid(presetIndex, presetShortNames, 1);
            if (prev != presetIndex) //If a new preset was selected
            {
                if (presetIndex != presetShortNames.Length - 1)
                {
                    SetNewWorkingPreset(new KCT_Preset(KCT_PresetManager.Instance.Presets[presetIndex]), false);
                }
                else
                {
                    SetNewWorkingPreset(null, true);
                }
            }

            //presetIndex = GUILayout.Toolbar(presetIndex, presetNames);

            GUILayout.EndScrollView();
            if (GUILayout.Button("Save as\nNew Preset", GUILayout.ExpandHeight(false)))
            {
                //create new preset
                SaveAsNewPreset(WorkingPreset);
            }
            if (WorkingPreset.AllowDeletion && presetIndex != presetShortNames.Length - 1 && GUILayout.Button("Delete Preset")) //allowed to be deleted and isn't Custom
            {
                DialogGUIBase[] options = new DialogGUIBase[2];
                options[0] = new DialogGUIButton("Delete File", DeleteActivePreset);
                options[1] = new DialogGUIButton("Cancel", DummyVoid);
                MultiOptionDialog dialog = new MultiOptionDialog("deletePresetPopup", "Are you sure you want to delete the selected Preset, file and all? This cannot be undone!", "Confirm Deletion", null, options);
                PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), dialog, false, HighLogic.UISkin);
            }
            GUILayout.EndVertical();

            //Main sections
            GUILayout.BeginVertical();
            presetMainScroll = GUILayout.BeginScrollView(presetMainScroll);
            //Preset info section)
            GUILayout.BeginVertical(HighLogic.Skin.textArea);
            GUILayout.Label("Preset Name: " + WorkingPreset.name);
            GUILayout.Label("Description: " + WorkingPreset.description);
            GUILayout.Label("Author(s): " + WorkingPreset.author);
            GUILayout.EndVertical();

            GUILayout.BeginHorizontal();
            //Features section
            GUILayout.BeginVertical();
            GUILayout.Label("Features", yellowText);
            GUILayout.BeginVertical(HighLogic.Skin.textArea);
            WorkingPreset.generalSettings.Enabled                 = GUILayout.Toggle(WorkingPreset.generalSettings.Enabled, "Mod Enabled", HighLogic.Skin.button);
            WorkingPreset.generalSettings.BuildTimes              = GUILayout.Toggle(WorkingPreset.generalSettings.BuildTimes, "Build Times", HighLogic.Skin.button);
            WorkingPreset.generalSettings.ReconditioningTimes     = GUILayout.Toggle(WorkingPreset.generalSettings.ReconditioningTimes, "Launchpad Reconditioning", HighLogic.Skin.button);
            WorkingPreset.generalSettings.ReconditioningBlocksPad = GUILayout.Toggle(WorkingPreset.generalSettings.ReconditioningBlocksPad, "Reconditioning Blocks Pad", HighLogic.Skin.button);
            WorkingPreset.generalSettings.TechUnlockTimes         = GUILayout.Toggle(WorkingPreset.generalSettings.TechUnlockTimes, "Tech Unlock Times", HighLogic.Skin.button);
            WorkingPreset.generalSettings.KSCUpgradeTimes         = GUILayout.Toggle(WorkingPreset.generalSettings.KSCUpgradeTimes, "KSC Upgrade Times", HighLogic.Skin.button);
            WorkingPreset.generalSettings.TechUpgrades            = GUILayout.Toggle(WorkingPreset.generalSettings.TechUpgrades, "Upgrades From Tech Tree", HighLogic.Skin.button);
            WorkingPreset.generalSettings.SharedUpgradePool       = GUILayout.Toggle(WorkingPreset.generalSettings.SharedUpgradePool, "Shared Upgrade Pool (KSCSwitcher)", HighLogic.Skin.button);

            GUILayout.BeginHorizontal();
            GUILayout.Label("Starting Upgrades:");
            WorkingPreset.generalSettings.StartingPoints = GUILayout.TextField(WorkingPreset.generalSettings.StartingPoints, GUILayout.Width(100));
            GUILayout.EndHorizontal();
            GUILayout.EndVertical();
            GUILayout.EndVertical(); //end Features


            GUILayout.BeginVertical(); //Begin time settings
            GUILayout.Label("Time Settings", yellowText);
            GUILayout.BeginVertical(HighLogic.Skin.textArea);
            GUILayout.BeginHorizontal();
            GUILayout.BeginVertical();
            GUILayout.Label("Overall Multiplier: ");
            double.TryParse(OMultTmp = GUILayout.TextField(OMultTmp, 10, GUILayout.Width(80)), out WorkingPreset.timeSettings.OverallMultiplier);
            GUILayout.Label("Merging Time Percent: ");
            double.TryParse(MTimePTmp = GUILayout.TextField(MTimePTmp, 10, GUILayout.Width(80)), out WorkingPreset.timeSettings.MergingTimePercent);
            GUILayout.EndVertical();
            GUILayout.EndHorizontal();
            GUILayout.BeginHorizontal();
            GUILayout.Label("Build Effect: ");
            double.TryParse(BEffTmp = GUILayout.TextField(BEffTmp, 10, GUILayout.Width(80)), out WorkingPreset.timeSettings.BuildEffect);
            GUILayout.EndHorizontal();
            GUILayout.BeginHorizontal();
            GUILayout.Label("Inventory Effect: ");
            double.TryParse(IEffTmp = GUILayout.TextField(IEffTmp, 10, GUILayout.Width(80)), out WorkingPreset.timeSettings.InventoryEffect);
            GUILayout.EndHorizontal();
            GUILayout.BeginHorizontal();
            GUILayout.Label("Reconditioning Effect: ");
            double.TryParse(ReEffTmp = GUILayout.TextField(ReEffTmp, 10, GUILayout.Width(80)), out WorkingPreset.timeSettings.ReconditioningEffect);
            GUILayout.EndHorizontal();
            GUILayout.BeginHorizontal();
            GUILayout.Label("Max Reconditioning: ");
            double.TryParse(MaxReTmp = GUILayout.TextField(MaxReTmp, 10, GUILayout.Width(80)), out WorkingPreset.timeSettings.MaxReconditioning);
            GUILayout.EndHorizontal();
            GUILayout.Label("Rollout-Reconditioning Split:");
            GUILayout.BeginHorizontal();
            //GUILayout.Label("Rollout", GUILayout.ExpandWidth(false));
            WorkingPreset.timeSettings.RolloutReconSplit = GUILayout.HorizontalSlider((float)Math.Floor(WorkingPreset.timeSettings.RolloutReconSplit * 100f), 0, 100) / 100.0;
            //GUILayout.Label("Recon.", GUILayout.ExpandWidth(false));
            GUILayout.EndHorizontal();
            GUILayout.Label((Math.Floor(WorkingPreset.timeSettings.RolloutReconSplit * 100)) + "% Rollout, " + (100 - Math.Floor(WorkingPreset.timeSettings.RolloutReconSplit * 100)) + "% Reconditioning");
            GUILayout.EndVertical();   //end time settings
            GUILayout.EndVertical();
            GUILayout.EndHorizontal(); //end feature/time setting split

            //begin formula settings
            GUILayout.BeginVertical();
            GUILayout.Label("Formula Settings (Advanced)", yellowText);
            GUILayout.BeginVertical(HighLogic.Skin.textArea);
            GUILayout.BeginHorizontal();
            if (GUILayout.Button("Show/Hide Formulas"))
            {
                showFormula = !showFormula;
            }
            if (GUILayout.Button("View Wiki in Browser"))
            {
                Application.OpenURL("https://github.com/linuxgurugamer/KCT/wiki");
            }
            GUILayout.EndHorizontal();

            if (showFormula)
            {
                //show half here, half on other side? Or all in one big list
                int textWidth = 350;
                GUILayout.BeginHorizontal();
                GUILayout.Label("NodeFormula: ");
                WorkingPreset.formulaSettings.NodeFormula = GUILayout.TextField(WorkingPreset.formulaSettings.NodeFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("UpgradeFunds: ");
                WorkingPreset.formulaSettings.UpgradeFundsFormula = GUILayout.TextField(WorkingPreset.formulaSettings.UpgradeFundsFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("UpgradeScience: ");
                WorkingPreset.formulaSettings.UpgradeScienceFormula = GUILayout.TextField(WorkingPreset.formulaSettings.UpgradeScienceFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("UpgradesForScience: ");
                WorkingPreset.formulaSettings.UpgradesForScience = GUILayout.TextField(WorkingPreset.formulaSettings.UpgradesForScience, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("ResearchFormula: ");
                WorkingPreset.formulaSettings.ResearchFormula = GUILayout.TextField(WorkingPreset.formulaSettings.ResearchFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("EffectivePart: ");
                WorkingPreset.formulaSettings.EffectivePartFormula = GUILayout.TextField(WorkingPreset.formulaSettings.EffectivePartFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("ProceduralPart: ");
                WorkingPreset.formulaSettings.ProceduralPartFormula = GUILayout.TextField(WorkingPreset.formulaSettings.ProceduralPartFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("BPFormula: ");
                WorkingPreset.formulaSettings.BPFormula = GUILayout.TextField(WorkingPreset.formulaSettings.BPFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("KSCUpgrade: ");
                WorkingPreset.formulaSettings.KSCUpgradeFormula = GUILayout.TextField(WorkingPreset.formulaSettings.KSCUpgradeFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("Reconditioning: ");
                WorkingPreset.formulaSettings.ReconditioningFormula = GUILayout.TextField(WorkingPreset.formulaSettings.ReconditioningFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("BuildRate: ");
                WorkingPreset.formulaSettings.BuildRateFormula = GUILayout.TextField(WorkingPreset.formulaSettings.BuildRateFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("UpgradeReset: ");
                WorkingPreset.formulaSettings.UpgradeResetFormula = GUILayout.TextField(WorkingPreset.formulaSettings.UpgradeResetFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("InventorySale: ");
                WorkingPreset.formulaSettings.InventorySaleFormula = GUILayout.TextField(WorkingPreset.formulaSettings.InventorySaleFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("RolloutCosts: ");
                WorkingPreset.formulaSettings.RolloutCostFormula = GUILayout.TextField(WorkingPreset.formulaSettings.RolloutCostFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("IntegrationCosts: ");
                WorkingPreset.formulaSettings.IntegrationCostFormula = GUILayout.TextField(WorkingPreset.formulaSettings.IntegrationCostFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("IntegrationTime: ");
                WorkingPreset.formulaSettings.IntegrationTimeFormula = GUILayout.TextField(WorkingPreset.formulaSettings.IntegrationTimeFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("NewLaunchPadCost: ");
                WorkingPreset.formulaSettings.NewLaunchPadCostFormula = GUILayout.TextField(WorkingPreset.formulaSettings.NewLaunchPadCostFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("RushCost: ");
                WorkingPreset.formulaSettings.RushCostFormula = GUILayout.TextField(WorkingPreset.formulaSettings.RushCostFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("AirlaunchCost: ");
                WorkingPreset.formulaSettings.AirlaunchCostFormula = GUILayout.TextField(WorkingPreset.formulaSettings.AirlaunchCostFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("AirlaunchTime: ");
                WorkingPreset.formulaSettings.AirlaunchTimeFormula = GUILayout.TextField(WorkingPreset.formulaSettings.AirlaunchTimeFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();
            }

            GUILayout.EndVertical();
            GUILayout.EndVertical(); //end formula settings

            GUILayout.EndScrollView();

            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            if (GUILayout.Button("Save", GUILayout.ExpandWidth(false)))
            {
                KCT_PresetManager.Instance.ActivePreset = WorkingPreset;
                KCT_PresetManager.Instance.SaveActiveToSaveData();
                WorkingPreset = null;

                if (!KCT_PresetManager.Instance.ActivePreset.generalSettings.Enabled)
                {
                    KCT_Utilities.DisableModFunctionality();
                }
                //KCT_GameStates.settings.enabledForSave = KCT_PresetManager.Instance.ActivePreset.generalSettings.Enabled;
                KCT_GameStates.settings.MaxTimeWarp          = newTimewarp;
                KCT_GameStates.settings.ForceStopWarp        = forceStopWarp;
                KCT_GameStates.settings.DisableAllMessages   = disableAllMsgs;
                KCT_GameStates.settings.OverrideLaunchButton = overrideLaunchBtn;
                KCT_GameStates.settings.Debug                = debug;
                KCT_GameStates.settings.AutoKACAlarms        = autoAlarms;
                KCT_GameStates.settings.AutoStockAlarms      = autoStockAlarms;
                KCT_GameStates.settings.CheckForDebugUpdates = debugUpdateChecking;

                KCT_GameStates.settings.Save();
                showSettings = false;
                if (!PrimarilyDisabled && !showFirstRun)
                {
                    ResetBLWindow();

                    //if (KCT_Events.instance.KCTButtonStock != null)
                    //    KCT_Events.instance.KCTButtonStock.SetTrue();
                    if (KCT_GameStates.toolbarControl != null)
                    {
                        KCT_GameStates.toolbarControl.SetTrue();
                    }

                    else
                    {
                        showBuildList = true;
                    }
                }
                if (!KCT_PresetManager.Instance.ActivePreset.generalSettings.Enabled)
                {
                    InputLockManager.RemoveControlLock("KCTKSCLock");
                }

                for (int j = 0; j < KCT_GameStates.TechList.Count; j++)
                {
                    KCT_GameStates.TechList[j].UpdateBuildRate(j);
                }

                foreach (KCT_KSC ksc in KCT_GameStates.KSCs)
                {
                    ksc.RecalculateBuildRates();
                    ksc.RecalculateUpgradedBuildRates();
                }
                KCT_GUI.ResetFormulaRateHolders();
            }
            if (GUILayout.Button("Cancel", GUILayout.ExpandWidth(false)))
            {
                WorkingPreset = null;
                showSettings  = false;
                if (!PrimarilyDisabled && !showFirstRun)
                {
                    ResetBLWindow();

                    //if (KCT_Events.instance.KCTButtonStock != null)
                    //    KCT_Events.instance.KCTButtonStock.SetTrue();
                    if (KCT_GameStates.toolbarControl != null)
                    {
                        KCT_GameStates.toolbarControl.SetTrue();
                    }

                    else
                    {
                        showBuildList = true;
                    }
                }

                for (int j = 0; j < KCT_GameStates.TechList.Count; j++)
                {
                    KCT_GameStates.TechList[j].UpdateBuildRate(j);
                }
            }
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();

            GUILayout.EndVertical();                       //end column 2

            GUILayout.BeginVertical(GUILayout.Width(100)); //Start general settings
            GUILayout.Label("General Settings", yellowText);
            GUILayout.Label("NOTE: Affects all saves!", yellowText);
            GUILayout.BeginVertical(HighLogic.Skin.textArea);
            GUILayout.Label("Max Timewarp");
            GUILayout.BeginHorizontal();
            if (GUILayout.Button("-", GUILayout.ExpandWidth(false)))
            {
                newTimewarp = Math.Max(newTimewarp - 1, 0);
            }
            //current warp setting
            GUILayout.Label(TimeWarp.fetch.warpRates[newTimewarp] + "x");
            if (GUILayout.Button("+", GUILayout.ExpandWidth(false)))
            {
                newTimewarp = Math.Min(newTimewarp + 1, TimeWarp.fetch.warpRates.Length - 1);
            }
            GUILayout.EndHorizontal();

            forceStopWarp     = GUILayout.Toggle(forceStopWarp, "Auto Stop TimeWarp", HighLogic.Skin.button);
            autoAlarms        = GUILayout.Toggle(autoAlarms, "Auto KAC Alarms", HighLogic.Skin.button);
            autoStockAlarms   = GUILayout.Toggle(autoStockAlarms, "Auto Stock Alarms", HighLogic.Skin.button);
            overrideLaunchBtn = GUILayout.Toggle(overrideLaunchBtn, "Override Launch Button", HighLogic.Skin.button);
            disableAllMsgs    = !GUILayout.Toggle(!disableAllMsgs, "Use Message System", HighLogic.Skin.button);
            debug             = GUILayout.Toggle(debug, "Debug Logging", HighLogic.Skin.button);

#if DEBUG
            debugUpdateChecking = GUILayout.Toggle(debugUpdateChecking, "Check for Dev Updates", HighLogic.Skin.button);
#endif

            GUILayout.EndVertical();
            GUILayout.EndVertical();

            GUILayout.EndHorizontal(); //end main split
            GUILayout.EndVertical();   //end window

            changed = GUI.changed;

            if (!Input.GetMouseButtonDown(1) && !Input.GetMouseButtonDown(2))
            {
                GUI.DragWindow();
            }
        }
Esempio n. 5
0
        private void ProcessRetirements(double time)
        {
            if (RetirementEnabled)
            {
                foreach (KeyValuePair <string, double> kvp in KerbalRetireTimes)
                {
                    ProtoCrewMember pcm = HighLogic.CurrentGame.CrewRoster[kvp.Key];
                    if (pcm == null)
                    {
                        _toRemove.Add(kvp.Key);
                    }
                    else
                    {
                        if (pcm.rosterStatus != ProtoCrewMember.RosterStatus.Available)
                        {
                            if (pcm.rosterStatus != ProtoCrewMember.RosterStatus.Assigned)
                            {
                                _toRemove.Add(kvp.Key);
                            }

                            continue;
                        }

                        if (pcm.inactive)
                        {
                            continue;
                        }

                        if (time > kvp.Value)
                        {
                            _toRemove.Add(kvp.Key);
                            _retirees.Add(kvp.Key);
                            pcm.rosterStatus = ProtoCrewMember.RosterStatus.Dead;
                        }
                    }
                }
            }

            // TODO remove from courses? Except I think they won't retire if inactive either so that's ok.
            if (_toRemove.Count > 0)
            {
                string msgStr = string.Empty;
                foreach (string s in _toRemove)
                {
                    KerbalRetireTimes.Remove(s);
                    if (HighLogic.CurrentGame.CrewRoster[s] != null && _retirees.Contains(s))
                    {
                        msgStr = $"{msgStr}\n{s}";
                    }
                }
                if (!string.IsNullOrEmpty(msgStr))
                {
                    PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f),
                                                 new Vector2(0.5f, 0.5f),
                                                 "CrewRetirementNotification",
                                                 "Crew Retirement",
                                                 "The following retirements have occurred:\n" + msgStr,
                                                 "OK",
                                                 true,
                                                 HighLogic.UISkin);
                }

                _toRemove.Clear();
            }

            if (_toRemove.Count > 0)
            {
                MaintenanceHandler.Instance?.ScheduleMaintenanceUpdate();
            }
        }
        public bool ElectionAndCheck()
        {
            #region Type election

            // TODO : Move the old version check in a process that call Update.

            // Check for old version and MMSarbianExt
            IEnumerable <AssemblyLoader.LoadedAssembly> oldMM =
                AssemblyLoader.loadedAssemblies.Where(
                    a => a.assembly.GetName().Name == Assembly.GetExecutingAssembly().GetName().Name)
                .Where(a => a.assembly.GetName().Version.CompareTo(new System.Version(1, 5, 0)) == -1);
            IEnumerable <AssemblyLoader.LoadedAssembly> oldAssemblies =
                oldMM.Concat(AssemblyLoader.loadedAssemblies.Where(a => a.assembly.GetName().Name == "MMSarbianExt"));
            if (oldAssemblies.Any())
            {
                IEnumerable <string> badPaths =
                    oldAssemblies.Select(a => a.path)
                    .Select(
                        p =>
                        Uri.UnescapeDataString(
                            new Uri(Path.GetFullPath(KSPUtil.ApplicationRootPath)).MakeRelativeUri(new Uri(p))
                            .ToString()
                            .Replace('/', Path.DirectorySeparatorChar)));
                string status =
                    "You have old versions of Module Manager (older than 1.5) or MMSarbianExt.\nYou will need to remove them for Module Manager and the mods using it to work\nExit KSP and delete those files :\n" +
                    String.Join("\n", badPaths.ToArray());
                PopupDialog.SpawnPopupDialog(new Vector2(0f, 1f), new Vector2(0f, 1f), "ModuleManagerOldVersions", "Old versions of Module Manager", status, "OK", false, UISkinManager.defaultSkin);
                Log("Old version of Module Manager present. Stopping");
                return(false);
            }


            //PopupDialog.SpawnPopupDialog(new Vector2(0.1f, 1f), new Vector2(0.2f, 1f), "Test of the dialog", "Stuff", "OK", false, UISkinManager.defaultSkin);

            Assembly currentAssembly = Assembly.GetExecutingAssembly();
            IEnumerable <AssemblyLoader.LoadedAssembly> eligible = from a in AssemblyLoader.loadedAssemblies
                                                                   let ass = a.assembly
                                                                             where ass.GetName().Name == currentAssembly.GetName().Name
                                                                             orderby ass.GetName().Version descending, a.path ascending
            select a;

            // Elect the newest loaded version of MM to process all patch files.
            // If there is a newer version loaded then don't do anything
            // If there is a same version but earlier in the list, don't do anything either.
            if (eligible.First().assembly != currentAssembly)
            {
                //loaded = true;
                Log("version " + currentAssembly.GetName().Version + " at " + currentAssembly.Location +
                    " lost the election");
                Destroy(gameObject);
                return(false);
            }
            string candidates = "";
            foreach (AssemblyLoader.LoadedAssembly a in eligible)
            {
                if (currentAssembly.Location != a.path)
                {
                    candidates += "Version " + a.assembly.GetName().Version + " " + a.path + " " + "\n";
                }
            }
            if (candidates.Length > 0)
            {
                Log("version " + currentAssembly.GetName().Version + " at " + currentAssembly.Location +
                    " won the election against\n" + candidates);
            }

            #endregion Type election

            return(true);
        }
Esempio n. 7
0
        public void Show(Part part)
        {
            if (IsVisible())
            {
                Hide();
                newPart = part;
                return;
            }

            LoadCfgFile();

            this.part = part;

            DialogGUISpace     spaceAxisLeft        = new DialogGUISpace(30f);
            DialogGUISpace     spaceAxisCenter      = new DialogGUISpace(115f);
            DialogGUISpace     spaceAxisRight       = new DialogGUISpace(120f);
            DialogGUISpace     spaceTransform       = new DialogGUISpace(15f);
            DialogGUISpace     spaceTransformRight  = new DialogGUISpace(70f);
            DialogGUIButton    buttonReferenceSpace = new DialogGUIButton(GetReferenceSpaceLabel, ToggleReferenceSpace, 100f, LINE_HEIGHT, false);
            DialogGUILabel     labelX             = new DialogGUILabel(FormatLabel("X"), LINE_HEIGHT);
            DialogGUILabel     labelY             = new DialogGUILabel(FormatLabel("Y"), LINE_HEIGHT);
            DialogGUILabel     labelZ             = new DialogGUILabel(FormatLabel("Z"), LINE_HEIGHT);
            DialogGUILabel     labelMinusPlus     = new DialogGUILabel(FormatLabel("- / +"), LINE_HEIGHT);
            DialogGUILabel     labelPosition      = new DialogGUILabel(FormatLabel("Position"), LABEL_WIDTH);
            DialogGUILabel     labelRotation      = new DialogGUILabel(FormatLabel("Rotation"), LABEL_WIDTH);
            DialogGUITextInput inputPositionX     = new DialogGUITextInput("", false, MAXLENGTH, delegate(string value) { return(SetPosition(0, value)); }, delegate { return(GetPosition(0)); }, TMP_InputField.ContentType.DecimalNumber, LINE_HEIGHT);
            DialogGUITextInput inputPositionY     = new DialogGUITextInput("", false, MAXLENGTH, delegate(string value) { return(SetPosition(1, value)); }, delegate { return(GetPosition(1)); }, TMP_InputField.ContentType.DecimalNumber, LINE_HEIGHT);
            DialogGUITextInput inputPositionZ     = new DialogGUITextInput("", false, MAXLENGTH, delegate(string value) { return(SetPosition(2, value)); }, delegate { return(GetPosition(2)); }, TMP_InputField.ContentType.DecimalNumber, LINE_HEIGHT);
            DialogGUITextInput inputDeltaPosition = new DialogGUITextInput("", false, MAXLENGTH, delegate(string value) { return(SetDeltaPosition(value)); }, delegate { return(deltaPosition.ToString(FORMAT)); }, TMP_InputField.ContentType.DecimalNumber, LINE_HEIGHT);
            DialogGUITextInput inputRotationX     = new DialogGUITextInput("", false, MAXLENGTH, delegate(string value) { return(SetRotation(0, value)); }, delegate { return(GetRotation(0)); }, TMP_InputField.ContentType.DecimalNumber, LINE_HEIGHT);
            DialogGUITextInput inputRotationY     = new DialogGUITextInput("", false, MAXLENGTH, delegate(string value) { return(SetRotation(1, value)); }, delegate { return(GetRotation(1)); }, TMP_InputField.ContentType.DecimalNumber, LINE_HEIGHT);
            DialogGUITextInput inputRotationZ     = new DialogGUITextInput("", false, MAXLENGTH, delegate(string value) { return(SetRotation(2, value)); }, delegate { return(GetRotation(2)); }, TMP_InputField.ContentType.DecimalNumber, LINE_HEIGHT);
            DialogGUITextInput inputDeltaRotation = new DialogGUITextInput("", false, MAXLENGTH, delegate(string value) { return(SetDeltaRotation(value)); }, delegate { return(deltaRotation.ToString(FORMAT)); }, TMP_InputField.ContentType.DecimalNumber, LINE_HEIGHT);
            DialogGUIButton    buttonPosXMinus    = new DialogGUIButton("-", delegate { Translate(0, true); }, LINE_HEIGHT, LINE_HEIGHT, false);
            DialogGUIButton    buttonPosXPlus     = new DialogGUIButton("+", delegate { Translate(0, false); }, LINE_HEIGHT, LINE_HEIGHT, false);
            DialogGUIButton    buttonPosYMinus    = new DialogGUIButton("-", delegate { Translate(1, true); }, LINE_HEIGHT, LINE_HEIGHT, false);
            DialogGUIButton    buttonPosYPlus     = new DialogGUIButton("+", delegate { Translate(1, false); }, LINE_HEIGHT, LINE_HEIGHT, false);
            DialogGUIButton    buttonPosZMinus    = new DialogGUIButton("-", delegate { Translate(2, true); }, LINE_HEIGHT, LINE_HEIGHT, false);
            DialogGUIButton    buttonPosZPlus     = new DialogGUIButton("+", delegate { Translate(2, false); }, LINE_HEIGHT, LINE_HEIGHT, false);
            DialogGUIButton    buttonDeltaPosDiv  = new DialogGUIButton("/10", delegate { SetDeltaPosition((deltaPosition / 10).ToString()); }, 35f, LINE_HEIGHT, false);
            DialogGUIButton    buttonDeltaPosMult = new DialogGUIButton("×10", delegate { SetDeltaPosition((deltaPosition * 10).ToString()); }, 35f, LINE_HEIGHT, false);
            DialogGUIButton    buttonRotXMinus    = new DialogGUIButton("-", delegate { Rotate(0, true); }, LINE_HEIGHT, LINE_HEIGHT, false);
            DialogGUIButton    buttonRotXPlus     = new DialogGUIButton("+", delegate { Rotate(0, false); }, LINE_HEIGHT, LINE_HEIGHT, false);
            DialogGUIButton    buttonRotYMinus    = new DialogGUIButton("-", delegate { Rotate(1, true); }, LINE_HEIGHT, LINE_HEIGHT, false);
            DialogGUIButton    buttonRotYPlus     = new DialogGUIButton("+", delegate { Rotate(1, false); }, LINE_HEIGHT, LINE_HEIGHT, false);
            DialogGUIButton    buttonRotZMinus    = new DialogGUIButton("-", delegate { Rotate(2, true); }, LINE_HEIGHT, LINE_HEIGHT, false);
            DialogGUIButton    buttonRotZPlus     = new DialogGUIButton("+", delegate { Rotate(2, false); }, LINE_HEIGHT, LINE_HEIGHT, false);
            DialogGUIButton    buttonDeltaRotDiv  = new DialogGUIButton("/10", delegate { SetDeltaRotation((deltaRotation / 10).ToString()); }, 35f, LINE_HEIGHT, false);
            DialogGUIButton    buttonDeltaRotMult = new DialogGUIButton("×10", delegate { SetDeltaRotation((deltaRotation * 10).ToString()); }, 35f, LINE_HEIGHT, false);

            DialogGUIButton buttonZeroRot = new DialogGUIButton("Zero", delegate { RotateZero(); }, 70f, LINE_HEIGHT, false);

            DialogGUIToggleButton toggleButtonAttachment = new DialogGUIToggleButton(showAttachment, "Attachment Rules", delegate { ToggleAttachment(); }, -1, LINE_HEIGHT);
            DialogGUIToggleButton toggleButtonColliders  = new DialogGUIToggleButton(showColliders, "Colliders", delegate { ToggleColliders(); }, -1, LINE_HEIGHT);
            DialogGUISpace        spaceToCenter          = new DialogGUISpace(-1);
            DialogGUIButton       buttonClose            = new DialogGUIButton("Close", delegate { CloseWindow(); }, 140f, LINE_HEIGHT, true);

            List <DialogGUIBase> dialogGUIBaseList = new List <DialogGUIBase>
            {
                new DialogGUIHorizontalLayout(TextAnchor.MiddleCenter, buttonReferenceSpace, spaceAxisLeft, labelX, spaceAxisCenter, labelY, spaceAxisCenter, labelZ, spaceAxisRight, labelMinusPlus, spaceTransformRight),
                new DialogGUIHorizontalLayout(TextAnchor.MiddleCenter, labelPosition, buttonPosXMinus, inputPositionX, buttonPosXPlus, spaceTransform, buttonPosYMinus, inputPositionY, buttonPosYPlus, spaceTransform, buttonPosZMinus, inputPositionZ, buttonPosZPlus, spaceTransform, buttonDeltaPosDiv, inputDeltaPosition, buttonDeltaPosMult, spaceTransformRight),
                new DialogGUIHorizontalLayout(TextAnchor.MiddleCenter, labelRotation, buttonRotXMinus, inputRotationX, buttonRotXPlus, spaceTransform, buttonRotYMinus, inputRotationY, buttonRotYPlus, spaceTransform, buttonRotZMinus, inputRotationZ, buttonRotZPlus, spaceTransform, buttonDeltaRotDiv, inputDeltaRotation, buttonDeltaRotMult, buttonZeroRot)
            };

            if (part.isCompund)
            {
                DialogGUILabel  labelCompound  = new DialogGUILabel(FormatLabel("Anchor"), LABEL_WIDTH);
                DialogGUIButton buttonCompound = new DialogGUIButton(GetCompoundLabel, ToggleCompound, 100f, LINE_HEIGHT, false);
                dialogGUIBaseList.Add(new DialogGUIHorizontalLayout(TextAnchor.MiddleCenter, labelCompound, buttonCompound));
            }
            dialogGUIBaseList.Add(new DialogGUIHorizontalLayout(toggleButtonAttachment, toggleButtonColliders));
            dialogGUIBaseList.Add(new DialogGUIHorizontalLayout(spaceToCenter, buttonClose, spaceToCenter));

            string windowTitle = FormatLabel("Precise Editor - ") + part.partInfo.title;

            dialog      = new MultiOptionDialog("partEditionDialog", "", windowTitle, HighLogic.UISkin, dialogRect, new DialogGUIVerticalLayout(dialogGUIBaseList.ToArray()));
            popupDialog = PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), dialog, false, HighLogic.UISkin, false);
            popupDialog.onDestroy.AddListener(SaveWindowPosition);
            popupDialog.onDestroy.AddListener(RemoveControlLock);
            popupDialog.onDestroy.AddListener(OnPopupDialogDestroy);

            SetTextInputColor(inputPositionX, axisLines.red);
            SetTextInputColor(inputPositionY, axisLines.green);
            SetTextInputColor(inputPositionZ, axisLines.cyan);
            SetTextInputColor(inputRotationX, axisLines.red);
            SetTextInputColor(inputRotationY, axisLines.green);
            SetTextInputColor(inputRotationZ, axisLines.cyan);

            SetTextInputListeners(inputPositionX);
            SetTextInputListeners(inputPositionY);
            SetTextInputListeners(inputPositionZ);
            SetTextInputListeners(inputRotationX);
            SetTextInputListeners(inputRotationY);
            SetTextInputListeners(inputRotationZ);
            SetTextInputListeners(inputDeltaPosition);
            SetTextInputListeners(inputDeltaRotation);

            if (showAttachment)
            {
                attachmentWindow.Show(part);
            }

            if (showColliders)
            {
                colliderWindow.Show(part);
            }

            axisLines.Show(part, referenceSpace, compoundTargetSelected);
        }
Esempio n. 8
0
        protected void VesselRecoveryRequested(Vessel v)
        {
            double        elapsedTime       = v.missionTime;
            List <string> retirementChanges = new List <string>();
            List <string> inactivity        = new List <string>();

            double UT = Planetarium.GetUniversalTime();

            // When flight duration was too short, mission training should not be set as expired.
            // This can happen when an on-the-pad failure occurs and the vessel is recovered.
            if (elapsedTime < settings.minFlightDurationSecondsForTrainingExpire)
            {
                return;
            }

            foreach (ProtoCrewMember pcm in v.GetVesselCrew())
            {
                bool hasSpace      = false;
                bool hasOrbit      = false;
                bool hasEVA        = false;
                bool hasEVAOther   = false;
                bool hasOther      = false;
                bool hasOrbitOther = false;
                bool hasLandOther  = false;
                int  curFlight     = pcm.careerLog.Last().flight;
                foreach (FlightLog.Entry e in pcm.careerLog.Entries)
                {
                    if (e.type == "TRAINING_mission")
                    {
                        SetExpiration(pcm.name, e, Planetarium.GetUniversalTime());
                    }

                    if (e.flight != curFlight)
                    {
                        continue;
                    }

                    bool isOther = false;
                    if (!string.IsNullOrEmpty(e.target) && e.target != Planetarium.fetch.Home.name)
                    {
                        isOther = hasOther = true;
                    }

                    if (!string.IsNullOrEmpty(e.type))
                    {
                        switch (e.type)
                        {
                        case "Suborbit":
                            hasSpace = true;
                            break;

                        case "Orbit":
                            if (isOther)
                            {
                                hasOrbitOther = true;
                            }
                            else
                            {
                                hasOrbit = true;
                            }
                            break;

                        case "ExitVessel":
                            if (isOther)
                            {
                                hasEVAOther = true;
                            }
                            else
                            {
                                hasEVA = true;
                            }
                            break;

                        case "Land":
                            if (isOther)
                            {
                                hasLandOther = true;
                            }
                            break;

                        default:
                            break;
                        }
                    }
                }
                double multiplier = 1d;
                double constant   = 0.5d;
                if (hasSpace)
                {
                    multiplier += settings.recSpace.x;
                    constant   += settings.recSpace.y;
                }
                if (hasOrbit)
                {
                    multiplier += settings.recOrbit.x;
                    constant   += settings.recOrbit.y;
                }
                if (hasOther)
                {
                    multiplier += settings.recOtherBody.x;
                    constant   += settings.recOtherBody.y;
                }
                if (hasEVA)
                {
                    multiplier += settings.recEVA.x;
                    constant   += settings.recEVA.y;
                }
                if (hasEVAOther)
                {
                    multiplier += settings.recEVAOther.x;
                    constant   += settings.recEVAOther.y;
                }
                if (hasOrbitOther)
                {
                    multiplier += settings.recOrbitOther.x;
                    constant   += settings.recOrbitOther.y;
                }
                if (hasLandOther)
                {
                    multiplier += settings.recLandOther.x;
                    constant   += settings.recLandOther.y;
                }

                double retTime;
                if (kerbalRetireTimes.TryGetValue(pcm.name, out retTime))
                {
                    double offset = constant * 86400d * settings.retireOffsetBaseMult / (1 + Math.Pow(Math.Max(curFlight + settings.retireOffsetFlightNumOffset, 0d), settings.retireOffsetFlightNumPow)
                                                                                         * UtilMath.Lerp(settings.retireOffsetStupidMin, settings.retireOffsetStupidMax, pcm.stupidity));
                    if (offset > 0d)
                    {
                        retTime += offset;
                        kerbalRetireTimes[pcm.name] = retTime;
                        retirementChanges.Add("\n" + pcm.name + ", no earlier than " + KSPUtil.PrintDate(retTime, false));
                    }
                }

                multiplier /= (ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.AstronautComplex) + 1d);

                double inactiveTime = elapsedTime * multiplier + constant * 86400d;
                pcm.SetInactive(inactiveTime, false);
                inactivity.Add("\n" + pcm.name + ", until " + KSPUtil.PrintDate(inactiveTime + UT, true, false));
            }
            if (inactivity.Count > 0)
            {
                string msgStr = "The following crew members will be on leave:";
                foreach (string s in inactivity)
                {
                    msgStr += s;
                }

                if (retirementEnabled && retirementChanges.Count > 0)
                {
                    msgStr += "\n\nThe following retirement changes have occurred:";
                    foreach (string s in retirementChanges)
                    {
                        msgStr += s;
                    }
                }

                PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f),
                                             new Vector2(0.5f, 0.5f),
                                             "CrewUpdateNotification",
                                             "Crew Updates",
                                             msgStr,
                                             "OK",
                                             true,
                                             HighLogic.UISkin);
            }
        }
Esempio n. 9
0
        private void WindowFunction(int windowID)
        {
            GUILayout.BeginHorizontal();

            bool oldShowInfo = _showInfo1;

            _showInfo1 = GUILayout.Toggle(_showInfo1, "ⓘ", HighLogic.Skin.button, GUILayout.ExpandWidth(false), GUILayout.Height(20));
            if (oldShowInfo != _showInfo1)
            {
                var settings = HighLogic.CurrentGame.Parameters.CustomParams <RP0Settings>();
                settings.AvionicsWindow_ShowInfo1 = _showInfo1;
                _shouldResetUIHeight = true;
            }

            if (_showInfo1)
            {
                GUILayout.Label(info1Text);
            }
            GUILayout.EndHorizontal();

            GUILayout.BeginVertical(HighLogic.Skin.box);
            GUILayout.Label("Choose the avionics type:", HighLogic.Skin.label);
            int oldConfigIdx = _selectedConfigIndex;

            _selectedConfigIndex = GUILayout.Toolbar(_selectedConfigIndex, _avionicsConfigNames, HighLogic.Skin.button);
            if (oldConfigIdx != _selectedConfigIndex)
            {
                _shouldResetUIHeight = true;
                _tooltipTexts.Clear();
            }

            string curCfgName = _avionicsConfigNames[_selectedConfigIndex];
            ProceduralAvionicsConfig curCfg = ProceduralAvionicsTechManager.GetProceduralAvionicsConfig(curCfgName);

            GUILayout.BeginHorizontal();

            oldShowInfo = _showInfo2;
            _showInfo2  = GUILayout.Toggle(_showInfo2, "ⓘ", HighLogic.Skin.button, GUILayout.ExpandWidth(false), GUILayout.Height(20));
            if (oldShowInfo != _showInfo2)
            {
                var settings = HighLogic.CurrentGame.Parameters.CustomParams <RP0Settings>();
                settings.AvionicsWindow_ShowInfo2 = _showInfo2;
                _shouldResetUIHeight = true;
            }

            if (_showInfo2)
            {
                GUILayout.Label(curCfg.description);
            }
            GUILayout.EndHorizontal();
            GUILayout.EndVertical();

            GUILayout.Space(7);

            GUILayout.BeginVertical(HighLogic.Skin.box);
            GUILayout.Label("Choose the tech level:", HighLogic.Skin.label);
            foreach (ProceduralAvionicsTechNode techNode in curCfg.TechNodes.Values)
            {
                DrawAvionicsConfigSelector(curCfg, techNode);
            }
            GUILayout.EndVertical();

            GUILayout.Space(7);

            GUILayout.BeginVertical(HighLogic.Skin.box);
            GUILayout.BeginHorizontal();

            oldShowInfo = _showInfo3;
            _showInfo3  = GUILayout.Toggle(_showInfo3, "ⓘ", HighLogic.Skin.button, GUILayout.ExpandWidth(false), GUILayout.Height(20));
            if (oldShowInfo != _showInfo3)
            {
                var settings = HighLogic.CurrentGame.Parameters.CustomParams <RP0Settings>();
                settings.AvionicsWindow_ShowInfo3 = _showInfo3;
                _shouldResetUIHeight = true;
            }

            if (_showInfo3)
            {
                GUILayout.Label(info3Text);
            }
            GUILayout.EndHorizontal();

            if (!IsScienceCore)
            {
                GUILayout.BeginHorizontal();
                GUILayout.BeginHorizontal(GUILayout.Width(250));
                GUILayout.Label("Controllable mass: ", HighLogic.Skin.label, GUILayout.Width(150));
                _sControllableMass = GUILayout.TextField(_sControllableMass, HighLogic.Skin.textField);
                GUILayout.Label("t", HighLogic.Skin.label);
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal(GUILayout.MaxWidth(50));
                float oldControlMass = _newControlMass;
                if (float.TryParse(_sControllableMass, out _newControlMass))
                {
                    float avionicsMass = GetShieldedAvionicsMass(_newControlMass);
                    GUILayout.Label($" ({avionicsMass * 1000:0.#} kg)", HighLogic.Skin.label, GUILayout.Width(150));
                }

                if (oldControlMass != _newControlMass)
                {
                    _tooltipTexts.Clear();
                }

                GUILayout.EndHorizontal();
                GUILayout.EndHorizontal();
            }

            GUILayout.BeginHorizontal();
            GUILayout.BeginHorizontal(GUILayout.Width(250));
            GUILayout.Label("EC amount: ", HighLogic.Skin.label, GUILayout.Width(150));
            _sECAmount = GUILayout.TextField(_sECAmount, HighLogic.Skin.textField);
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal(GUILayout.MaxWidth(50));
            if (float.TryParse(_sECAmount, out float ecAmount))
            {
                GUILayout.Label($" ({_ecTank.mass * ecAmount:0.#} kg)", HighLogic.Skin.label, GUILayout.Width(150));
            }
            GUILayout.EndHorizontal();
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal(GUILayout.Width(250));
            _gc ??= new GUIContent();
            _gc.text    = "Additional tank volume: ";
            _gc.tooltip = "How much tank volume will be left for other resources after applying the desired controllable mass and amount of EC.";
            GUILayout.Label(_gc, HighLogic.Skin.label, GUILayout.Width(150));
            GUI.enabled   = _seekVolumeMethod != null;
            _sExtraVolume = GUILayout.TextField(_sExtraVolume, HighLogic.Skin.textField);
            GUI.enabled   = true;
            GUILayout.Label("l", HighLogic.Skin.label);
            GUILayout.EndHorizontal();

            if (_showROTankSizeWarning)
            {
                GUILayout.Label("ROTanks does not currently support automatic resizing to correct dimensions. Increase the part size manually until it has sufficient volume.", HighLogic.Skin.label);
            }
            else if (_showSizeWarning)
            {
                GUILayout.Label("Not enough volume to apply parameters. Increase the part size manually until it has sufficient volume.", HighLogic.Skin.label);
            }

            GUILayout.EndVertical();

            GUILayout.BeginHorizontal();
            _gc.text    = "Apply (resize to fit)";
            _gc.tooltip = "Applies the parameters above and resizes the part to have the correct amount of volume";
            if (GUILayout.Button(_gc, HighLogic.Skin.button))
            {
                ApplyAvionicsSettings(shouldSeekVolume: true);
            }

            _gc.text    = "Apply (preserve dimensions)";
            _gc.tooltip = "Tries to apply the parameters above but doesn't resize the part even if there isn't enough volume, or if there's extra volume";
            if (GUILayout.Button(_gc, HighLogic.Skin.button))
            {
                ApplyAvionicsSettings(shouldSeekVolume: false);
            }

            if (GUILayout.Button("Close", HighLogic.Skin.button))
            {
                if (!avionicsConfigName.Equals(curCfgName))
                {
                    PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f),
                                                 new Vector2(0.5f, 0.5f),
                                                 new MultiOptionDialog(
                                                     "ConfirmProceduralAvionicsClose",
                                                     "Your selected avionics type does not match the current tab shown. Close window anyway?",
                                                     "Avionics Mismatch",
                                                     HighLogic.UISkin,
                                                     new Rect(0.5f, 0.5f, 150f, 60f),
                                                     new DialogGUIFlexibleSpace(),
                                                     new DialogGUIVerticalLayout(
                                                         new DialogGUIFlexibleSpace(),
                                                         new DialogGUIButton("Yes",
                                                                             () =>
                    {
                        // Reset tab
                        curCfgName           = avionicsConfigName;
                        _selectedConfigIndex = _avionicsConfigNames.IndexOf(curCfgName);
                        _shouldResetUIHeight = true;

                        showGUI = false;
                    }, 140.0f, 30.0f, true),
                                                         new DialogGUIButton("Cancel", () => { }, 140.0f, 30.0f, true)
                                                         )),
                                                 false,
                                                 HighLogic.UISkin);
                }
                else
                {
                    showGUI = false;
                }
            }
            GUILayout.EndHorizontal();

            GUI.DragWindow();

            Tooltip.Instance.RecordTooltip(_windowId);
        }
Esempio n. 10
0
        public static void DrawPresetWindow(int windowID)
        {
            GUIStyle yellowText = new GUIStyle(GUI.skin.label);

            yellowText.normal.textColor = Color.yellow;

            if (_workingPreset == null)
            {
                SetNewWorkingPreset(new KCT_Preset(PresetManager.Instance.ActivePreset), false); //might need to copy instead of assign here
                _presetIndex = PresetManager.Instance.GetIndex(_workingPreset);
            }

            GUILayout.BeginVertical();
            GUILayout.BeginHorizontal();

            //preset selector
            GUILayout.BeginVertical();
            GUILayout.Label("Presets", yellowText, GUILayout.ExpandHeight(false));
            //preset toolbar in a scrollview
            _presetScrollView = GUILayout.BeginScrollView(_presetScrollView, GUILayout.Width(_presetPosition.width / 6f)); //TODO: update HighLogic.Skin.textArea
            string[] presetShortNames = PresetManager.Instance.PresetShortNames(true);
            if (_presetIndex == -1)
            {
                SetNewWorkingPreset(null, true);
            }
            if (_isChanged && _presetIndex < presetShortNames.Length - 1 && !Utilities.ConfigNodesAreEquivalent(_workingPreset.AsConfigNode(), PresetManager.Instance.Presets[_presetIndex].AsConfigNode())) //!KCT_PresetManager.Instance.PresetsEqual(WorkingPreset, KCT_PresetManager.Instance.Presets[presetIndex], true)
            {
                SetNewWorkingPreset(null, true);
            }

            int prev = _presetIndex;

            _presetIndex = GUILayout.SelectionGrid(_presetIndex, presetShortNames, 1);
            if (prev != _presetIndex)    //If a new preset was selected
            {
                if (_presetIndex != presetShortNames.Length - 1)
                {
                    SetNewWorkingPreset(new KCT_Preset(PresetManager.Instance.Presets[_presetIndex]), false);
                }
                else
                {
                    SetNewWorkingPreset(null, true);
                }
            }

            //presetIndex = GUILayout.Toolbar(presetIndex, presetNames);

            GUILayout.EndScrollView();
            if (GUILayout.Button("Save as\nNew Preset", GUILayout.ExpandHeight(false)))
            {
                //create new preset
                SaveAsNewPreset(_workingPreset);
            }
            if (_workingPreset.AllowDeletion && _presetIndex != presetShortNames.Length - 1 && GUILayout.Button("Delete Preset")) //allowed to be deleted and isn't Custom
            {
                DialogGUIBase[] options = new DialogGUIBase[2];
                options[0] = new DialogGUIButton("Delete File", DeleteActivePreset);
                options[1] = new DialogGUIButton("Cancel", RemoveInputLocks);
                MultiOptionDialog dialog = new MultiOptionDialog("deletePresetPopup", "Are you sure you want to delete the selected Preset, file and all? This cannot be undone!", "Confirm Deletion", null, options);
                PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), dialog, false, HighLogic.UISkin);
            }
            GUILayout.EndVertical();

            //Main sections
            GUILayout.BeginVertical();
            _presetMainScroll = GUILayout.BeginScrollView(_presetMainScroll);
            //Preset info section)
            GUILayout.BeginVertical(HighLogic.Skin.textArea);
            GUILayout.Label("Preset Name: " + _workingPreset.Name);
            GUILayout.Label("Description: " + _workingPreset.Description);
            GUILayout.Label("Author(s): " + _workingPreset.Author);
            GUILayout.EndVertical();

            GUILayout.BeginHorizontal();
            //Features section
            GUILayout.BeginVertical();
            GUILayout.Label("Features", yellowText);
            GUILayout.BeginVertical(HighLogic.Skin.textArea);
            _workingPreset.GeneralSettings.Enabled                 = GUILayout.Toggle(_workingPreset.GeneralSettings.Enabled, "Mod Enabled", HighLogic.Skin.button);
            _workingPreset.GeneralSettings.BuildTimes              = GUILayout.Toggle(_workingPreset.GeneralSettings.BuildTimes, "Build Times", HighLogic.Skin.button);
            _workingPreset.GeneralSettings.ReconditioningTimes     = GUILayout.Toggle(_workingPreset.GeneralSettings.ReconditioningTimes, "Launchpad Reconditioning", HighLogic.Skin.button);
            _workingPreset.GeneralSettings.ReconditioningBlocksPad = GUILayout.Toggle(_workingPreset.GeneralSettings.ReconditioningBlocksPad, "Reconditioning Blocks Pad", HighLogic.Skin.button);
            _workingPreset.GeneralSettings.TechUnlockTimes         = GUILayout.Toggle(_workingPreset.GeneralSettings.TechUnlockTimes, "Tech Unlock Times", HighLogic.Skin.button);
            _workingPreset.GeneralSettings.KSCUpgradeTimes         = GUILayout.Toggle(_workingPreset.GeneralSettings.KSCUpgradeTimes, "KSC Upgrade Times", HighLogic.Skin.button);
            _workingPreset.GeneralSettings.TechUpgrades            = GUILayout.Toggle(_workingPreset.GeneralSettings.TechUpgrades, "Upgrades From Tech Tree", HighLogic.Skin.button);
            _workingPreset.GeneralSettings.SharedUpgradePool       = GUILayout.Toggle(_workingPreset.GeneralSettings.SharedUpgradePool, "Shared Upgrade Pool (KSCSwitcher)", HighLogic.Skin.button);
            _workingPreset.GeneralSettings.CommonBuildLine         = GUILayout.Toggle(_workingPreset.GeneralSettings.CommonBuildLine, "Common build line for SPH+VAB", HighLogic.Skin.button);

            GUILayout.BeginHorizontal();
            GUILayout.Label("Starting Upgrades:");
            _workingPreset.GeneralSettings.StartingPoints = GUILayout.TextField(_workingPreset.GeneralSettings.StartingPoints, GUILayout.Width(100));
            GUILayout.EndHorizontal();
            GUILayout.EndVertical();
            GUILayout.EndVertical(); //end Features


            GUILayout.BeginVertical(); //Begin time settings
            GUILayout.Label("Time Settings", yellowText);
            GUILayout.BeginVertical(HighLogic.Skin.textArea);
            GUILayout.BeginHorizontal();
            GUILayout.Label("Overall Multiplier: ");
            double.TryParse(_oMultTmp = GUILayout.TextField(_oMultTmp, 10, GUILayout.Width(80)), out _workingPreset.TimeSettings.OverallMultiplier);
            GUILayout.EndHorizontal();
            GUILayout.BeginHorizontal();
            GUILayout.Label("Build Effect: ");
            double.TryParse(_bEffTmp = GUILayout.TextField(_bEffTmp, 10, GUILayout.Width(80)), out _workingPreset.TimeSettings.BuildEffect);
            GUILayout.EndHorizontal();
            GUILayout.BeginHorizontal();
            GUILayout.Label("Inventory Effect: ");
            double.TryParse(_iEffTmp = GUILayout.TextField(_iEffTmp, 10, GUILayout.Width(80)), out _workingPreset.TimeSettings.InventoryEffect);
            GUILayout.EndHorizontal();
            GUILayout.BeginHorizontal();
            GUILayout.Label("Reconditioning Effect: ");
            double.TryParse(_reEffTmp = GUILayout.TextField(_reEffTmp, 10, GUILayout.Width(80)), out _workingPreset.TimeSettings.ReconditioningEffect);
            GUILayout.EndHorizontal();
            GUILayout.BeginHorizontal();
            GUILayout.Label("Max Reconditioning: ");
            double.TryParse(_maxReTmp = GUILayout.TextField(_maxReTmp, 10, GUILayout.Width(80)), out _workingPreset.TimeSettings.MaxReconditioning);
            GUILayout.EndHorizontal();
            GUILayout.Label("Rollout-Reconditioning Split:");
            GUILayout.BeginHorizontal();
            //GUILayout.Label("Rollout", GUILayout.ExpandWidth(false));
            _workingPreset.TimeSettings.RolloutReconSplit = GUILayout.HorizontalSlider((float)Math.Floor(_workingPreset.TimeSettings.RolloutReconSplit * 100f), 0, 100) / 100.0;
            //GUILayout.Label("Recon.", GUILayout.ExpandWidth(false));
            GUILayout.EndHorizontal();
            GUILayout.Label((Math.Floor(_workingPreset.TimeSettings.RolloutReconSplit * 100)) + "% Rollout, " + (100 - Math.Floor(_workingPreset.TimeSettings.RolloutReconSplit * 100)) + "% Reconditioning");
            GUILayout.EndVertical();   //end time settings
            GUILayout.EndVertical();
            GUILayout.EndHorizontal(); //end feature/time setting split

            //begin formula settings
            GUILayout.BeginVertical();
            GUILayout.Label("Formula Settings (Advanced)", yellowText);
            GUILayout.BeginVertical(HighLogic.Skin.textArea);
            GUILayout.BeginHorizontal();
            if (GUILayout.Button("Show/Hide Formulas"))
            {
                _showFormula = !_showFormula;
            }
            GUILayout.EndHorizontal();

            if (_showFormula)
            {
                //show half here, half on other side? Or all in one big list
                int textWidth = 350;
                GUILayout.BeginHorizontal();
                GUILayout.Label("NodeFormula: ");
                _workingPreset.FormulaSettings.NodeFormula = GUILayout.TextField(_workingPreset.FormulaSettings.NodeFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("UpgradeFunds: ");
                _workingPreset.FormulaSettings.UpgradeFundsFormula = GUILayout.TextField(_workingPreset.FormulaSettings.UpgradeFundsFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("UpgradesForScience: ");
                _workingPreset.FormulaSettings.UpgradesForScience = GUILayout.TextField(_workingPreset.FormulaSettings.UpgradesForScience, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("ResearchFormula: ");
                _workingPreset.FormulaSettings.ResearchFormula = GUILayout.TextField(_workingPreset.FormulaSettings.ResearchFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("EffectivePart: ");
                _workingPreset.FormulaSettings.EffectivePartFormula = GUILayout.TextField(_workingPreset.FormulaSettings.EffectivePartFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("ProceduralPart: ");
                _workingPreset.FormulaSettings.ProceduralPartFormula = GUILayout.TextField(_workingPreset.FormulaSettings.ProceduralPartFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("BPFormula: ");
                _workingPreset.FormulaSettings.BPFormula = GUILayout.TextField(_workingPreset.FormulaSettings.BPFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("KSCUpgrade: ");
                _workingPreset.FormulaSettings.KSCUpgradeFormula = GUILayout.TextField(_workingPreset.FormulaSettings.KSCUpgradeFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("Reconditioning: ");
                _workingPreset.FormulaSettings.ReconditioningFormula = GUILayout.TextField(_workingPreset.FormulaSettings.ReconditioningFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("BuildRate: ");
                _workingPreset.FormulaSettings.BuildRateFormula = GUILayout.TextField(_workingPreset.FormulaSettings.BuildRateFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("UpgradeReset: ");
                _workingPreset.FormulaSettings.UpgradeResetFormula = GUILayout.TextField(_workingPreset.FormulaSettings.UpgradeResetFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("InventorySale: ");
                _workingPreset.FormulaSettings.InventorySaleFormula = GUILayout.TextField(_workingPreset.FormulaSettings.InventorySaleFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("RolloutCosts: ");
                _workingPreset.FormulaSettings.RolloutCostFormula = GUILayout.TextField(_workingPreset.FormulaSettings.RolloutCostFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("IntegrationCosts: ");
                _workingPreset.FormulaSettings.IntegrationCostFormula = GUILayout.TextField(_workingPreset.FormulaSettings.IntegrationCostFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("IntegrationTime: ");
                _workingPreset.FormulaSettings.IntegrationTimeFormula = GUILayout.TextField(_workingPreset.FormulaSettings.IntegrationTimeFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("NewLaunchPadCost: ");
                _workingPreset.FormulaSettings.NewLaunchPadCostFormula = GUILayout.TextField(_workingPreset.FormulaSettings.NewLaunchPadCostFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("RushCost: ");
                _workingPreset.FormulaSettings.RushCostFormula = GUILayout.TextField(_workingPreset.FormulaSettings.RushCostFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("AirlaunchCost: ");
                _workingPreset.FormulaSettings.AirlaunchCostFormula = GUILayout.TextField(_workingPreset.FormulaSettings.AirlaunchCostFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("AirlaunchTime: ");
                _workingPreset.FormulaSettings.AirlaunchTimeFormula = GUILayout.TextField(_workingPreset.FormulaSettings.AirlaunchTimeFormula, GUILayout.Width(textWidth));
                GUILayout.EndHorizontal();
            }

            GUILayout.EndVertical();
            GUILayout.EndVertical(); //end formula settings

            GUILayout.EndScrollView();

            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            if (GUILayout.Button("Save", GUILayout.ExpandWidth(false)))
            {
                PresetManager.Instance.ActivePreset = _workingPreset;
                PresetManager.Instance.SaveActiveToSaveData();
                _workingPreset = null;

                if (!PresetManager.Instance.ActivePreset.GeneralSettings.Enabled)
                {
                    Utilities.DisableModFunctionality();
                }
                KCTGameStates.Settings.MaxTimeWarp          = _newTimewarp;
                KCTGameStates.Settings.ForceStopWarp        = _forceStopWarp;
                KCTGameStates.Settings.DisableAllMessages   = _disableAllMsgs;
                KCTGameStates.Settings.OverrideLaunchButton = _overrideLaunchBtn;
                KCTGameStates.Settings.Debug         = _debug;
                KCTGameStates.Settings.AutoKACAlarms = _autoAlarms;

                KCTGameStates.Settings.Save();
                GUIStates.ShowSettings = false;
                if (!IsPrimarilyDisabled && !GUIStates.ShowFirstRun)
                {
                    ResetBLWindow();
                    GUIStates.ShowBuildList = true;
                    RefreshToolbarState();
                }
                if (!PresetManager.Instance.ActivePreset.GeneralSettings.Enabled)
                {
                    InputLockManager.RemoveControlLock("KCTKSCLock");
                }

                for (int j = 0; j < KCTGameStates.TechList.Count; j++)
                {
                    KCTGameStates.TechList[j].UpdateBuildRate(j);
                }

                foreach (KSCItem ksc in KCTGameStates.KSCs)
                {
                    ksc.RecalculateBuildRates();
                    ksc.RecalculateUpgradedBuildRates();
                }
                ResetFormulaRateHolders();
                KSCContextMenuOverrider.AreTextsUpdated = false;
            }
            if (GUILayout.Button("Cancel", GUILayout.ExpandWidth(false)))
            {
                _workingPreset         = null;
                GUIStates.ShowSettings = false;
                if (!IsPrimarilyDisabled && !GUIStates.ShowFirstRun)
                {
                    ResetBLWindow();
                    GUIStates.ShowBuildList = true;
                    RefreshToolbarState();
                }

                for (int j = 0; j < KCTGameStates.TechList.Count; j++)
                {
                    KCTGameStates.TechList[j].UpdateBuildRate(j);
                }
            }
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();

            GUILayout.EndVertical();                       //end column 2

            GUILayout.BeginVertical(GUILayout.Width(100)); //Start general settings
            GUILayout.Label("General Settings", yellowText);
            GUILayout.Label("NOTE: Affects all saves!", yellowText);
            GUILayout.BeginVertical(HighLogic.Skin.textArea);
            GUILayout.Label("Max Timewarp");
            GUILayout.BeginHorizontal();
            if (GUILayout.Button("-", GUILayout.ExpandWidth(false)))
            {
                _newTimewarp = Math.Max(_newTimewarp - 1, 0);
            }
            //current warp setting
            GUILayout.Label(TimeWarp.fetch.warpRates[_newTimewarp] + "x");
            if (GUILayout.Button("+", GUILayout.ExpandWidth(false)))
            {
                _newTimewarp = Math.Min(_newTimewarp + 1, TimeWarp.fetch.warpRates.Length - 1);
            }
            GUILayout.EndHorizontal();

            _forceStopWarp     = GUILayout.Toggle(_forceStopWarp, "Auto Stop TimeWarp", HighLogic.Skin.button);
            _autoAlarms        = GUILayout.Toggle(_autoAlarms, "Auto KAC Alarms", HighLogic.Skin.button);
            _overrideLaunchBtn = GUILayout.Toggle(_overrideLaunchBtn, "Override Launch Button", HighLogic.Skin.button);
            //useBlizzyToolbar = GUILayout.Toggle(useBlizzyToolbar, "Use Toolbar Mod", HighLogic.Skin.button);
            _disableAllMsgs = !GUILayout.Toggle(!_disableAllMsgs, "Use Message System", HighLogic.Skin.button);
            _debug          = GUILayout.Toggle(_debug, "Debug Logging", HighLogic.Skin.button);

            GUILayout.EndVertical();
            GUILayout.EndVertical();

            GUILayout.EndHorizontal(); //end main split
            GUILayout.EndVertical();   //end window

            _isChanged = GUI.changed;

            if (!Input.GetMouseButtonDown(1) && !Input.GetMouseButtonDown(2))
            {
                GUI.DragWindow();
            }
        }
Esempio n. 11
0
        public void Update()
        {
            if (HighLogic.CurrentGame == null || HighLogic.CurrentGame.CrewRoster == null)
            {
                return;
            }

            // Catch earlies
            if (firstLoad)
            {
                firstLoad = false;
                List <string> newHires = new List <string>();

                foreach (ProtoCrewMember pcm in HighLogic.CurrentGame.CrewRoster.Crew)
                {
                    if ((pcm.rosterStatus == ProtoCrewMember.RosterStatus.Assigned || pcm.rosterStatus == ProtoCrewMember.RosterStatus.Available) && !kerbalRetireTimes.ContainsKey(pcm.name))
                    {
                        newHires.Add(pcm.name);
                        OnCrewHired(pcm, int.MinValue);
                    }
                }
                if (newHires.Count > 0)
                {
                    string msgStr = "Crew will retire as follows:";
                    foreach (string s in newHires)
                    {
                        msgStr += "\n" + s + ", no earlier than " + KSPUtil.PrintDate(kerbalRetireTimes[s], false);
                    }

                    PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f),
                                                 new Vector2(0.5f, 0.5f),
                                                 "InitialRetirementDateNotification",
                                                 "Initial Retirement Date",
                                                 msgStr
                                                 + "\n(Retirement will be delayed the more intersting flights they fly.)",
                                                 "OK",
                                                 false,
                                                 HighLogic.UISkin);
                }
            }

            // Retirements
            double time = Planetarium.GetUniversalTime();

            if (nextUpdate < time)
            {
                nextUpdate = time + updateInterval;

                if (retirementEnabled)
                {
                    foreach (KeyValuePair <string, double> kvp in kerbalRetireTimes)
                    {
                        ProtoCrewMember pcm = HighLogic.CurrentGame.CrewRoster[kvp.Key];
                        if (pcm == null)
                        {
                            toRemove.Add(kvp.Key);
                        }
                        else
                        {
                            if (pcm.rosterStatus != ProtoCrewMember.RosterStatus.Available)
                            {
                                if (pcm.rosterStatus != ProtoCrewMember.RosterStatus.Assigned)
                                {
                                    toRemove.Add(kvp.Key);
                                }

                                continue;
                            }

                            if (pcm.inactive)
                            {
                                continue;
                            }

                            if (time > kvp.Value)
                            {
                                toRemove.Add(kvp.Key);
                                retirees.Add(kvp.Key);
                                pcm.rosterStatus = ProtoCrewMember.RosterStatus.Dead;
                            }
                        }
                    }
                }

                for (int i = ActiveCourses.Count; i-- > 0;)
                {
                    ActiveCourse course = ActiveCourses[i];
                    if (course.ProgressTime(time)) //returns true when the course completes
                    {
                        ActiveCourses.RemoveAt(i);
                    }
                }

                for (int i = expireTimes.Count; i-- > 0;)
                {
                    TrainingExpiration e = expireTimes[i];
                    if (time > e.expiration)
                    {
                        ProtoCrewMember pcm = HighLogic.CurrentGame.CrewRoster[e.pcmName];
                        if (pcm != null)
                        {
                            for (int j = pcm.careerLog.Entries.Count; j-- > 0;)
                            {
                                int eC = e.entries.Count;
                                if (eC == 0)
                                {
                                    break;
                                }
                                FlightLog.Entry ent = pcm.careerLog[j];
                                for (int k = eC; k-- > 0;)
                                {
                                    if (e.Compare(k, ent))
                                    {
                                        ScreenMessages.PostScreenMessage(pcm.name + ": Expired: " + GetPrettyCourseName(ent.type) + ent.target);
                                        ent.type = "expired_" + ent.type;
                                        e.entries.RemoveAt(k);
                                    }
                                }
                            }
                        }
                        expireTimes.RemoveAt(i);
                    }
                }

                // TODO remove from courses? Except I think they won't retire if inactive either so that's ok.
                if (toRemove.Count > 0)
                {
                    string msgStr = string.Empty;
                    foreach (string s in toRemove)
                    {
                        kerbalRetireTimes.Remove(s);
                        if (HighLogic.CurrentGame.CrewRoster[s] != null)
                        {
                            msgStr += "\n" + s;
                        }
                    }
                    if (!string.IsNullOrEmpty(msgStr))
                    {
                        PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f),
                                                     new Vector2(0.5f, 0.5f),
                                                     "CrewRetirementNotification",
                                                     "Crew Retirement",
                                                     "The following retirements have occurred:\n" + msgStr,
                                                     "OK",
                                                     true,
                                                     HighLogic.UISkin);
                    }

                    toRemove.Clear();
                }
            }

            // UI fixing
            if (inAC)
            {
                if (astronautComplex == null)
                {
                    KSP.UI.Screens.AstronautComplex[] mbs = GameObject.FindObjectsOfType <KSP.UI.Screens.AstronautComplex>();
                    int maxCount = -1;
                    foreach (KSP.UI.Screens.AstronautComplex c in mbs)
                    {
                        int count = c.ScrollListApplicants.Count + c.ScrollListAssigned.Count + c.ScrollListAvailable.Count + c.ScrollListKia.Count;
                        if (count > maxCount)
                        {
                            maxCount         = count;
                            astronautComplex = c;
                        }
                    }

                    if (astronautComplex == null)
                    {
                        return;
                    }
                }
                int newAv   = astronautComplex.ScrollListAvailable.Count;
                int newAsgn = astronautComplex.ScrollListAssigned.Count;
                int newKIA  = astronautComplex.ScrollListKia.Count;
                if (newAv != countAvailable || newKIA != countKIA || newAsgn != countAssigned)
                {
                    countAvailable = newAv;
                    countAssigned  = newAsgn;
                    countKIA       = newKIA;

                    foreach (KSP.UI.UIListData <KSP.UI.UIListItem> u in astronautComplex.ScrollListAvailable)
                    {
                        KSP.UI.CrewListItem cli = u.listItem.GetComponent <KSP.UI.CrewListItem>();
                        if (cli != null)
                        {
                            FixTooltip(cli);
                            if (cli.GetCrewRef().inactive)
                            {
                                cli.MouseoverEnabled = false;
                                bool notTraining = true;
                                for (int i = ActiveCourses.Count; i-- > 0 && notTraining;)
                                {
                                    foreach (ProtoCrewMember pcm in ActiveCourses[i].Students)
                                    {
                                        if (pcm == cli.GetCrewRef())
                                        {
                                            notTraining = false;
                                            cli.SetLabel("Training, done " + KSPUtil.PrintDate(ActiveCourses[i].startTime + ActiveCourses[i].GetTime(ActiveCourses[i].Students), false));
                                            break;
                                        }
                                    }
                                }
                                if (notTraining)
                                {
                                    cli.SetLabel("Recovering");
                                }
                            }
                        }
                    }

                    foreach (KSP.UI.UIListData <KSP.UI.UIListItem> u in astronautComplex.ScrollListAssigned)
                    {
                        KSP.UI.CrewListItem cli = u.listItem.GetComponent <KSP.UI.CrewListItem>();
                        if (cli != null)
                        {
                            FixTooltip(cli);
                        }
                    }

                    foreach (KSP.UI.UIListData <KSP.UI.UIListItem> u in astronautComplex.ScrollListKia)
                    {
                        KSP.UI.CrewListItem cli = u.listItem.GetComponent <KSP.UI.CrewListItem>();
                        if (cli != null)
                        {
                            if (retirees.Contains(cli.GetName()))
                            {
                                cli.SetLabel("Retired");
                                cli.MouseoverEnabled = false;
                            }
                        }
                    }
                }
            }
        }
Esempio n. 12
0
        public tabs toolingTab()
        {
            MaybeUpdate();
            currentToolingType = null;
            GUILayout.BeginHorizontal();
            try {
                GUILayout.FlexibleSpace();
                GUILayout.Label("Tooling Types", HighLogic.Skin.label);
                GUILayout.FlexibleSpace();
            } finally {
                GUILayout.EndHorizontal();
            }
            int counter = 0;

            GUILayout.BeginHorizontal();
            try {
                foreach (string type in ToolingDatabase.toolings.Keys)
                {
                    if (counter % 3 == 0 && counter != 0)
                    {
                        GUILayout.EndHorizontal();
                        GUILayout.BeginHorizontal();
                    }
                    counter++;
                    if (GUILayout.Button(type))
                    {
                        currentToolingType = type;
                    }
                }
            } finally {
                GUILayout.EndHorizontal();
            }

            if (untooledParts.Count > 0)
            {
                GUILayout.BeginHorizontal();
                try {
                    GUILayout.Label("Untooled Parts:", HighLogic.Skin.label, GUILayout.Width(312));
                    GUILayout.Label("Tooling cost", rightLabel, GUILayout.Width(72));
                    GUILayout.Label("Untooled", rightLabel, GUILayout.Width(72));
                    GUILayout.Label("Tooled", rightLabel, GUILayout.Width(72));
                } finally {
                    GUILayout.EndHorizontal();
                }
                untooledTypesScroll = GUILayout.BeginScrollView(untooledTypesScroll, GUILayout.Height(144), GUILayout.Width(572));
                try {
                    foreach (untooledPart uP in untooledParts)
                    {
                        GUILayout.BeginHorizontal();
                        try {
                            GUILayout.Label(uP.name, boldLabel, GUILayout.Width(312));
                            GUILayout.Label(uP.toolingCost.ToString("N0") + "f", rightLabel, GUILayout.Width(72));
                            float untooledCost = uP.toolingCost * uP.untooledMultiplier;
                            GUILayout.Label(untooledCost.ToString("N0") + "f", rightLabel, GUILayout.Width(72));
                            GUILayout.Label((uP.totalCost - untooledCost).ToString("N0") + "f", rightLabel, GUILayout.Width(72));
                        } finally {
                            GUILayout.EndHorizontal();
                        }
                    }
                } finally {
                    GUILayout.EndScrollView();
                }
                GUILayout.BeginHorizontal();
                try {
                    GUILayout.Label("Total vessel cost if all parts are tooled: " + (EditorLogic.fetch.ship.GetShipCosts(out _, out _) - EditorLogic.fetch.ship.parts.Slinq().SelectMany(p => p.FindModulesImplementing <ModuleTooling>().Slinq()).Where(mt => !mt.IsUnlocked()).Select(mt => mt.GetModuleCost(mt.part.partInfo.cost, ModifierStagingSituation.CURRENT)).Sum()));
                } finally {
                    GUILayout.EndHorizontal();
                }
                GUILayout.BeginHorizontal();
                try {
                    if (GUILayout.Button("Tool All"))
                    {
                        var  totalToolingCost = untooledParts.Slinq().Select(up => up.toolingCost).Sum();
                        bool canAfford        = Funding.Instance.Funds >= totalToolingCost;
                        PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f),
                                                     new Vector2(0.5f, 0.5f),
                                                     new MultiOptionDialog(
                                                         "ConfirmAllToolingsPurchase",
                                                         "Tooling for all untooled parts will cost " + totalToolingCost.ToString("N0") + " funds.",
                                                         "Tooling Purchase",
                                                         HighLogic.UISkin,
                                                         new Rect(0.5f, 0.5f, 150f, 60f),
                                                         new DialogGUIFlexibleSpace(),
                                                         new DialogGUIVerticalLayout(
                                                             new DialogGUIFlexibleSpace(),
                                                             new DialogGUIButton(canAfford ? "Purchase All Toolings" : "Can't Afford",
                                                                                 () =>
                        {
                            if (canAfford)
                            {
                                Funding.Instance.AddFunds(-totalToolingCost, TransactionReasons.RnDPartPurchase);
                                EditorLogic.fetch.ship.Parts.Slinq().SelectMany(p => p.FindModulesImplementing <ModuleTooling>().Slinq()).Where(mt => !mt.IsUnlocked()).ForEach(mt => {
                                    mt.PurchaseTooling();
                                    mt.Events["ToolingEvent"].guiActiveEditor = false;
                                });
                                GameEvents.onEditorShipModified.Fire(EditorLogic.fetch.ship);
                            }
                        }, 140.0f, 30.0f, true),
                                                             new DialogGUIButton("Close", () => { }, 140.0f, 30.0f, true)
                                                             )),
                                                     false,
                                                     HighLogic.UISkin);
                    }
                } finally {
                    GUILayout.EndHorizontal();
                }
            }
            return(currentToolingType == null ? tabs.Tooling : tabs.ToolingType);
        }
Esempio n. 13
0
        public void TimeWarpWindow(int id)
        {
            GUILayout.BeginHorizontal();
            GUILayout.BeginVertical();

            scrollPos = GUILayout.BeginScrollView(scrollPos);

            editToggle = GUILayout.Toggle(editToggle, "Create", skin.button);
            selected   = GUILayout.SelectionGrid(selected, names, 1, smallButtonStyle);

            currentRates = customWarps.Find(r => r.Name == names[selected] ||
                                            (names[selected].Contains("<") && names[selected].Split('<', '>')[2] == r.Name)
                                            );

            if (currentRates == null)
            {
                currentRates = StandardWarp;
            }

            GUILayout.EndScrollView();

            GUILayout.EndVertical();

            GUILayout.BeginVertical();
            scrollPos2 = GUILayout.BeginScrollView(scrollPos2);

            if (editToggle)
            {
                bool canExport = true;

                GUILayout.BeginVertical(GUILayout.ExpandHeight(true));

                warpName = GUILayout.TextField(warpName);
                for (int i = 1; i < 8; i++)
                {
                    if (i < 4 || !physics)
                    {
                        w[i] = GUILayout.TextField(w[i]);
                    }
                }
#if false
                w1 = GUILayout.TextField(w1);
                w2 = GUILayout.TextField(w2);
                w3 = GUILayout.TextField(w3);
                if (!physics)
                {
                    w4 = GUILayout.TextField(w4);
                    w5 = GUILayout.TextField(w5);
                    w6 = GUILayout.TextField(w6);
                    w7 = GUILayout.TextField(w7);
                }
#endif
                physics = GUILayout.Toggle(physics, "Physics Warp?");

                GUILayout.EndVertical();

                if (GUILayout.Button("Save"))
                {
                    float[] rates;
                    if (physics)
                    {
                        rates = new float[4];
                    }
                    else
                    {
                        rates = new float[8];
                    }

                    rates[0] = 1f;

                    float pw;
                    for (int i = 1; i < 8; i++)
                    {
                        if (i < 4 || !physics)
                        {
                            if (float.TryParse(w[i], out pw))
                            {
                                rates[i] = pw;
                            }
                            else
                            {
                                canExport = false;
                            }
                        }
                    }
#if false
                    float pw1;
                    if (float.TryParse(w1, out pw1))
                    {
                        rates[1] = pw1;
                    }
                    else
                    {
                        canExport = false;
                    }
                    float pw2;
                    if (float.TryParse(w2, out pw2))
                    {
                        rates[2] = pw2;
                    }
                    else
                    {
                        canExport = false;
                    }
                    float pw3;
                    if (float.TryParse(w3, out pw3))
                    {
                        rates[3] = pw3;
                    }
                    else
                    {
                        canExport = false;
                    }
                    if (!physics)
                    {
                        float pw4;
                        if (float.TryParse(w4, out pw4))
                        {
                            rates[4] = pw4;
                        }
                        else
                        {
                            canExport = false;
                        }
                        float pw5;
                        if (float.TryParse(w5, out pw5))
                        {
                            rates[5] = pw5;
                        }
                        else
                        {
                            canExport = false;
                        }
                        float pw6;
                        if (float.TryParse(w6, out pw6))
                        {
                            rates[6] = pw6;
                        }
                        else
                        {
                            canExport = false;
                        }
                        float pw7;
                        if (float.TryParse(w7, out pw7))
                        {
                            rates[7] = pw7;
                        }
                        else
                        {
                            canExport = false;
                        }
                    }
#endif
                    if (canExport)
                    {
                        TimeWarpRates timeWarpRates = new TimeWarpRates(warpName, rates, physics);
                        customWarps.Add(timeWarpRates);
                        SaveCustomWarpRates();
                        editToggle = false;
                        //SetWarpRates (timeWarpRates);
                        warpName = "Name";
                        physics  = false;
                        InitW();
#if false
                        w[1] = "10";
                        w[2] = "100";
                        w[3] = "1000";
                        w[4] = "10000";
                        w[5] = "100000";
                        w[6] = "1000000";
                        w[7] = "10000000";
#endif
                    }
                    else
                    {
                        //PopupDialog.SpawnPopupDialog (new MultiOptionDialog("Cannot save because there are non-numbers in the editing fields", "Error", null), false, null);
                        var dialog = new MultiOptionDialog("btw1", "Cannot save because there are non-numbers in the editing fields", "Error", HighLogic.UISkin, new DialogGUIBase[] {
                            new DialogGUIButton("OK", () => { })
                        });
                        PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), dialog, false, HighLogic.UISkin, true);
                    }
                    //save the settings, so if they have been regenerated, it exsists and wont cause errors
                    BetterTimeWarp.SettingsNode.Save(BetterTimeWarpInitializer.BTW_CFG_FILE);
                }
                if (GUILayout.Button("Cancel", smallButtonStyle))
                {
                    editToggle = false;
                    warpName   = "Name";
                    physics    = false;
                    InitW();
#if false
                    w[1] = "10";
                    w[2] = "100";
                    w[3] = "1000";
                    w[4] = "10000";
                    w[5] = "100000";
                    w[6] = "1000000";
                    w[7] = "10000000";
#endif
                }
            }
            else
            {
                GUILayout.BeginVertical(GUILayout.ExpandHeight(true));
                for (int i = 1; i <= 8; i++)
                {
                    if (i <= 4 || !currentRates.Physics)
                    {
                        var f = currentRates.Rates[i - 1];
                        GUILayout.Label("<b><color=lime>" + i.ToString() + ":</color></b> <color=white>" + f.ToString(TimeWarpRates.rateFmt(f)) + "x</color>");
                    }
                }
#if false
                GUILayout.Label("<b><color=lime>1:</color></b> <color=white>" + currentRates.Rates[0].ToString(TimeWarpRates.rateFmt(currentRates.Rates[0]) + "x</color>");
                                GUILayout.Label("<b><color=lime>2:</color></b> <color=white>" + currentRates.Rates[1].ToString("N0") + "x</color>");
                                GUILayout.Label("<b><color=lime>3:</color></b> <color=white>" + currentRates.Rates[2].ToString("N0") + "x</color>");
                                GUILayout.Label("<b><color=lime>4:</color></b> <color=white>" + currentRates.Rates[3].ToString("N0") + "x</color>");
                                if (!currentRates.Physics)
                {
                    GUILayout.Label("<b><color=lime>5:</color></b> <color=white>" + currentRates.Rates[4].ToString("N0") + "x</color>");
                    GUILayout.Label("<b><color=lime>6:</color></b> <color=white>" + currentRates.Rates[5].ToString("N0") + "x</color>");
                    GUILayout.Label("<b><color=lime>7:</color></b> <color=white>" + currentRates.Rates[6].ToString("N0") + "x</color>");
                    GUILayout.Label("<b><color=lime>8:</color></b> <color=white>" + currentRates.Rates[7].ToString("N0") + "x</color>");
                }
#endif
                GUILayout.EndVertical();

                GUILayout.Space(15f);
                if (GUILayout.Button("Select"))
                {
                    SetWarpRates(currentRates);
                }
                if (currentRates != StandardWarp && currentRates != StandardPhysWarp && GUILayout.Button("Edit", smallButtonStyle))
                {
                    if (currentRates != StandardWarp && currentRates != StandardPhysWarp)
                    {
                        if (!currentRates.Physics)
                        {
                            SetWarpRates(StandardWarp, false);
                        }
                        else
                        {
                            SetWarpRates(StandardPhysWarp, false);
                        }
                        customWarps.Remove(currentRates);
                        editToggle = true;
                        warpName   = currentRates.Name;
                        physics    = currentRates.Physics;

                        for (int i = 1; i < 8; i++)
                        {
                            if (i < 4 || !physics)
                            {
                                w[i] = currentRates.Rates[i].ToString(TimeWarpRates.rateFmt(currentRates.Rates[i]));
                            }
                        }
#if false
                        w1 = currentRates.Rates[1].ToString(TimeWarpRates.rateFmt(currentRates.Rates[1]));
                        w2 = currentRates.Rates[2].ToString(TimeWarpRates.rateFmt(currentRates.Rates[2]));
                        w3 = currentRates.Rates[3].ToString(TimeWarpRates.rateFmt(currentRates.Rates[3]));
                        if (!physics)
                        {
                            w4 = currentRates.Rates[4].ToString(TimeWarpRates.rateFmt(currentRates.Rates[4]));
                            w5 = currentRates.Rates[5].ToString(TimeWarpRates.rateFmt(currentRates.Rates[5]));
                            w6 = currentRates.Rates[6].ToString(TimeWarpRates.rateFmt(currentRates.Rates[6]));
                            w7 = currentRates.Rates[7].ToString(TimeWarpRates.rateFmt(currentRates.Rates[7]));
                        }
#endif
                        selected = 0;
                    }
                    else
                    {
                        //PopupDialog.SpawnPopupDialog (new MultiOptionDialog("Cannot edit standard warp rates", "Better Time Warp", null), true, null);

                        var dialog = new MultiOptionDialog("btw2", "Cannot edit standard warp rates", "Better Time Warp", HighLogic.UISkin, new DialogGUIBase[] {
                            new DialogGUIButton("OK", () => { })
                        });
                        PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), dialog, false, HighLogic.UISkin, true);
                    }
                }
                if (currentRates != StandardWarp && currentRates != StandardPhysWarp && GUILayout.Button("Delete", smallButtonStyle))
                {
                    if (currentRates != StandardWarp && currentRates != StandardPhysWarp)
                    {
                        customWarps.Remove(currentRates);
                        selected = 0;
                        SaveCustomWarpRates();
                        //	PopupDialog.SpawnPopupDialog (new MultiOptionDialog("Deleted " + currentRates.Name + " time warp rates", "Better Time Warp", null), true, null);



                        var dialog = new MultiOptionDialog("btw3", "Deleted " + currentRates.Name + " time warp rates", "Better Time Warp", HighLogic.UISkin, new DialogGUIBase[] {
                            new DialogGUIButton("OK", () => {
                                // winState = winContent.close;
                            })
                        });
                        PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), dialog, false, HighLogic.UISkin, true);
                        // winState = winContent.dialog;



                        SetWarpRates(StandardWarp, false);
                    }
                    else
                    {
                        //PopupDialog.SpawnPopupDialog (new MultiOptionDialog("Cannot delete standard warp rates", "Better Time Warp", null), true, null);

                        var dialog = new MultiOptionDialog("btw4", "Cannot delete standard warp rates", "Better Time Warp", HighLogic.UISkin, new DialogGUIBase[] {
                            new DialogGUIButton("OK", () => { })
                        });
                        PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), dialog, false, HighLogic.UISkin, true);
                    }
                }
            }
            GUILayout.EndScrollView();
            GUILayout.EndVertical();

            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            if (GUILayout.Button("Simple", GUILayout.ExpandWidth(true)))
            {
                advWindowOpen = false;
            }
            showPhysicsSettings = GUILayout.Toggle(showPhysicsSettings, "<color=lime>Physics Settings</color>", skin.button, GUILayout.ExpandWidth(true));
            GUILayout.EndHorizontal();
            if (!lockWindow())
            {
                GUI.DragWindow();
            }
        }
        /// <summary>
        /// Shows Health monitor when the AppLauncher/Blizzy's Toolbar button is clicked
        /// </summary>
        public void DisplayData()
        {
            Core.Log("KerbalHealthScenario.DisplayData", Core.LogLevel.Important);
            UpdateKerbals(true);
            if (selectedKHS == null)
            {
                Core.Log("No kerbal selected, showing overall list.");
                DialogGUILayoutBase layout = new DialogGUIVerticalLayout(true, true);
                if (page > PageCount)
                {
                    page = PageCount;
                }
                if (ShowPages)
                {
                    layout.AddChild(new DialogGUIHorizontalLayout(true, false,
                                                                  new DialogGUIButton("<<", FirstPage, () => (page > 1), true),
                                                                  new DialogGUIButton("<", PageUp, () => (page > 1), false),
                                                                  new DialogGUIHorizontalLayout(TextAnchor.LowerCenter, new DialogGUILabel("Page " + page + "/" + PageCount)),
                                                                  new DialogGUIButton(">", PageDown, () => (page < PageCount), false),
                                                                  new DialogGUIButton(">>", LastPage, () => (page < PageCount), true)));
                }
                gridContents = new List <DialogGUIBase>((Core.KerbalHealthList.Count + 1) * colNumMain);
                // Creating column titles
                gridContents.Add(new DialogGUILabel("Name", true));
                gridContents.Add(new DialogGUILabel("Condition", true));
                gridContents.Add(new DialogGUILabel("Health", true));
                gridContents.Add(new DialogGUILabel("Change/day", true));
                gridContents.Add(new DialogGUILabel("Time Left", true));
                gridContents.Add(new DialogGUILabel("Radiation", true));
                gridContents.Add(new DialogGUILabel("", true));
                // Initializing Health Monitor's grid with empty labels, to be filled in Update()
                List <KerbalHealthStatus> kerbals = new List <KerbalHealth.KerbalHealthStatus>(Core.KerbalHealthList.Values);
                for (int i = FirstLine; i < FirstLine + LineCount; i++)
                {
                    for (int j = 0; j < colNumMain - 1; j++)
                    {
                        gridContents.Add(new DialogGUILabel("", true));
                    }
                    gridContents.Add(new DialogGUIButton <int>("Details", (n) => { selectedKHS = kerbals[n]; Invalidate(); }, i));
                }
                layout.AddChild(new DialogGUIGridLayout(new RectOffset(0, 0, 0, 0), new Vector2(colWidth, 30), new Vector2(colSpacing, 10), UnityEngine.UI.GridLayoutGroup.Corner.UpperLeft, UnityEngine.UI.GridLayoutGroup.Axis.Horizontal, TextAnchor.MiddleCenter, UnityEngine.UI.GridLayoutGroup.Constraint.FixedColumnCount, colNumMain, gridContents.ToArray()));
                monitorPosition.width = gridWidthMain + 10;
                monitorWindow         = PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), new MultiOptionDialog("Health Monitor", "", "Health Monitor", HighLogic.UISkin, monitorPosition, layout), false, HighLogic.UISkin, false);
            }

            else
            {
                Core.Log("Showing details for " + selectedKHS.Name + ".");
                gridContents = new List <DialogGUIBase>();
                gridContents.Add(new DialogGUILabel("Name:"));
                gridContents.Add(new DialogGUILabel(""));
                gridContents.Add(new DialogGUILabel("Level:"));
                gridContents.Add(new DialogGUILabel(""));
                gridContents.Add(new DialogGUILabel("Status:"));
                gridContents.Add(new DialogGUILabel(""));
                gridContents.Add(new DialogGUILabel("Max HP:"));
                gridContents.Add(new DialogGUILabel(""));
                gridContents.Add(new DialogGUILabel("HP:"));
                gridContents.Add(new DialogGUILabel(""));
                gridContents.Add(new DialogGUILabel("HP Change:"));
                gridContents.Add(new DialogGUILabel(""));
                if (Core.IsKerbalLoaded(selectedKHS.PCM) && !selectedKHS.HasCondition("Frozen"))
                {
                    foreach (HealthFactor f in Core.Factors)
                    {
                        gridContents.Add(new DialogGUILabel(f.Title + ":"));
                        gridContents.Add(new DialogGUILabel(""));
                    }
                }
                gridContents.Add(new DialogGUILabel("Recuperation:"));
                gridContents.Add(new DialogGUILabel(""));
                gridContents.Add(new DialogGUILabel("Condition:"));
                gridContents.Add(new DialogGUILabel(""));
                gridContents.Add(new DialogGUILabel("Exposure:"));
                gridContents.Add(new DialogGUILabel(""));
                gridContents.Add(new DialogGUILabel("Radiation:"));
                gridContents.Add(new DialogGUILabel(""));
                gridContents.Add(new DialogGUILabel("Accumulated Dose:"));
                gridContents.Add(new DialogGUILabel(""));
                gridContents.Add(new DialogGUILabel("Radiation HP Loss:"));
                gridContents.Add(new DialogGUILabel(""));
                monitorPosition.width = gridWidthDetails + 10;
                monitorWindow         = PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), new MultiOptionDialog("Health Monitor", "", "Health Details", HighLogic.UISkin, monitorPosition, new DialogGUIVerticalLayout(new DialogGUIGridLayout(new RectOffset(0, 0, 0, 0), new Vector2(colWidth, 30), new Vector2(colSpacing, 10), UnityEngine.UI.GridLayoutGroup.Corner.UpperLeft, UnityEngine.UI.GridLayoutGroup.Axis.Horizontal, TextAnchor.MiddleCenter, UnityEngine.UI.GridLayoutGroup.Constraint.FixedColumnCount, colNumDetails, gridContents.ToArray()), new DialogGUIButton("Back", () => { selectedKHS = null; Invalidate(); }, gridWidthDetails, 20, false))), false, HighLogic.UISkin, false);
            }
            dirty = true;
        }
Esempio n. 15
0
        public static void PopUpVesselError(List <BuildListVessel> errored)
        {
            DialogGUIBase[] options = new DialogGUIBase[2];
            options[0] = new DialogGUIButton("Understood", () => { });
            options[1] = new DialogGUIButton("Delete Vessels", () =>
            {
                foreach (BuildListVessel blv in errored)
                {
                    blv.RemoveFromBuildList();
                    Utilities.AddFunds(blv.GetTotalCost(), TransactionReasons.VesselRollout);
                    //remove any associated recon_rollout
                }
            });

            string txt        = "The following KCT vessels contain missing or invalid parts and have been quarantined. Either add the missing parts back into your game or delete the vessels. A file containing the ship names and missing parts has been added to your save folder.\n";
            string txtToWrite = "";

            foreach (BuildListVessel blv in errored)
            {
                txt        += blv.ShipName + "\n";
                txtToWrite += blv.ShipName + "\n";
                txtToWrite += string.Join("\n", blv.GetMissingParts());
                txtToWrite += "\n\n";
            }

            //make new file for missing ships
            string filename = KSPUtil.ApplicationRootPath + "/saves/" + HighLogic.SaveFolder + "/missingParts.txt";

            File.WriteAllText(filename, txtToWrite);

            //remove all rollout and recon items since they're invalid without the ships
            foreach (BuildListVessel blv in errored)
            {
                //remove any associated recon_rollout
                foreach (KSCItem ksc in KCTGameStates.KSCs)
                {
                    for (int i = 0; i < ksc.Recon_Rollout.Count; i++)
                    {
                        ReconRollout rr = ksc.Recon_Rollout[i];
                        if (rr.AssociatedID == blv.Id.ToString())
                        {
                            ksc.Recon_Rollout.Remove(rr);
                            i--;
                        }
                    }

                    for (int i = 0; i < ksc.AirlaunchPrep.Count; i++)
                    {
                        AirlaunchPrep ap = ksc.AirlaunchPrep[i];
                        if (ap.AssociatedID == blv.Id.ToString())
                        {
                            ksc.AirlaunchPrep.Remove(ap);
                            i--;
                        }
                    }
                }
            }

            var diag = new MultiOptionDialog("missingPartsPopup", txt, "Vessels Contain Missing Parts", null, options);

            PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), diag, false, HighLogic.UISkin);
        }
Esempio n. 16
0
        public tabs toolingTab()
        {
            MaybeUpdate();
            currentToolingType = null;
            GUILayout.BeginHorizontal();
            try {
                GUILayout.FlexibleSpace();
                GUILayout.Label("Tooling Types", HighLogic.Skin.label);
                GUILayout.FlexibleSpace();
            } finally {
                GUILayout.EndHorizontal();
            }
            int counter = 0;

            GUILayout.BeginHorizontal();
            try {
                foreach (string type in ToolingDatabase.toolings.Keys)
                {
                    if (counter % 3 == 0 && counter != 0)
                    {
                        GUILayout.EndHorizontal();
                        GUILayout.BeginHorizontal();
                    }
                    counter++;
                    if (GUILayout.Button(type))
                    {
                        currentToolingType = type;
                    }
                }
            } finally {
                GUILayout.EndHorizontal();
            }

            if (untooledParts.Count > 0)
            {
                GUILayout.BeginHorizontal();
                try {
                    GUILayout.Label("Untooled Parts:", HighLogic.Skin.label, GUILayout.Width(312));
                    GUILayout.Label("Tooling cost", rightLabel, GUILayout.Width(72));
                    GUILayout.Label("Untooled", rightLabel, GUILayout.Width(72));
                    GUILayout.Label("Tooled", rightLabel, GUILayout.Width(72));
                } finally {
                    GUILayout.EndHorizontal();
                }
                untooledTypesScroll = GUILayout.BeginScrollView(untooledTypesScroll, GUILayout.Height(204), GUILayout.Width(572));
                try {
                    foreach (untooledPart uP in untooledParts)
                    {
                        GUILayout.BeginHorizontal();
                        try
                        {
                            GUILayout.Label(uP.name, boldLabel, GUILayout.Width(312));
                            GUILayout.Label($"{uP.toolingCost:N0}f", rightLabel, GUILayout.Width(72));
                            var untooledExtraCost = GetUntooledExtraCost(uP);
                            GUILayout.Label($"{uP.totalCost:N0}f", rightLabel, GUILayout.Width(72));
                            GUILayout.Label($"{(uP.totalCost - untooledExtraCost):N0}f", rightLabel, GUILayout.Width(72));
                        }
                        finally {
                            GUILayout.EndHorizontal();
                        }
                    }
                } finally {
                    GUILayout.EndScrollView();
                }
                GUILayout.BeginHorizontal();
                try {
                    GUILayout.Label($"Total vessel cost if all parts are tooled: {allTooledCost:N0}");
                } finally {
                    GUILayout.EndHorizontal();
                }
                GUILayout.BeginHorizontal();
                try {
                    if (GUILayout.Button("Tool All"))
                    {
                        var untooledParts = EditorLogic.fetch.ship.Parts.Slinq().SelectMany(p => p.FindModulesImplementing <ModuleTooling>().Slinq())
                                            .Where(mt => !mt.IsUnlocked())
                                            .ToList();

                        float totalToolingCost = ModuleTooling.PurchaseToolingBatch(untooledParts, isSimulation: true);
                        bool  canAfford        = Funding.Instance.Funds >= totalToolingCost;
                        PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f),
                                                     new Vector2(0.5f, 0.5f),
                                                     new MultiOptionDialog(
                                                         "ConfirmAllToolingsPurchase",
                                                         $"Tooling for all untooled parts will cost {totalToolingCost:N0} funds.",
                                                         "Tooling Purchase",
                                                         HighLogic.UISkin,
                                                         new Rect(0.5f, 0.5f, 150f, 60f),
                                                         new DialogGUIFlexibleSpace(),
                                                         new DialogGUIVerticalLayout(
                                                             new DialogGUIFlexibleSpace(),
                                                             new DialogGUIButton(canAfford ? "Purchase All Toolings" : "Can't Afford",
                                                                                 () =>
                        {
                            if (canAfford)
                            {
                                ModuleTooling.PurchaseToolingBatch(untooledParts);
                                untooledParts.ForEach(mt =>
                                {
                                    mt.Events["ToolingEvent"].guiActiveEditor = false;
                                });
                                GameEvents.onEditorShipModified.Fire(EditorLogic.fetch.ship);
                            }
                        }, 140.0f, 30.0f, true),
                                                             new DialogGUIButton("Close", () => { }, 140.0f, 30.0f, true)
                                                             )),
                                                     false,
                                                     HighLogic.UISkin);
                    }
                } finally {
                    GUILayout.EndHorizontal();
                }
            }
            return(currentToolingType == null ? tabs.Tooling : tabs.ToolingType);
        }
Esempio n. 17
0
        internal void Update()
        {
            if (GameSettings.MODIFIER_KEY.GetKey() && Input.GetKeyDown(KeyCode.F11) &&
                (HighLogic.LoadedScene == GameScenes.SPACECENTER || HighLogic.LoadedScene == GameScenes.MAINMENU) &&
                !inRnDCenter)
            {
                if (menu == null)
                {
                    menu = PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f),
                                                        new Vector2(0.5f, 0.5f),
                                                        new MultiOptionDialog(
                                                            "ModuleManagerMenu",
                                                            "",
                                                            "ModuleManager",
                                                            HighLogic.UISkin,
                                                            new Rect(0.5f, 0.5f, 150f, 60f),
                                                            new DialogGUIFlexibleSpace(),
                                                            new DialogGUIVerticalLayout(
                                                                new DialogGUIFlexibleSpace(),
                                                                new DialogGUIButton("Reload Database",
                                                                                    delegate
                    {
                        MMPatchLoader.keepPartDB = false;
                        StartCoroutine(DataBaseReloadWithMM());
                    }, 140.0f, 30.0f, true),
                                                                new DialogGUIButton("Quick Reload Database",
                                                                                    delegate
                    {
                        MMPatchLoader.keepPartDB = true;
                        StartCoroutine(DataBaseReloadWithMM());
                    }, 140.0f, 30.0f, true),
                                                                new DialogGUIButton("Dump Database to Files",
                                                                                    delegate
                    {
                        StartCoroutine(DataBaseReloadWithMM(true));
                    }, 140.0f, 30.0f, true),
                                                                new DialogGUIButton("Close", () => { }, 140.0f, 30.0f, true)
                                                                )),
                                                        false,
                                                        HighLogic.UISkin);
                }
                else
                {
                    menu.Dismiss();
                    menu = null;
                }
            }

            if (totalTime.IsRunning && HighLogic.LoadedScene == GameScenes.MAINMENU)
            {
                totalTime.Stop();
                Log("Total loading Time = " + ((float)totalTime.ElapsedMilliseconds / 1000).ToString("F3") + "s");

                Application.runInBackground = GameSettings.SIMULATE_IN_BACKGROUND;
                QualitySettings.vSyncCount  = GameSettings.SYNC_VBL;
                Application.targetFrameRate = GameSettings.FRAMERATE_LIMIT;
            }

            float offsetY = textPos;
            float h;

            if (warning)
            {
                h       = warning.text.Length > 0 ? warning.textBounds.size.y : 0;
                offsetY = offsetY + h;
                warning.rectTransform.localPosition = new Vector3(0, offsetY);
            }

            if (status)
            {
                status.text = MMPatchLoader.Instance.status;
                h           = status.text.Length > 0 ? status.textBounds.size.y: 0;
                offsetY     = offsetY + h;
                status.transform.localPosition = new Vector3(0, offsetY);
            }

            if (errors)
            {
                errors.text = MMPatchLoader.Instance.errors;
                h           = errors.text.Length > 0 ? errors.textBounds.size.y: 0;
                offsetY     = offsetY + h;
                errors.transform.localPosition = new Vector3(0, offsetY);
            }

            if (reloading)
            {
                float percent = 0;
                if (!GameDatabase.Instance.IsReady())
                {
                    percent = GameDatabase.Instance.ProgressFraction();
                }
                else if (!MMPatchLoader.Instance.IsReady())
                {
                    percent = 1f + MMPatchLoader.Instance.ProgressFraction();
                }
                else if (!PartLoader.Instance.IsReady())
                {
                    percent = 2f + PartLoader.Instance.ProgressFraction();
                }

                int intPercent = Mathf.CeilToInt(percent * 100f / 3f);
                ScreenMessages.PostScreenMessage("Database reloading " + intPercent + "%", Time.deltaTime,
                                                 ScreenMessageStyle.UPPER_CENTER);
            }
        }
Esempio n. 18
0
        public void Start()
        {
            //Checkers are identified by the type name and _version field name.
            FieldInfo[] fields =
                GetAllTypes()
                .Where(t => t.Name == "CompatibilityChecker")
                .Select(t => t.GetField("_version", BindingFlags.Static | BindingFlags.NonPublic))
                .Where(f => f != null)
                .Where(f => f.FieldType == typeof(int))
                .ToArray();

            //Let the latest version of the checker execute.
            if (_version != fields.Max(f => (int)f.GetValue(null)))
            {
                return;
            }

            Debug.Log(string.Format("[CompatibilityChecker] Running checker version {0} from '{1}'", _version, Assembly.GetExecutingAssembly().GetName().Name));

            //Other checkers will see this version and not run.
            //This accomplishes the same as an explicit "ran" flag with fewer moving parts.
            _version = int.MaxValue;

            //A mod is incompatible if its compatibility checker has an IsCompatible method which returns false.
            string[] incompatible =
                fields
                .Select(f => f.DeclaringType.GetMethod("IsCompatible", Type.EmptyTypes))
                .Where(m => m.IsStatic)
                .Where(m => m.ReturnType == typeof(bool))
                .Where(m =>
            {
                try
                {
                    return(!(bool)m.Invoke(null, new object[0]));
                }
                catch (Exception e)
                {
                    //If a mod throws an exception from IsCompatible, it's not compatible.
                    Debug.LogWarning(string.Format("[CompatibilityChecker] Exception while invoking IsCompatible() from '{0}':\n\n{1}", m.DeclaringType.Assembly.GetName().Name, e));
                    return(true);
                }
            })
                .Select(m => m.DeclaringType.Assembly.GetName().Name)
                .ToArray();

            //A mod is incompatible with Unity if its compatibility checker has an IsUnityCompatible method which returns false.
            string[] incompatibleUnity =
                fields
                .Select(f => f.DeclaringType.GetMethod("IsUnityCompatible", Type.EmptyTypes))
                .Where(m => m != null)  //Mods without IsUnityCompatible() are assumed to be compatible.
                .Where(m => m.IsStatic)
                .Where(m => m.ReturnType == typeof(bool))
                .Where(m =>
            {
                try
                {
                    return(!(bool)m.Invoke(null, new object[0]));
                }
                catch (Exception e)
                {
                    //If a mod throws an exception from IsUnityCompatible, it's not compatible.
                    Debug.LogWarning(string.Format("[CompatibilityChecker] Exception while invoking IsUnityCompatible() from '{0}':\n\n{1}", m.DeclaringType.Assembly.GetName().Name, e));
                    return(true);
                }
            })
                .Select(m => m.DeclaringType.Assembly.GetName().Name)
                .ToArray();

            Array.Sort(incompatible);
            Array.Sort(incompatibleUnity);

            string message = string.Empty;

            /*if (SixtyFourBitsMayHaveAChanceAtLife())
             *{
             *   message += "WARNING: You are using 64-bit KSP on Windows. This version of KSP is known to cause crashes. It's highly recommended that you use either 32-bit KSP on Windows or switch to Linux.";
             *}*/

            if (incompatible.Length > 0 || incompatibleUnity.Length > 0)
            {
                message += Localizer.Format("FARCompatCheckWarning");

                if (incompatible.Length > 0)
                {
                    Debug.LogWarning("[CompatibilityChecker] Incompatible mods detected: " + string.Join(", ", incompatible));
                    message += Localizer.Format("FARCompatCheckKSP", Versioning.version_major, Versioning.version_minor, Versioning.Revision);
                    message += string.Join("\n", incompatible);
                }

                if (incompatibleUnity.Length > 0)
                {
                    Debug.LogWarning("[CompatibilityChecker] Incompatible mods (Unity) detected: " + string.Join(", ", incompatibleUnity));
                    message += Localizer.Format("FARCompatCheckUnity", Application.unityVersion);
                    message += string.Join("\n", incompatibleUnity);
                }
            }

            if (incompatible.Length > 0 || incompatibleUnity.Length > 0)
            {
                PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), "CompatibilityChecker", Localizer.Format("FARCompatCheckTitle"), message, Localizer.Format("FARGUIOKButton"), true, HighLogic.UISkin);
            }
        }
Esempio n. 19
0
        /// <summary>
        /// Loads the contract group details from the given config node.
        /// </summary>
        /// <param name="configNode">The config node to load from</param>
        /// <returns>Whether we were successful.</returns>
        public bool Load(ConfigNode configNode)
        {
            try
            {
                dataNode = new DataNode(configNode.GetValue("name"), this);

                LoggingUtil.CaptureLog = true;
                ConfigNodeUtil.SetCurrentDataNode(dataNode);
                bool   valid = true;
                string unused;

                valid &= ConfigNodeUtil.ParseValue <string>(configNode, "name", x => name = x, this);
                valid &= ConfigNodeUtil.ParseValue <string>(configNode, "displayName", x => displayName = x, this, name);
                valid &= ConfigNodeUtil.ParseValue <string>(configNode, "minVersion", x => minVersionStr = x, this, parent == null ? "" : parent.minVersion.ToString());
                valid &= ConfigNodeUtil.ParseValue <int>(configNode, "maxCompletions", x => maxCompletions = x, this, 0, x => Validation.GE(x, 0));
                valid &= ConfigNodeUtil.ParseValue <int>(configNode, "maxSimultaneous", x => maxSimultaneous = x, this, 0, x => Validation.GE(x, 0));
                valid &= ConfigNodeUtil.ParseValue <List <string> >(configNode, "disabledContractType", x => disabledContractType = x, this, new List <string>());
                valid &= ConfigNodeUtil.ParseValue <Agent>(configNode, "agent", x => agent = x, this, parent == null ? (Agent)null : parent.agent);
                valid &= ConfigNodeUtil.ParseValue <string>(configNode, "sortKey", x => sortKey = x, this, displayName);
                valid &= ConfigNodeUtil.ParseValue <string>(configNode, "tip", x => unused = x, this, "");

                if (configNode.HasValue("sortKey") && parent == null)
                {
                    sortKey = displayName;
                    LoggingUtil.LogWarning(this, "{0}: Using the sortKey field is only applicable on child CONTRACT_GROUP elements", ErrorPrefix());
                }

                if (!string.IsNullOrEmpty(minVersionStr))
                {
                    if (Util.Version.VerifyAssemblyVersion("ContractConfigurator", minVersionStr) == null)
                    {
                        valid = false;

                        var    ainfoV  = Attribute.GetCustomAttribute(typeof(ExceptionLogWindow).Assembly, typeof(AssemblyInformationalVersionAttribute)) as AssemblyInformationalVersionAttribute;
                        string title   = "Contract Configurator " + ainfoV.InformationalVersion + " Message";
                        string message = "The contract group '" + name + "' requires at least Contract Configurator " + minVersionStr +
                                         " to work, and you are running version " + ainfoV.InformationalVersion +
                                         ".  Please upgrade Contract Configurator to use the contracts in this group.";
                        DialogGUIButton dialogOption = new DialogGUIButton("Okay", new Callback(DoNothing), true);
                        PopupDialog.SpawnPopupDialog(new MultiOptionDialog("ContractConfiguratorMsg", message, title, UISkinManager.GetSkin("default"), dialogOption), false, UISkinManager.GetSkin("default"));
                    }
                }

                // Load DATA nodes
                valid &= dataNode.ParseDataNodes(configNode, this, dataValues, uniquenessChecks);

                // Do the deferred loads
                valid &= ConfigNodeUtil.ExecuteDeferredLoads();

                // Do post-deferred load warnings
                if (agent == null)
                {
                    LoggingUtil.LogWarning(this, "{0}: Providing the agent field for all CONTRACT_GROUP nodes is highly recommended, as the agent is used to group contracts in Mission Control.", ErrorPrefix());
                }
                if (string.IsNullOrEmpty(minVersionStr) || minVersion < ContractConfigurator.ENHANCED_UI_VERSION)
                {
                    LoggingUtil.LogWarning(this, "{0}: No minVersion or older minVersion provided.  It is recommended that the minVersion is set to at least 1.15.0 to turn important warnings for deprecated functionality into errors.", ErrorPrefix());
                }
                if (!configNode.HasValue("displayName"))
                {
                    LoggingUtil.LogWarning(this, "{0}: No display name provided.  A display name is recommended, as it is used in the Mission Control UI.", ErrorPrefix());
                }

                config = configNode.ToString();
                log   += LoggingUtil.capturedLog;
                LoggingUtil.CaptureLog = false;

                // Load child groups
                foreach (ConfigNode childNode in ConfigNodeUtil.GetChildNodes(configNode, "CONTRACT_GROUP"))
                {
                    ContractGroup child     = null;
                    string        childName = childNode.GetValue("name");
                    try
                    {
                        child = new ContractGroup(childName);
                    }
                    catch (ArgumentException)
                    {
                        LoggingUtil.LogError(this, "Couldn't load CONTRACT_GROUP '{0}' due to a duplicate name.", childName);
                        valid = false;
                        continue;
                    }

                    child.parent          = this;
                    valid                &= child.Load(childNode);
                    child.dataNode.Parent = dataNode;
                    if (child.hasWarnings)
                    {
                        hasWarnings = true;
                    }
                }

                // Check for unexpected values - always do this last
                valid &= ConfigNodeUtil.ValidateUnexpectedValues(configNode, this);

                // Invalidate children
                if (!valid)
                {
                    Invalidate();
                }

                enabled = valid;
                return(valid);
            }
            catch
            {
                enabled = false;
                throw;
            }
        }
Esempio n. 20
0
        public void VesselToCraftFile(ConfigNode VesselNode)
        {
            //This code is taken from InflightShipSave by Claw, using the CC-BY-NC-SA license.
            //This code thus is licensed under the same license, despite the GPLv3 license covering original KCT code
            //See https://github.com/ClawKSP/InflightShipSave

            ProtoVessel VesselToSave = HighLogic.CurrentGame.AddVessel(VesselNode);

            if (VesselToSave.vesselRef == null)
            {
                Log("Vessel reference is null!");
                return;
            }

            try
            {
                string ShipName = VesselToSave.vesselName;

                //Vessel FromFlight = FlightGlobals.Vessels.Find(v => v.id == VesselToSave.vesselID);
                try
                {
                    VesselToSave.vesselRef.Load();
                }
                catch (Exception ex)
                {
                    Debug.LogException(ex);
                    Log("Attempting to continue.");
                }

                ShipConstruct ConstructToSave  = new ShipConstruct(ShipName, "", VesselToSave.vesselRef.Parts[0]);
                Quaternion    OriginalRotation = VesselToSave.vesselRef.vesselTransform.rotation;
                Vector3       OriginalPosition = VesselToSave.vesselRef.vesselTransform.position;

                VesselToSave.vesselRef.SetRotation(new Quaternion(0, 0, 0, 1));
                Vector3 ShipSize = ShipConstruction.CalculateCraftSize(ConstructToSave);
                VesselToSave.vesselRef.SetPosition(new Vector3(0, ShipSize.y + 2, 0));


                ConfigNode CN = new ConfigNode("ShipConstruct");
                CN = ConstructToSave.SaveShip();
                //SanitizeShipNode(CN);
                CleanEditorNodes(CN);

                //VesselToSave.rotation = OriginalRotation;
                //VesselToSave.position = OriginalPosition;

                if (ConstructToSave.shipFacility == EditorFacility.SPH)
                {
                    string filename = UrlDir.ApplicationRootPath + "saves/" + HighLogic.SaveFolder
                                      + "/Ships/SPH/" + ShipName + "_Rescued.craft";
                    CN.Save(filename);

                    //ScreenMessage message = new ScreenMessage(ShipName + " converted to " + filename, 6, ScreenMessageStyle.UPPER_CENTER);
                    //ScreenMessages.PostScreenMessage(message);

                    PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), "Convert", "Conversion Complete",
                                                 "Vessel has been converted to a craft file:\n" + filename,
                                                 "Ok", false, HighLogic.UISkin);
                }
                else
                {
                    string filename = UrlDir.ApplicationRootPath + "saves/" + HighLogic.SaveFolder
                                      + "/Ships/VAB/" + ShipName + "_Rescued.craft";
                    CN.Save(filename);

                    //ScreenMessage message = new ScreenMessage(ShipName + " converted to " + filename, 6, ScreenMessageStyle.UPPER_CENTER);
                    //ScreenMessages.PostScreenMessage(message);

                    PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), "Convert", "Conversion Complete",
                                                 "Vessel has been converted to a craft file:\n" + filename,
                                                 "Ok", false, HighLogic.UISkin);
                }
            }
            catch (Exception e)
            {
                Debug.LogException(e);
            }
            finally
            {
                HighLogic.CurrentGame.DestroyVessel(VesselToSave.vesselRef);
                VesselToSave.vesselRef.Die();
            }
            //End of Claw's code. Thanks Claw!
        }
        IEnumerator ClusterioPreflightResourceCheck()
        {
            Debug.Log("XenoIndustryLaunchCosts: PreflightResourceCheck");

            string bodyName = "Kerbin"; // Launching only works on Kerbin for now

            yield return(StartCoroutine(XenoIndustrySignpost.GetClusterioInventory(bodyName, clusterioInventory)));

            CalculateLaunchCosts(ref latestLaunchCosts);

            bool pass = true;

            foreach (KeyValuePair <string, int> kvPair in latestLaunchCosts)
            {
                if (!clusterioInventory.ContainsKey(kvPair.Key) || clusterioInventory[kvPair.Key] < kvPair.Value)
                {
                    pass = false;
                    break;
                }
            }

            if (!pass)
            { // Insufficient resources to launch
                string message = "You do not have enough resources to launch this vessel! This vessel needs: \n";

                foreach (KeyValuePair <string, int> kvPair in latestLaunchCosts)
                {
                    message += String.Format("\n {0} {1} (you have {2})", kvPair.Value, kvPair.Key, (clusterioInventory.ContainsKey(kvPair.Key)) ? clusterioInventory[kvPair.Key] : 0);
                }

                message += "\n";

                MultiOptionDialog dialog = new MultiOptionDialog("InsufficientClusterioResources", message, "Insufficient resources!", UISkinManager.GetSkin("KSP window 7"),
                                                                 new DialogGUIBase[]
                {
                    new DialogGUIButton("Unable to Launch", null)
                });

                PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), dialog, false, null);
            }
            else
            { // Launch can proceed
                string message = "Launching this vessel will require: \n";

                foreach (KeyValuePair <string, int> kvPair in latestLaunchCosts)
                {
                    message += String.Format("\n {0} {1} (you have {2})", kvPair.Value, kvPair.Key, (clusterioInventory.ContainsKey(kvPair.Key)) ? clusterioInventory[kvPair.Key] : 0);
                }

                message += "\n";

                MultiOptionDialog dialog = new MultiOptionDialog("ClusterioLaunchConfirmation", message, "Launch Possible", UISkinManager.GetSkin("KSP window 7"),
                                                                 new DialogGUIBase[]
                {
                    new DialogGUIButton("Launch", new Callback(ProceedToLaunch)),
                    new DialogGUIButton("Cancel", null)
                });

                PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), dialog, false, null);
            }
        }
Esempio n. 22
0
        public void ImportVessel(string name)
        {
            if (System.IO.File.Exists(name))
            {
                Log($"Importing vessel: {name}");
                ConfigNode storedNode = ConfigNode.Load(name);

                ConfigNode vesselNode = storedNode.GetNode("VESSEL");

                vesselNode.SetValue("pid", Guid.NewGuid().ToString());

                if (WarnOfInvalidParts(vesselNode, true))
                {
                    return;
                }

                List <ProtoCrewMember> crewAdded = new List <ProtoCrewMember>();

                if (!_includeCrew)
                {
                    //clear out all crew on vessel
                    StripCrew(vesselNode);
                }
                else
                {
                    //create crewmembers if they don't exist, set all of them to assigned
                    try
                    {
                        foreach (ConfigNode partNode in vesselNode.GetNodes("PART"))
                        {
                            if (partNode.HasValue("crew"))
                            {
                                List <string> toRemove = new List <string>();
                                foreach (ConfigNode.Value crewValue in partNode.values)//(string crewmember in partNode.GetValues("crew"))
                                {
                                    if (crewValue.name != "crew")
                                    {
                                        continue;
                                    }

                                    string crewmember = crewValue.value;
                                    //find the confignode saved with the vessel
                                    ConfigNode crewNode = storedNode.GetNodes("CREW")?.FirstOrDefault(c => c.GetValue("name") == crewmember);
                                    if (crewNode == null || crewNode.GetValue("type") != "Crew") //if no data or is tourist then remove from ship
                                    {
                                        //can't find the required data, so remove that kerbal from the ship
                                        Log($"Vessel occupant is not crew: {crewmember}");
                                        toRemove.Add(crewmember);
                                        continue;
                                    }


                                    ProtoCrewMember newCrew = new ProtoCrewMember(HighLogic.CurrentGame.Mode, crewNode, ProtoCrewMember.KerbalType.Crew);
                                    if (HighLogic.CurrentGame.CrewRoster.Exists(crewmember)) //there's already a kerbal with that name (sadness :( )
                                    {
                                        //alright, rename this kerbal to a new name
                                        string newName = RenameKerbal(crewmember);
                                        newCrew.ChangeName(newName);
                                        crewValue.value = newName;
                                    }
                                    Log($"Creating crewmember {newCrew.name}");
                                    //add the crew member to the crew roster
                                    //the function to do this is hidden for some reason. yay!
                                    HighLogic.CurrentGame.CrewRoster.AddCrewMember(newCrew); //no longer hidden! MORE YAY!
                                    crewAdded.Add(newCrew);
                                }
                                foreach (string crewmember in toRemove) //remove all crews that shouldn't be here anymore
                                {
                                    //find the value with this kerbal and remove it
                                    foreach (ConfigNode.Value val in partNode.values)
                                    {
                                        if (val.name == "crew" && val.value == crewmember)
                                        {
                                            Log($"Removing non-valid crew member {val.value}");
                                            partNode.values.Remove(val);
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Log("Encountered exception while transferring crew. The exception follows. Stripping crew data.");
                        Debug.LogException(ex);

                        StripCrew(vesselNode);

                        PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), "errorPopup", "Error Occurred",
                                                     "Unable to import crew. An exception occurred and has been logged.",
                                                     "Ok", false, HighLogic.UISkin);

                        return;
                    }
                }

                ProtoVessel addedVessel = HighLogic.CurrentGame.AddVessel(vesselNode);
                foreach (ProtoCrewMember crew in crewAdded)
                {
                    Log($"Assigning {crew.name}");
                    addedVessel.AddCrew(crew);
                }
                //In 1.2.2+ saving fails when there are two copies of a ship with crew onboard both. Might be part ID related.
                //All I know is that if I terminate the original flight, I can import crew. Otherwise it NREs when it tries to save the flight state.

                PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), "Import", "Import complete",
                                             "Vessel has been imported",
                                             "Ok", false, HighLogic.UISkin);
            }
        }
Esempio n. 23
0
        private void VesselRecoveryProcessing(ProtoVessel v, MissionRecoveryDialog mrDialog, float data)
        {
            Debug.Log("[RP-0] - Vessel recovery processing");

            var retirementChanges = new List <string>();
            var inactivity        = new List <string>();

            double UT = Planetarium.GetUniversalTime();

            // normally we would use v.missionTime, but that doesn't seem to update
            // when you're not actually controlling the vessel
            double elapsedTime = UT - v.launchTime;

            Debug.Log($"[RP-0] mission elapsedTime: {KSPUtil.PrintDateDeltaCompact(elapsedTime, true, true)}");

            // When flight duration was too short, mission training should not be set as expired.
            // This can happen when an on-the-pad failure occurs and the vessel is recovered.
            // We could perhaps override this if they're not actually in flight
            // (if the user didn't recover right from the pad I think this is a fair assumption)
            if (elapsedTime < Settings.minFlightDurationSecondsForTrainingExpire)
            {
                Debug.Log($"[RP-0] - mission time too short for crew to be inactive (elapsed time was {elapsedTime}, settings set for {Settings.minFlightDurationSecondsForTrainingExpire})");
                return;
            }

            var validStatuses = new List <string>
            {
                FlightLog.EntryType.Flight.ToString(), Situation_FlightHigh, FlightLog.EntryType.Suborbit.ToString(),
                FlightLog.EntryType.Orbit.ToString(), FlightLog.EntryType.ExitVessel.ToString(),
                FlightLog.EntryType.Land.ToString(), FlightLog.EntryType.Flyby.ToString()
            };

            foreach (ProtoCrewMember pcm in v.GetVesselCrew())
            {
                Debug.Log("[RP-0] - Found ProtoCrewMember: " + pcm.displayName);

                var    allFlightsDict = new Dictionary <string, int>();
                int    curFlight      = pcm.careerLog.Last().flight;
                double inactivityMult = 0;
                double retirementMult = 0;

                foreach (FlightLog.Entry e in pcm.careerLog.Entries)
                {
                    if (e.type == "Nationality")
                    {
                        continue;
                    }
                    if (e.type == TrainingType_Mission)
                    {
                        SetExpiration(pcm.name, e, Planetarium.GetUniversalTime());
                    }

                    if (validStatuses.Contains(e.type))
                    {
                        int situationCount;
                        var key = $"{e.target}-{e.type}";
                        if (allFlightsDict.ContainsKey(key))
                        {
                            situationCount      = allFlightsDict[key];
                            allFlightsDict[key] = ++situationCount;
                        }
                        else
                        {
                            situationCount = 1;
                            allFlightsDict.Add(key, situationCount);
                        }

                        if (e.flight != curFlight)
                        {
                            continue;
                        }

                        if (TryGetBestSituationMatch(e.target, e.type, "Retire", out double situationMult))
                        {
                            double countMult = 1 + Math.Pow(situationCount - 1, Settings.retireOffsetFlightNumPow);
                            retirementMult += situationMult / countMult;
                        }

                        if (TryGetBestSituationMatch(e.target, e.type, "Inactive", out double inactivMult))
                        {
                            inactivityMult += inactivMult;
                        }
                    }
                }

                Debug.Log("[RP-0]  retirementMult: " + retirementMult);
                Debug.Log("[RP-0]  inactivityMult: " + inactivityMult);

                double acMult = ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.AstronautComplex) + 1;
                Debug.Log("[RP-0]  AC multiplier: " + acMult);

                if (KerbalRetireTimes.TryGetValue(pcm.name, out double retTime))
                {
                    double stupidityPenalty = UtilMath.Lerp(Settings.retireOffsetStupidMin, Settings.retireOffsetStupidMax, pcm.stupidity);
                    Debug.Log($"[RP-0]  stupidityPenalty for {pcm.stupidity}: {stupidityPenalty}");
                    double retireOffset = retirementMult * 86400 * Settings.retireOffsetBaseMult / stupidityPenalty;

                    if (retireOffset > 0)
                    {
                        KerbalRetireIncreases.TryGetValue(pcm.name, out double retIncreaseTotal);
                        retIncreaseTotal += retireOffset;
                        if (retIncreaseTotal > Settings.retireIncreaseCap)
                        {
                            // Cap the total retirement increase at a specific number of years
                            retireOffset    -= retIncreaseTotal - Settings.retireIncreaseCap;
                            retIncreaseTotal = Settings.retireIncreaseCap;
                        }
                        KerbalRetireIncreases[pcm.name] = retIncreaseTotal;

                        string sRetireOffset = KSPUtil.PrintDateDelta(retireOffset, false, false);
                        Debug.Log("[RP-0] retire date increased by: " + sRetireOffset);

                        retTime += retireOffset;
                        KerbalRetireTimes[pcm.name] = retTime;
                        retirementChanges.Add($"\n{pcm.name}, +{sRetireOffset}, no earlier than {KSPUtil.PrintDate(retTime, false)}");
                    }
                }

                inactivityMult = Math.Max(1, inactivityMult);
                double elapsedTimeDays  = elapsedTime / 86400;
                double inactiveTimeDays = Math.Pow(Math.Max(Settings.inactivityMinFlightDurationDays, elapsedTimeDays), Settings.inactivityFlightDurationExponent) *
                                          Math.Min(Settings.inactivityMaxSituationMult, inactivityMult) / acMult;
                double inactiveTime = inactiveTimeDays * 86400;
                Debug.Log("[RP-0] inactive for: " + KSPUtil.PrintDateDeltaCompact(inactiveTime, true, false));

                pcm.SetInactive(inactiveTime, false);
                inactivity.Add($"\n{pcm.name}, until {KSPUtil.PrintDate(inactiveTime + UT, true, false)}");
            }

            if (inactivity.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("The following crew members will be on leave:");
                foreach (string s in inactivity)
                {
                    sb.Append(s);
                }

                if (RetirementEnabled && retirementChanges.Count > 0)
                {
                    sb.Append("\n\nThe following retirement changes have occurred:");
                    foreach (string s in retirementChanges)
                    {
                        sb.Append(s);
                    }
                }

                PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f),
                                             new Vector2(0.5f, 0.5f),
                                             "CrewUpdateNotification",
                                             "Crew Updates",
                                             sb.ToString(),
                                             "OK",
                                             true,
                                             HighLogic.UISkin);
            }
        }
Esempio n. 24
0
        /* Not required anymore. At least
         * public static bool IsABadIdea()
         * {
         *  return (intPtr.ToInt64() == long.MaxValue) && (Environment.OSVersion.Platform == PlatformID.Win32NT);
         * }
         */

        private IEnumerator DataBaseReloadWithMM(bool dump = false)
        {
            QualitySettings.vSyncCount  = 0;
            Application.targetFrameRate = -1;

            patchRunner = new MMPatchRunner(new PrefixLogger("ModuleManager", new UnityLogger(Debug.unityLogger)));

            float totalLoadWeight = GameDatabase.Instance.LoadWeight() + PartLoader.Instance.LoadWeight();
            bool  startedReload   = false;

            UISkinDef skinDef           = HighLogic.UISkin;
            UIStyle   centeredTextStyle = new UIStyle(skinDef.label)
            {
                alignment = TextAnchor.UpperCenter
            };

            PopupDialog reloadingDialog = PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f),
                                                                       new Vector2(0.5f, 0.5f),
                                                                       new MultiOptionDialog(
                                                                           "ModuleManagerReloading",
                                                                           "",
                                                                           "ModuleManager - Reloading Database",
                                                                           skinDef,
                                                                           new Rect(0.5f, 0.5f, 600f, 60f),
                                                                           new DialogGUIFlexibleSpace(),
                                                                           new DialogGUIVerticalLayout(
                                                                               new DialogGUIFlexibleSpace(),
                                                                               new DialogGUILabel(delegate()
            {
                float progressFraction;
                if (!startedReload)
                {
                    progressFraction = 0f;
                }
                else if (!GameDatabase.Instance.IsReady() || !PostPatchLoader.Instance.IsReady())
                {
                    progressFraction  = GameDatabase.Instance.ProgressFraction() * GameDatabase.Instance.LoadWeight();
                    progressFraction /= totalLoadWeight;
                }
                else if (!PartLoader.Instance.IsReady())
                {
                    progressFraction  = GameDatabase.Instance.LoadWeight() + (PartLoader.Instance.ProgressFraction() * GameDatabase.Instance.LoadWeight());
                    progressFraction /= totalLoadWeight;
                }
                else
                {
                    progressFraction = 1f;
                }

                return($"Overall progress: {progressFraction:P0}");
            }, centeredTextStyle, expandW : true),
                                                                               new DialogGUILabel(delegate()
            {
                if (!startedReload)
                {
                    return("Starting");
                }
                else if (!GameDatabase.Instance.IsReady())
                {
                    return(GameDatabase.Instance.ProgressTitle());
                }
                else if (!PostPatchLoader.Instance.IsReady())
                {
                    return(PostPatchLoader.Instance.ProgressTitle());
                }
                else if (!PartLoader.Instance.IsReady())
                {
                    return(PartLoader.Instance.ProgressTitle());
                }
                else
                {
                    return("");
                }
            }),
                                                                               new DialogGUISpace(5f),
                                                                               new DialogGUILabel(() => patchRunner.Status)
                                                                               )
                                                                           ),
                                                                       false,
                                                                       skinDef);

            yield return(null);

            GameDatabase.Instance.Recompile = true;
            GameDatabase.Instance.StartLoad();

            startedReload = true;

            yield return(null);

            StartCoroutine(patchRunner.Run());

            // wait for it to finish
            while (!GameDatabase.Instance.IsReady())
            {
                yield return(null);
            }

            PostPatchLoader.Instance.StartLoad();

            while (!PostPatchLoader.Instance.IsReady())
            {
                yield return(null);
            }

            if (dump)
            {
                OutputAllConfigs();
            }

            PartLoader.Instance.StartLoad();

            while (!PartLoader.Instance.IsReady())
            {
                yield return(null);
            }

            // Needs more work.
            //ConfigNode game = HighLogic.CurrentGame.config.GetNode("GAME");

            //if (game != null && ResearchAndDevelopment.Instance != null)
            //{
            //    ScreenMessages.PostScreenMessage("GAME found");
            //    ConfigNode scenario = game.GetNodes("SCENARIO").FirstOrDefault((ConfigNode n) => n.name == "ResearchAndDevelopment");
            //    if (scenario != null)
            //    {
            //        ScreenMessages.PostScreenMessage("SCENARIO found");
            //        ResearchAndDevelopment.Instance.OnLoad(scenario);
            //    }
            //}

            QualitySettings.vSyncCount  = GameSettings.SYNC_VBL;
            Application.targetFrameRate = GameSettings.FRAMERATE_LIMIT;

            reloadingDialog.Dismiss();
        }
Esempio n. 25
0
        static bool Prefix(ref ProtoVessel pv, ref bool quick)
        {
            if (pv == null)
            {
                return(true);
            }

            // get a hard drive. any hard drive will do, no need to find a specific one.
            ProtoPartModuleSnapshot protoHardDrive = null;

            foreach (var p in pv.protoPartSnapshots)
            {
                foreach (var pm in Lib.FindModules(p, "HardDrive"))
                {
                    protoHardDrive = pm;
                    break;
                }
                if (protoHardDrive != null)
                {
                    break;
                }
            }

            if (protoHardDrive == null)
            {
                return(true);                // no drive on the vessel - nothing to do.
            }
            double scienceToCredit = 0.0;

            List <DialogGUIBase> labels = new List <DialogGUIBase>();

            foreach (Drive drive in Drive.GetDrives(pv, true))
            {
                foreach (File file in drive.files.Values)
                {
                    double totalScienceValue = file.subjectData.ScienceValue(file.size);
                    file.subjectData.RemoveScienceCollectedInFlight(totalScienceValue);
                    file.subjectData.UpdateSubjectCompletion(totalScienceValue);

                    if (file.useStockCrediting)
                    {
                        file.ConvertToStockData().Save(protoHardDrive.moduleValues.AddNode("ScienceData"));
                        file.subjectData.SetAsPersistent();
                    }
                    else
                    {
                        double subjectValue = file.subjectData.ScienceValue(file.size, true);
                        file.subjectData.AddScienceToRnDSubject(subjectValue);
                        scienceToCredit += subjectValue;
                        GameEvents.OnScienceRecieved.Fire((float)subjectValue, file.subjectData.RnDSubject, pv, false);                         // needed for contracts
                        labels.Add(new DialogGUILabel(Lib.BuildString(
                                                          Lib.Color("+ " + subjectValue.ToString("F1"), Lib.Kolor.Science),
                                                          " (",
                                                          Lib.Color(file.subjectData.ScienceRetrievedInKSC.ToString("F1"), Lib.Kolor.Science, true),
                                                          " / ",
                                                          Lib.Color(file.subjectData.ScienceMaxValue.ToString("F1"), Lib.Kolor.Science, true),
                                                          ") : ",
                                                          file.subjectData.FullTitle
                                                          )));
                    }
                }

                foreach (Sample sample in drive.samples.Values)
                {
                    double totalScienceValue = sample.subjectData.ScienceValue(sample.size);
                    sample.subjectData.RemoveScienceCollectedInFlight(totalScienceValue);
                    sample.subjectData.UpdateSubjectCompletion(totalScienceValue);

                    if (sample.useStockCrediting)
                    {
                        sample.ConvertToStockData().Save(protoHardDrive.moduleValues.AddNode("ScienceData"));
                        sample.subjectData.SetAsPersistent();
                    }
                    else
                    {
                        double subjectValue = sample.subjectData.ScienceValue(sample.size, true);
                        sample.subjectData.AddScienceToRnDSubject(subjectValue);
                        scienceToCredit += subjectValue;
                        GameEvents.OnScienceRecieved.Fire((float)subjectValue, sample.subjectData.RnDSubject, pv, false);                         // needed for contracts
                        labels.Add(new DialogGUILabel(Lib.BuildString(
                                                          Lib.Color("+ " + subjectValue.ToString("F1"), Lib.Kolor.Science),
                                                          " (",
                                                          Lib.Color(sample.subjectData.ScienceRetrievedInKSC.ToString("F1"), Lib.Kolor.Science, true),
                                                          " / ",
                                                          Lib.Color(sample.subjectData.ScienceMaxValue.ToString("F1"), Lib.Kolor.Science, true),
                                                          ") : ",
                                                          sample.subjectData.FullTitle
                                                          )));
                    }
                }
            }

            protoHardDrive.moduleName = "ModuleScienceContainer";

            if (scienceToCredit > 0.0)
            {
                ResearchAndDevelopment.Instance.AddScience((float)scienceToCredit, TransactionReasons.VesselRecovery);

                // ideally we should hack the stock dialog to add the little science widgets to it but I'm lazy
                // plus it looks like crap anyway
                PopupDialog.SpawnPopupDialog
                (
                    new MultiOptionDialog
                    (
                        "scienceResults", "", pv.vesselName + " " + Local.VesselRecovery_title, HighLogic.UISkin, new Rect(0.3f, 0.5f, 350f, 100f),                      //" recovery"
                        new DialogGUIVerticalLayout
                        (
                            new DialogGUIBox(Local.VesselRecovery_info + " : " + Lib.Color(scienceToCredit.ToString("F1") + " " + Local.VesselRecovery_CREDITS, Lib.Kolor.Science, true), 340f, 30f),                            //"SCIENCE RECOVERED"" CREDITS"
                            new DialogGUIScrollList
                            (
                                new Vector2(340f, 250f), false, true,
                                new DialogGUIVerticalLayout(labels.ToArray())
                            ),
                            new DialogGUIButton(Local.VesselRecovery_OKbutton, null, 340f, 30f, true, HighLogic.UISkin.button)                            //"OK"
                        )
                    ),
                    false, HighLogic.UISkin
                );
            }

            return(true);            // continue to the original code
        }
Esempio n. 26
0
        /// <summary>
        /// Launch a PopupDialog containing the view.
        /// Use Dismiss() to get rid of it.
        /// </summary>
        public PopupDialog Show()
        {
            if (dialog == null)
            {
                if (Math.Abs(prevUIScale - GameSettings.UI_SCALE) > 0.05)
                {
                    // New UI Scale setting, so we can't open the real window yet.
                    // Instead, we open a scratch window to see how much
                    // distortion is applied at this level of scaling.
                    dialog = PopupDialog.SpawnPopupDialog(
                        mainWindowAnchorMin,
                        mainWindowAnchorMax,
                        new MultiOptionDialog("", "", "",
                                              AstrogatorSkin,
                                              geometry,
                                              new DialogGUIHorizontalLayout()
                    {
                        OnUpdate = () => {
                            if (needUIScaleOffsetUpdate)
                            {
                                needUIScaleOffsetUpdate = false;
                                replaceScratchWindowWithRealView();
                            }
                        }
                    }
                                              ),
                        false,
                        AstrogatorSkin,
                        false
                        );
                    needUIScaleOffsetUpdate = true;
                }
                else
                {
                    // Calculate where the new window should go based on the
                    // difference between where we said the scratch window should
                    // go and where it actually went.
                    Rect offsetGeometry = geometry;
                    offsetGeometry.x -= uiScaleOffset.x;
                    offsetGeometry.y -= uiScaleOffset.y;

                    dialog = PopupDialog.SpawnPopupDialog(
                        mainWindowAnchorMin,
                        mainWindowAnchorMax,
                        new MultiOptionDialog(
                            Localizer.Format("astrogator_mainTitle"),
                            ModelDescription(model),
                            Localizer.Format("astrogator_mainTitle") + " " + versionString,
                            skinToUse,
                            offsetGeometry,
                            this
                            ),
                        false,
                        skinToUse,
                        false
                        );

                    // Add the close button in the upper right corner after the PopupDialog has been created.
                    AddFloatingButton(
                        dialog.transform,
                        -mainWindowPadding.right - mainWindowSpacing, -mainWindowPadding.top,
                        closeStyle,
                        "astrogator_closeButtonTooltip",
                        closeCallback
                        );

                    // Add the settings button next to the close button.
                    // If the settings are visible it's a back '<' icon, otherwise a wrench+screwdriver.
                    AddFloatingButton(
                        dialog.transform,
                        -mainWindowPadding.right - 3 * mainWindowSpacing - buttonIconWidth,
                        -mainWindowPadding.top,
                        settingsToggleStyle,
                        settingsToggleTooltip,
                        toggleSettingsVisible
                        );
                }
            }
            return(dialog);
        }
        public void Start()
        {
            // Checkers are identified by the type name and version field name.
            FieldInfo[] fields =
                getAllTypes()
                .Where(t => t.Name == "CompatibilityChecker")
                .Select(t => t.GetField("_version", BindingFlags.Static | BindingFlags.NonPublic))
                .Where(f => f != null)
                .Where(f => f.FieldType == typeof(int))
                .ToArray();

            // Let the latest version of the checker execute.
            if (_version != fields.Max(f => (int)f.GetValue(null)))
            {
                return;
            }

            Debug.Log(String.Format("[CompatibilityChecker] Running checker version {0} from '{1}'", _version, Assembly.GetExecutingAssembly().GetName().Name));

            // Other checkers will see this version and not run.
            // This accomplishes the same as an explicit "ran" flag with fewer moving parts.
            _version = int.MaxValue;

            // A mod is incompatible if its compatibility checker has an IsCompatible method which returns false.
            String[] incompatible =
                fields
                .Select(f => f.DeclaringType.GetMethod("IsCompatible", Type.EmptyTypes))
                .Where(m => m.IsStatic)
                .Where(m => m.ReturnType == typeof(bool))
                .Where(m =>
            {
                try
                {
                    return(!(bool)m.Invoke(null, new object[0]));
                }
                catch (Exception e)
                {
                    // If a mod throws an exception from IsCompatible, it's not compatible.
                    Debug.LogWarning(String.Format("[CompatibilityChecker] Exception while invoking IsCompatible() from '{0}':\n\n{1}", m.DeclaringType.Assembly.GetName().Name, e));
                    return(true);
                }
            })
                .Select(m => m.DeclaringType.Assembly.GetName().Name)
                .ToArray();

            // A mod is incompatible with Unity if its compatibility checker has an IsUnityCompatible method which returns false.
            String[] incompatibleUnity =
                fields
                .Select(f => f.DeclaringType.GetMethod("IsUnityCompatible", Type.EmptyTypes))
                .Where(m => m != null)  // Mods without IsUnityCompatible() are assumed to be compatible.
                .Where(m => m.IsStatic)
                .Where(m => m.ReturnType == typeof(bool))
                .Where(m =>
            {
                try
                {
                    return(!(bool)m.Invoke(null, new object[0]));
                }
                catch (Exception e)
                {
                    // If a mod throws an exception from IsUnityCompatible, it's not compatible.
                    Debug.LogWarning(String.Format("[CompatibilityChecker] Exception while invoking IsUnityCompatible() from '{0}':\n\n{1}", m.DeclaringType.Assembly.GetName().Name, e));
                    return(true);
                }
            })
                .Select(m => m.DeclaringType.Assembly.GetName().Name)
                .ToArray();

            Array.Sort(incompatible);
            Array.Sort(incompatibleUnity);

            String message = String.Empty;

            if (IsWin64())
            {
                message += "WARNING: You are using 64-bit KSP on Windows. This version of KSP is known to cause crashes. It's highly recommended that you use either 32-bit KSP on Windows or switch to Linux.";
            }

            if ((incompatible.Length > 0) || (incompatibleUnity.Length > 0))
            {
                message += ((message == String.Empty) ? "Some" : "\n\nAdditionally, some") + " installed mods may be incompatible with this version of Kerbal Space Program. Features may be broken or disabled. Please check for updates to the listed mods.";

                if (incompatible.Length > 0)
                {
                    Debug.LogWarning("[CompatibilityChecker] Incompatible mods detected: " + String.Join(", ", incompatible));
                    message += String.Format("\n\nThese mods are incompatible with KSP {0}.{1}.{2}:\n\n", Versioning.version_major, Versioning.version_minor, Versioning.Revision);
                    message += String.Join("\n", incompatible);
                }

                if (incompatibleUnity.Length > 0)
                {
                    Debug.LogWarning("[CompatibilityChecker] Incompatible mods (Unity) detected: " + String.Join(", ", incompatibleUnity));
                    message += String.Format("\n\nThese mods are incompatible with Unity {0}:\n\n", Application.unityVersion);
                    message += String.Join("\n", incompatibleUnity);
                }
            }

            if ((incompatible.Length > 0) || (incompatibleUnity.Length > 0) || IsWin64())
            {
                PopupDialog.SpawnPopupDialog("Incompatible Mods Detected", message, "OK", true, HighLogic.Skin);
            }
        }
Esempio n. 28
0
        public void DelayedStart()
        {
            if (Utilities.CurrentGameIsMission())
            {
                return;
            }

            KCTDebug.Log("DelayedStart start");
            if (PresetManager.Instance?.ActivePreset == null || !PresetManager.Instance.ActivePreset.GeneralSettings.Enabled)
            {
                return;
            }

            if (KCT_GUI.IsPrimarilyDisabled)
            {
                return;
            }

            //The following should only be executed when fully enabled for the save

            if (KCTGameStates.ActiveKSC == null)
            {
                Utilities.SetActiveKSCToRSS();
            }

            KCTDebug.Log("Checking vessels for missing parts.");
            //check that all parts are valid in all ships. If not, warn the user and disable that vessel (once that code is written)
            if (!KCTGameStates.VesselErrorAlerted)
            {
                var erroredVessels = new List <BuildListVessel>();
                foreach (KSCItem KSC in KCTGameStates.KSCs) //this is faster on subsequent scene changes
                {
                    foreach (BuildListVessel blv in KSC.VABList)
                    {
                        if (!blv.AllPartsValid)
                        {
                            KCTDebug.Log(blv.ShipName + " contains invalid parts!");
                            erroredVessels.Add(blv);
                        }
                    }
                    foreach (BuildListVessel blv in KSC.VABWarehouse)
                    {
                        if (!blv.AllPartsValid)
                        {
                            KCTDebug.Log(blv.ShipName + " contains invalid parts!");
                            erroredVessels.Add(blv);
                        }
                    }
                    foreach (BuildListVessel blv in KSC.SPHList)
                    {
                        if (!blv.AllPartsValid)
                        {
                            KCTDebug.Log(blv.ShipName + " contains invalid parts!");
                            erroredVessels.Add(blv);
                        }
                    }
                    foreach (BuildListVessel blv in KSC.SPHWarehouse)
                    {
                        if (!blv.AllPartsValid)
                        {
                            KCTDebug.Log(blv.ShipName + " contains invalid parts!");
                            erroredVessels.Add(blv);
                        }
                    }
                }
                if (erroredVessels.Count > 0)
                {
                    PopUpVesselError(erroredVessels);
                }
                KCTGameStates.VesselErrorAlerted = true;
            }

            if (HighLogic.LoadedSceneIsEditor && KCTGameStates.EditorShipEditingMode)
            {
                KCTDebug.Log($"Editing {KCTGameStates.EditedVessel.ShipName}");
                EditorLogic.fetch.shipNameField.text = KCTGameStates.EditedVessel.ShipName;
            }

            if (HighLogic.LoadedScene == GameScenes.SPACECENTER)
            {
                KCTDebug.Log("SP Start");
                if (!KCT_GUI.IsPrimarilyDisabled)
                {
                    if (ToolbarManager.ToolbarAvailable && KCTGameStates.Settings.PreferBlizzyToolbar)
                    {
                        if (KCTGameStates.ShowWindows[0])
                        {
                            KCT_GUI.ToggleVisibility(true);
                        }
                        else
                        {
                            if (KCTEvents.Instance != null && KCTGameStates.ToolbarControl != null)
                            {
                                if (KCTGameStates.ShowWindows[0])
                                {
                                    KCT_GUI.ToggleVisibility(true);
                                }
                            }
                        }
                    }
                    KCT_GUI.ResetBLWindow();
                }
                else
                {
                    KCT_GUI.GUIStates.ShowBuildList = false;
                    KCTGameStates.ShowWindows[0]    = false;
                }
                KCTDebug.Log("SP UI done");

                if (KCTGameStates.IsFirstStart)
                {
                    KCTDebug.Log("Showing first start.");
                    KCTGameStates.IsFirstStart     = false;
                    KCT_GUI.GUIStates.ShowFirstRun = true;

                    //initialize the proper launchpad
                    KCTGameStates.ActiveKSC.ActiveLPInstance.level = Utilities.GetBuildingUpgradeLevel(SpaceCenterFacility.LaunchPad);
                }

                KCTDebug.Log("SP switch starting");
                KCTGameStates.ActiveKSC.SwitchLaunchPad(KCTGameStates.ActiveKSC.ActiveLaunchPadID);
                KCTDebug.Log("SP switch done");

                foreach (KSCItem ksc in KCTGameStates.KSCs)
                {
                    for (int i = 0; i < ksc.Recon_Rollout.Count; i++)
                    {
                        ReconRollout rr = ksc.Recon_Rollout[i];
                        if (rr.RRType != ReconRollout.RolloutReconType.Reconditioning && Utilities.FindBLVesselByID(new Guid(rr.AssociatedID)) == null)
                        {
                            KCTDebug.Log($"Invalid Recon_Rollout at {ksc.KSCName}. ID {rr.AssociatedID} not found.");
                            ksc.Recon_Rollout.Remove(rr);
                            i--;
                        }
                    }

                    for (int i = 0; i < ksc.AirlaunchPrep.Count; i++)
                    {
                        AirlaunchPrep ap = ksc.AirlaunchPrep[i];
                        if (Utilities.FindBLVesselByID(new Guid(ap.AssociatedID)) == null)
                        {
                            KCTDebug.Log($"Invalid KCT_AirlaunchPrep at {ksc.KSCName}. ID {ap.AssociatedID} not found.");
                            ksc.AirlaunchPrep.Remove(ap);
                            i--;
                        }
                    }
                }
                KCTDebug.Log("SP done");
            }

            if (HighLogic.LoadedSceneIsFlight && KCTGameStates.IsSimulatedFlight)
            {
                Utilities.EnableSimulationLocks();
                if (KCTGameStates.SimulationParams.SimulationUT > 0 &&
                    FlightDriver.CanRevertToPrelaunch)    // Used for checking whether the player has saved and then loaded back into that save
                {
                    KCTDebug.Log($"Setting simulation UT to {KCTGameStates.SimulationParams.SimulationUT}");
                    Planetarium.SetUniversalTime(KCTGameStates.SimulationParams.SimulationUT);
                }

                AddSimulationWatermark();
            }

            if (KCTGameStates.IsSimulatedFlight && HighLogic.LoadedSceneIsGame && !HighLogic.LoadedSceneIsFlight)
            {
                string msg = "Current save appears to be a simulation with no way to automatically revert to the pre-simulation state. An older save needs to be loaded manually now.";
                PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), "errorPopup", "KCT Simulation error", msg, "Understood", false, HighLogic.UISkin);
            }

            KCTDebug.Log("DelayedStart finished");
        }
Esempio n. 29
0
        private void ButtonOnTrue()
        {
            // Store labels in separate data structure for easy access when updating
            labelMap.Clear();
            List <LifeSupportReportable> modules =
                FlightGlobals.ActiveVessel.FindPartModulesImplementing <LifeSupportReportable>();
            // Calculate once on window generation, instead of each frame
            bool buttonEnable = !FlightGlobals.ActiveVessel.isEVA &&
                                FlightGlobals.ActiveVessel.HasModule <Cons2LSModule>();
            // Cell padding
            RectOffset offset            = new RectOffset(20, 0, 10, 0);
            DialogGUIVerticalLayout vert = new DialogGUIVerticalLayout(
                false, false, 1f,
                new RectOffset(), TextAnchor.UpperLeft);

            DialogGUIBase[] vertHeader;

            if (compress)
            {
                vertHeader = new DialogGUIBase[2]
                {
                    new DialogGUILabel("<b>Kerbal</b>", true, true),
                    new DialogGUILabel("<b>Life Support</b>", true, true)
                };
            }
            else
            {
                vertHeader = new DialogGUIBase[4]
                {
                    new DialogGUILabel("<b>Kerbal</b>", true, true),
                    new DialogGUILabel("<b>Ship Life Support</b>", true, true),
                    new DialogGUILabel("<b>Suit Life Support</b>", true, true),
                    new DialogGUILabel("", true, true)
                };
            }

            vert.AddChild(
                new DialogGUIGridLayout(new RectOffset(),
                                        new Vector2(cellWidth, 20),
                                        Vector2.zero,
                                        UnityEngine.UI.GridLayoutGroup.Corner.UpperLeft,
                                        UnityEngine.UI.GridLayoutGroup.Axis.Horizontal,
                                        TextAnchor.MiddleLeft,
                                        UnityEngine.UI.GridLayoutGroup.Constraint.FixedColumnCount,
                                        compress ? 2 : 4,
                                        vertHeader
                                        ));

            emptyPartLabels.Clear();

            DialogGUILabel emptyLabel = new DialogGUILabel("", true, true);

            foreach (LifeSupportReportable module in modules)
            {
                if (module.part.protoModuleCrew.Count == 0)
                {
                    emptyPartLabels.Add(module.part, new DialogGUILabel("EE", true, true));
                    continue;
                }

                List <ProtoCrewMember> crew        = new List <ProtoCrewMember>(module.part.protoModuleCrew);
                List <DialogGUIBase>   kerbalCells = new List <DialogGUIBase>();
                crew.Sort(CompareCrewNames);
                vert.AddChild(new DialogGUILabel($"{ORANGE}<b>{module.part.partInfo.title}</b></color>"));

                foreach (ProtoCrewMember kerbal in crew)
                {
                    GUIElements elems = new GUIElements(kerbal, buttonEnable);
                    labelMap.Add(kerbal.name, elems);
                    kerbalCells.Add(elems.nameLabel);
                    kerbalCells.Add(elems.shipLS);
                    if (!compress)
                    {
                        elems.nameLabel.SetOptionText(kerbal.name);
                        kerbalCells.Add(elems.evaLS);
                        kerbalCells.Add(elems.fillEVAButton);
                    }

                    // Add raw EVA tracking values
                    if (Config.DEBUG_SHOW_EVA)
                    {
                        kerbalCells.Add(emptyLabel);
                        kerbalCells.Add(elems.evaLS_Value);
                        kerbalCells.Add(elems.evaProp);
                        kerbalCells.Add(emptyLabel);
                    }
                }

                vert.AddChild(
                    new DialogGUIGridLayout(new RectOffset(),
                                            new Vector2(cellWidth, 20),
                                            Vector2.zero,
                                            UnityEngine.UI.GridLayoutGroup.Corner.UpperLeft,
                                            UnityEngine.UI.GridLayoutGroup.Axis.Horizontal,
                                            TextAnchor.MiddleLeft,
                                            UnityEngine.UI.GridLayoutGroup.Constraint.FixedColumnCount,
                                            compress ? 2 : 4,
                                            kerbalCells.ToArray()));
            }

            if (emptyPartLabels.Count > 0 && !compress)
            {
                vert.AddChild(new DialogGUISpace(20));

                foreach (Part part in emptyPartLabels.Keys)
                {
                    vert.AddChild(
                        new DialogGUIGridLayout(new RectOffset(),
                                                new Vector2(cellWidth * 2, 20),
                                                Vector2.zero,
                                                UnityEngine.UI.GridLayoutGroup.Corner.UpperLeft,
                                                UnityEngine.UI.GridLayoutGroup.Axis.Horizontal,
                                                TextAnchor.MiddleLeft,
                                                UnityEngine.UI.GridLayoutGroup.Constraint.FixedColumnCount, 2,
                                                new DialogGUILabel($"{ORANGE}{part.partInfo.title}</color>"),
                                                emptyPartLabels[part]
                                                ));
                }
            }

            // How can the SizeUp() -> RefreshGUI() -> OnButtonTrue() dependency
            // be altered to make these fields static, so that they don't have
            // to be re-initialized each time?
            sizeUpButton   = new DialogGUIButton("+", SizeUp, CanSizeUp, buttonHeight, buttonHeight, false);
            sizeDownButton = new DialogGUIButton("-", SizeDown, CanSizeDown, buttonHeight, buttonHeight, false);

            DialogGUIToggleButton compressButton = new DialogGUIToggleButton(
                compress, "Minimize", ToggleCompressGUI, w: 70, h: buttonHeight);
            DialogGUIHorizontalLayout compressLayout = new DialogGUIHorizontalLayout(
                false, true, 0f, noOffset, TextAnchor.MiddleLeft,
                compressButton, sizeDownButton, sizeUpButton);

            riskToggle = new DialogGUIToggle(
                EVALifeSupportTracker.AllowUnsafeActivity,
                "Allow unsafe crew transfer",
                RiskButtonSelected);
            riskLayout = new DialogGUIHorizontalLayout(
                0f, 0f, 0f, noOffset, TextAnchor.MiddleLeft,
                riskToggle);

            // Define the header which contains additional info
            // (status, Consumables)
            DialogGUIGridLayout statusGrid =
                new DialogGUIGridLayout(noOffset,
                                        new Vector2(cellWidth * (compress ? 1 : 2), 25),
                                        Vector2.zero,
                                        UnityEngine.UI.GridLayoutGroup.Corner.UpperLeft,
                                        UnityEngine.UI.GridLayoutGroup.Axis.Horizontal,
                                        TextAnchor.MiddleLeft,
                                        UnityEngine.UI.GridLayoutGroup.Constraint.FixedColumnCount, 2,
                                        statusLabel, compressLayout);

            // Contains the statusGrid and the "unsafe" toggle
            DialogGUIGridLayout masterGrid =
                new DialogGUIGridLayout(statusOffset,
                                        new Vector2(cellWidth * (compress ? 2 : 4), 25),
                                        new Vector2(0f, 5f),
                                        UnityEngine.UI.GridLayoutGroup.Corner.UpperLeft,
                                        UnityEngine.UI.GridLayoutGroup.Axis.Horizontal,
                                        TextAnchor.MiddleLeft,
                                        UnityEngine.UI.GridLayoutGroup.Constraint.FixedColumnCount, 1,
                                        statusGrid, riskLayout);

            // Set up the pop window
            size.x = compress ? 270 : 470;
            MultiOptionDialog multi = new MultiOptionDialog(
                "lifesupport_readout",
                "",
                "LifeSupport Readout",
                UISkinManager.defaultSkin,
                new Rect(position, size),
                masterGrid,
                new DialogGUIScrollList(Vector2.zero, false, true,
                                        new DialogGUIVerticalLayout(false, false, 1f,
                                                                    offset, TextAnchor.UpperLeft,
                                                                    new DialogGUIContentSizer(
                                                                        UnityEngine.UI.ContentSizeFitter.FitMode.Unconstrained,
                                                                        UnityEngine.UI.ContentSizeFitter.FitMode.PreferredSize,
                                                                        true),
                                                                    vert)));

            gui = PopupDialog.SpawnPopupDialog(
                multi,
                false,
                UISkinManager.defaultSkin,
                false,
                "");

            showgui = true;
            drewgui = false;
        }
Esempio n. 30
0
        public override void OnLoad(ConfigNode node)
        {
            try
            {
                base.OnLoad(node);
                LoadTree();

                if (Utilities.CurrentGameIsMission())
                {
                    return;
                }

                KCTDebug.Log("Reading from persistence.");
                KCTGameStates.KSCs.Clear();
                KCTGameStates.ActiveKSC = null;
                KCTGameStates.InitAndClearTechList();
                KCTGameStates.TechUpgradesTotal = 0;
                KCTGameStates.SciPointsTotal    = -1;
                KCT_GUI.ResetUpgradePointCounts();

                var kctVS = new KCT_DataStorage();
                if (node.GetNode(kctVS.GetType().Name) is ConfigNode cn)
                {
                    ConfigNode.LoadObjectFromConfig(kctVS, cn);
                }

                bool foundStockKSC = false;
                foreach (ConfigNode ksc in node.GetNodes("KSC"))
                {
                    string name       = ksc.GetValue("KSCName");
                    var    loaded_KSC = new KSCItem(name);
                    loaded_KSC.FromConfigNode(ksc);
                    if (loaded_KSC?.KSCName?.Length > 0)
                    {
                        loaded_KSC.RDUpgrades[1] = KCTGameStates.TechUpgradesTotal;
                        if (KCTGameStates.KSCs.Find(k => k.KSCName == loaded_KSC.KSCName) == null)
                        {
                            KCTGameStates.KSCs.Add(loaded_KSC);
                        }
                        foundStockKSC |= string.Equals(loaded_KSC.KSCName, Utilities._legacyDefaultKscId, StringComparison.OrdinalIgnoreCase);
                    }
                }

                Utilities.SetActiveKSCToRSS();
                if (foundStockKSC)
                {
                    TryMigrateStockKSC();
                }

                var protoTechNodes      = new Dictionary <string, ProtoTechNode>(); // list of all the protoTechNodes that have been researched
                var inDevProtoTechNodes = new Dictionary <string, ProtoTechNode>(); // list of all the protoTechNodes that are being researched

                // get the TechList node containing the TechItems with the tech nodes currently being researched from KCT's ConfigNode
                if (node.GetNode("TechList") is ConfigNode tmp)
                {
                    foreach (ConfigNode techNode in tmp.GetNodes("Tech"))
                    {
                        var techStorageItem = new KCT_TechStorageItem();
                        ConfigNode.LoadObjectFromConfig(techStorageItem, techNode);
                        TechItem techItem = techStorageItem.ToTechItem();
                        techItem.ProtoNode = new ProtoTechNode(techNode.GetNode("ProtoNode"));
                        KCTGameStates.TechList.Add(techItem);

                        // save proto nodes that are in development
                        inDevProtoTechNodes.Add(techItem.ProtoNode.techID, techItem.ProtoNode);
                    }
                }
                if (HighLogic.LoadedSceneIsEditor)
                {
                    // get the nodes that have been researched from ResearchAndDevelopment
                    protoTechNodes = Utilities.GetUnlockedProtoTechNodes();
                    // iterate through all loaded parts to check if any of them should be experimental
                    foreach (AvailablePart ap in PartLoader.LoadedPartsList)
                    {
                        if (Utilities.PartIsUnlockedButNotPurchased(protoTechNodes, ap) || inDevProtoTechNodes.ContainsKey(ap.TechRequired))
                        {
                            Utilities.AddExperimentalPart(ap);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                KCTGameStates.ErroredDuringOnLoad = true;
                Debug.LogError("[KCT] ERROR! An error while KCT loading data occurred. Things will be seriously broken!");
                PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), "errorPopup", "Error Loading KCT Data", "ERROR! An error occurred while loading KCT data. Things will be seriously broken! Please report this error to LRTR GitHub and attach the log file. The game will be UNPLAYABLE in this state!", "Understood", false, HighLogic.UISkin);
            }
        }