Example #1
0
 private static string getConfigStringFromNode(string[] keys, int keyIndex, JSONNode node, string modname)
 {
     try
     {
         if (keys.Length > 0 && keyIndex < keys.Length - 1)
         {
             if (node.HasChild(keys[keyIndex]))
             {
                 // has child
                 JSONNode c = new JSONNode(NodeType.Object);
                 c = node.GetAs <JSONNode>(keys[keyIndex]);
                 return(getConfigStringFromNode(keys, keyIndex + 1, c, modname));
             }
             else
             {
                 return("");
             }
         }
         else
         {
             return(node.GetAs <string>(keys[keyIndex]));
         }
     }
     catch (Exception exception)
     {
         Helpers.Utilities.WriteLog("ColonyAPI", "Error loading configuration (" + modname + "):" + keys.Length.ToString() + keyIndex.ToString() + exception.Message + exception.StackTrace);
         return("");
     }
 }
 private static bool getConfigBoolFromNode(string[] keys, int keyIndex, JSONNode node)
 {
     try
     {
         if (keys.Length > 0 && keyIndex < keys.Length - 1)
         {
             if (node.HasChild(keys[keyIndex]))
             {
                 // has child
                 JSONNode c = new JSONNode(NodeType.Object);
                 c = node.GetAs <JSONNode>(keys[keyIndex]);
                 return(getConfigBoolFromNode(keys, keyIndex + 1, c));
             }
             else
             {
                 return(false);
             }
         }
         else
         {
             return(node.GetAs <bool>(keys[keyIndex]));
         }
     }
     catch (Exception exception)
     {
         Utilities.WriteLog("Error getting configuration:" + keys[0] + keys.Length.ToString() + keyIndex.ToString() + exception.Message + exception.StackTrace);
         return(false);
     }
 }
Example #3
0
        private static JSONNode GetConfigNodeFromNode(string[] keys, int keyIndex, JSONNode node, string modname, string key)
        {
            try
            {
                if (keys.Length > 0 && keyIndex < keys.Length - 1)
                {
                    if (node.HasChild(keys[keyIndex]))
                    {
                        JSONNode c = new JSONNode(NodeType.Object);
                        c = node.GetAs <JSONNode>(keys[keyIndex]);
                        return(GetConfigNodeFromNode(keys, keyIndex + 1, c, modname, key));
                    }
                    else
                    {
                        return(new JSONNode(NodeType.Array));
                    }
                }
                else
                {
                    return(node.GetAs <JSONNode>(keys[keyIndex]));
                }
            }
            catch (Exception e)
            {
                Helpers.Logging.WriteLog(NewColonyAPIEntry.ModName,
                                         "Error loading configuration (" + modname + "): " + key + " - " + keyIndex.ToString() + "\n" + e.Message + "\n\n" + e.StackTrace, Helpers.Logging.LogType.Issue);

                Helpers.Logging.WriteLog(modname,
                                         "Error loading configuration (" + modname + "): " + key + " - " + keyIndex.ToString() + "\n" + e.Message + "\n\n" + e.StackTrace, Helpers.Logging.LogType.Issue, true, true);
                return(new JSONNode(NodeType.Array));
            }
        }
Example #4
0
        public static void SendMenu(Players.Player player, JSONNode json)
        {
            NetworkMenu menu = new NetworkMenu();

            json.TryGetAsOrDefault("header", out string header, "Title");
            menu.LocalStorage.SetAs("header", header);

            if (json.HasChild("width"))
            {
                menu.Width = json.GetAs <int>("width");
            }
            else
            {
                menu.Width = SettlersConfiguration.GetorDefault("MenuWidth", 1000);
            }

            if (json.HasChild("height"))
            {
                menu.Height = json.GetAs <int>("height");
            }
            else
            {
                menu.Height = SettlersConfiguration.GetorDefault("MenuHeight", 700);
            }

            foreach (JSONNode item in (json.GetAs <JSONNode>("Items")).LoopArray())
            {
                if (LoadItem(item, ref menu, player, out var menuItem))
                {
                    menu.Items.Add(menuItem);
                }
            }

            NetworkMenuManager.SendServerPopup(player, menu);
        }
Example #5
0
        static void RotateOffset(JSONNode node, string suffix)
        {
            Vector3 position = new Vector3(node.GetAs <float>("offsetx"), node.GetAs <float>("offsety"), node.GetAs <float>("offsetz"));

            switch (suffix)
            {
            case "x+":
                position = new Vector3(position.x, position.y, position.z);
                break;

            case "x-":
                position = new Vector3(-position.x, position.y, -position.z);
                break;

            case "z+":
                position = new Vector3(-position.z, position.y, position.x);
                break;

            case "z-":
                position = new Vector3(position.z, position.y, -position.x);
                break;

            default:
                Assert.IsTrue(false, "Suffix not x+, x-, z+ or z-");
                throw new System.ArgumentException();
            }
            node.SetAs("offsetx", position.x);
            node.SetAs("offsety", position.y);
            node.SetAs("offsetz", position.z);
        }
