Ejemplo n.º 1
0
        private static void OnChanged(object sender, FileSystemEventArgs e)
        {
            try
            {
                var writeTime = File.GetLastWriteTime(filePath);

                if (writeTime - lastWriteTime <= new TimeSpan(0, 0, 0, 0, 50)) // Hack: avoid event being triggered twice caused by bug by checking if time since last save is > 50ms.
                {
                    return;
                }

                lastWriteTime = writeTime;

                Thread.Sleep(100); // File in use for some reason (by the watcher i assume).

                Console.Write($"Reloading...");
                Data?.Dispose();
                Data = null;
                LoadFile();
                Console.WriteLine(" done.");
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex);
            }
        }
Ejemplo n.º 2
0
        public static void ChangeData(string json)
        {
            var newData = ParseData(json);

            Data.Dispose();
            Data = newData;
        }
Ejemplo n.º 3
0
        /// <param name="allowOffline">If true then this method will be called even if rust data is currently unavailable.</param>
        private Func <object, object> WrapMethod(Func <object, object> func, bool allowOffline = false)
        {
            data = DataManager.Data;
            return(parameters =>
            {
                object apiResponse;

                if (data == null || !allowOffline && data.Disposed)
                {
                    apiResponse = Error(HttpStatusCode.ServiceUnavailable, "Api is currently unavailable, try again.");
                }
                else
                {
                    apiResponse = func(parameters);
                }

                Response response = new Response
                {
                    StatusCode = (apiResponse as ApiResponse)?.StatusCode ?? HttpStatusCode.OK,
                    Contents = stream =>
                    {
                        var bytes = Encoding.UTF8.GetBytes(apiResponse is string?(string)apiResponse: JsonConvert.SerializeObject(apiResponse, serializerSettings));
                        stream.Write(bytes, 0, bytes.Length);
                    },
                    ContentType = "application/json"
                };
                return response;
            });
        }
Ejemplo n.º 4
0
        private static RustData ParseData(string contents)
        {
            var     data  = new RustData();
            JObject jData = JObject.Parse(contents);

            data.Items = jData["items"].ToObject <Dictionary <string, Item> >();

            // Set shortname
            foreach (var keyval in data.Items)
            {
                keyval.Value.Shortname = keyval.Key;
            }

            data.Meta       = jData["meta"].ToObject <Meta>();
            data.Recipes    = new Dictionary <string, Recipe>();
            data.Cookables  = new Dictionary <string, Cookable>();
            data.DamageInfo = jData["damageInfo"].ToObject <Dictionary <string, DamageInfo> >();

            var jRecipes   = jData["recipes"].Value <JObject>();
            var jCookables = jData["cookables"].Value <JObject>();

            foreach (var keyval in jRecipes)
            {
                dynamic jRecipe   = keyval.Value;
                string  shortname = keyval.Key;
                var     recipe    = keyval.Value.ToObject <Recipe>();

                recipe.Output = ParseRecipeItem(jRecipe.output, data.Items);
                recipe.Input  = ((JArray)jRecipe.input).Select(r => ParseRecipeItem(r, data.Items)).ToList();

                if (jRecipe.parent != null)
                {
                    recipe.Parent = data.Items[(string)jRecipe.parent];
                }

                data.Recipes.Add(shortname, recipe);
            }

            foreach (var keyval in jCookables)
            {
                dynamic jCookable = keyval.Value;
                string  shortname = keyval.Key;
                var     cookable  = keyval.Value.ToObject <Cookable>();

                cookable.Output      = ParseRecipeItem(jCookable.output, data.Items);
                cookable.UsableOvens = ((JArray)jCookable.usableOvens).Select(jItem => data.Items[jItem["shortname"].Value <string>()]).ToList();

                data.Cookables.Add(shortname, cookable);
            }

            return(data);
        }
