private bool PartModuleCheck(Part p, ConfigNode.Value v)
        {
            foreach (PartModule pm in p.Modules)
            {
                if (v.name == "name")
                {
                    if (pm.moduleName == v.value)
                    {
                        return(true);
                    }
                }
                else if (v.name == "EngineType")
                {
                    ModuleEngines me = pm as ModuleEngines;
                    return(me != null && me.engineType.ToString() == v.value);
                }

                foreach (BaseField field in pm.Fields)
                {
                    if (field != null && field.name == v.name && field.originalValue != null && field.originalValue.ToString() == v.value)
                    {
                        return(true);
                    }
                }
            }
            return(false);
        }
Beispiel #2
0
        void AddResourcesToPotentialReactions(ConfigNode reactantNode)
        {
            if (reactantNode == null)
            {
                return;
            }

            PartResourceDefinitionList resourceDefinitions = PartResourceLibrary.Instance.resourceDefinitions;

            for (int j = 0; j < reactantNode.values.Count; ++j)
            {
                ConfigNode.Value v = reactantNode.values[j];
                if (v.name != "resource")
                {
                    continue;
                }

                string resString = v.value;
                if (resourceDefinitions.Contains(resString))
                {
                    PartResourceDefinition p = resourceDefinitions[resString];

                    if (reactantPotentialReactions.ContainsKey(p.id))
                    {
                        continue;
                    }

                    Debug.Log("[Blastwave]: Adding " + p.name + " as possible reactant");
                    reactantPotentialReactions.Add(p.id, new HashSet <ExplosiveReaction>());
                }
            }
        }