Example #6
0
        public Empire(JSONNode json)
        {
            Name = json.GetAs <string>("Name");
            Tag  = json.GetAsOrDefault <string>("Tag", "");

            //announcement = json.GetAs<string>("Announcement");
            automaticRequest = json.GetAs <bool>("automaticRequest");

            //Load Permissions
            int i = (int)Rank.Emperor;

            foreach (var permission in json.GetAs <JSONNode>("Permissions").LoopArray())
            {
                permissions[i++] = (Permissions)Enum.Parse(typeof(Permissions), permission.GetAs <string>());
            }

            //Load members
            foreach (var member in json.GetAs <JSONNode>("Members").LoopArray())
            {
                NetworkID nID  = NetworkID.Parse(member.GetAs <string>("ID"));
                Rank      rank = (Rank)Enum.Parse(typeof(Rank), member.GetAs <string>("Rank"));

                members.Add(nID, rank);
            }

            //Load Request
            foreach (var requests in json.GetAs <JSONNode>("Requests").LoopArray())
            {
                NetworkID nID = NetworkID.Parse(requests.GetAs <string>());
                joinRequest.Add(nID);
            }

            empires.Add(this);
        }
 public override ITrackableBlock InitializeFromJSON(Players.Player player, JSONNode node)
 {
     blockType = ItemTypes.IndexLookup.GetIndex(node.GetAs <string>("type"));
     InitializeJob(player, (Vector3Int)node["position"], node.GetAs <int>("npcID"));
     if (guardSettings == null)
     {
         guardSettings = SetupSettings();
     }
     return(this);
 }
        public override ITrackableBlock InitializeFromJSON(Players.Player player, JSONNode node)
        {
            blockInventory = new NPCInventory(node["inventory"]);
            storedFuel     = node.GetAs <float>("storedFuel");
            blockType      = ItemTypes.IndexLookup.GetIndex(node.GetAs <string>("type"));
            Vector3Int position = (Vector3Int)node["position"];

            positionNPC = GetPositionNPC(position);
            InitializeJob(player, position, node.GetAs <int>("npcID"));
            return(this);
        }
Example #9
0
        public override ITrackableBlock InitializeFromJSON(Players.Player player, JSONNode node)
        {
            typeBelow = ItemTypes.IndexLookup.GetOrGenerate(node.GetAs <string>("typeBelow"));
            JSONNode customDataNode = ItemTypes.GetType(typeBelow).CustomDataNode;

            if (customDataNode != null)
            {
                MiningCooldown = customDataNode.GetAsOrDefault("minerMiningTime", 8f);
            }
            InitializeJob(player, (Vector3Int)node["position"], node.GetAs <int>("npcID"));
            return(this);
        }
        public static string getConfigString(string key)
        {
            string[] keys = key.Split('.');

            if (keys.Length > 0)
            {
                return(getConfigStringFromNode(keys, 0, configSettings));
            }
            else
            {
                return(configSettings.GetAs <string>(key));
            }
        }
Example #11
0
 public static void localize(string locName, string locFilename, JSONNode jsonFromMod, string keyprefix, bool verbose)
 {
     try {
         string   patchPath = MultiPath.Combine("gamedata", "localization", locName, locFilename);
         JSONNode jsonToPatch;
         if (Pipliz.JSON.JSON.Deserialize(patchPath, out jsonToPatch, false))
         {
             foreach (KeyValuePair <string, JSONNode> entry in jsonFromMod.LoopObject())
             {
                 string realkey = keyprefix + entry.Key;
                 string val     = jsonFromMod.GetAs <string>(entry.Key);
                 if (!jsonToPatch.HasChild(realkey))
                 {
                     Pipliz.Log.Write(string.Format("translation '{0}' => '{1}' added to '{2}/{3}'. This will apply AFTER next restart!!!", realkey, val, locName, locFilename));
                 }
                 else if (!jsonToPatch.GetAs <string>(realkey).Equals(val))
                 {
                     Pipliz.Log.Write(string.Format("translation '{0}' => '{1}' changed in '{2}/{3}'. This will apply AFTER next restart!!!", realkey, val, locName, locFilename));
                 }
                 jsonToPatch.SetAs(realkey, val);
             }
             Pipliz.JSON.JSON.Serialize(patchPath, jsonToPatch);
             log(string.Format("Patched mod localization file '{0}/{1}' into '{2}'", locName, locFilename, patchPath), verbose);
         }
         else
         {
             log(string.Format("Could not deserialize json from '{0}'", patchPath), verbose);
         }
     } catch (Exception) {
         log(string.Format("Exception while localizing {0}", Path.Combine(locName, locFilename)), verbose);
     }
 }
