Иконка ресурса

FREE VirtualQuarries : 2.5.0 2.5.0

Нет прав для скачивания
C#:
// Все права принадлежат дискорд сообществу https://discord.gg/VgNHPpNrz6
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Oxide.Core;
using UnityEngine;
using Oxide.Game.Rust.Cui;
using Oxide.Core.Plugins;
using Facepunch;
using VLB;
namespace Oxide.Plugins {
    [Info("VirtualQuarries", "ThePitereq", "2.5.0")]
    public class VirtualQuarries : RustPlugin {
        [PluginReference]
        private readonly Plugin ImageLibrary, PopUpAPI, ServerRewards, Economics, IQEconomic, BankSystem, ShoppyStock;
        private static VirtualQuarries _plugin;
        private readonly Dictionary<ulong, CachedSurvey> cachedSurveys = new();
        private readonly Dictionary<ulong, List<RequiredItem>> cachedRequirements = new();
        private readonly Dictionary<ulong, string> cachedSort = new();
        private readonly Dictionary<ulong, int> cachedPage = new();
        private readonly Dictionary<ulong, Dictionary<string, int>> cachedQuarryCount = new();
        private readonly Dictionary<ulong, string> cachedSurveyType = new();
        private readonly Dictionary<ulong, float> commandCooldowns = new();
        private static DateTime lastOperation = DateTime.Now;
        private class CachedSurvey {
            public string profile = string.Empty;
            public readonly List<QuarryResource> resources = new();
        }
#region Init
        private void Init() {
            _plugin = this;
            config = Config.ReadObject<PluginConfig>();
            Config.WriteObject(config);
            LoadData();
            LoadMessages();
        }
        private void OnServerInitialized() {
            if (config.economyPlugin == 1 && Economics == null) PrintWarning("Economics plugin not found! You will not be able to upgrade your quarries with server currency!");
            else if (config.economyPlugin == 2 && ServerRewards == null) PrintWarning("ServerRewards plugin not found! You will not be able to upgrade your quarries with server currency!");
            else if (config.economyPlugin == 3 && IQEconomic == null) PrintWarning("IQEconomic plugin not found! You will not be able to upgrade your quarries with server currency!");
            else if (config.economyPlugin == 4 && BankSystem == null) PrintWarning("BankSystem plugin not found! You will not be able to upgrade your quarries with server currency!");
            else if (config.economyPlugin == 5 && ShoppyStock == null) PrintWarning("ShoppyStock plugin not found! You will not be able to upgrade your quarries with server currency!");
            if (ImageLibrary == null) PrintWarning("ImageLibrary plugin not found! It is required for all images to work!");
            if (PopUpAPI == null) PrintWarning("PopUpAPI plugin not found! The Pop-Up messages will not display!");
            else if (PopUpAPI.Version.Major < 2) PrintWarning("You are using old version of PopUpAPI! Update it to 2.0.0 or newer, or plugin will print errors or no pop-up messages at all!");
            if (config.surveyThrow) Unsubscribe(nameof(OnExplosiveThrown));
            AddImage("https://images.pvrust.eu/ui_icons/VirtualQuarries/arrow_right_0.png", "UI_VirtualQuarries_arrow_right_0", 0);
            AddImage("https://images.pvrust.eu/ui_icons/VirtualQuarries/arrow_left_0.png", "UI_VirtualQuarries_arrow_left_0", 0);
            AddImage("https://images.pvrust.eu/ui_icons/VirtualQuarries/shared_0.png", "UI_VirtualQuarries_shared_0", 0);
            AddImage("https://images.pvrust.eu/ui_icons/VirtualQuarries/search_0.png", "UI_VirtualQuarries_search_0", 0);
            if (config.requirePermission) permission.RegisterPermission("virtualquarries.use", this);
            if (config.sharingRequirePermission) permission.RegisterPermission("virtualquarries.share", this);
            if (config.quarryPerm) permission.RegisterPermission("virtualquarries.static.quarry", this);
            if (config.pumpJackPerm) permission.RegisterPermission("virtualquarries.static.pumpjack", this);
            foreach (var permissionKey in config.permissions.Keys) permission.RegisterPermission(permissionKey, this);
            foreach (var permissionKey in config.surveys.Values) if (permissionKey.permission != string.Empty) permission.RegisterPermission(permissionKey.permission, this);
            foreach (var permissionKey in config.quarryProfiles.Values) {
                if (permissionKey.permission != string.Empty) permission.RegisterPermission(permissionKey.permission, this);
                foreach (var resourceKey in permissionKey.resources.Values) if (resourceKey.permission != string.Empty) permission.RegisterPermission(resourceKey.permission, this);
                foreach (var upgradeKey in permissionKey.upgrades) if (upgradeKey.requiredPerm != string.Empty) permission.RegisterPermission(upgradeKey.requiredPerm, this);
            }
            if (config.storeContainers) timer.Every(config.containerSaveInterval, () => SaveContainers());
            foreach (var command in config.commandList) cmd.AddChatCommand(command, this, nameof(VirtualQuarriesCommand));
            foreach (var profile in config.quarryProfiles.Values) {
                if (profile.icon.iconUrl != "") AddImage(profile.icon.iconUrl, profile.icon.shortname, profile.icon.skin);
                foreach (var resource in profile.resources) {
                    if (resource.Value.iconUrl != "") AddImage(resource.Value.iconUrl, resource.Value.shortname, resource.Value.skin);
                    foreach (var additional in resource.Value.additionalItems) if (additional.iconUrl != "") AddImage(additional.iconUrl, additional.shortname, additional.skin);
                }
                foreach (var item in profile.requiredItems) if (item.iconUrl != "") AddImage(item.iconUrl, item.shortname, item.skin);
                foreach (var upgrade in profile.upgrades) foreach (var item in upgrade.requiredItems) if (item.iconUrl != "") AddImage(item.iconUrl, item.shortname, item.skin);
            }
            foreach (var survey in config.surveys.Values) if (survey.surveyItem.iconUrl != "") AddImage(survey.surveyItem.iconUrl, survey.surveyItem.shortname, survey.surveyItem.skin);
            timer.Once(1f, () => SetupQuarries());
            foreach (var player in BasePlayer.activePlayerList) {
                playerCache.TryAdd(player.userID, player.displayName);
                playerCache[player.userID] = player.displayName;
                if (config.offlineQuarryOwnerKickTime == 0) continue;
                DateTime now = DateTime.Now;
                foreach (var quarry in data.quarries) {
                    if (quarry.Value.owner != player.userID) continue;
                    quarry.Value.lastOwnerOnline = now;
                }
            }
            if (config.offlineQuarryOwnerKickTime > 0) CheckQuarryKicks();
        }
        private void SetupQuarries() {
            if (config.staticQuarries) {
                if (!config.disableRunningEffect) {
                    foreach (var quarry in BaseNetworkable.serverEntities.OfType<MiningQuarry>()) {
                        if (quarry.staticType == MiningQuarry.QuarryType.None && quarry.OwnerID != 0) continue;
                        quarry.SetOn(false);
                        quarry.CancelInvoke();
                        quarry.engineSwitchPrefab.instance.SetFlag(BaseEntity.Flags.On, true);
                        quarry.SetFlag(BaseEntity.Flags.On, true);
                        quarry.SendNetworkUpdate();
                    }
                }
                foreach (var quarry in data.staticQuarries.ToList()) {
                    if (quarry.Key == uint.MaxValue) continue;
                    MiningQuarry quarryEnt = BaseNetworkable.serverEntities.Find(new NetworkableId(quarry.Key)) as MiningQuarry;
                    if (!quarryEnt) {
                        foreach (var user in quarry.Value) {
                            BoxStorage storage = BaseNetworkable.serverEntities.Find(new NetworkableId(user.Value)) as BoxStorage;
                            storage?.Kill();
                        }
                        data.staticQuarries.Remove(quarry.Key);
                        continue;
                    }
                    if (quarryEnt.staticType == MiningQuarry.QuarryType.None) continue;
                    foreach (var user in quarry.Value) {
                        BoxStorage storage = BaseNetworkable.serverEntities.Find(new NetworkableId(user.Value)) as BoxStorage;
                        if (!storage) {
                            Puts($"[VirtualQuarries ERROR] Static quarry of {user.Key} is missing output container!");
                            continue;
                        }
                        GroundWatch gw = storage.GetComponent<GroundWatch>();
                        if (gw) UnityEngine.Object.Destroy(gw);
                        DestroyOnGroundMissing dogm = storage.GetComponent<DestroyOnGroundMissing>();
                        if (dogm) UnityEngine.Object.Destroy(dogm);
                        if (storage.children.Count == 0) {
                            Puts($"[VirtualQuarries ERROR] Static quarry of {user.Key} is missing fuel container!");
                            continue;
                        }
                        storage.inventory.capacity = config.staticResourceSize;
                        BoxStorage fuelStorage = storage.children[0] as BoxStorage;
                        if (fuelStorage) {
                            gw = fuelStorage.GetComponent<GroundWatch>();
                            if (gw) UnityEngine.Object.Destroy(gw);
                            dogm = fuelStorage.GetComponent<DestroyOnGroundMissing>();
                            if (dogm) UnityEngine.Object.Destroy(dogm);
                            fuelStorage.inventory.capacity = config.staticFuelSize;
                        }
                        VirtualQuarry vQuarry = storage.GetComponent<VirtualQuarry>();
                        if (!vQuarry) {
                            storage.gameObject.AddComponent<VirtualQuarry>();
                            vQuarry = storage.GetComponent<VirtualQuarry>();
                        }
                        vQuarry.SetupQuarry(VirtualQuarry.VqType.Static, linkedQuarry : quarryEnt);
                    }
                }
            }
            else Unsubscribe(nameof(OnQuarryToggled));
            if (config.excavatorQuarry) {
                if (config.excavatorResources.Count < 4) {
                    PrintWarning("You don't have all 4 resources required to run excavator properly! Generating new ones...");
                    config.excavatorResources = new Dictionary<string, List<StaticQuarryOutput>>() {
                        {
                            "Stone", new List<StaticQuarryOutput>() {
                                new StaticQuarryOutput() {
                                    shortname = "stones", amount = 5000
                                }
                            }
                        }
                        , {
                            "Metal", new List<StaticQuarryOutput>() {
                                new StaticQuarryOutput() {
                                    shortname = "metal.fragments", amount = 2500
                                }
                            }
                        }
                        , {
                            "Sulfur", new List<StaticQuarryOutput>() {
                                new StaticQuarryOutput() {
                                    shortname = "sulfur.ore", amount = 1000
                                }
                            }
                        }
                        , {
                            "HQM", new List<StaticQuarryOutput>() {
                                new StaticQuarryOutput() {
                                    shortname = "hq.metal.ore", amount = 50
                                }
                            }
                        }
                    }
                    ;
                    Config.WriteObject(config);
                }
                foreach (var arm in BaseNetworkable.serverEntities.OfType<ExcavatorArm>()) {
                    arm.StopMining();
                    arm.SetFlag(BaseEntity.Flags.Reserved8, true);
                    arm.SetFlag(BaseEntity.Flags.On, true);
                }
                foreach (var engin in BaseNetworkable.serverEntities.OfType<DieselEngine>()) {
                    engin.cachedFuelTime = float.MaxValue;
                    engin.SetFlag(BaseEntity.Flags.On, true, false, true);
                }
                if (data.staticQuarries.ContainsKey(uint.MaxValue)) {
                    foreach (var user in data.staticQuarries[uint.MaxValue]) {
                        BoxStorage storage = BaseNetworkable.serverEntities.Find(new NetworkableId(user.Value)) as BoxStorage;
                        if (!storage) continue;
                        GroundWatch gw = storage.GetComponent<GroundWatch>();
                        if (gw) UnityEngine.Object.Destroy(gw);
                        DestroyOnGroundMissing dogm = storage.GetComponent<DestroyOnGroundMissing>();
                        if (dogm) UnityEngine.Object.Destroy(dogm);
                        if (storage.children.Count == 0) {
                            Puts($"[VirtualQuarries ERROR] Excavator quarry of {user.Key} is missing fuel container!");
                            continue;
                        }
                        BoxStorage fuelStorage = storage.children[0] as BoxStorage;
                        if (fuelStorage) {
                            gw = fuelStorage.GetComponent<GroundWatch>();
                            if (gw) UnityEngine.Object.Destroy(gw);
                            dogm = fuelStorage.GetComponent<DestroyOnGroundMissing>();
                            if (dogm) UnityEngine.Object.Destroy(dogm);
                        }
                        VirtualQuarry vQuarry = storage.GetOrAddComponent<VirtualQuarry>();
                        string mineType = data.excavatorOutputs.TryGetValue(user.Key, out string output) ? output : string.Empty;
                        vQuarry.SetupQuarry(VirtualQuarry.VqType.Excavator, resource : mineType);
                    }
                }
            }
            else Unsubscribe(nameof(OnExcavatorResourceSet));
            if (!config.staticQuarries && !config.excavatorQuarry) Unsubscribe(nameof(CanLootEntity));
            foreach (var quarry in data.quarries) {
                cachedQuarryCount.TryAdd(quarry.Value.owner, new Dictionary<string, int>());
                cachedQuarryCount[quarry.Value.owner].TryAdd(quarry.Value.profile, 0);
                cachedQuarryCount[quarry.Value.owner][quarry.Value.profile]++;
                BoxStorage storage = BaseNetworkable.serverEntities.Find(new NetworkableId(quarry.Value.netId)) as BoxStorage;
                VirtualQuarry vQuarry = storage?.GetComponent<VirtualQuarry>();
                if (!storage) {
                    Puts($"[VirtualQuarries ERROR] Quarry with ID {quarry.Key} had missing resource container! Recreating...");
                    SpawnQuarry(playerId : quarry.Value.owner, restoreId : quarry.Key );
                    storage = BaseNetworkable.serverEntities.Find(new NetworkableId(quarry.Value.netId)) as BoxStorage;
                }
                else {
                    GroundWatch gw = storage.GetComponent<GroundWatch>();
                    if (gw) UnityEngine.Object.Destroy(gw);
                    DestroyOnGroundMissing dogm = storage.GetComponent<DestroyOnGroundMissing>();
                    if (dogm) UnityEngine.Object.Destroy(dogm);
                    BoxStorage fuelStorage = null;
                    List<UpgradeConfig> upgrades = config.quarryProfiles[quarry.Value.profile].upgrades;
                    if (storage.children.Count == 0) {
                        fuelStorage = GameManager.server.CreateEntity(config.storagePrefab, storage.transform.position) as BoxStorage;
                        fuelStorage.Spawn();
                        UnityEngine.Object.Destroy(fuelStorage.GetComponent<GroundWatch>());
                        UnityEngine.Object.Destroy(fuelStorage.GetComponent<DestroyOnGroundMissing>());
                        fuelStorage.SetParent(storage);
                        fuelStorage.transform.position = storage.transform.position + new Vector3(0, 0.7f, 0);
                        if (quarry.Value.level < upgrades.Count) fuelStorage.inventory.capacity = upgrades[quarry.Value.level].fuelCapacity;
                        Puts($"[VirtualQuarries ERROR] Spawning missing quarry fuel container of quarry with ID {quarry.Key}...");
                    }
                    fuelStorage = storage.children[0] as BoxStorage;
                    if (fuelStorage) {
                        gw = fuelStorage.GetComponent<GroundWatch>();
                        if (gw) UnityEngine.Object.Destroy(gw);
                        dogm = fuelStorage.GetComponent<DestroyOnGroundMissing>();
                        if (dogm) UnityEngine.Object.Destroy(dogm);
                    }
                    else {
                        fuelStorage = GameManager.server.CreateEntity(config.storagePrefab, storage.transform.position) as BoxStorage;
                        fuelStorage.Spawn();
                        UnityEngine.Object.Destroy(fuelStorage.GetComponent<GroundWatch>());
                        UnityEngine.Object.Destroy(fuelStorage.GetComponent<DestroyOnGroundMissing>());
                        fuelStorage.SetParent(storage);
                        fuelStorage.transform.position = storage.transform.position + new Vector3(0, 0.7f, 0);
                        if (quarry.Value.level < upgrades.Count) fuelStorage.inventory.capacity = upgrades[quarry.Value.level].fuelCapacity;
                        Puts($"Spawning missing quarry fuel container of quarry with ID {quarry.Key}...");
                    }
                    if (!vQuarry) storage.gameObject.AddComponent<VirtualQuarry>();
                    if (!config.quarryProfiles.ContainsKey(quarry.Value.profile)) {
                        PrintWarning($"There is a quarry with profile '{quarry.Value.profile}' but it is missing in the configuration!");
                        continue;
                    }
                    if (quarry.Value.level < upgrades.Count) {
                        (storage.children[0] as BoxStorage).inventory.capacity = upgrades[quarry.Value.level].fuelCapacity;
                        storage.inventory.capacity = upgrades[quarry.Value.level].capacity;
                    }
                    else PrintWarning($"Quarry with ID {quarry.Key} have more upgrades than is added to config! You need to add more levels or remove this quarry from data, or plugin will print errors!");
                }
                vQuarry = storage.GetComponent<VirtualQuarry>();
                vQuarry.SetupQuarry(id : quarry.Key);
            }
        }
        private void Unload() {
            if (config.storeContainers) SaveContainers();
            if (config.excavatorQuarry) {
                foreach (var arm in BaseNetworkable.serverEntities.OfType<ExcavatorArm>()) {
                    arm.SetFlag(BaseEntity.Flags.Reserved8, false);
                    arm.SetFlag(BaseEntity.Flags.On, false);
                }
                foreach (var engin in BaseNetworkable.serverEntities.OfType<DieselEngine>()) {
                    engin.cachedFuelTime = 0;
                    engin.SetFlag(BaseEntity.Flags.On, false);
                }
            }
            if (config.staticQuarries) {
                foreach (var quarry in BaseNetworkable.serverEntities.OfType<MiningQuarry>()) {
                    if (quarry.staticType == MiningQuarry.QuarryType.None && quarry.OwnerID != 0) continue;
                    quarry.SetOn(false);
                    quarry.CancelInvoke();
                    quarry.engineSwitchPrefab.instance.SetFlag(BaseEntity.Flags.On, false);
                    quarry.SetFlag(BaseEntity.Flags.On, false);
                    quarry.SendNetworkUpdate();
                }
            }
            SaveData();
            foreach (var player in BasePlayer.activePlayerList) {
                CuiHelper.DestroyUi(player, "VirtualQuarriesUI_Main");
                CuiHelper.DestroyUi(player, "VirtualQuarriesUI_New");
                CuiHelper.DestroyUi(player, "VirtualQuarriesUI_NewCursor");
                CuiHelper.DestroyUi(player, "VirtualQuarriesUI_Back");
                CuiHelper.DestroyUi(player, "VirtualQuarriesUI_Players");
                CuiHelper.DestroyUi(player, "VirtualQuarriesUI_Levels");
            }
            foreach (var netId in data.quarries.Values) {
                BoxStorage quarry = BaseNetworkable.serverEntities.Find(new NetworkableId(netId.netId)) as BoxStorage;
                if (quarry) GameObject.Destroy(quarry.GetComponent<VirtualQuarry>());
            }
            foreach (var quarryId in data.staticQuarries.ToList()) {
                foreach (var player in quarryId.Value) {
                    BoxStorage quarry = BaseNetworkable.serverEntities.Find(new NetworkableId(player.Value)) as BoxStorage;
                    if (quarry) GameObject.Destroy(quarry.GetComponent<VirtualQuarry>());
                }
            }
            SaveData();
        }
        private void OnNewSave() {
            config = Config.ReadObject<PluginConfig>();
            Config.WriteObject(config);
            if (config.wipeData) {
                LoadData();
                data = new PluginData();
                SaveData();
                if (config.consoleLogs) Puts("Plugin data has been wiped successfully!");
            }
        }
#endregion
#region RUST Hooks
        private void OnPlayerConnected(BasePlayer player) {
            playerCache.TryAdd(player.userID, player.displayName);
            playerCache[player.userID] = player.displayName;
            if (config.offlineQuarryOwnerKickTime == 0) return;
            DateTime now = DateTime.Now;
            foreach (var quarry in data.quarries) {
                if (quarry.Value.owner != player.userID) continue;
                quarry.Value.lastOwnerOnline = now;
            }
        }
        private void OnLootEntityEnd(BasePlayer player) {
            CuiHelper.DestroyUi(player, "VirtualQuarriesUI_Back");
            CuiHelper.DestroyUi(player, "VirtualQuarriesUI_Levels");
        }
        private void OnExplosiveThrown(BasePlayer player, BaseEntity entity, ThrownWeapon item) {
            if (item.ShortPrefabName.Contains("survey_charge") && item.skinID == 0) {
                entity.Kill();
                Item survey = ItemManager.CreateByName("surveycharge");
                NextTick(() => player.GiveItem(survey));
                PopUpAPI?.Call("ShowPopUp", player, config.popUpPreset, Lang("NoSurveyThrow", player.UserIDString, config.commandList[0]));
            }
        }
        private object OnEntityTakeDamage(BoxStorage entity) {
            if (entity.transform.position.y < -390) return config.returnValue;
            return null;
        }
        private void OnQuarryToggled(MiningQuarry quarry, BasePlayer player) {
            quarry.SetOn(false);
            quarry.CancelInvoke();
            quarry.engineSwitchPrefab.instance.SetFlag(BaseEntity.Flags.On, true);
            quarry.SetFlag(BaseEntity.Flags.On, true);
            quarry.SendNetworkUpdate();
        }
        private object OnExcavatorResourceSet(ExcavatorArm arm, string type, BasePlayer player) {
            if (!data.staticQuarries.ContainsKey(uint.MaxValue) || !data.staticQuarries[uint.MaxValue].ContainsKey(player.userID)) {
                PopUpAPI?.Call("ShowPopUp", player, config.popUpPreset, Lang("OpenStorageFirst", player.UserIDString));
                return false;
            }
            ulong storageId = data.staticQuarries[uint.MaxValue][player.userID];
            BoxStorage storage = BaseNetworkable.serverEntities.Find(new NetworkableId(storageId)) as BoxStorage;
            if (!storage) {
                PopUpAPI?.Call("ShowPopUp", player, config.popUpPreset, Lang("ErrorOccured", player.UserIDString));
                return false;
            }
            VirtualQuarry vq = storage.GetComponent<VirtualQuarry>();
            vq.SwitchExcavatorType(type);
            vq.SwitchEngine(false);
            data.excavatorOutputs[player.userID] = type;
            PopUpAPI?.Call("ShowPopUp", player, config.popUpPreset, Lang("SwitchedResource", player.UserIDString, type));
            if (!arm.IsOn()) {
                arm.SetFlag(BaseEntity.Flags.On, true);
                ExcavatorServerEffects.SetMining(true, true);
            }
            return false;
        }
        private object OnExcavatorSuppliesRequest(ExcavatorArm arm, BasePlayer player) {
            PopUpAPI?.Call("ShowPopUp", player, config.popUpPreset, Lang("NoAirDrops", player.UserIDString));
            return false;
        }
        private object CanLootEntity(BasePlayer player, StorageContainer storage) {
            if (!storage) return null;
            if (config.excavatorQuarry && storage is ExcavatorOutputPile excavatorStorage) {
                if (config.excavatorPerm && !permission.UserHasPermission(player.UserIDString, "virtualquarries.static.excavator")) {
                    PopUpAPI?.Call("ShowPopUp", player, config.popUpPreset, Lang("NoPermissionQuarry", player.UserIDString));
                    return false;
                }
                uint excavatorId = uint.MaxValue;
                data.staticQuarries.TryAdd(excavatorId, new Dictionary<ulong, ulong>());
                if (!data.staticQuarries[excavatorId].ContainsKey(player.userID)) SpawnQuarry(VirtualQuarry.VqType.Excavator, player, excavatorStorage);
                else OpenQuarry(player, VirtualQuarry.VqType.Excavator, quarryStorage : excavatorStorage);
                return false;
            }
            if (config.excavatorQuarry && storage is DieselEngine dieselStorage) {
                if (config.excavatorPerm && !permission.UserHasPermission(player.UserIDString, "virtualquarries.static.excavator")) {
                    PopUpAPI?.Call("ShowPopUp", player, config.popUpPreset, Lang("NoPermissionQuarry", player.UserIDString));
                    return false;
                }
                uint excavatorId = uint.MaxValue;
                data.staticQuarries.TryAdd(excavatorId, new Dictionary<ulong, ulong>());
                if (!data.staticQuarries[excavatorId].ContainsKey(player.userID)) SpawnQuarry(VirtualQuarry.VqType.Excavator, player, dieselStorage);
                else OpenQuarry(player, VirtualQuarry.VqType.Excavator, quarryStorage : dieselStorage);
                return false;
            }
            if (config.staticQuarries && storage is ResourceExtractorFuelStorage quarryStorage) {
                MiningQuarry quarry = quarryStorage.GetParentEntity() as MiningQuarry;
                if (!quarry) return null;
                if (quarry.staticType == MiningQuarry.QuarryType.None && quarry.OwnerID != 0) return null;
                if (config.quarryPerm && quarry.ShortPrefabName == "mininquarry_static" && !permission.UserHasPermission(player.UserIDString, "virtualquarries.static.quarry")) {
                    PopUpAPI?.Call("ShowPopUp", player, config.popUpPreset, Lang("NoPermissionQuarry", player.UserIDString));
                    return false;
                }
                if (config.pumpJackPerm && quarry.ShortPrefabName == "pumpjack-static" && !permission.UserHasPermission(player.UserIDString, "virtualquarries.static.pumpjack")) {
                    PopUpAPI?.Call("ShowPopUp", player, config.popUpPreset, Lang("NoPermissionPumpJack", player.UserIDString));
                    return false;
                }
                data.staticQuarries.TryAdd(quarry.net.ID.Value, new Dictionary<ulong, ulong>());
                if (!data.staticQuarries[quarry.net.ID.Value].ContainsKey(player.userID)) SpawnQuarry(VirtualQuarry.VqType.Static, player, quarryStorage, quarry);
                else OpenQuarry(player, VirtualQuarry.VqType.Static, true, 0, quarryStorage, quarry);
                return false;
            }
            return null;
        }
#endregion
#region Commands
        [ConsoleCommand("UI_VirtualQuarries")]
        private void VirtualQuarriesConsoleCommand(ConsoleSystem.Arg arg) {
            BasePlayer player = arg.Player();
            if (config.commandCooldown > 0) {
                if (commandCooldowns.ContainsKey(player.userID) && Time.realtimeSinceStartup - commandCooldowns[player.userID] < config.commandCooldown) return;
                commandCooldowns[player.userID] = Time.realtimeSinceStartup;
            }
            if (config.requirePermission && !permission.UserHasPermission(player.UserIDString, "virtualquarries.use")) {
                PopUpAPI?.Call("ShowPopUp", player, config.popUpPreset, Lang("NoPermission", player.UserIDString));
                return;
            }
            switch (arg.Args[0]) {
                case "close" : CuiHelper.DestroyUi(player, "VirtualQuarriesUI_NewCursor");
                CuiHelper.DestroyUi(player, "VirtualQuarriesUI_New");
                CuiHelper.DestroyUi(player, "VirtualQuarriesUI_Main");
                CuiHelper.DestroyUi(player, "VirtualQuarriesUI_Players");
                break;
                case "new" : CuiHelper.DestroyUi(player, "VirtualQuarriesUI_Main");
                SelectSurveyTypeUI(player);
                break;
                case "back" : CuiHelper.DestroyUi(player, "VirtualQuarriesUI_Main");
                CuiHelper.DestroyUi(player, "VirtualQuarriesUI_NewCursor");
                CuiHelper.DestroyUi(player, "VirtualQuarriesUI_New");
                CuiHelper.DestroyUi(player, "VirtualQuarriesUI_Back");
                CuiHelper.DestroyUi(player, "VirtualQuarriesUI_Players");
                CuiHelper.DestroyUi(player, "VirtualQuarriesUI_Levels");
                player.EndLooting();
                if (arg.Args.Length == 1) ShowQuarryMenuUI(player);
                else ShowQuarryMenuUI(player, 1, int.Parse(arg.Args[1]));
                break;
                case "throw_open" : cachedSurveyType.TryAdd(player.userID, "");
                cachedSurveyType[player.userID] = arg.Args[1];
                CuiHelper.DestroyUi(player, "VirtualQuarriesUI_New");
                ShowNewQuarryUI(player, true);
                break;
                case "throw" : TrySurveyThrow(player);
                break;
                case "place" : TryPlaceQuarry(player);
                break;
                case "view" : ShowQuarryMenuUI(player, int.Parse(arg.Args[1]), int.Parse(arg.Args[2]));
                break;
                case "engine" : TryStartQuarry(player, int.Parse(arg.Args[1]));
                break;
                case "fuel" : OpenQuarry(player, isFuel : true, dataId : int.Parse(arg.Args[1]));
                break;
                case "storage" : OpenQuarry(player, dataId : int.Parse(arg.Args[1]));
                break;
                case "delete" : TryRemoveQuarry(player, int.Parse(arg.Args[1]));
                break;
                case "sortOwned" : ChangeSort(player, "owned");
                break;
                case "sortShared" : ChangeSort(player, "shared");
                break;
                case "sortDisable" : ChangeSort(player, "disable");
                break;
                case "page" : int page = int.Parse(arg.Args[1]);
                cachedPage.TryAdd(player.userID, page);
                cachedPage[player.userID] = page;
                ShowQuarryMenuUI(player, page);
                break;
                case "action" : CuiHelper.DestroyUi(player, "VirtualQuarriesUI_Main");
                if (arg.Args.Length == 2) ManageQuarryPlayersUI(player, arg.Args[1]);
                else if (arg.Args.Length == 3) ManageQuarryPlayersUI(player, arg.Args[1], int.Parse(arg.Args[2]));
                else if (arg.Args.Length == 4) ManageQuarryPlayersUI(player, arg.Args[1], int.Parse(arg.Args[2]), int.Parse(arg.Args[3]));
                else if (arg.Args.Length >= 5) ManageQuarryPlayersUI(player, arg.Args[1], int.Parse(arg.Args[2]), int.Parse(arg.Args[3]), arg.Args[4]);
                break;
                case "doAction" : ManageQuarryUser(player, arg.Args[1], int.Parse(arg.Args[2]), ulong.Parse(arg.Args[3]));
                break;
                case "list" : ShowQuarryAccessList(player, int.Parse(arg.Args[1]));
                break;
                case "upgrade" : TryUpgradeQuarry(player, int.Parse(arg.Args[1]), arg.Args[2]);
                break;
                default : ShowQuarryMenuUI(player);
                break;
            }
        }
        private void VirtualQuarriesCommand(BasePlayer player) => ShowQuarryMenuUI(player);
#endregion
#region Function Methods
#region All Quarries
        private void OpenQuarry(BasePlayer player, VirtualQuarry.VqType vqType = VirtualQuarry.VqType.Default, bool isFuel = false, int dataId = 0, StorageContainer quarryStorage = null, MiningQuarry quarry = null) {
            if (vqType == VirtualQuarry.VqType.Default) {
                QuarryData qd = data.quarries[dataId];
                if (qd.owner != player.userID && !qd.authPlayers.Contains(player.userID)) return;
                if (config.lockAccesNoPerm) {
                    Dictionary<string, int> playerPerm = new Dictionary<string, int>();
                    foreach (var configPerm in config.permissions) if (permission.UserHasPermission(player.UserIDString, configPerm.Key)) playerPerm = configPerm.Value;
                    if (!playerPerm.ContainsKey(qd.profile)) {
                        PopUpAPI?.Call("ShowPopUp", player, config.popUpPreset, Lang("NoLongerProfilePerm", player.UserIDString));
                        return;
                    }
                    if (config.checkQuarryAmount) {
                        int quarryCount = 0;
                        foreach (var quarryCheck in data.quarries) {
                            if (quarryCheck.Value.owner == player.userID && quarryCheck.Value.profile == qd.profile) quarryCount++;
                        }
                        if (quarryCount > playerPerm[qd.profile]) {
                            PopUpAPI?.Call("ShowPopUp", player, config.popUpPreset, Lang("TooManyQuarriesPermMissing", player.UserIDString));
                            return;
                        }
                    }
                }
            }
            BoxStorage storage;
            bool isExcavator = false;
            if (vqType == VirtualQuarry.VqType.Default) {
                storage = GetQuarry(dataId);
                if (!storage) {
                    PopUpAPI?.Call("ShowPopUp", player, config.popUpPreset, Lang("ErrorOccured", player.UserIDString));
                    return;
                }
            }
            else {
                isExcavator = vqType == VirtualQuarry.VqType.Excavator;
                ulong quarryId = isExcavator ? uint.MaxValue : quarry.net.ID.Value;
                VirtualQuarry.VqType type = isExcavator ? VirtualQuarry.VqType.Excavator : VirtualQuarry.VqType.Static;
                ulong storageId = data.staticQuarries[quarryId][player.userID];
                storage = BaseNetworkable.serverEntities.Find(new NetworkableId(storageId)) as BoxStorage;
                if (!storage) {
                    SpawnQuarry(type, player, quarryStorage, quarry);
                    return;
                }
            }
            player.EndLooting();
            if (vqType == VirtualQuarry.VqType.Default) {
                CuiHelper.DestroyUi(player, "VirtualQuarriesUI_Main");
                if (isFuel) {
                    storage = storage.children[0] as BoxStorage;
                    storage.inventory.canAcceptItem = (item, i) => IsFuel(item, data.quarries[dataId].profile);
                }
                else {
                    storage.inventory.canAcceptItem = (item, i) => IsResourceOutput(item, data.quarries[dataId].profile);
                    AddQuarryLevelsUI(player, dataId);
                }
                AddBackButtonUI(player, dataId);
            }
            else {
                ulong quarryId = isExcavator ? uint.MaxValue : quarryStorage.net.ID.Value;
                if (quarryStorage.ShortPrefabName == "fuelstorage") {
                    BoxStorage parent = storage;
                    storage = storage.children[0] as BoxStorage;
                    storage.inventory.canAcceptItem = (item, i) => IsStaticFuel(item);
                    storage.inventory.onItemAddedRemoved = (item, b) => CheckForNewFuel(item, b, parent);
                    storage.inventory.capacity = config.staticFuelSize;
                }
                else if (quarryStorage.ShortPrefabName == "engine") {
                    BoxStorage parent = storage;
                    storage = storage.children[0] as BoxStorage;
                    storage.inventory.canAcceptItem = (item, i) => IsExcavatorFuel(item);
                    storage.inventory.onItemAddedRemoved = (item, b) => CheckForNewFuel(item, b, parent);
                    storage.inventory.capacity = config.excavatorFuelSize;
                }
                else if (!isExcavator) {
                    int type = quarry.ShortPrefabName == "pumpjack-static" ? 3 : convertType[quarry.staticType];
                    storage.inventory.canAcceptItem = (item, i) => IsStaticResourceOutput(item, type);
                    storage.inventory.capacity = config.staticResourceSize;
                }
                else {
                    storage.inventory.canAcceptItem = (item, i) => IsStaticResourceOutput(item, 4);
                    storage.inventory.capacity = config.excavatorResourceSize;
                }
                PopUpAPI?.Call("ShowPopUp", player, config.popUpPreset, Lang("PrivateInventoryInfo", player.UserIDString));
            }
            player.inventory.loot.AddContainer(storage.inventory);
            player.inventory.loot.entitySource = storage;
            player.inventory.loot.PositionChecks = false;
            player.inventory.loot.MarkDirty();
            player.inventory.loot.SendImmediate();
            player.ClientRPC(RpcTarget.Player("RPC_OpenLootPanel", player), "generic_resizable");
            Interface.CallHook("OnLootEntity", player, storage);
        }
        //vqType - Quarry Type (All Hooks)
        //player - Static Quarry Types
        //storage - Static Quarry Types
        //quarry - Static Quarry Types
        //playerId - Default Quarry Types
        //restoreId - Default Quarry Types
        private void SpawnQuarry(VirtualQuarry.VqType vqType = VirtualQuarry.VqType.Default, BasePlayer player = null, StorageContainer storage = null, MiningQuarry quarry = null, ulong playerId = 0, int restoreId = -1) {
            bool staticQuarry = vqType != VirtualQuarry.VqType.Default;
            if (!staticQuarry && restoreId == -1 && (!cachedSurveys.ContainsKey(playerId) || (cachedSurveys.ContainsKey(playerId) && cachedSurveys[playerId].resources.Count == 0))) return;
            int worldSize = Convert.ToInt32(World.Size);
            float startX = -worldSize / 1.5f;
            float startZ = worldSize / 1.5f;
            Vector3 newLocation = new Vector3(startX + Core.Random.Range(-50, 50), -400, startZ + Core.Random.Range(-50, 50));
            BoxStorage resourceStorage = GameManager.server.CreateEntity(config.storagePrefab, newLocation) as BoxStorage;
            UnityEngine.Object.Destroy(resourceStorage.GetComponent<GroundWatch>());
            UnityEngine.Object.Destroy(resourceStorage.GetComponent<DestroyOnGroundMissing>());
            resourceStorage.Spawn();
            if (vqType != VirtualQuarry.VqType.Default) resourceStorage.inventory.capacity = staticQuarry ? config.staticResourceSize : config.excavatorResourceSize;
            BoxStorage fuelStorage = GameManager.server.CreateEntity(config.storagePrefab, newLocation) as BoxStorage;
            UnityEngine.Object.Destroy(fuelStorage.GetComponent<GroundWatch>());
            UnityEngine.Object.Destroy(fuelStorage.GetComponent<DestroyOnGroundMissing>());
            fuelStorage.Spawn();
            fuelStorage.SetParent(resourceStorage);
            fuelStorage.transform.position = newLocation + new Vector3(0, 0.7f, 0);
            VirtualQuarry vQuarry = resourceStorage.GetOrAddComponent<VirtualQuarry>();
            if (vqType != VirtualQuarry.VqType.Default) {
                ulong id = !quarry ? uint.MaxValue : quarry.net.ID.Value;
                fuelStorage.inventory.capacity = staticQuarry ? config.staticFuelSize : config.excavatorFuelSize;
                data.staticQuarries[id].TryAdd(player.userID, resourceStorage.net.ID.Value);
                data.staticQuarries[id][player.userID] = resourceStorage.net.ID.Value;
                vQuarry.SetupQuarry(vqType, linkedQuarry : quarry);
                if (storage is ResourceExtractorFuelStorage resourceExtractorFuelStorage) OpenQuarry(player, vqType, true, 0, resourceExtractorFuelStorage, quarry);
                else if (storage is DieselEngine engine) OpenQuarry(player, vqType, true, 0, engine, quarry);
                else if (storage is ExcavatorOutputPile outputPile) OpenQuarry(player, vqType, true, 0, outputPile, quarry);
            }
            else {
                string profile;
                int level = 0;
                int quarryId = restoreId == -1 ? data.quarryCount : restoreId;
                if (restoreId == -1) {
                    data.quarries.TryAdd(data.quarryCount, new QuarryData() {
                        netId = resourceStorage.net.ID.Value, owner = playerId, resources = cachedSurveys[playerId].resources, profile = cachedSurveys[playerId].profile,
                    }
                    );
                    profile = cachedSurveys[playerId].profile;
                    if (config.consoleLogs) Puts($"Player {playerId} placed new quarry with ID {data.quarryCount}.");
                    data.quarryCount++;
                }
                else {
                    profile = data.quarries[restoreId].profile;
                    level = data.quarries[restoreId].level;
                    data.quarries[restoreId].netId = resourceStorage.net.ID.Value;
                }
                List<UpgradeConfig> upgrades = config.quarryProfiles[profile].upgrades;
                resourceStorage.inventory.capacity = upgrades[level].capacity;
                fuelStorage.inventory.capacity = upgrades[level].fuelCapacity;
                vQuarry.SetupQuarry(id : quarryId);
                cachedSurveys.Remove(playerId);
                cachedRequirements.Remove(playerId);
                if (config.storeContainers && restoreId != -1 && storageCache.ContainsKey(restoreId)) {
                    foreach (var item in storageCache[restoreId].resource) {
                        Item restoreItem = ItemManager.CreateByName(item.shortname, item.amount, item.skin);
                        if (!string.IsNullOrEmpty(item.displayName)) restoreItem.name = item.displayName;
                        restoreItem.MoveToContainer(resourceStorage.inventory);
                    }
                    foreach (var item in storageCache[restoreId].fuel) {
                        Item restoreItem = ItemManager.CreateByName(item.shortname, item.amount, item.skin);
                        if (!string.IsNullOrEmpty(item.displayName)) restoreItem.name = item.displayName;
                        restoreItem.MoveToContainer(fuelStorage.inventory);
                    }
                }
            }
        }
#endregion
#region Default Quarries
        private void ShowQuarryAccessList(BasePlayer player, int quarryId) {
            if (data.quarries[quarryId].owner != player.userID && !data.quarries[quarryId].authPlayers.Contains(player.userID)) return;
            string accessList = Lang("AccessListStart", player.UserIDString);
            foreach (var playerId in data.quarries[quarryId].authPlayers) accessList += Lang("AccessListList", player.UserIDString, playerCache[playerId]);
            if (accessList == Lang("AccessListStart", player.UserIDString)) accessList += Lang("AccessListNoAdded", player.UserIDString);
            PopUpAPI?.Call("ShowPopUp", player, config.popUpPreset, accessList, 12);
        }
        private void TryUpgradeQuarry(BasePlayer player, int quarryId, string type) {
            if (data.quarries[quarryId].owner != player.userID && !data.quarries[quarryId].authPlayers.Contains(player.userID)) return;
            QuarryData quarry = data.quarries[quarryId];
            List<UpgradeConfig> upgrades = config.quarryProfiles[quarry.profile].upgrades;
            if (quarry.level >= upgrades.Count - 1) return;
            if (upgrades[quarry.level + 1].requiredPerm != string.Empty && !permission.UserHasPermission(player.UserIDString, upgrades[quarry.level + 1].requiredPerm)) {
                PopUpAPI?.Call("ShowPopUp", player, config.popUpPreset, Lang("NoPermToUpgrade", player.UserIDString));
                return;
            }
            if (type == "currency") {
                if (upgrades[quarry.level + 1].requiredRp == 0) return;
                ulong userId = player.userID.Get();
                if (config.economyPlugin == 1) {
                    if (Economics.Call<double>("Balance", userId) >= upgrades[quarry.level + 1].requiredRp) {
                        Economics.Call("Withdraw", userId, Convert.ToDouble(upgrades[quarry.level + 1].requiredRp));
                        UpgradeQuarry(player, quarryId, type);
                    }
                    else PopUpAPI?.Call("ShowPopUp", player, config.popUpPreset, Lang("NotEnoughCurrency", player.UserIDString));
                }
                else if (config.economyPlugin == 2) {
                    if (ServerRewards.Call<int>("CheckPoints", userId) >= upgrades[quarry.level + 1].requiredRp) {
                        ServerRewards.Call("TakePoints", userId, upgrades[quarry.level + 1].requiredRp);
                        UpgradeQuarry(player, quarryId, type);
                    }
                    else PopUpAPI?.Call("ShowPopUp", player, config.popUpPreset, Lang("NotEnoughCurrency", player.UserIDString));
                }
                else if (config.economyPlugin == 3) {
                    if (IQEconomic.Call<int>("API_GET_BALANCE", userId) >= upgrades[quarry.level + 1].requiredRp) {
                        IQEconomic.Call("API_REMOVE_BALANCE", userId, upgrades[quarry.level + 1].requiredRp);
                        UpgradeQuarry(player, quarryId, type);
                    }
                    else PopUpAPI?.Call("ShowPopUp", player, config.popUpPreset, Lang("NotEnoughCurrency", player.UserIDString));
                }
                else if (config.economyPlugin == 4) {
                    if (BankSystem.Call<int>("Balance", userId) >= upgrades[quarry.level + 1].requiredRp) {
       
// ... [Code preview truncated due to length. Full source in attached file] ...

Автор
15FPS
Скачиваний
0
Просмотры
1
Первый выпуск
Обновление
Оценка
0.00 звёзд 0 оценок
Сверху