Ejemplo n.º 5
0
        private static void LoadFile()
        {
            string contents = File.ReadAllText(filePath);

            Data = ParseData(contents);

            if (!File.Exists("auths.json"))
            {
                SaveAuthTries();
            }
            else
            {
                authTries = JsonConvert.DeserializeObject <Dictionary <string, int> >(File.ReadAllText("auths.json"));
            }
        }
        private RustData ParseData()
        {
            var startTime = Time.realtimeSinceStartup;
            var data      = new RustData();

            // Parse damage data
            {
                var prefabs = new List <string>();

                string[] endsWithBlacklist =
                {
                    ".twig.prefab",
                    ".wood.prefab",
                    ".stone.prefab",
                    ".metal.prefab",
                    ".toptier.prefab",
                    ".item.prefab",
                    ".close-end.prefab",
                    "open-end.prefab",
                    "close-start.prefab",
                    "open-start.prefab",
                    "close-end.asset",
                    "open-end.asset",
                    "close-start.asset",
                    "open-start.asset",
                    "impact.prefab",
                    "knock.prefab",
                    "ladder_prop.prefab",
                };

                foreach (var str in GameManifest.Get().pooledStrings)
                {
                    if (!str.str.StartsWith("assets/"))
                    {
                        continue;
                    }
                    if (!str.str.StartsWith("assets/prefabs/building"))
                    {
                        continue;
                    }
                    if (endsWithBlacklist.Any(prefab => str.str.EndsWith(prefab)))
                    {
                        continue;
                    }

                    prefabs.Add(str.str);
                }

                var prefabObjects = prefabs.Select(name => GameManager.server.FindPrefab(name)).ToList();

                foreach (var prefab in prefabObjects)
                {
                    if (prefab == null)
                    {
                        Debug.LogError("Prefab null");
                        continue;
                    }

                    var buildingBlock = prefab.GetComponent <BuildingBlock>();

                    if (buildingBlock != null)
                    {
                        Dictionary <string, DamageInfo> damageInfos = GetDamageInfos(prefab);

                        foreach (var keyval in damageInfos)
                        {
                            if (data.DamageInfo.ContainsKey(keyval.Key))
                            {
                                data.DamageInfo[keyval.Key].MergeWith(keyval.Value);
                            }
                            else
                            {
                                data.DamageInfo.Add(keyval.Key, keyval.Value);
                            }

                            //Debug.Log(keyval.Key + ": [" + String.Join(", ", keyval.Value.Damages.Select(kv => kv.Key + "=" + Math.Ceiling(kv.Value.TotalHits)).ToArray()) + "]");
                        }
                    }
                }
            }

            Debug.Log("Damage data parsed");

            ovenTemperatures.Clear();

            // Find ovens and populate oven info
            foreach (ItemDefinition item in ItemManager.itemList)
            {
                var deployableMod = item.GetComponent <ItemModDeployable>();

                if (deployableMod != null)
                {
                    var deployObject = deployableMod.entityPrefab.Get();
                    var oven         = deployObject.GetComponent <BaseOven>();

                    if (oven != null)
                    {
                        ovenTemperatures.Add(item.shortname, GetProperty <float>(oven, "cookingTemperature"));
                        //Debug.Log(item.shortname + ": " + oven.temperature + " - " + ovenTemperatures[item.shortname]);
                    }
                }
            }

            Debug.Log("Got oven information...");

            // Add cooking and smelting data
            foreach (ItemDefinition item in ItemManager.itemList)
            {
                var cookableMod = item.GetComponent <ItemModCookable>();

                if (cookableMod != null)
                {
                    var exportCookable = new ExportCookable();
                    data.CookableInfo.Add(item.shortname, exportCookable);

                    exportCookable.Output = new ExportRecipeItem
                    {
                        Count  = cookableMod.amountOfBecome,
                        ItemId = cookableMod.becomeOnCooked.shortname
                    };

                    exportCookable.TTC = cookableMod.cookTime;
                    // burnable.fuel -= (float)(0.5 * ((double)this.cookingTemperature / 200.0));

                    foreach (var keyval in ovenTemperatures)
                    {
                        string shortname = keyval.Key;
                        float  ovenTemp  = keyval.Value;

                        if (ovenTemp >= cookableMod.lowTemp && ovenTemp <= cookableMod.highTemp)
                        {
                            var   ovenDef      = ItemManager.FindItemDefinition(shortname).GetComponent <ItemModDeployable>().entityPrefab.Get().GetComponent <BaseOven>();
                            var   ovenFuel     = ovenDef.fuelType.GetComponent <ItemModBurnable>();
                            float fuelConsumed = (float)(cookableMod.cookTime * (ovenTemp / 200.0) / ovenFuel.fuelAmount);

                            exportCookable.UsableOvens.Add(new ExportCookable.Oven
                            {
                                Shortname    = shortname,
                                FuelConsumed = fuelConsumed,
                                Fuel         = ovenDef.fuelType.shortname
                            });
                        }
                    }
                }
            }

            Debug.Log("Cooking and smelting data parsed");

            foreach (ItemDefinition item in ItemManager.itemList)
            {
                if (excludeList.Contains(item.shortname))
                {
                    continue;
                }

                var newItem = new ExportItem();
                newItem.Name        = item.displayName.english;
                newItem.Description = item.displayDescription.english;
                newItem.MaxStack    = item.stackable;
                newItem.Category    = item.category.ToString();
                newItem.Category    = newItem.Category.Substring(0, 1).ToLower() + newItem.Category.Substring(1);

                // Set meta depending on item type
                var consumable = item.GetComponent <ItemModConsumable>();
                var consume    = item.GetComponent <ItemModConsume>();
                var deployable = item.GetComponent <ItemModDeployable>();
                var wearable   = item.GetComponent <ItemModWearable>();
                var cookable   = item.GetComponent <ItemModCookable>();
                var entity     = item.GetComponent <ItemModEntity>();

                if (consumable != null)
                {
                    newItem.Meta = new MetaConsumable(item)
                    {
                        Effects             = consumable.effects,
                        ItemsGivenOnConsume = consume?.product
                    };
                }
                else if (deployable != null)
                {
                    var deployPrefab = deployable.entityPrefab.Get();
                    var oven         = deployPrefab.GetComponent <BaseOven>();
                    var bed          = deployPrefab.GetComponent <SleepingBag>();

                    if (oven != null)
                    {
                        newItem.Meta = new MetaOven(item)
                        {
                            Oven = oven
                        };
                    }
                    else if (bed != null)
                    {
                        newItem.Meta = new MetaBed(item)
                        {
                            Bed = bed
                        };
                    }
                }
                else if (wearable != null)
                {
                    if (wearable.HasProtections())
                    {
                        var protections = wearable.protectionProperties;

                        newItem.Meta = new MetaWearable(item)
                        {
                            Protections = protections
                        };
                    }
                }
                else if (cookable != null)
                {
                    newItem.Meta = new MetaCookable(item)
                    {
                        Cookable = cookable
                    };
                }
                else if (entity != null)
                {
                    var prefab = entity.entityPrefab.Get();

                    var thrownWeapon   = prefab.GetComponent <ThrownWeapon>();
                    var baseProjectile = prefab.GetComponent <global::BaseProjectile>();

                    if (thrownWeapon != null)
                    {
                        var throwable = thrownWeapon.prefabToThrow.Get();
                        var explosive = throwable.GetComponent <TimedExplosive>();

                        if (explosive != null)
                        {
                            newItem.Meta = new MetaWeaponDamage(item)
                            {
                                TimedExplosive = explosive
                            };
                        }
                    }
                    else if (baseProjectile != null)
                    {
                        var primaryAmmo   = baseProjectile.primaryMagazine.ammoType;
                        var projectileMod = primaryAmmo.GetComponent <ItemModProjectile>();

                        var projectilePrefab = projectileMod.projectileObject.Get();
                        var projectile       = projectilePrefab.GetComponent <Projectile>();

                        newItem.Meta = new MetaWeaponDamage(item)
                        {
                            ProjectileMod  = projectileMod,
                            BaseProjectile = baseProjectile,
                            Projectile     = projectile
                        };
                    }
                }

                data.Items.Add(item.shortname, newItem);
            }

            Debug.Log("Items parsed");

            foreach (ItemBlueprint blueprint in ItemManager.bpList)
            {
                if (excludeList.Contains(blueprint.targetItem.shortname))
                {
                    continue;
                }

                var newRecipe = new ExportRecipe();

                newRecipe.TTC    = (int)blueprint.time;
                newRecipe.Level  = blueprint.UnlockLevel;
                newRecipe.Price  = blueprint.UnlockPrice;
                newRecipe.Parent = blueprint.targetItem.Parent?.shortname;

                foreach (ItemAmount ingredient in blueprint.ingredients)
                {
                    newRecipe.Input.Add(new ExportRecipeItem
                    {
                        Count  = (int)ingredient.amount,
                        ItemId = ingredient.itemDef.shortname
                    });
                }

                newRecipe.Output = new ExportRecipeItem
                {
                    Count  = blueprint.amountToCreate,
                    ItemId = blueprint.targetItem.shortname
                };

                data.Recipes.Add(blueprint.targetItem.shortname, newRecipe);
            }

            Debug.Log("Blueprints parsed");

            var endTime   = Time.realtimeSinceStartup;
            var totalTime = endTime - startTime;

            data.Meta.Time = totalTime;

            return(data);
        }