Example #12
0
        public override ITrackableBlock InitializeFromJSON(Players.Player player, JSONNode node)
        {
            BlockInventory  = new NPCInventory(10000000f, node ["inventory"]);
            ShouldTakeItems = false;
            node.TryGetAs("shouldTakeItems", out ShouldTakeItems);
            Fullname = node.GetAs <string> ("fullname");
            JSONNode jsonTodos = node ["todoblocks"];

            Todoblocks = new List <BlueprintTodoBlock> ();
            foreach (JSONNode jsonBlock in jsonTodos.LoopArray())
            {
                Todoblocks.Add(new BlueprintTodoBlock(jsonBlock));
            }
            InitializeJob(player, (Vector3Int)node ["position"], node.GetAs <int> ("npcID"));
            return(this);
        }
 public override ITrackableBlock InitializeFromJSON(Players.Player player, JSONNode node)
 {
     blockType           = ItemTypes.IndexLookup.GetOrGenerate(node.GetAs <string>("type"));
     position            = (Vector3Int)node["position"];
     PreferedNPCPosition = GetPositionNPC(position);
     return(base.InitializeFromJSON(player, node));
 }
Example #14
0
        public static LabelData GetLabelData(JSONNode json)
        {
            json.TryGetAsOrDefault("text", out string text, "Text key not found");

            UnityEngine.Color      color      = UnityEngine.Color.black;
            UnityEngine.TextAnchor alignement = UnityEngine.TextAnchor.MiddleLeft;

            if (json.HasChild("color"))
            {
                color = GetColor(json.GetAs <string>("color"));
            }

            if (json.TryGetAs("alignement", out string alignementStr))
            {
                Enum.TryParse(alignementStr, true, out alignement);
            }

            json.TryGetAsOrDefault("fontsize", out int fontSize, 18);

            LabelData.ELocalizationType localizationType = LabelData.ELocalizationType.Sentence;

            if (json.TryGetAs("localizationType", out string localizationString) && Enum.TryParse(localizationString, true, out LabelData.ELocalizationType newLocalization))
            {
                localizationType = newLocalization;
            }

            return(new LabelData(text, color, alignement, fontSize, localizationType));
        }
Example #15
0
 public CrateInventory(JSONNode node, Colony c)
 {
     Colony            = c;
     Position          = (Vector3Int)node[nameof(Position)];
     CrateType         = StorageFactory.CrateTypes[node.GetAs <string>(nameof(CrateType))];
     Contents          = node[nameof(Contents)].JsonDeerialize <Dictionary <ushort, StoredItem> >();
     StorageTypeLookup = node[nameof(StorageTypeLookup)].JsonDeerialize <Dictionary <StorageType, List <StoredItem> > >();
 }
Example #16
0
 public static T getAsOrElse <T> (this JSONNode node, string identifier, string otherIdentifier)
 {
     if (!node.TryGetAs(identifier, out T result))
     {
         result = node.GetAs <T> (otherIdentifier);
     }
     return(result);
 }
Example #17
0
        private void AddMagicEffect(IPlayerMagicItem playerMagicItem)
        {
            _playerVariables.SetAs("MovePower", _playerVariables.GetAs <float>("MovePower") + playerMagicItem.MovementSpeed);
            _playerVariables.SetAs("JumpPower", _playerVariables.GetAs <float>("JumpPower") + playerMagicItem.JumpPower);
            _playerVariables.SetAs("FlySpeedBase", _playerVariables.GetAs <float>("FlySpeedBase") + playerMagicItem.FlySpeed);
            _playerVariables.SetAs("Gravity", _playerVariables.GetAs <float>("Gravity") + playerMagicItem.Gravity);

            var fallDmg = _playerVariables.GetAs <float>("FallDamageBaseDamage") + playerMagicItem.FallDamage;

            if (fallDmg < 0)
            {
                fallDmg = 0;
            }

            _playerVariables.SetAs("FallDamageBaseDamage", fallDmg);

            var falldmgUnit = _playerVariables.GetAs <float>("FallDamagePerUnit") + playerMagicItem.FallDamagePerUnit;

            if (falldmgUnit < 0)
            {
                falldmgUnit = 0;
            }

            _playerVariables.SetAs("FallDamagePerUnit", falldmgUnit);
            _playerVariables.SetAs("BuildDistance", _playerVariables.GetAs <float>("BuildDistance") + playerMagicItem.BuildDistance);
        }