Beispiel #3
0
        public IRCConfig()
        {
            ConfigNode settingsConfigNode = ConfigNode.Load(settingsFile) ?? new ConfigNode();

            ConfigNode.LoadObjectFromConfig(this, settingsConfigNode);

            for (int ix = 0; ix < settingsConfigNode.values.Count; ix++)
            {
                ConfigNode.Value node = settingsConfigNode.values[ix];

                if (node.name.StartsWith("rect-"))
                {
                    string[] elements = node.value.Split(',');
                    if (elements.Length == 4)
                    {
                        string name = node.name.Substring("rect-".Length);

                        float left   = float.Parse(elements[0]);
                        float top    = float.Parse(elements[1]);
                        float width  = float.Parse(elements[2]);
                        float height = float.Parse(elements[3]);

                        Rect rectValue = new Rect(left, top, width, height);

                        this.windowRects[name] = rectValue;
                    }
                }
            }
        }
        public override void OnLoad(ConfigNode gameNode)
        {
            try
            {
                UnityEngine.Debug.Log(string.Format("Scenario content to be read:\n{0}", gameNode));

                //Other variables
                for (int i = 0; i < gameNode.values.Count; i++)
                {
                    ConfigNode.Value value = gameNode.values[i];
                    string           name  = value.name;
                    switch (name)
                    {
                    case "DisplayModeTracking":
                        CNVCommNetUI.CustomModeTrackingStation = (CNVCommNetUI.CustomDisplayMode)((int)Enum.Parse(typeof(CNVCommNetUI.CustomDisplayMode), value.value));
                        break;

                    case "DisplayModeFlight":
                        CNVCommNetUI.CustomModeFlightMap = (CNVCommNetUI.CustomDisplayMode)((int)Enum.Parse(typeof(CNVCommNetUI.CustomDisplayMode), value.value));
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                UnityEngine.Debug.LogError(string.Format("Error when loading CNVCommNetScenario: {0}", e.Message));
            }
        }
Beispiel #5
0
 private static bool CompareRecursive(ConfigNode expectNode, ConfigNode gotNode)
 {
     if (expectNode.values.Count != gotNode.values.Count || expectNode.nodes.Count != gotNode.nodes.Count)
     {
         return(false);
     }
     for (int i = 0; i < expectNode.values.Count; ++i)
     {
         ConfigNode.Value eVal = expectNode.values[i];
         ConfigNode.Value gVal = gotNode.values[i];
         if (eVal.name != gVal.name || eVal.value != gVal.value)
         {
             return(false);
         }
     }
     for (int i = 0; i < expectNode.nodes.Count; ++i)
     {
         ConfigNode eNode = expectNode.nodes[i];
         ConfigNode gNode = gotNode.nodes[i];
         if (!CompareRecursive(eNode, gNode))
         {
             return(false);
         }
     }
     return(true);
 }
Beispiel #6
0
 /// <summary>
 /// This gets called once at game load time, from the Loader class in this mod. We load our kerbal
 /// colors from this. It's assumed that it has one key for each kerbal class, whose value is the
 /// default ColorSource value to use for that class.  If there's a kerbal class that doesn't have
 /// a corresponding entry here, then it will get displayed with the "Unknown" color.
 /// </summary>
 /// <param name="config"></param>
 public static void LoadConfig(ConfigNode config)
 {
     // Read in all the configs.
     _kerbalClassColorDefaults = new Dictionary <string, string>();
     for (int i = 0; i < config.values.Count; ++i)
     {
         ConfigNode.Value entry = config.values[i];
         if (Kerbals.Classes.Contains(entry.name) || KERBAL_CLASS_UNKNOWN.Equals(entry.name))
         {
             if (string.IsNullOrEmpty(entry.value))
             {
                 Logging.Warn(config.name + " config: No value specified for class " + entry.name + ", skipping");
                 continue;
             }
             try
             {
                 ColorSources.Validate(entry.value);
             }
             catch (ArgumentException e)
             {
                 Logging.Warn(config.name + " config: Invalid value '" + entry.value + "' for class " + entry.name + ", skipping. " + e.Message);
                 continue;
             }
             Logging.Log(config.name + " config: " + entry.name + " = " + entry.value);
             _kerbalClassColorDefaults.Add(entry.name, entry.value);
         }
         else
         {
             Logging.Warn(config.name + " config: No such class '" + entry.name + "' exists, skipping");
             continue;
         }
     }
 }
 public Ingredient(ConfigNode.Value ingredient)
 {
     name = ingredient.name;
     if (!double.TryParse(ingredient.value, out ratio))
     {
         ratio = 0;
     }
 }
Beispiel #8
0
 public Ingredient(ConfigNode.Value ingredient)
 {
     Name = ingredient.name;
     if (double.TryParse(ingredient.value, out Ratio) == false)
     {
         Ratio = 0;
     }
 }
Beispiel #9
0
        private void SanitizeNode(string partName, ConfigNode module, ConfigNode[] templates)
        {
            string name = module.GetValue("name");

            if (module.HasNode("ScienceData"))
            {
                module.RemoveNodes("ScienceData");
            }
            if (name == "Log")
            {
                module.ClearValues();
            }

            ConfigNode template = templates.FirstOrDefault(t => t.GetValue("name") == name && (!t.HasValue("parts") || t.GetValue("parts").Split(',').Contains(partName)));

            if (template == null)
            {
                return;
            }
            //ConfigNode.ValueList values = template.values;
            //for (int i = values.Count - 1; i >= 0; i--)
            //{
            //    ConfigNode.Value val = values[i];

            foreach (ConfigNode.Value val in template.values)
            {
                module.SetValue(val.name, val.value);
            }

            //ConfigNode[] nodes = template.GetNodes();
            //for (int i = nodes.Length -1; i >= 0; i--)
            //{
            //    ConfigNode node = nodes[i];
            foreach (ConfigNode node in template.GetNodes()) //This should account for nested nodes, like RealChutes' PARACHUTE node
            {
                if (module.HasNode(node.name))
                {
                    for (int i1 = node.values.Count - 1; i1 >= 0; i1--)
                    {
                        ConfigNode.Value val = node.values[i1];
                        //foreach (ConfigNode.Value val in node.values)
                        module.GetNode(node.name).SetValue(val.name, val.value);
                    }
                }
            }

            //nodes = module.GetNodes("MODULE");
            //for (int i = nodes.Count() - 1; i >= 0; i--)
            //{
            //    ConfigNode node = nodes[i];

            foreach (ConfigNode node in module.GetNodes("MODULE"))
            {
                SanitizeNode(partName, node, templates);
            }
            //}
        }
 /// <summary>
 /// Here when the game is loading on startup, assuming that the config node is
 /// actually present.
 /// </summary>
 /// <param name="config"></param>
 public static void LoadConfig(ConfigNode config)
 {
     for (int i = 0; i < config.values.Count; ++i)
     {
         ConfigNode.Value entry = config.values[i];
         Logging.Log("Primary info format: " + entry.name + " -> " + entry.value);
         formatByResourcesId[entry.name] = entry.value;
     }
 }
Beispiel #11
0
        protected override bool transform_value(ConfigNode.Value val, out int value)
        {
            value = 0;
            var res = PartResourceLibrary.Instance.GetDefinition(val.value);

            if (res != null)
            {
                value = res.id;
                return(true);
            }
            return(false);
        }
Beispiel #12
0
        public emttr(ConfigNode.Value cnv)
        {
            name  = cnv.name;
            scale = 1;

            string[] scs = cnv.value.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            clrs = new Color[5];

            for (byte x = 0; x < 5; x++)
            {
                clrs[x] = ConfigNode.ParseColor(x > scs.Length - 1 ? "1,1,1" : scs[x] + "," + Mathf.Clamp(6f / x - 1.25f, 0f, 1f).ToString());                  // Yes it's lame to convert to a string just to convert it back to a float, but I don't care
            }
        }
 public override void OnLoad(ConfigNode node)
 {
     for (int i = 0; i < node.values.Count; i++)
     {
         ConfigNode.Value v = node.values[i];
         if (v.name == "suffix")
         {
             if (portSuffixes == null)
             {
                 portSuffixes = new List <string> ();
             }
             portSuffixes.Add(v.value);
         }
     }
 }
Beispiel #14
0
        void shValue(ConfigNode.Value value, int level)
        {
            if (value.value.Contains(findvalue) == false)
            {
                return;
            }
            if (value.value.Contains(fvalue) == false)
            {
                return;
            }
            GUI.Label(new Rect(5 + level * 30, h * 20, 140 - level * 30, 20), value.name);
            value.value = GUI.TextField(new Rect(140 + level * 30, h * 20, 450 - level * 30, 20), value.value);

            h++;
        }
Beispiel #15
0
        public static string WriteRootNode(ConfigNode node)
        {
            StringBuilder builder = new StringBuilder();

            //print("node.values.Count " + node.values.Count + " node.nodes.Count " + node.nodes.Count);
            for (int i = 0; i < node.values.Count; i++)
            {
                ConfigNode.Value item = node.values[i];
                builder.AppendLine(string.Concat(item.name, " = ", item.value));
            }
            for (int j = 0; j < node.nodes.Count; j++)
            {
                WriteNodeString(node.nodes[j], ref builder, string.Empty);
            }
            return(builder.ToString());
        }
Beispiel #16
0
        public static void WriteNodeString(ConfigNode node, ref StringBuilder builder, string indent)
        {
            builder.AppendLine(string.Concat(indent, node.name));
            builder.AppendLine(string.Concat(indent, "{"));
            string str = string.Concat(indent, "  ");

            for (int i = 0; i < node.values.Count; i++)
            {
                ConfigNode.Value item = node.values[i];
                builder.AppendLine(string.Concat(str, item.name, " = ", item.value));
            }
            for (int j = 0; j < node.nodes.Count; j++)
            {
                WriteNodeString(node, ref builder, str);
            }
            builder.AppendLine(string.Concat(indent, "}"));
        }
Beispiel #17
0
        // Borrowed from smokeScreen
        public static string WriteRootNode(ConfigNode node)
        {
            StringBuilder builder = new StringBuilder();

            //print("node.values.Count " + node.values.Count + " node.nodes.Count " + node.nodes.Count);
            for (int i = 0; i < node.values.Count; i++)
            {
                ConfigNode.Value item = node.values[i];
                //builder.AppendLine(string.Concat(item.name, " = ", item.value));
                builder.Append(string.Concat(item.name, " = ", item.value, "\n"));                 //not sure why but the default newLine character messes up the parsing
            }
            for (int j = 0; j < node.nodes.Count; j++)
            {
                WriteNodeString(node.nodes[j], ref builder, string.Empty);
            }
            return(builder.ToString());
        }
Beispiel #18
0
        void shValue(ConfigNode.Value value, int level)
        {
            if (value.value.Contains(findvalue) == false)
            {
                return;
            }
            if (value.value.Contains(fvalue) == false)
            {
                return;
            }
            GUI.Label(new Rect(5 + level * 30, h * 20, 140 - level * 30, 20), value.name);
            value.value = GUI.TextField(new Rect(140 + level * 30, h * 20, 450 - level * 30, 20), value.value);

            h++;
            if (isOut == true)
            {
                File.AppendAllText("GameData/DTS_zh/Debug.txt", "".PadRight(level * 4) + value.name + "\t" + value.value + "\r\n");
            }
        }
 /// <summary>
 /// Config-loader method.  This is called from the Loader class in this mod, once, at
 /// KSP startup.  It loads all necessary config from the relevant node, named above.
 /// </summary>
 /// <param name="config"></param>
 public static void LoadConfig(ConfigNode config)
 {
     Logging.Log("Loading naming rules");
     _namingRules = new List <KeyValuePair <string, VesselType> >();
     for (int i = 0; i < config.values.Count; ++i)
     {
         ConfigNode.Value rule = config.values[i];
         VesselType       vesselType;
         try
         {
             vesselType = (VesselType)Enum.Parse(typeof(VesselType), rule.name);
         }
         catch (ArgumentException)
         {
             Logging.Error(CONFIG_NODE_NAME + " config: Invalid vessel type '" + rule.name + "' specified, skipping");
             continue;
         }
         string matchString = Canonicalize(rule.value);
         Logging.Log(rule.name + " = '" + matchString + "'");
         _namingRules.Add(new KeyValuePair <string, VesselType>(matchString, vesselType));
     }
 }
Beispiel #20
0
        /// <summary>
        /// Here when the scenario is loading. It's called after the other stock
        /// info is loaded.
        /// </summary>
        /// <param name="node"></param>
        public override void OnLoad(ConfigNode node)
        {
            base.OnLoad(node);

            defaultVariants = new Dictionary <string, string>();

            // Populate our default variants from the config node.
            for (int i = 0; i < node.values.Count; ++i)
            {
                ConfigNode.Value value = node.values[i];
                if (!value.name.StartsWith(PART_PREFIX))
                {
                    continue;
                }
                string tweakedPart     = value.name.Substring(PART_PREFIX.Length);
                string selectedVariant = value.value;
                Logging.Log("Loading default variant: " + tweakedPart + " = " + selectedVariant);
                defaultVariants.Add(tweakedPart, selectedVariant);
            }

            // Set our preferences on the loaded parts.
            InitializeParts();
        }
Beispiel #21
0
        public Ingredient(ConfigNode.Value ingredient)
        {
            name        = ingredient.name;
            discardable = name.EndsWith("*");
            if (discardable)
            {
                name = name.Substring(0, name.Length - 1);
            }
            ratio = 0;
            heat  = 0;
            string value  = ingredient.value;
            var    values = ParseExtensions.ParseArray(value, ',', ' ', '\t');

            if (values.Length > 0)
            {
                double.TryParse(values[0], out ratio);
            }
            if (values.Length > 1)
            {
                double.TryParse(values[1], out heat);
            }
            SetProperties();
        }
Beispiel #22
0
        List <KeyValuePair <double, Color> > Parse(ConfigNode node, List <KeyValuePair <double, Color> > defaultValue)
        {
            for (int i = 0; i < node?.values?.Count; i++)
            {
                ConfigNode.Value val = node.values[i];

                defaultValue = defaultValue ?? new List <KeyValuePair <double, Color> >();

                if (double.TryParse(val.name, out double alt) && TryParse.Color(val.value, out Color color))
                {
                    defaultValue.Add(new KeyValuePair <double, Color>(alt, color));
                }
                else
                {
                    defaultValue = null;
                    break;
                }

                defaultValue = defaultValue.OrderBy(v => v.Key).ToList();
            }

            return(defaultValue);
        }
        public static bool TryParseDustColour(ConfigNode.Value cfgVal, string bodyName, out Color loadedColour)
        {
            loadedColour = Color.clear;
            string colourString = cfgVal.value;

            string[] colourValues = colourString.Split(' ');
            if (colourValues.Length > 4)
            {
                Debug.LogWarning("[CollisionFX] Invalid colour definition in body \"" +
                                 bodyName + "\": Too many parameters.");
                return(false);
            }
            float        r, g, b, a;
            NumberStyles flags = NumberStyles.AllowDecimalPoint;

            if (!float.TryParse(colourValues[0], flags, CultureInfo.InvariantCulture, out r))
            {
                Debug.LogWarning("[CollisionFX] Invalid colour definition in body \"" +
                                 bodyName + "\": \"" + colourValues[0] + "\" is not a valid integer.");
                return(false);
            }
            if (!float.TryParse(colourValues[1], flags, CultureInfo.InvariantCulture, out g))
            {
                Debug.LogWarning("[CollisionFX] Invalid colour definition in body \"" +
                                 bodyName + "\": \"" + colourValues[1] + "\" is not a valid integer.");
                return(false);
            }
            if (!float.TryParse(colourValues[2], flags, CultureInfo.InvariantCulture, out b))
            {
                Debug.LogWarning("[CollisionFX] Invalid colour definition in body \"" +
                                 bodyName + "\": \"" + colourValues[2] + "\" is not a valid integer.");
                return(false);
            }

            // Allow using the value ranges 0.0 -> 1.0 and 0 -> 255.
            // Determine whether there are any numbers after a decimal point.
            if (r % 1 == 0)
            {
                r /= 255f;
            }
            if (g % 1 == 0)
            {
                g /= 255f;
            }
            if (b % 1 == 0)
            {
                b /= 255f;
            }

            if (colourValues.Length == 4)
            {
                if (!float.TryParse(colourValues[3], flags, CultureInfo.InvariantCulture, out a))
                {
                    Debug.LogWarning("[CollisionFX] Invalid colour definition in body \"" +
                                     bodyName + "\": \"" + colourValues[3] + "\" is not a valid integer.");
                    return(false);
                }
                if (a % 1 == 0)
                {
                    a /= 255;
                }
                loadedColour = new Color(r, g, b, a);
            }
            else
            {
                loadedColour = new Color(r, g, b);
            }

            return(true);
        }
Beispiel #24
0
 private void AssertValue(string name, string value, ConfigNode.Value nodeValue)
 {
     Assert.Equal(name, nodeValue.name);
     Assert.Equal(value, nodeValue.value);
 }
Beispiel #25
0
        /// <summary>
        /// Load our assets through the asset bundle system.
        /// </summary>
        private void LoadAssets()
        {
            StringBuilder sb = StringBuilderCache.Acquire();

            sb.Append("file://").Append(KSPUtil.ApplicationRootPath).Append("GameData/MOARdV/AvionicsSystems/mas-{0}.assetbundle");
            string assetFormat = sb.ToStringAndRelease();

            string platform = string.Empty;

            switch (Application.platform)
            {
            case RuntimePlatform.LinuxPlayer:
                platform = "linux";
                break;

            case RuntimePlatform.OSXPlayer:
                platform = "osx";
                break;

            case RuntimePlatform.WindowsPlayer:
                platform = "windows";
                break;

            default:
                Utility.LogError(this, "Unsupported/unexpected platform {0}", Application.platform);
                return;
            }

            shaders.Clear();
            AssetBundle bundle = LoadAssetBundle(assetFormat, platform);

            if (bundle == null)
            {
                return;
            }

            string[] assetNames = bundle.GetAllAssetNames();
            int      len        = assetNames.Length;

            Shader shader;

            for (int i = 0; i < len; i++)
            {
                if (assetNames[i].EndsWith(".shader"))
                {
                    shader = bundle.LoadAsset <Shader>(assetNames[i]);
                    if (!shader.isSupported)
                    {
                        Utility.LogError(this, "Shader {0} - unsupported in this configuration", shader.name);
                    }
                    shaders[shader.name] = shader;
                }
            }

            bundle.Unload(false);

            fonts.Clear();
            bundle = LoadAssetBundle(assetFormat, "font");
            if (bundle == null)
            {
                return;
            }

            assetNames = bundle.GetAllAssetNames();
            len        = assetNames.Length;

            Font font;

            for (int i = 0; i < len; i++)
            {
                if (assetNames[i].EndsWith(".ttf"))
                {
                    font = bundle.LoadAsset <Font>(assetNames[i]);

                    string[] fnames = font.fontNames;
                    if (fnames.Length == 0)
                    {
                        Utility.LogError(this, "Font {0} - did not find fontName.", font.name);
                    }
                    else
                    {
                        if (fonts.ContainsKey(fnames[0]))
                        {
                            // TODO: Do I need to keep all of the fonts in this dictionary?  Or is one
                            // adequate?
                            fonts[fnames[0]].Add(font);
                        }
                        else
                        {
                            Utility.LogMessage(this, "Adding font \"{0}\" from asset bundle.", fnames[0]);
                            List <Font> fontList = new List <Font>();
                            fontList.Add(font);
                            fonts[fnames[0]] = fontList;
                        }
                    }
                }
            }
            bundle.Unload(false);

            Utility.LogInfo(this, "Found {0} RPM shaders and {1} fonts.", shaders.Count, fonts.Count);

            // User fonts.  We put them here to make sure that internal
            // shaders exist already.
            ConfigNode[] masBitmapFont = GameDatabase.Instance.GetConfigNodes("MAS_BITMAP_FONT");
            for (int masFontIdx = 0; masFontIdx < masBitmapFont.Length; ++masFontIdx)
            {
                LoadBitmapFont(masBitmapFont[masFontIdx]);
            }

            // Generate our list of radio navigation beacons.
            navaids.Clear();
            ConfigNode[] navaidGroupNode = GameDatabase.Instance.GetConfigNodes("MAS_NAVAID");
            for (int navaidGroupIdx = 0; navaidGroupIdx < navaidGroupNode.Length; ++navaidGroupIdx)
            {
                ConfigNode[] navaidNode = navaidGroupNode[navaidGroupIdx].GetNodes("NAVAID");
                for (int navaidIdx = 0; navaidIdx < navaidNode.Length; ++navaidIdx)
                {
                    bool   canAdd = true;
                    NavAid navaid = new NavAid();
                    navaid.maximumRange    = -1.0;
                    navaid.maximumRangeDME = -1.0;

                    navaid.name = string.Empty;
                    if (!navaidNode[navaidIdx].TryGetValue("name", ref navaid.name))
                    {
                        Utility.LogError(this, "Did not get 'name' for NAVAID");
                        canAdd = false;
                    }

                    navaid.identifier = string.Empty;
                    if (!navaidNode[navaidIdx].TryGetValue("id", ref navaid.identifier))
                    {
                        Utility.LogError(this, "Did not get 'id' for NAVAID {0}", navaid.name);
                        canAdd = false;
                    }

                    navaid.celestialName = string.Empty;
                    if (!navaidNode[navaidIdx].TryGetValue("celestialName", ref navaid.celestialName))
                    {
                        Utility.LogError(this, "Did not get 'celestialName' for NAVAID {0}", navaid.name);
                        canAdd = false;
                    }

                    navaid.frequency = 0.0f;
                    if (!navaidNode[navaidIdx].TryGetValue("frequency", ref navaid.frequency))
                    {
                        Utility.LogError(this, "Did not get 'frequency' for NAVAID {0}", navaid.name);
                        canAdd = false;
                    }

                    navaid.latitude = 0.0;
                    if (!navaidNode[navaidIdx].TryGetValue("latitude", ref navaid.latitude))
                    {
                        Utility.LogError(this, "Did not get 'latitude' for NAVAID {0}", navaid.name);
                        canAdd = false;
                    }

                    navaid.longitude = 0.0;
                    if (!navaidNode[navaidIdx].TryGetValue("longitude", ref navaid.longitude))
                    {
                        Utility.LogError(this, "Did not get 'longitude' for NAVAID {0}", navaid.name);
                        canAdd = false;
                    }

                    navaid.altitude = 0.0;
                    if (!navaidNode[navaidIdx].TryGetValue("altitude", ref navaid.altitude))
                    {
                        Utility.LogError(this, "Did not get 'altitude' for NAVAID {0}", navaid.name);
                        canAdd = false;
                    }

                    string type = string.Empty;
                    if (!navaidNode[navaidIdx].TryGetValue("type", ref type))
                    {
                        Utility.LogError(this, "Did not get 'type' for NAVAID {0}", navaid.name);
                        canAdd = false;
                    }
                    switch (type)
                    {
                    case "NDB":
                        navaid.type = NavAidType.NDB;
                        break;

                    case "NDB DME":
                        navaid.type = NavAidType.NDB_DME;
                        break;

                    case "VOR":
                        navaid.type = NavAidType.VOR;
                        break;

                    case "VOR DME":
                        navaid.type = NavAidType.VOR_DME;
                        break;

                    case "ILS":
                        navaid.type = NavAidType.ILS;
                        break;

                    case "ILS DME":
                        navaid.type = NavAidType.ILS_DME;
                        break;

                    default:
                        Utility.LogError(this, "Did not get valid 'type' for NAVAID {0}", navaid.name);
                        canAdd = false;
                        break;
                    }

                    navaid.maximumRangeLocalizer = 0.0;
                    navaid.maximumRangeGlidePath = 0.0;
                    navaid.glidePathDefault      = 3.0;
                    navaid.approachHeadingILS    = 0.0f;
                    navaid.localizerSectorILS    = 0.0f;
                    if (navaid.type == NavAidType.ILS || navaid.type == NavAidType.ILS_DME)
                    {
                        if (!navaidNode[navaidIdx].TryGetValue("maximumRangeLocalizer", ref navaid.maximumRangeLocalizer))
                        {
                            Utility.LogError(this, "Did not get 'maximumRangeLocalizer' for {1} {0}", navaid.name, navaid.type);
                            canAdd = false;
                        }
                        if (!navaidNode[navaidIdx].TryGetValue("maximumRangeGlidePath", ref navaid.maximumRangeGlidePath))
                        {
                            Utility.LogError(this, "Did not get 'maximumRangeGlidePath' for {1} {0}", navaid.name, navaid.type);
                            canAdd = false;
                        }
                        if (!navaidNode[navaidIdx].TryGetValue("glidePathDefault", ref navaid.glidePathDefault))
                        {
                            Utility.LogError(this, "Did not get 'glidePathDefault' for {1} {0}", navaid.name, navaid.type);
                            canAdd = false;
                        }
                        if (!navaidNode[navaidIdx].TryGetValue("approachHeadingILS", ref navaid.approachHeadingILS))
                        {
                            Utility.LogError(this, "Did not get 'approachBearingILS' for {1} {0}", navaid.name, navaid.type);
                            canAdd = false;
                        }
                        if (!navaidNode[navaidIdx].TryGetValue("localizerSectorILS", ref navaid.localizerSectorILS))
                        {
                            Utility.LogError(this, "Did not get 'horizontalSectorILS' for {1} {0}", navaid.name, navaid.type);
                            canAdd = false;
                        }
                    }

                    if (canAdd)
                    {
                        navaids.Add(navaid);
                    }
                }
            }

            morseCode.Clear();
            ConfigNode[] morseCodeNode = GameDatabase.Instance.GetConfigNodes("MAS_MORSE_CODE");
            for (int morseCodeGroupIdx = 0; morseCodeGroupIdx < morseCodeNode.Length; ++morseCodeGroupIdx)
            {
                int numEntries = morseCodeNode[morseCodeGroupIdx].CountValues;
                for (int entry = 0; entry < numEntries; ++entry)
                {
                    ConfigNode.Value val = morseCodeNode[morseCodeGroupIdx].values[entry];
                    if (val.name.Length > 1)
                    {
                        Utility.LogError(this, "Got an invalid morse code of '{0}'", val.name);
                    }
                    else
                    {
                        AudioClip clip = GameDatabase.Instance.GetAudioClip(val.value);
                        if (clip == null)
                        {
                            Utility.LogError(this, "Could not load audio clip {0} for morse code '{1}", val.value, val.name);
                        }
                        else
                        {
                            morseCode[val.value[0]] = clip;
                        }
                    }
                }
            }

            subPages.Clear();
            ConfigNode[] subPageNode = GameDatabase.Instance.GetConfigNodes("MAS_SUB_PAGE");
            for (int subPageIdx = 0; subPageIdx < subPageNode.Length; ++subPageIdx)
            {
                string subPageName = string.Empty;
                if (subPageNode[subPageIdx].TryGetValue("name", ref subPageName))
                {
                    List <ConfigNode> subPageNodes = new List <ConfigNode>();
                    ConfigNode[]      nodes        = subPageNode[subPageIdx].GetNodes();

                    subPageNodes.AddRange(nodes);

                    subPages.Add(subPageName, subPageNodes);
                }
                else
                {
                    Utility.LogError(this, "Found a MAS_SUB_PAGE missing 'name'.  Skipping.");
                }
            }
        }
        public override void OnLoad(ConfigNode gameNode)
        {
            try
            {
                CNCLog.Verbose("Scenario content to be read:\n{0}", gameNode);

                //Other variables
                for (int i = 0; i < gameNode.values.Count; i++)
                {
                    ConfigNode.Value value = gameNode.values[i];
                    string           name  = value.name;
                    switch (name)
                    {
                    case "DisplayModeTracking":
                        CNCCommNetUI.CustomModeTrackingStation = (CNCCommNetUI.CustomDisplayMode)((int)Enum.Parse(typeof(CNCCommNetUI.CustomDisplayMode), value.value));
                        break;

                    case "DisplayModeFlight":
                        CNCCommNetUI.CustomModeFlightMap = (CNCCommNetUI.CustomDisplayMode)((int)Enum.Parse(typeof(CNCCommNetUI.CustomDisplayMode), value.value));
                        break;

                    case "HideGroundStations":
                        this.hideGroundStations = Boolean.Parse(value.value);
                        break;
                    }
                }

                //Constellations
                if (gameNode.HasNode("Constellations"))
                {
                    ConfigNode   constellationNode  = gameNode.GetNode("Constellations");
                    ConfigNode[] constellationNodes = constellationNode.GetNodes();

                    if (constellationNodes.Length < 1) // missing constellation list
                    {
                        CNCLog.Error("The 'Constellations' node is malformed! Reverted to the default constellation list.");
                        constellations = CNCSettings.Instance.Constellations;
                    }
                    else
                    {
                        constellations.Clear();
                        for (int i = 0; i < constellationNodes.Length; i++)
                        {
                            Constellation newConstellation = new Constellation();
                            ConfigNode.LoadObjectFromConfig(newConstellation, constellationNodes[i]);
                            constellations.Add(newConstellation);
                        }
                    }
                }
                else
                {
                    CNCLog.Verbose("The 'Constellations' node is not found. The default constellation list is loaded.");
                    constellations = CNCSettings.Instance.Constellations;
                }

                constellations.Sort();

                //Ground stations
                if (gameNode.HasNode("GroundStations"))
                {
                    ConfigNode   stationNode  = gameNode.GetNode("GroundStations");
                    ConfigNode[] stationNodes = stationNode.GetNodes();

                    if (stationNodes.Length < 1) // missing ground-station list
                    {
                        CNCLog.Error("The 'GroundStations' node is malformed! Reverted to the default list of ground stations.");
                        persistentGroundStations = CNCSettings.Instance.GroundStations;
                    }
                    else
                    {
                        persistentGroundStations.Clear();
                        for (int i = 0; i < stationNodes.Length; i++)
                        {
                            CNCCommNetHome dummyGroundStation = new CNCCommNetHome();
                            ConfigNode.LoadObjectFromConfig(dummyGroundStation, stationNodes[i]);
                            if (!stationNodes[i].HasNode("Frequencies")) // empty list is not saved as empty node in persistent.sfs
                            {
                                dummyGroundStation.deleteFrequencies();  // clear the default frequency list
                            }
                            persistentGroundStations.Add(dummyGroundStation);
                        }
                    }
                }
                else
                {
                    CNCLog.Verbose("The 'GroundStations' node is not found. The default list of ground stations is loaded from KSP's data.");
                    persistentGroundStations = CNCSettings.Instance.GroundStations;
                }
            }
            catch (Exception e)
            {
                CNCLog.Error("Error when loading CNCCommNetScenario: {0}", e.Message);
            }
        }
        private void CheckNeedsRecursive(NodeStack nodeStack, UrlDir.UrlConfig urlConfig)
        {
            ConfigNode original = nodeStack.value;

            for (int i = 0; i < original.values.Count; ++i)
            {
                ConfigNode.Value val     = original.values[i];
                string           valname = val.name;
                try
                {
                    if (CheckNeedsName(ref valname))
                    {
                        val.name = valname;
                    }
                    else
                    {
                        original.values.Remove(val);
                        i--;
                        progress.NeedsUnsatisfiedValue(urlConfig, nodeStack.GetPath() + '/' + val.name);
                    }
                }
                catch (ArgumentOutOfRangeException e)
                {
                    progress.Exception("ArgumentOutOfRangeException in CheckNeeds for value \"" + val.name + "\"", e);
                    throw;
                }
                catch (Exception e)
                {
                    progress.Exception("General Exception in CheckNeeds for value \"" + val.name + "\"", e);
                    throw;
                }
            }

            for (int i = 0; i < original.nodes.Count; ++i)
            {
                ConfigNode node     = original.nodes[i];
                string     nodeName = node.name;

                if (nodeName == null)
                {
                    progress.Error(urlConfig, "Error - Node in file " + urlConfig.SafeUrl() + " subnode: " + nodeStack.GetPath() + " has config.name == null");
                }

                try
                {
                    if (CheckNeedsName(ref nodeName))
                    {
                        node.name = nodeName;
                        CheckNeedsRecursive(nodeStack.Push(node), urlConfig);
                    }
                    else
                    {
                        original.nodes.Remove(node);
                        i--;
                        progress.NeedsUnsatisfiedNode(urlConfig, nodeStack.GetPath() + '/' + node.name);
                    }
                }
                catch (ArgumentOutOfRangeException e)
                {
                    progress.Exception("ArgumentOutOfRangeException in CheckNeeds for node \"" + node.name + "\"", e);
                    throw;
                }
                catch (Exception e)
                {
                    progress.Exception("General Exception " + e.GetType().Name + " for node \"" + node.name + "\"", e);
                    throw;
                }
            }
        }
Beispiel #28
0
        public static ConfigNode DrawObjectSelector <T>(ConfigNode sourceNode, ref int selectedObjIndex, ref String objString, ref Vector2 objListPos, Rect placementBase, ref Rect placement, ConfigNode.Value filter = null)
        {
            List <ConfigNode> nodeList;

            if (filter != null)
            {
                nodeList = sourceNode.GetNodes(ConfigHelper.OBJECT_NODE, filter.name, filter.value).ToList();
            }
            else
            {
                nodeList = sourceNode.GetNodes().ToList();
            }

            string configName = ((ConfigName)Attribute.GetCustomAttribute(typeof(T), typeof(ConfigName))).Name;

            String[] objList              = nodeList.Select(node => node.GetValue(configName)).ToArray();
            float    nodeHeight           = placement.height;
            Rect     selectBoxOutlineRect = GetRect(placementBase, ref placement);

            placement.height = nodeHeight - 1;
            Rect selectBoxRect = GetRect(placementBase, ref placement);

            placement.height = nodeList.Count;
            Rect selectBoxItemsRect = GetRect(placementBase, ref placement);

            placement.height = 1;
            Rect optButtonRect = GetRect(placementBase, ref placement);

            SplitRect(ref selectBoxRect, ref optButtonRect, (15f / 16));


            GUI.Box(selectBoxOutlineRect, "");
            selectBoxRect.x      += 10;
            selectBoxRect.width  -= 20;
            selectBoxRect.y      += 10;
            selectBoxRect.height -= 20;

            selectBoxItemsRect.x = 0;
            selectBoxItemsRect.y = 0;
            if (nodeList.Count <= 3)
            {
                selectBoxItemsRect.width = selectBoxRect.width;
            }
            else
            {
                selectBoxItemsRect.width = selectBoxRect.width - 20;
            }

            objListPos = GUI.BeginScrollView(selectBoxRect, objListPos, selectBoxItemsRect);
            int oldselectedObjIndex = selectedObjIndex;

            if (selectedObjIndex == -1)
            {
                selectedObjIndex = 0;
            }
            selectedObjIndex = GUI.SelectionGrid(selectBoxItemsRect, selectedObjIndex, objList, 1);
            GUI.EndScrollView();
            placement.y += nodeHeight - 1;

            optButtonRect.x -= 5;
            optButtonRect.y += 10;
            if (nodeList.Count > 0)
            {
                if (GUI.Button(optButtonRect, UP_ARROW) && selectedObjIndex > 0)
                {
                    int        moveIndex = selectedObjIndex;
                    ConfigNode item      = nodeList[--selectedObjIndex];
                    nodeList.Remove(item);
                    nodeList.Add(item);
                    sourceNode.RemoveNode(item);
                    sourceNode.AddNode(item);
                    for (int i = moveIndex; i < nodeList.Count - 1; i++)
                    {
                        item = nodeList[moveIndex];
                        nodeList.Remove(item);
                        nodeList.Add(item);
                        sourceNode.RemoveNode(item);
                        sourceNode.AddNode(item);
                    }
                }
                optButtonRect.y += optButtonRect.height * (nodeHeight - 3);
                if (GUI.Button(optButtonRect, DOWN_ARROW) && selectedObjIndex < nodeList.Count - 1)
                {
                    ConfigNode item = nodeList[selectedObjIndex];
                    nodeList.Remove(item);
                    nodeList.Add(item);
                    sourceNode.RemoveNode(item);
                    sourceNode.AddNode(item);
                    int moveIndex = ++selectedObjIndex;
                    for (int i = moveIndex; i < nodeList.Count - 1; i++)
                    {
                        item = nodeList[moveIndex];
                        nodeList.Remove(item);
                        nodeList.Add(item);
                        sourceNode.RemoveNode(item);
                        sourceNode.AddNode(item);
                    }
                }
            }
            Rect listEditTextRect = GetRect(placementBase, ref placement);

            listEditTextRect.x     += 10;
            listEditTextRect.width -= 20;
            listEditTextRect.y     -= 5;

            Rect listEditRect   = new Rect(listEditTextRect);
            Rect listAddRect    = new Rect(listEditTextRect);
            Rect listRemoveRect = new Rect(listEditTextRect);

            SplitRect(ref listEditTextRect, ref listEditRect, (1f / 2));
            SplitRect(ref listEditRect, ref listAddRect, (1f / 3));
            SplitRect(ref listAddRect, ref listRemoveRect, (1f / 2));

            listEditTextRect.width -= 5;
            listEditRect.width     -= 5;
            listAddRect.width      -= 5;
            listRemoveRect.width   -= 5;

            if (selectedObjIndex != oldselectedObjIndex && nodeList.Count > 0)
            {
                objString = nodeList[selectedObjIndex].GetValue(configName);
            }
            objString = GUI.TextField(listEditTextRect, objString);
            String name = objString;

            if (objString.Length > 0 && !objString.Contains(' ') && !nodeList.Exists(n => n.GetValue(configName) == name))
            {
                if (nodeList.Count > 0 && GUI.Button(listEditRect, "#"))
                {
                    nodeList[selectedObjIndex].SetValue(configName, objString, true);
                }
                if (GUI.Button(listAddRect, "+"))
                {
                    ConfigNode newNode = new ConfigNode(ConfigHelper.OBJECT_NODE);
                    newNode.SetValue(configName, objString, true);
                    if (filter != null)
                    {
                        newNode.SetValue(filter.name, filter.value, true);
                    }
                    nodeList.Add(newNode);
                    sourceNode.AddNode(newNode);
                }
            }
            else
            {
                listEditRect.width += listAddRect.width;
                GUI.Label(listEditRect, "Invalid Name!");
            }
            if (nodeList.Count > 0 && GUI.Button(listRemoveRect, "-"))
            {
                ConfigNode item = nodeList[selectedObjIndex];
                nodeList.Remove(item);
                sourceNode.RemoveNode(item);
                if (selectedObjIndex >= nodeList.Count)
                {
                    selectedObjIndex = nodeList.Count - 1;
                }
            }
            placement.y += 1 + spacingOffset;

            if (nodeList.Count == 0)
            {
                return(null);
            }
            return(nodeList[selectedObjIndex]);
        }
        // Search for a value by a path alike string
        private static ConfigNode.Value RecurseVariableSearch(string path, ConfigNode currentNode)
        {
            //log("path:" + path);
            if (path[0] == '/')
                return RecurseVariableSearch(path.Substring(1), topNode);
            int nextSep = path.IndexOf('/');

            // make sure we don't stop on a ",/" which would be a value separator
            // it's a hack that should be replaced with a proper regex for the whole node search
            while (nextSep > 0 && path[nextSep - 1] == ',')
                nextSep = path.IndexOf('/', nextSep + 1);

            if (path[0] == '@')
            {
                if (nextSep < 2)
                    return null;

                string subName = path.Substring(1, nextSep - 1);
                string nodeType, nodeName;
                ConfigNode target = null;

                if (subName.Contains("["))
                {
                    // @NODETYPE[Name]/
                    nodeType = subName.Split('[')[0];
                    nodeName = subName.Split('[')[1].Replace("]", "");
                }
                else
                {
                    // @NODETYPE/
                    nodeType = subName;
                    nodeName = string.Empty;
                }

                ConfigNode[] list = GameDatabase.Instance.GetConfigNodes(nodeType);
                if (list.Length == 0)
                {
                    log("Can't find nodeType:" + nodeType);
                    return null;
                }

                if (nodeName == string.Empty)
                {
                    target = list[0];
                }
                else
                {
                    for (int i = 0; i < list.Length; i++)
                    {
                        if (list[i].HasValue("name") && WildcardMatch(list[i].GetValue("name"), nodeName))
                        {
                            target = list[i];
                            break;
                        }
                    }
                }
                return target != null ? RecurseVariableSearch(path.Substring(nextSep + 1), target) : null;
            }
            if (path.StartsWith("../"))
            {
                if (nodeStack.Count == 1)
                    return null;
                ConfigNode.Value result;
                ConfigNode top = nodeStack.Pop();
                try
                {
                    result = RecurseVariableSearch(path.Substring(3), nodeStack.Peek());
                }
                finally
                {
                    nodeStack.Push(top);
                }
                return result;
            }

            // Node search
            if (nextSep > 0 && path[nextSep - 1] != ',')
            {
                // Big case of code duplication here ...
                // TODO : replace with a regex

                string subName = path.Substring(0, nextSep);
                string constraint = "";
                string nodeType, nodeName;
                int index = 0;
                if (subName.Contains(":HAS["))
                {
                    int start = subName.IndexOf(":HAS[");
                    constraint = subName.Substring(start + 5, subName.LastIndexOf(']') - start - 5);
                    subName = subName.Substring(0, start);
                }
                else if (subName.Contains(","))
                {
                    string tag = subName.Split(',')[1];
                    subName = subName.Split(',')[0];
                    int.TryParse(tag, out index);
                }

                if (subName.Contains("["))
                {
                    // format NODETYPE[Name] {...}
                    // or NODETYPE[Name, index] {...}
                    nodeType = subName.Split('[')[0];
                    nodeName = subName.Split('[')[1].Replace("]", "");
                }
                else
                {
                    // format NODETYPE {...}
                    nodeType = subName;
                    nodeName = null;
                }

                if (constraint.Length > 0)
                {
                    // get the first one matching
                    ConfigNode last = null;
                    while (true)
                    {
                        ConfigNode n = FindConfigNodeIn(currentNode, nodeType, nodeName, index++);
                        if (n == last || n == null)
                            break;
                        if (CheckConstraints(n, constraint))
                            return RecurseVariableSearch(path.Substring(nextSep + 1), n);
                        last = n;
                    }
                    return null;
                }
                else
                {
                    // just get one node
                    ConfigNode n = FindConfigNodeIn(currentNode, nodeType, nodeName, index);
                    if (n != null)
                        return RecurseVariableSearch(path.Substring(nextSep + 1), n);
                    return null;
                }
            }

            // Value search

            Match match = parseVarKey.Match(path);
            if (!match.Success)
            {
                log("Cannot parse variable search command: " + path);
                return null;
            }

            string valName = match.Groups[1].Value;

            int idx = 0;
            if (match.Groups[2].Success)
                int.TryParse(match.Groups[2].Value, out idx);

            ConfigNode.Value cVal = FindValueIn(currentNode, valName, idx);
            if (cVal == null)
            {
                log("Cannot find key " + valName + " in " + currentNode.name);
                return null;
            }
            
            if (match.Groups[3].Success)
            {
                ConfigNode.Value newVal = new ConfigNode.Value(cVal.name, cVal.value);
                int splitIdx = 0;
                int.TryParse(match.Groups[3].Value, out splitIdx);

                char sep = ',';
                if (match.Groups[4].Success)
                    sep = match.Groups[4].Value[0];
                string[] split = newVal.value.Split(sep);
                if (splitIdx < split.Length)
                    newVal.value = split[splitIdx];
                else
                    newVal.value = "";
                return newVal;
            }
            return cVal;
        }
Beispiel #30
0
 protected abstract bool transform_value(ConfigNode.Value val, out T value);
Beispiel #31
0
 protected override bool transform_value(ConfigNode.Value val, out string value)
 {
     value = val.value;
     return(true);
 }