Example #18
0
        private void AddMagicEffect(IPlayerMagicItem playerMagicItem)
        {
            if (!string.IsNullOrEmpty(playerMagicItem.LightColor) && UnityEngine.ColorUtility.TryParseHtmlString(playerMagicItem.LightColor, out var color))
            {
                _playerVariables.SetAs("LightColorR", color.r);
                _playerVariables.SetAs("LightColorG", color.g);
                _playerVariables.SetAs("LightColorB", color.b);
            }

            _playerVariables.SetAs("MovePower", _playerVariables.GetAs <float>("MovePower") + playerMagicItem.MovementSpeed);
            _playerVariables.SetAs("JumpPower", _playerVariables.GetAs <float>("JumpPower") + playerMagicItem.JumpPower);
            _playerVariables.SetAs("FlySpeedBase", _playerVariables.GetAs <float>("FlySpeedBase") + playerMagicItem.FlySpeed);
            _playerVariables.SetAs("LightRange", _playerVariables.GetAs <float>("LightRange") + playerMagicItem.MovementSpeed);

            var fallDmg = _playerVariables.GetAs <float>("FallDamageBaseDamage") + playerMagicItem.FallDamage;

            if (fallDmg < 0)
            {
                fallDmg = 0;
            }

            _playerVariables.SetAs("FallDamageBaseDamage", fallDmg);

            var falldmgUnit = _playerVariables.GetAs <float>("FallDamagePerUnit") + playerMagicItem.FallDamagePerUnit;

            if (falldmgUnit < 0)
            {
                falldmgUnit = 0;
            }

            _playerVariables.SetAs("FallDamagePerUnit", falldmgUnit);
            _playerVariables.SetAs("BuildDistance", _playerVariables.GetAs <float>("BuildDistance") + playerMagicItem.BuildDistance);
        }
Example #19
0
 public override ITrackableBlock InitializeFromJSON(Players.Player player, JSONNode node)
 {
     InitializeJob(player, (Vector3Int)node["position"], node.GetAs <int>("npcID"));
     if (guardSettings == null)
     {
         guardSettings = SetupSettings();
     }
     return(this);
 }
Example #20
0
        //Ref menu is added for change LocalStorage -> avoid client error
        public static bool LoadItem(JSONNode item, ref NetworkMenu menu, Players.Player player, out List <IItem> menuItem)
        {
            string itemType = item.GetAs <string>("type").Trim().ToLower();
            bool   found    = false;

            menuItem = null;

            switch (itemType)
            {
            case "patchnotes":
                if (item.TryGetAsOrDefault <string>("mod", out string mod, ""))
                {
                    var info = default(JSONNode);

                    foreach (var modJson in GameInitializer.AllModInfos.Values)
                    {
                        if (modJson.TryGetAs("name", out string modName) && string.Equals(mod, modName, StringComparison.InvariantCultureIgnoreCase))
                        {
                            info = modJson;
                            break;
                        }
                    }

                    if (info.TryGetAs <JSONNode>("patchnotes", out var patchNotesJson))
                    {
                        int i = 0;
                        menuItem = new List <IItem>();

                        foreach (var node in patchNotesJson.LoopArray())
                        {
                            i++;

                            node.TryGetAsOrDefault("version", out string version, "Undefined");
                            menuItem.Add(new Label(new LabelData("Version " + version, UnityEngine.TextAnchor.MiddleLeft, 24, LabelData.ELocalizationType.None)));

                            if (node.TryGetAs <JSONNode>("notes", out var versionNotesJson))
                            {
                                foreach (var note in versionNotesJson.LoopArray())
                                {
                                    menuItem.Add(new Label(new LabelData("    * " + note.ToString().Replace("\"", ""), UnityEngine.TextAnchor.MiddleLeft, 14, LabelData.ELocalizationType.None)));
                                }
                            }

                            if (i > 10)
                            {
                                break;
                            }
                        }
                    }
                }
                else
                {
                    APILogger.Log(ChatColor.red, "found patchnotes wiki item but mod property was not found");
                }

                found = true;
                break;
Example #21
0
        /// <summary>
        /// Called with the root json node to load the data from
        /// </summary>
        public virtual void LoadJSON(JSONNode node)
        {
            JSONNode array = node.GetAs <JSONNode>("array");

            for (int i = 0; i < array.ChildCount; i++)
            {
                GrowableBlockManager.RegisterGrowableBlock(MakeGrowableBlock(array[i]));
            }
        }
        public static T GetorDefault <T>(string key, T defaultVal)
        {
            if (!_rootSettings.HasChild(key))
            {
                SetValue(key, defaultVal);
            }

            return(_rootSettings.GetAs <T>(key));
        }
Example #23
0
        public MachineState(JSONNode baseNode, Players.Player owner)
        {
            MAX_DURABILITY[owner] = DEFAULT_MAX_DURABILITY;
            MAX_FUEL[owner]       = DEFAULT_MAX_FUEL;
            MAX_LOAD[owner]       = DEFAULT_MAX_LOAD;

            Position    = (Vector3Int)baseNode[nameof(Position)];
            Durability  = baseNode.GetAs <float>(nameof(Durability));
            Fuel        = baseNode.GetAs <float>(nameof(Fuel));
            MachineType = baseNode.GetAs <string>(nameof(MachineType));

            if (baseNode.TryGetAs <float>(nameof(Load), out var load))
            {
                Load = load;
            }

            MachineSettings = MachineManager.GetCallbacks(MachineType);
        }
        // construct from JSON
        public TrackedItem(JSONNode json)
        {
            ushort type = json.GetAs <ushort>("itemType");

            ItemTypes.TryGetType(type, out this.item);
            this.interval = json.GetAs <ushort>("interval");

            JSONNode jsonAmounts;

            if (json.TryGetAs("values", out jsonAmounts) && jsonAmounts.NodeType == NodeType.Array)
            {
                int i = 0;
                foreach (JSONNode jsonAmount in jsonAmounts.LoopArray())
                {
                    int val = jsonAmount.GetAs <int>();
                    this.itemAmount[i] = val;
                    i++;
                }
            }
        }
Example #25
0
        public override ITrackableBlock InitializeFromJSON(Players.Player player, JSONNode node)
        {
            originalPosition = (Vector3Int)node[nameof(originalPosition)];
            this.player      = player;
            lastRally        = node.GetAsOrDefault <double>(nameof(lastRally), 0);
            InitializeJob(player, (Vector3Int)node["position"], node.GetAs <int>("npcID"));
            lastDayTrumpeted   = node.GetAsOrDefault <double>(nameof(lastDayTrumpeted), TimeCycle.TotalTime);
            lastNightTrumpeted = node.GetAsOrDefault <double>(nameof(lastNightTrumpeted), TimeCycle.TotalTime);

            return(this);
        }
Example #26
0
 /// <summary>
 /// Get a JSONNode from the datamanager by name
 /// </summary>
 /// <param name="name"></param>
 /// <returns></returns>
 public static JSONNode getNode(string name)
 {
     if (hasNode(name))
     {
         return(dataObj.GetAs <JSONNode>(name));
     }
     else
     {
         return(new JSONNode(NodeType.Object));
     }
 }
Example #27
0
        public static JSONNode GetConfigNode(string modname, string key)
        {
            JSONNode configNode = GetConfigDataNode(modname);

            string[] keys = key.Split('.');
            if (keys.Length > 0)
            {
                return(GetConfigNodeFromNode(keys, 0, configNode, modname, key));
            }
            else
            {
                return(configNode.GetAs <JSONNode>(key));
            }
        }
Example #28
0
        public static float getConfigFloat(string modname, string key)
        {
            JSONNode configNode = getConfigDataNode(modname);

            string[] keys = key.Split('.');

            if (keys.Length > 0)
            {
                return(getConfigFloatFromNode(keys, 0, configNode, modname));
            }
            else
            {
                return(configNode.GetAs <float>(key));
            }
        }
Example #29
0
        public static bool getConfigBoolean(string modname, string key)
        {
            JSONNode configNode = getConfigDataNode(modname);

            string[] keys = key.Split('.');

            if (keys.Length > 0)
            {
                return(getConfigBoolFromNode(keys, 0, configNode, modname));
            }
            else
            {
                return(configNode.GetAs <bool>(key));
            }
        }
Example #30
0
        public virtual void LoadJSON(JSONNode node)
        {
            JSONNode table = node.GetAs <JSONNode>("table");

            foreach (var pair in table.LoopObject())
            {
                Players.Player player = Players.GetPlayer(NetworkID.Parse(pair.Key));
                JSONNode       array  = pair.Value;
                for (int i = 0; i < array.ChildCount; i++)
                {
                    var job = CreateAreaJob(player, array[i]);
                    if (!AreaJobTracker.RegisterAreaJob(job))
                    {
                        job.OnRemove();
                    }
                }
            }
        }