using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Oxide.Core;
using Oxide.Game.Rust.Cui;
using UnityEngine;
#region Cache
private readonly Dictionary<ulong, ulong> _recyclerOwners = new();
private readonly HashSet<ulong> _recyclerItemContainers = new();
private readonly HashSet<ulong> _inputItemContainers = new();
private readonly HashSet<ulong> _storageAdapters = new();
private readonly HashSet<ulong> _playersWithUi = new();
#endregion
#region Game Hooks
private void Init()
{
permission.RegisterPermission(PermissionUseRecycler, this);
permission.RegisterPermission(PermissionVip, this);
permission.RegisterPermission(PermissionAdmin, this);
foreach (var command in _config.Commands)
{
cmd.AddChatCommand(command, this, nameof(CommandGetRecycler));
}
cmd.AddChatCommand("upgraderecycler", this, nameof(CommandUpgradeRecycler));
cmd.AddChatCommand("togglerecycler", this, nameof(ToggleRecyclerConfig));
cmd.AddConsoleCommand("industrialrecycler.openinput", this, nameof(OpenInputStorage));
cmd.AddConsoleCommand("industrialrecycler.openoutput", this, nameof(OpenOutputStorage));
}
private void OnServerInitialized()
{
_instance = this;
foreach (var recycler in UnityEngine.Object.FindObjectsOfType<Recycler>())
{
if (recycler.OwnerID != 0UL)
{
recycler.gameObject.AddComponent<RecyclerComponent>();
}
}
}
private void Unload()
{
foreach (var recyclerComponent in UnityEngine.Object.FindObjectsOfType<RecyclerComponent>())
{
UnityEngine.Object.Destroy(recyclerComponent);
}
foreach (var player in BasePlayer.activePlayerList)
{
CuiHelper.DestroyUi(player, UiOverlayName);
}
}
private void OnItemAddedToContainer(ItemContainer container, Item item)
{
Recycler recycler = container.entityOwner as Recycler ?? container.entityOwner?.GetParentEntity() as Recycler;
if (recycler == null)
return;
var recyclerComponent = recycler.GetComponent<RecyclerComponent>();
if (recyclerComponent == null)
return;
bool isMainRecycler = container.entityOwner is Recycler;
ulong containerUid = container.uid.Value;
if (isMainRecycler && _recyclerItemContainers.Contains(containerUid))
{
ProcessRecyclerItems(recyclerComponent, item);
}
else if (!isMainRecycler && _inputItemContainers.Contains(containerUid))
{
recyclerComponent.HandleItemTransfers();
}
}
private void OnEntityBuilt(Planner planner, GameObject entityObject)
{
var player = planner?.GetOwnerPlayer();
var baseEntity = entityObject.GetComponent<BaseEntity>();
if (player == null || baseEntity == null || baseEntity.ShortPrefabName != ItemName || baseEntity.skinID != _config.RecyclerSkinId)
return;
int maxRecyclers = _config.MaxRecyclersPerPlayer;
if (permission.UserHasPermission(player.UserIDString, PermissionAdmin))
{
maxRecyclers = int.MaxValue;
}
else if (permission.UserHasPermission(player.UserIDString, PermissionVip))
{
maxRecyclers = _config.MaxRecyclersVip;
}
if (_recyclerOwners.Count(entry => entry.Value == player.userID) >= maxRecyclers)
{
player.ChatMessage(lang.GetMessage("RecyclerLimitReached", this, player.UserIDString));
timer.Once(1, () => GiveRecyclerItem(player));
NextTick(() => baseEntity?.Kill());
return;
}
if (!InitializeRecyclerPlacement(player, baseEntity))
{
player.ChatMessage(lang.GetMessage("InvalidPlacement", this, player.UserIDString));
timer.Once(1, () => GiveRecyclerItem(player));
}
else
{
player.ChatMessage(lang.GetMessage("RecyclerPlaced", this, player.UserIDString));
}
NextTick(() => baseEntity?.Kill());
}
private object CanPickupEntity(BasePlayer player, IndustrialStorageAdaptor adapter)
{
if (adapter?.net?.ID.Value != null && _storageAdapters.Contains(adapter.net.ID.Value))
{
adapter.GetParentEntity()?.GetParentEntity()?.Kill();
GiveRecyclerItem(player);
player.ChatMessage(lang.GetMessage("RecyclerPickedUp", this, player.UserIDString));
return false;
}
return null;
}
private object OnEntityKill(Recycler recycler)
{
if (!IsRecyclerOwned(recycler))
return null;
UnregisterRecyclerOwnership(recycler);
DropRecyclerItems(recycler);
return null;
}
private bool IsRecyclerOwned(Recycler recycler)
{
return recycler.OwnerID != 0UL && _recyclerOwners.ContainsKey(recycler.net.ID.Value);
}
private void UnregisterRecyclerOwnership(Recycler recycler)
{
_recyclerOwners.Remove(recycler.net.ID.Value);
}
private void DropRecyclerItems(Recycler recycler)
{
var recyclerComponent = recycler.GetComponent<RecyclerComponent>();
recyclerComponent?.DropItems();
}
void OnLootEntity(BasePlayer player, Recycler recycler)
{
if (recycler == null || player == null)
return;
if (recycler.OwnerID != 0UL && _recyclerOwners.ContainsKey(recycler.net.ID.Value))
{
_playersWithUi.Add(player.userID);
string recyclerId = recycler.net.ID.Value.ToString();
CreateUi(player, recyclerId);
}
}
private void OnPlayerLootEnd(PlayerLoot playerLoot)
{
BasePlayer player = playerLoot.GetComponentInParent<BasePlayer>();
if (player == null)
return;
if (_playersWithUi.Contains(player.userID))
{
_playersWithUi.Remove(player.userID);
CuiHelper.DestroyUi(player, UiOverlayName);
}
}
#endregion
#region UI
private void CreateUi(BasePlayer player, string recyclerId)
{
var container = new CuiElementContainer();
container.Add(
new CuiPanel
{
CursorEnabled = true,
Image =
{
Color = "1 1 1 0.15",
Sprite = "assets/content/ui/ui.background.transparent.radial.psd",
Material = "assets/content/ui/uibackgroundblur.mat",
},
RectTransform =
{
AnchorMin = _config.AnchorMin,
AnchorMax = _config.AnchorMax,
OffsetMin = "341.64 405.595",
OffsetMax = "554.76 505.605",
},
},
"Overlay",
UiOverlayName
);
container.Add(
new CuiElement
{
Name = "Text",
Parent = UiOverlayName,
Components =
{
new CuiTextComponent
{
Text = "INDUSTRIAL RECYCLER",
Font = "robotocondensed-bold.ttf",
FontSize = 17,
Align = TextAnchor.MiddleCenter,
Color = "1 1 1 1",
},
new CuiOutlineComponent { Color = "0 0 0 1", Distance = "1 1" },
new CuiRectTransformComponent
{
AnchorMin = "0.5 0.5",
AnchorMax = "0.5 0.5",
OffsetMin = "-86.493 0",
OffsetMax = "86.492 34.875",
},
},
}
);
container.Add(
new CuiButton
{
Button =
{
Color = "0.3960785 0.4666667 0.2627451 1",
Command = $"industrialrecycler.openinput {recyclerId}",
Close = UiOverlayName,
},
Text =
{
Text = lang.GetMessage("InputButton", this, player.UserIDString),
Font = "robotocondensed-regular.ttf",
FontSize = 18,
Align = TextAnchor.MiddleCenter,
Color = "1 1 1 1",
},
RectTransform =
{
AnchorMin = "0.5 0.5",
AnchorMax = "0.5 0.5",
OffsetMin = "-104.206 -49.58",
OffsetMax = "-2.394 -17.22",
},
},
UiOverlayName,
"Input"
);
container.Add(
new CuiButton
{
Button =
{
Color = "0.3960785 0.4666667 0.2627451 1",
Command = $"industrialrecycler.openoutput {recyclerId}",
Close = UiOverlayName,
},
Text =
{
Text = lang.GetMessage("OutputButton", this, player.UserIDString),
Font = "robotocondensed-regular.ttf",
FontSize = 18,
Align = TextAnchor.MiddleCenter,
Color = "1 1 1 1",
},
RectTransform =
{
AnchorMin = "0.5 0.5",
AnchorMax = "0.5 0.5",
OffsetMin = "1.994 -49.58",
OffsetMax = "103.806 -17.22",
},
},
UiOverlayName,
"Output"
);
container.Add(
new CuiButton
{
Button =
{
Color = "0.3960785 0.7666667 0.2627451 1",
Command = $"chat.say /togglerecycler",
Close = "ToggleConfig",
},
Text =
{
Text = lang.GetMessage("ToggleConfig", this),
Font = "robotocondensed-regular.ttf",
FontSize = 14,
Align = TextAnchor.MiddleCenter,
Color = "1 1 1 1",
},
RectTransform =
{
AnchorMin = "1 1",
AnchorMax = "1 1",
OffsetMin = "-110 -20",
OffsetMax = "0 0",
},
},
UiOverlayName,
"ToggleConfig"
);
CuiHelper.DestroyUi(player, UiOverlayName);
CuiHelper.AddUi(player, container);
}
private void OpenInputStorage(ConsoleSystem.Arg arg)
{
OpenStorage(arg, true);
}
private void OpenOutputStorage(ConsoleSystem.Arg arg)
{
OpenStorage(arg, false);
}
private void OpenStorage(ConsoleSystem.Arg arg, bool isInput)
{
var player = arg.Player();
if (player == null)
{
return;
}
if (arg.Args.Length == 0)
{
return;
}
if (!uint.TryParse(arg.Args[0], out uint recyclerId))
{
return;
}
var networkableId = new NetworkableId(recyclerId);
var recycler = BaseNetworkable.serverEntities.Find(networkableId) as Recycler;
if (recycler != null)
{
var recyclerComponent = recycler.GetComponent<RecyclerComponent>();
if (recyclerComponent != null)
{
var storage = isInput ? recyclerComponent.InputStorage : recyclerComponent.OutputStorage;
player.inventory.loot.StartLootingEntity(storage, true);
player.inventory.loot.AddContainer(storage.inventory);
player.inventory.loot.SendImmediate();
player.ClientRPCPlayer(null, player, "RPC_OpenLootPanel", storage.panelName);
}
}
}
#endregion
#region Main
private void CommandGetRecycler(BasePlayer player, string command, string[] args)
{
if (player == null)
return;
if (!permission.UserHasPermission(player.UserIDString, PermissionUseRecycler))
{
player.ChatMessage(lang.GetMessage("NoPermission", this, player.UserIDString));
return;
}
BasePlayer targetPlayer = player;
if (args != null && args.Length > 0)
{
targetPlayer = BasePlayer.Find(args[0]);
if (targetPlayer == null)
{
player.ChatMessage(lang.GetMessage("PlayerNotFound", this, player.UserIDString));
return;
}
}
if (GiveRecyclerItem(targetPlayer))
{
player.ChatMessage(lang.GetMessage("RecyclerGiven", this, player.UserIDString));
if (targetPlayer != player)
{
targetPlayer.ChatMessage(lang.GetMessage("RecyclerReceived", this, targetPlayer.UserIDString));
}
}
else
{
player.ChatMessage(lang.GetMessage("RecyclerNotGiven", this, player.UserIDString));
if (targetPlayer != player)
{
targetPlayer.ChatMessage(lang.GetMessage("RecyclerNotReceived", this, targetPlayer.UserIDString));
}
}
}
private bool GiveRecyclerItem(BasePlayer player)
{
var recyclerItem = ItemManager.CreateByName(ItemName, 1, _config.RecyclerSkinId);
if (recyclerItem == null)
return false;
recyclerItem.name = "Recycler";
return player.inventory.GiveItem(recyclerItem);
}
private void CommandUpgradeRecycler(BasePlayer player, string command, string[] args)
{
if (!permission.UserHasPermission(player.UserIDString, PermissionUseRecycler))
{
player.ChatMessage(lang.GetMessage("NoPermission", this, player.UserIDString));
return;
}
int maxRecyclers = _config.MaxRecyclersPerPlayer;
if (permission.UserHasPermission(player.UserIDString, PermissionAdmin))
{
maxRecyclers = int.MaxValue;
}
else if (permission.UserHasPermission(player.UserIDString, PermissionVip))
{
maxRecyclers = _config.MaxRecyclersVip;
}
if (_recyclerOwners.Count(entry => entry.Value == player.userID) >= maxRecyclers)
{
player.ChatMessage(lang.GetMessage("RecyclerLimitReached", this, player.UserIDString));
return;
}
if (!UpgradeToIndustrialRecycler(player))
{
player.ChatMessage(lang.GetMessage("NoRecyclerInView", this, player.UserIDString));
}
else
{
player.ChatMessage(lang.GetMessage("RecyclerUpgraded", this, player.UserIDString));
}
}
private Recycler FindRecyclerInView(BasePlayer player)
{
if (Physics.Raycast(player.eyes.HeadRay(), out RaycastHit hit, 5f))
{
BaseEntity entity = hit.GetEntity();
return entity as Recycler;
}
return null;
}
private bool InitializeRecyclerPlacement(BasePlayer player, BaseEntity baseEntity, int turn = 0)
{
var supportingFoundation = FindSupportingFoundation(baseEntity);
if (supportingFoundation == null)
return false;
var spawnedRecycler = SpawnRecyclerWithComponents(player, baseEntity, supportingFoundation, turn);
if (spawnedRecycler == null)
return false;
spawnedRecycler.gameObject.AddComponent<RecyclerComponent>();
return true;
}
private bool InitializeUpgradeRecycler(BasePlayer player, Recycler recycler, int turn = 0)
{
var spawnedRecycler = UpgradeRecyclerWithComponents(player, recycler, turn);
if (spawnedRecycler == null)
return false;
spawnedRecycler.gameObject.AddComponent<RecyclerComponent>();
return true;
}
private BuildingBlock FindSupportingFoundation(BaseEntity baseEntity)
{
Vector3 origin = baseEntity.transform.position + Vector3.up * 0.1f;
if (Physics.Raycast(origin, Vector3.down, out RaycastHit hitData, 4f, LayerMask.GetMask("Construction")))
{
return hitData.GetEntity() as BuildingBlock;
}
return null;
}
private Recycler SetupStorageAndAdapters(Recycler recycler, BasePlayer player)
{
Vector3 inputOffset,
inputAdapterOffset,
outputOffset,
outputAdapterOffset;
Quaternion inputRotation,
outputRotation,
inputAdapterRotation,
outputAdapterRotation;
if (_config.UseAlternativeAdapterConfig)
{
inputOffset = new Vector3(0.0f, 0.72f, 0.11f);
inputAdapterOffset = new Vector3(0.32f, -0.6f, -0.03f);
outputOffset = new Vector3(-0.4f, 0.8f, 0.2f);
outputAdapterOffset = new Vector3(-0.07f, 0.535f, 0.397f);
inputRotation = Quaternion.Euler(0, 180, 191);
outputRotation = Quaternion.Euler(169, 90, 180);
inputAdapterRotation = Quaternion.Euler(0, 0, 0);
outputAdapterRotation = Quaternion.Euler(180, 90, 0);
}
else
{
inputOffset = new Vector3(-1.0f, 0.72f, 0.31f);
inputAdapterOffset = new Vector3(0.00f, -0.15f, -0.25f);
outputOffset = new Vector3(-0.9f, 0.72f, -0.09f);
outputAdapterOffset = new Vector3(0.00f, 0.26f, -0.05f);
inputRotation = Quaternion.Euler(90, 90, 180);
outputRotation = Quaternion.Euler(180, 90, 180);
inputAdapterRotation = Quaternion.Euler(180, 90, 270);
outputAdapterRotation = Quaternion.Euler(0, 90, 0);
}
var inputStorage = SpawnEntity(InputStoragePrefabPath, recycler, player, inputOffset, inputRotation);
SpawnEntity(AdapterPrefabPath, inputStorage, player, inputAdapterOffset, inputAdapterRotation);
var outputStorage = SpawnEntity(OutputStoragePrefabPath, recycler, player, outputOffset, outputRotation);
SpawnEntity(AdapterPrefabPath, outputStorage, player, outputAdapterOffset, outputAdapterRotation);
return recycler;
}
private Recycler UpgradeRecyclerWithComponents(BasePlayer player, Recycler recycler, int turn = 0)
{
return SetupStorageAndAdapters(recycler, player);
}
private Recycler SpawnRecyclerWithComponents(BasePlayer player, BaseEntity baseEntity, BuildingBlock foundation, int turn = 0)
{
var recycler = SpawnEntity(RecyclerPrefabPath, foundation, player, baseEntity.transform.position, baseEntity.transform.rotation * Quaternion.Euler(0, turn, 0)) as Recycler;
if (recycler == null)
return null;
return SetupStorageAndAdapters(recycler, player);
}
private BaseEntity SpawnEntity(string prefabPath, BaseEntity parent, BasePlayer player, Vector3 position, Quaternion rotation)
{
var entity = GameManager.server.CreateEntity(prefabPath, Vector3.zero, Quaternion.identity, true);
if (entity == null)
return null;
entity.OwnerID = player.userID;
if (parent != null)
{
entity.SetParent(parent, true);
}
if (parent is BuildingBlock)
{
entity.transform.position = position;
entity.transform.rotation = rotation;
}
else
{
entity.transform.localPosition = position;
entity.transform.localRotation = rotation;
}
entity.Spawn();
entity.SendNetworkUpdateImmediate();
return entity;
}
private void ProcessRecyclerItems(RecyclerComponent recyclerComponent, Item item)
{
if (item.position < 6)
{
recyclerComponent.Recycler.StartRecycling();
}
else
{
if (!item.MoveToContainer(recyclerComponent.OutputStorage.inventory))
{
recyclerComponent.Recycler.StopRecycling();
}
}
}
private bool UpgradeToIndustrialRecycler(BasePlayer player)
{
if (Physics.Raycast(player.eyes.HeadRay(), out RaycastHit hit, 5f))
{
BaseEntity baseEntity = hit.GetEntity();
if (baseEntity is Recycler recycler && recycler.OwnerID == player.userID)
{
if (!InitializeUpgradeRecycler(player, baseEntity as Recycler, 90))
{
player.ChatMessage(lang.GetMessage("InvalidPlacement", this, player.UserIDString));
timer.Once(1, () => GiveRecyclerItem(player));
return false;
}
else
{
player.ChatMessage(lang.GetMessage("RecyclerPlaced", this, player.UserIDString));
}
return true;
}
}
return false;
}
private void ToggleRecyclerConfig(BasePlayer player, string command, string[] args)
{
if (!permission.UserHasPermission(player.UserIDString, PermissionUseRecycler))
{
player.ChatMessage(lang.GetMessage("NoPermission", this, player.UserIDString));
return;
}
Recycler recycler = FindRecyclerInView(player);
if (recycler == null)
{
player.ChatMessage(lang.GetMessage("NoRecyclerInView", this, player.UserIDString));
return;
}
var recyclerComponent = recycler.GetComponent<RecyclerComponent>();
if (recyclerComponent == null)
{
player.ChatMessage(lang.GetMessage("RecyclerComponentNotFound", this, player.UserIDString));
return;
}
recyclerComponent.ToggleConfig();
player.ChatMessage(lang.GetMessage("RecyclerConfigToggled", this, player.UserIDString));
}
#endregion
#region Configuration
private class Configuration
{
[JsonProperty("Commands")]
public List<string> Commands { get; set; }
[JsonProperty("Max Recyclers Per Player")]
public int MaxRecyclersPerPlayer { get; set; }
[JsonProperty("Max Recyclers Vip (industrialrecycler.vip)")]
public int MaxRecyclersVip { get; set; }
[JsonProperty("Recycler Item SkinId")]
public ulong RecyclerSkinId { get; set; }
[JsonProperty("AnchorMin")]
public string AnchorMin { get; set; }
[JsonProperty("AnchorMax")]
public string AnchorMax { get; set; }
[JsonProperty("Alternative Adapter Configuration")]
public bool UseAlternativeAdapterConfig { get; set; }
[JsonProperty("Hide Storage Containers")]
public bool HideStorageContainers { get; set; }
[JsonProperty("Only owner can access recycler")]
public bool OnlyOwnerAccess { get; set; }
[JsonProperty("Allow team members to access recycler")]
public bool AllowTeamAccess { get; set; }
[JsonProperty("Version")]
public VersionNumber Version { get; set; }
}
protected override void LoadConfig()
{
base.LoadConfig();
try
{
_config = Config.ReadObject<Configuration>() ?? throw new Exception("Failed to read configuration file.");
bool configChanged = false;
if (_config.Version != Version)
{
_config.Version = Version;
configChanged = true;
}
if (string.IsNullOrEmpty(_config.AnchorMin))
{
_config.AnchorMin = "0.5 0";
configChanged = true;
}
if (string.IsNullOrEmpty(_config.AnchorMax))
{
_config.AnchorMax = "0.5 0";
configChanged = true;
}
if (!_config.UseAlternativeAdapterConfig)
{
_config.UseAlternativeAdapterConfig = false;
configChanged = true;
}
if (configChanged)
{
SaveConfig();
}
}
catch (Exception ex)
{
PrintError($"There was an error in your configuration file: {ex.Message}. Default values will be used.");
LoadDefaultConfig();
}
}
protected override void LoadDefaultConfig()
{
_config = GetDefaultConfig();
SaveConfig();
}
protected override void SaveConfig()
{
Config.WriteObject(_config, true);
}
private Configuration GetDefaultConfig()
{
return new Configuration
{
Commands = new List<string> { "getrecycler", "irecycler", "giverecycler" },
MaxRecyclersPerPlayer = 1,
MaxRecyclersVip = 2,
RecyclerSkinId = 3357927081,
AnchorMin = "0.5 0",
AnchorMax = "0.5 0",
UseAlternativeAdapterConfig = false,
HideStorageContainers = false,
OnlyOwnerAccess = true,
AllowTeamAccess = true,
Version = Version,
};
}
#endregion
#region Localization
protected override void LoadDefaultMessages()
{
lang.RegisterMessages(
new Dictionary<string, string>
{
["NoPermission"] = "You do not have permission to use this command.",
["RecyclerLimitReached"] = "You have reached the recycler limit.",
["InvalidPlacement"] = "The recycler must be placed on a construction block.",
["RecyclerPlaced"] = "Recycler placed successfully.",
["RecyclerPickedUp"] = "Recycler picked up, item returned to inventory.",
["RecyclerGiven"] = "Recycler given to your inventory.",
["RecyclerReceived"] = "You have received a recycler.",
["RecyclerNotGiven"] = "Failed to give recycler.",
["RecyclerNotReceived"] = "Failed to receive recycler.",
["NoRecyclerInView"] = "No recycler in sight to upgrade.",
["RecyclerComponentNotFound"] = "Recycler component not found.",
["RecyclerConfigToggled"] = "Recycler configuration toggled successfully.",
["PlayerNotFound"] = "The specified player could not be found.",
["ToggleConfig"] = "Toggle",
["InputButton"] = "Input",
["OutputButton"] = "Output",
},
this
);
lang.RegisterMessages(
new Dictionary<string, string>
{
["NoPermission"] = "Você não tem permissão para usar este comando.",
["RecyclerLimitReached"] = "Você atingiu o limite de recicladores.",
["InvalidPlacement"] = "O reciclador deve ser colocado sobre um bloco de construção.",
["RecyclerPlaced"] = "Reciclador colocado com sucesso.",
["RecyclerPickedUp"] = "Reciclador recolhido, item devolvido ao inventário.",
["RecyclerGiven"] = "Reciclador fornecido ao seu inventário.",
["RecyclerReceived"] = "Você recebeu um reciclador.",
["RecyclerNotGiven"] = "Falha ao fornecer o reciclador.",
["RecyclerNotReceived"] = "Falha ao receber o reciclador.",
["NoRecyclerInView"] = "Nenhum reciclador à vista para atualizar.",
["RecyclerComponentNotFound"] = "Componente de reciclador não encontrado.",
["RecyclerConfigToggled"] = "Configuração do reciclador alternada com sucesso.",
["PlayerNotFound"] = "O jogador especificado não pôde ser encontrado.",
["ToggleConfig"] = "Alterar",
["InputButton"] = "Entrada",
["OutputButton"] = "Saída",
},
this,
"pt-BR"
);
lang.RegisterMessages(
new Dictionary<string, string>
{
["NoPermission"] = "Sie haben keine Erlaubnis, diesen Befehl zu verwenden.",
["RecyclerLimitReached"] = "Sie haben die Grenze für Recycler erreicht.",
["InvalidPlacement"] = "Der Recycler muss auf einem Baublock platziert werden.",
["RecyclerPlaced"] = "Recycler erfolgreich platziert.",
["RecyclerPickedUp"] = "Recycler aufgenommen, Artikel in das Inventar zurückgegeben.",
["RecyclerGiven"] = "Recycler wurde Ihrem Inventar hinzugefügt.",
["RecyclerReceived"] = "Sie haben einen Recycler erhalten.",
["RecyclerNotGiven"] = "Recycle fehlerhaft vorhanden.",
["RecyclerNotReceived"] = "Falschen Empfang des Recyclers.",
["NoRecyclerInView"] = "Kein Recycler in Sicht, um aufzurüsten.",
["RecyclerComponentNotFound"] = "Recycler-Komponente nicht gefunden.",
["RecyclerConfigToggled"] = "Recycler-Konfiguration erfolgreich umgeschaltet.",
["PlayerNotFound"] = "Der angegebene Spieler konnte nicht gefunden werden.",
["ToggleConfig"] = "Umschalten",
["InputButton"] = "Eingang",
["OutputButton"] = "Ausgang",
},
this,
"de"
);
lang.RegisterMessages(
new Dictionary<string, string>
{
["NoPermission"] = "No tienes permiso para usar este comando.",
["RecyclerLimitReached"] = "Has alcanzado el límite de recicladores.",
["InvalidPlacement"] = "El reciclador debe colocarse en un bloque de construcción.",
["RecyclerPlaced"] = "Reciclador colocado con éxito.",
["RecyclerPickedUp"] = "Reciclador recogido, artículo devuelto al inventario.",
["RecyclerGiven"] = "Reciclador dado a tu inventario.",
["RecyclerReceived"] = "Has recibido un reciclador.",
["RecyclerNotGiven"] = "Fallo al dar el reciclador.",
["RecyclerNotReceived"] = "Fallo al recibir el reciclador.",
["NoRecyclerInView"] = "No hay reciclador a la vista para mejorar.",
["RecyclerComponentNotFound"] = "Componente de reciclador no encontrado.",
["RecyclerConfigToggled"] = "Configuración del reciclador alternada con éxito.",
["PlayerNotFound"] = "No se pudo encontrar al jugador especificado.",
["ToggleConfig"] = "Alternar",
["InputButton"] = "Entrada",
["OutputButton"] = "Salida",
},
this,
"es"
);
}
#endregion
#region Component
private class RecyclerComponent : MonoBehaviour
{
public Recycler Recycler { get; private set; }
public StorageContainer InputStorage { get; private set; }
public StorageContainer OutputStorage { get; private set; }
public int CurrentConfigState { get; private set; }
private const int MaxStorageCapacity = 48;
private const float TransferInterval = 10f;
private enum RecyclerConfig
{
Default = 1,
Alternative = 2,
}
private void Awake()
{
Recycler = GetComponent<Recycler>();
if (Recycler == null)
{
Debug.LogError("Recycler component is missing on this GameObject.");
enabled = false;
return;
}
// Start with a default known state
CurrentConfigState = (int)RecyclerConfig.Default;
InitializeRecyclerComponents();
}
private void InitializeRecyclerComponents()
{
foreach (MonoBehaviour mb in GetComponents<MonoBehaviour>())
{
var type = mb.GetType();
if (type != typeof(Recycler) && type != typeof(RecyclerComponent) && type.Name != "Ground_Watch")
{
Destroy(mb);
}
}
if (!ValidateStorageContainers())
{
Debug.LogError("Failed to validate storage containers.");
enabled = false;
return;
}
SetupRecycler();
RegisterEntities();
InvokeRepeating(nameof(HandleItemTransfers), 0f, TransferInterval);
}
private bool ValidateStorageContainers()
{
InputStorage = Recycler.children.OfType<StorageContainer>().FirstOrDefault(c => c?.name == InputStoragePrefabPath);
OutputStorage = Recycler.children.OfType<StorageContainer>().FirstOrDefault(c => c?.name == OutputStoragePrefabPath);
return InputStorage != null && OutputStorage != null;
}
private void RegisterEntities()
{
_instance._inputItemContainers.Add(InputStorage.inventory.uid.Value);
_instance._recyclerItemContainers.Add(Recycler.inventory.uid.Value);
var inputAdapter = InputStorage.children.OfType<IndustrialStorageAdaptor>().FirstOrDefault();
if (inputAdapter != null)
_instance._storageAdapters.Add(inputAdapter.net.ID.Value);
var outputAdapter = OutputStorage.children.OfType<IndustrialStorageAdaptor>().FirstOrDefault();
if (outputAdapter != null)
_instance._storageAdapters.Add(outputAdapter.net.ID.Value);
}
private void SetupRecycler()
{
if (Recycler == null || InputStorage == null || OutputStorage == null)
{
Debug.LogError("Attempted to setup recycler with null components.");
return;
}
_instance._recyclerOwners[Recycler.net.ID.Value] = Recycler.OwnerID;
InputStorage.inventory.capacity = MaxStorageCapacity;
OutputStorage.inventory.capacity = MaxStorageCapacity;
}
public void HandleItemTransfers()
{
int availableRecyclerSlots = 6 - Recycler.inventory.itemList.Count;
if (OutputStorage.inventory.IsFull())
{
Recycler.StopRecycling();
return;
}
TransferItemsFromRecyclerToOutput(ref availableRecyclerSlots);
TransferItemsFromInputToRecycler(ref availableRecyclerSlots);
if (availableRecyclerSlots < 6 && Recycler.inventory.itemList.Count > 0)
{
Recycler.StartRecycling();
}
}
private void TransferItemsFromRecyclerToOutput(ref int availableRecyclerSlots)
{
for (int slot = 6; slot < Recycler.inventory.capacity; slot++)
{
var itemInRecycler = Recycler.inventory.GetSlot(slot);
if (itemInRecycler != null && itemInRecycler.MoveToContainer(OutputStorage.inventory))
{
availableRecyclerSlots++;
}
}
}
private void TransferItemsFromInputToRecycler(ref int availableRecyclerSlots)
{
var inputItems = new List<Item>(InputStorage.inventory.itemList);
foreach (var item in inputItems)
{
if (item.info.Blueprint != null)
{
MoveItemToRecycler(item, ref availableRecyclerSlots);
}
else
{
item.MoveToContainer(OutputStorage.inventory);
}
}
}
private void MoveItemToRecycler(Item item, ref int availableRecyclerSlots)
{
if (availableRecyclerSlots <= 0)
return;
for (int slot = 0; slot < 6; slot++)
{
if (Recycler.inventory.GetSlot(slot) == null && item.MoveToContainer(Recycler.inventory, slot))
{
availableRecyclerSlots--;
break;
}
}
}
public void ToggleConfig()
{
CancelInvoke(nameof(HandleItemTransfers));
CurrentConfigState = (int)(CurrentConfigState == (int)RecyclerConfig.Default ? RecyclerConfig.Alternative : RecyclerConfig.Default);
List<(string Shortname, int Amount, float ConditionNormalized)> ExtractItemDetails(ItemContainer container) =>
container?.itemList?.Select(item => (item.info.shortname, item.amount, item.conditionNormalized)).ToList() ?? new List<(string, int, float)>();
var inputItemDetails = ExtractItemDetails(InputStorage.inventory);
var outputItemDetails = ExtractItemDetails(OutputStorage.inventory);
ClearExistingComponents();
UpdateAdapterPositions();
InitializeRecyclerComponents();
if (InputStorage == null || OutputStorage == null || Recycler == null)
{
Debug.LogError("As referências dos contêineres não foram atualizadas.");
return;
}
foreach (var (shortname, amount, condition) in inputItemDetails)
CreateAndMoveItem(shortname, amount, condition, InputStorage.inventory);
foreach (var (shortname, amount, condition) in outputItemDetails)
CreateAndMoveItem(shortname, amount, condition, OutputStorage.inventory);
}
private void CreateAndMoveItem(string shortname, int amount, float conditionNormalized, ItemContainer container)
{
var item = ItemManager.CreateByName(shortname, amount);
if (item != null)
{
item.conditionNormalized = conditionNormalized;
if (!item.MoveToContainer(container))
item.Remove();
}
}
private void UpdateAdapterPositions()
{
ClearExistingComponents();
Vector3 inputOffset,
outputOffset,
inputAdapterOffset,
outputAdapterOffset;
Quaternion inputRotation,
outputRotation,
inputAdapterRotation,
outputAdapterRotation;
if (CurrentConfigState == (int)RecyclerConfig.Default)
{
inputOffset = new Vector3(0.0f, 0.72f, 0.11f);
outputOffset = new Vector3(-0.4f, 0.8f, 0.2f);
inputAdapterOffset = new Vector3(0.32f, -0.6f, -0.03f);
outputAdapterOffset = new Vector3(-0.07f, 0.535f, 0.397f);
inputRotation = Quaternion.Euler(0, 180, 191);
outputRotation = Quaternion.Euler(169, 90, 180);
inputAdapterRotation = Quaternion.Euler(0, 0, 0);
outputAdapterRotation = Quaternion.Euler(180, 90, 0);
}
else
{
if (_instance._config.HideStorageContainers)
{
inputOffset = new Vector3(0.0f, 0.72f, 0.11f);
outputOffset = new Vector3(-0.4f, 0.72f, 0.2f);
inputAdapterOffset = new Vector3(0.836f, -0.3301f, 0.18f);
outputAdapterOffset = new Vector3(-0.227f, 0.33f, 0.434f);
inputRotation = Quaternion.Euler(0, 0, 180);
outputRotation = Quaternion.Euler(180, 90, 180);
inputAdapterRotation = Quaternion.Euler(0, 0, 0);
outputAdapterRotation = Quaternion.Euler(180, 90, 0);
}
else
{
inputOffset = new Vector3(-1.0f, 0.72f, 0.31f);
outputOffset = new Vector3(-0.9f, 0.72f, -0.09f);
inputAdapterOffset = new Vector3(0.00f, -0.15f, -0.25f);
outputAdapterOffset = new Vector3(0.00f, 0.26f, -0.05f);
inputRotation = Quaternion.Euler(90, 90, 180);
outputRotation = Quaternion.Euler(180, 90, 180);
inputAdapterRotation = Quaternion.Euler(180, 90, 270);
outputAdapterRotation = Quaternion.Euler(0, 90, 0);
}
}
BasePlayer ownerPlayer = BasePlayer.FindByID(Recycler.OwnerID);
if (ownerPlayer != null)
{
var inputStorage = _instance.SpawnEntity(InputStoragePrefabPath, Recycler, ownerPlayer, inputOffset, inputRotation) as StorageContainer;
if (inputStorage == null)
{
Debug.LogError("Failed to spawn input storage.");
return;
}
_instance.SpawnEntity(AdapterPrefabPath, inputStorage, ownerPlayer, inputAdapterOffset, inputAdapterRotation);
var outputStorage = _instance.SpawnEntity(OutputStoragePrefabPath, Recycler, ownerPlayer, outputOffset, outputRotation) as StorageContainer;
if (outputStorage == null)
{
Debug.LogError("Failed to spawn output storage.");
return;
}
_instance.SpawnEntity(AdapterPrefabPath, outputStorage, ownerPlayer, outputAdapterOffset, outputAdapterRotation);
}
}
private void ClearExistingComponents()
{
foreach (var child in Recycler.children.ToList())
{
if (child is StorageContainer || child is IndustrialStorageAdaptor)
{
child.Kill();
}
}
}
internal void DropItems()
{
var allItems = GatherAllItems();
DropItemsInBatches(allItems, MaxStorageCapacity);
}
private List<Item> GatherAllItems()
{
return InputStorage.inventory.itemList.Concat(OutputStorage.inventory.itemList).Concat(Recycler.inventory.itemList).ToList();
}
private void DropItemsInBatches(List<Item> items, int batchSize)
{
var recyclerPosition = Recycler.transform.position;
var recyclerRotation = Recycler.transform.rotation;
for (int i = 0; i < items.Count; i += batchSize)
{
var itemBatch = items.Skip(i).Take(batchSize).ToList();
SpawnDroppedItemContainer(recyclerPosition, recyclerRotation, itemBatch);
}
}
private DroppedItemContainer SpawnDroppedItemContainer(Vector3 position, Quaternion rotation, List<Item> itemsToDrop)
{
var containerPrefabPath = "assets/prefabs/misc/item drop/item_drop.prefab";
var droppedItemContainer = GameManager.server.CreateEntity(containerPrefabPath, position, rotation) as DroppedItemContainer;
if (droppedItemContainer == null)
return null;
InitializeItemContainer(droppedItemContainer, itemsToDrop);
droppedItemContainer.Spawn();
return droppedItemContainer;
}
private void InitializeItemContainer(DroppedItemContainer container, List<Item> items)
{
container.inventory = new ItemContainer();
container.inventory.ServerInitialize(null, items.Count);
container.inventory.GiveUID();
container.inventory.entityOwner = container;
foreach (var item in items)
{
item.MoveToContainer(container.inventory);
}
}
private void OnDestroy()
{
CancelInvoke(nameof(HandleItemTransfers));
}
}
#endregion
}
}
Assistant
The script appears to be a plugin for the game Rust, written using the Oxide API. It's designed to automate recycling processes by allowing players to attach industrial storage and adapters to in-game recyclers. Below is a high-level breakdown of the key features and components of the script:
Permissions: There are three permission levels used in this script - industrialrecycler.give, industrialrecycler.vip, and industrialrecycler.admin. These permissions control access to various commands and functionalities of the plugin.
Commands: The script uses chat and console commands for players to interact with the plugin:
Chat Commands:
"/getrecycler": Allows players to obtain a recycler.
"/upgraderecycler": Upgrades a recycler in view.
"/togglerecycler": Toggles the recycler's configuration.
Console Commands:
"industrialrecycler.openinput" and "industrialrecycler.openoutput": Allow players to open the input and output storage UI for a recycler.
Recycler Initialization: When a recycler is placed, the plugin spawns the necessary storage and adapter entities as children of the recycler and registers their ownership to the player.
Recycler Component:
The RecyclerComponent is attached to each recycler, managing the automation of item transfers between input storage, recycler inventory, and output storage.
It periodically transfers recyclable items from input storage to the recycler and moves processed items to output storage.
The component supports switching between different configurations via the ToggleConfig function.
UI Management: A simple user interface allows players to interact with the recycler and its storage components. The UI displays buttons to open input and output storages and to toggle configurations.
Item Drop and Cleanup: On recycler removal, items are dropped onto the ground to ensure no items are lost.
Configuration and Localization: The plugin supports multiple languages and allows certain settings, such as the number of recyclers a player can own and the appearance of the recycler, to be configured via a JSON file.
The script effectively leverages Oxide's API to integrate with Rust's game mechanics, offering controlled automation that enhances gameplay while maintaining balance through permissions and configurations. If you have any specific questions or need help with a particular part of the script, feel free to ask!
User
using Oxide.Core.Plugins;
using System;
using System.Collections.Generic;
using Oxide.Core;
using Oxide.Game.Rust;
using UnityEngine;
using System.Reflection;
using Oxide.Core.Libraries.Covalence;
using System.Linq;
namespace Oxide.Plugins
{
[Info("PreventLooting", "CaseMan", "1.15.0", ResourceId = 2469)]
[Description("Prevent looting by other players")]
code
Assistant
This script is a Rust plugin, built using Oxide (now uMod's) API, called PreventLooting. It is designed to manage permissions related to looting entities, including players and specific in-game objects, thereby preventing unauthorized access. Here's a breakdown of the script's functionality and components:
Key Features and Functionalities:
Permission System:
The plugin enables the use of permission checks to control which actions are allowed based on user permissions.
Six permissions are defined: preventlooting.use, preventlooting.player, preventlooting.corpse, preventlooting.backpack, preventlooting.storage, and preventlooting.admin.
Plugin References:
This plugin supports integration with other plugins like Friends, ZoneManager, and DynamicPVP to expand its functionality.
Friends API and Teams are used to determine if a looter has special privileges.
Looting Prevention Mechanisms:
The plugin provides hooks to prevent looting of players, corpses, entities (like storage containers), and backpacks.
Hooks also encompass looting or interacting with weapon racks, picking up items, and authorizing on tool cupboards.
Zoning and Dynamic PVP Checks:
If configured, the plugin can prevent looting based on player zones as defined by ZoneManager or if the player is in a Dynamic PVP zone.
Configurable Options:
The configuration allows for toggling looting permissions and interactions, such as whether players can loot their own corpses or operate ovens.
Exclude specific entities from being protected.
Authorization Checks:
Determines looting permissions based on authorization lists and building privilege checks.
Sharing System:
Allows players to share or unshare access to their entities with other players.
Commands like /share, /unshare, /sharelist, and /shareclear enable a user to manage these permissions.
Localization:
The plugin supports multiple languages, allowing server operators to provide messages in different languages.
User
quero usar a mesma lógica do prevent looting , usando também [PluginReference] Plugin Friends; para o meu plugin IndustrialRecycler, com as configs OnlyOwnerAccess, AllowTeamAccess e AllowFriendsAccess, para bloquear o acesso ao recycler, ajuste meu plugin IndustrialRecycler e me mande completo
Assistant
To incorporate the logic from the PreventLooting plugin into the IndustrialRecycler plugin, we need to introduce similar permission checks and configurations using the Friends plugin as well as any already established configuration settings like AllowTeamAccess and OnlyOwnerAccess. Here's how you can adjust your IndustrialRecycler plugin:
Add Plugin References:
Reference the Friends plugin.
Introduce Configuration Options:
Add configurations for AllowFriendsAccess, OnlyOwnerAccess, and AllowTeamAccess.
Implement Permission Checks:
Implement logic to check if the player is the owner, a friend, or a team member before allowing access to the recycler.
Below is the complete code integrating these changes:
csharp
User
diverssos metódos estão falvando da versão original, e traduções também, recoloque todos e ajuste, aqui como era antes:
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Oxide.Core;
using Oxide.Game.Rust.Cui;
using UnityEngine;
Here is the updated IndustrialRecycler plugin with the requested changes, ensuring all methods and translations from your original version are included and the permissions via Friends, Owner, and Team access are checked:
csharp
User
foi removido? CanPickupEntity
me mande ele atualizado se sim
Assistant
Apologies for the oversight. Let's integrate the CanPickupEntity method into the updated IndustrialRecycler plugin. This method is used to prevent unauthorized players from picking up recyclers or associated components.
Here’s the updated version of the IndustrialRecycler plugin including the CanPickupEntity method:
csharp
User
preciso que seja criado para os storages da recycler algo parecido tbm
private object CanLootEntity(BasePlayer player, Recycler recycler)
{
if (!HasAccess(player, recycler))
{
player.ChatMessage(lang.GetMessage("NoAccess", this, player.UserIDString));
return false;
}
return null;
}
Assistant
Sure! To add similar access control logic for the storage containers attached to the recyclers, we can introduce a method that uses the same HasAccess logic to determine if a player can access the storage containers. Here's how you can add this feature:
csharp
User
pq esse valores estão ficando nulos quando atualizo a configuração para incluir eles na nova veersão?
"Only owner can access recycler": false,
"Allow team members to access recycler": false,
"Allow friends to access recycler": false,
o que precisao alterar para eles ficarem como no valor padrão
Assistant
When updating configurations to include new settings in a plugin, the default values for these settings must be explicitly set when loading the configuration. If your configuration doesn't already include these settings, they will be null by default because they are missing from the configuration file.
To ensure that these settings are assigned default values when loading the configuration, you should initialize them in the LoadConfig method. Here's the part of your plugin that handles configuration loading, updated to ensure that the new settings are correctly initialized if they are not present in the configuration file:
csharp
protected override void LoadConfig()
{
base.LoadConfig();
try
{
_config = Config.ReadObject<Configuration>() ?? throw new Exception("Failed to read configuration file.");
bool configChanged = false;
if (_config.Version != Version)
{
_config.Version = Version;
configChanged = true;
}
if (string.IsNullOrEmpty(_config.AnchorMin))
{
_config.AnchorMin = "0.5 0";
configChanged = true;
}
if (string.IsNullOrEmpty(_config.AnchorMax))
{
_config.AnchorMax = "0.5 0";
configChanged = true;
}
if (!_config.UseAlternativeAdapterConfig)
{
_config.UseAlternativeAdapterConfig = false;
configChanged = true;
}
// Ensure new configuration keys have default values if not already present
if (!Config.ContainsKey("Only owner can access recycler"))
{
_config.OnlyOwnerAccess = true; // Default value
configChanged = true;
}
if (!Config.ContainsKey("Allow team members to access recycler"))
{
_config.AllowTeamAccess = true; // Default value
configChanged = true;
}
if (!Config.ContainsKey("Allow friends to access recycler"))
{
_config.AllowFriendsAccess = true; // Default value
configChanged = true;
}
if (configChanged)
{
SaveConfig();
}
}
catch (Exception ex)
{
PrintError($"There was an error in your configuration file: {ex.Message}. Default values will be used.");
LoadDefaultConfig();
}
}
User
'DynamicConfigFile' does not contain a definition for 'ContainsKey' and no accessible extension method 'ContainsKey' accepting a first argument of type 'DynamicConfigFile' could be found (are you missing a using directive or an assembly reference?)CS1061
Assistant
The error you're encountering is due to an attempt to use the ContainsKey method, which is not available on the DynamicConfigFile type used by Oxide for plugin configuration management. Instead, you should directly check the presence of keys within the _config object you parsed from the configuration file.
Here’s how you can modify your code to check for the existence of keys in a way that works with Oxide's configuration system:
csharp
protected override void LoadConfig()
{
base.LoadConfig();
try
{
_config = Config.ReadObject<Configuration>() ?? throw new Exception("Failed to read configuration file.");
bool configChanged = false;
if (_config.Version != Version)
{
_config.Version = Version;
configChanged = true;
}
if (string.IsNullOrEmpty(_config.AnchorMin))
{
_config.AnchorMin = "0.5 0";
configChanged = true;
}
if (string.IsNullOrEmpty(_config.AnchorMax))
{
_config.AnchorMax = "0.5 0";
configChanged = true;
}
if (!_config.UseAlternativeAdapterConfig)
{
_config.UseAlternativeAdapterConfig = false;
configChanged = true;
}
// Ensure new configuration keys have default values if not already present
if (_config.OnlyOwnerAccess.Equals(null))
{
_config.OnlyOwnerAccess = true; // Default value
configChanged = true;
}
if (_config.AllowTeamAccess.Equals(null))
{
_config.AllowTeamAccess = true; // Default value
configChanged = true;
}
if (_config.AllowFriendsAccess.Equals(null))
{
_config.AllowFriendsAccess = true; // Default value
configChanged = true;
}
if (configChanged)
{
SaveConfig();
}
}
catch (Exception ex)
{
PrintError($"There was an error in your configuration file: {ex.Message}. Default values will be used.");
LoadDefaultConfig();
}
}
User
consegue faze rum check se a versão da config antiga for menor que atual atualizar
Assistant
Certainly! To update the configuration file based on version changes, you can implement a version check within your LoadConfig method. When you load the configuration, compare the version number from the file to the current version of your plugin. If the loaded version is older, you can update the configuration with new defaults and save it back.
Here's how you can implement such logic:
csharp
protected override void LoadConfig()
{
base.LoadConfig();
try
{
_config = Config.ReadObject<Configuration>() ?? throw new Exception("Failed to read configuration file.");
bool configChanged = false;
// Check if the configuration version is older than the plugin version
if (_config.Version == null || _config.Version < Version)
{
PrintWarning("Updating configuration file to new version.");
_config.Version = Version;
configChanged = true;
// Set new settings defaults in case they are not set in older versions
if (!_config.OnlyOwnerAccess.HasValue)
{
_config.OnlyOwnerAccess = true; // Default value
configChanged = true;
}
if (!_config.AllowTeamAccess.HasValue)
{
_config.AllowTeamAccess = true; // Default value
configChanged = true;
}
if (!_config.AllowFriendsAccess.HasValue)
{
_config.AllowFriendsAccess = true; // Default value
configChanged = true;
}
}
if (string.IsNullOrEmpty(_config.AnchorMin))
{
_config.AnchorMin = "0.5 0";
configChanged = true;
}
if (string.IsNullOrEmpty(_config.AnchorMax))
{
_config.AnchorMax = "0.5 0";
configChanged = true;
}
if (configChanged)
{
PrintWarning("Configuration changes detected, saving changes.");
SaveConfig();
}
}
catch (Exception ex)
{
PrintError($"There was an error in your configuration file: {ex.Message}. Default values will be used.");
LoadDefaultConfig();
}
}
User
ajustei assim, está correto?
protected override void LoadConfig()
{
base.LoadConfig();
try
{
_config = Config.ReadObject() ?? throw new Exception("Failed to read configuration file.");
code
bool configChanged = false;
// Check if the configuration version is older than the plugin version
if (_config.Version == null || _config.Version < Version)
{
PrintWarning("Updating configuration file to new version.");
_config.Version = Version;
_config.OnlyOwnerAccess = true; // Default value
_config.AllowTeamAccess = true; // Default value
_config.AllowFriendsAccess = true; // Default value
configChanged = true;
}
if (string.IsNullOrEmpty(_config.AnchorMin))
{
_config.AnchorMin = "0.5 0";
configChanged = true;
}
if (string.IsNullOrEmpty(_config.AnchorMax))
{
_config.AnchorMax = "0.5 0";
configChanged = true;
}
if (configChanged)
{
PrintWarning("Configuration changes detected, saving changes.");
SaveConfig();
}
}
catch (Exception ex)
{
PrintError($"There was an error in your configuration file: {ex.Message}. Default values will be used.");
LoadDefaultConfig();
}
}
Assistant
Yes, the adjustments you've made look correct for updating your configuration based on version changes. Let's go through your setup to confirm:
Version Check: You correctly check if the configuration version is either null or less than the current plugin version. This triggers an update process for the configuration data.
Setting Default Values: When you detect that the version is outdated, you properly update the necessary configuration values such as OnlyOwnerAccess, AllowTeamAccess, and AllowFriendsAccess to their default values. This ensures that these settings are initialized, even if they weren't present in the previous configuration.
Configuration Change Detection: You use a configChanged flag to determine if any changes were made to the configuration. If changes were made, you save the configuration back to the file system.
Logging: You have included logging with PrintWarning to inform about configuration updates and changes, which is useful for debugging and maintenance.
Error Handling: By catching exceptions during configuration loading, you fall back to loading the default configuration if an error occurs, ensuring robustness.
Overall, your approach effectively updates the configuration when needed, maintains proper logging and error handling, and ensures that the configuration is saved correctly after updates. Just ensure that the VersionNumber Version represents the current plugin version you're comparing against. If everything else in your configuration and plugin setup aligns with your use case, you're on the right track!
class PreventLooting : RustPlugin
{
#region Variables
[PluginReference] Plugin Friends;
[PluginReference] Plugin ZoneManager;
[PluginReference] Plugin DynamicPVP;
bool UsePermission;
bool UseFriendsAPI;
bool UseTeams;
bool AdminCanLoot;
bool CanAuthCB;
bool CanLootPl;
bool CanLootCorpse;
bool CanLootEnt;
bool CanRWMount;
bool CanRWSwap;
bool CanRWTake;
bool CanRWUnload;
bool CanRWLoad;
bool CanLootBackpack;
bool CanLootBackpackPlugin;
bool CanPickup;
bool CanOvenToggle;
bool IncludeZoneMode;
bool UseZoneManager;
bool UseDynamicPVP;
bool UseExcludeEntities;
bool UseCupboard;
List<object> UseCupboardInclude;
bool UseOnlyInCupboardRange;
List<object> UseOnlyInCupboardRangeInclude;
bool WipeDetected = false;
List<object> ZoneID;
List<object> ExcludeEntities;
string PLPerm = "preventlooting.use";
string PlayerPerm = "preventlooting.player";
string CorpsePerm = "preventlooting.corpse";
string BackpackPerm = "preventlooting.backpack";
string StoragePerm = "preventlooting.storage";
string AdmPerm = "preventlooting.admin";
class StoredData
{
public Dictionary<ulong, EntityData> Data = new Dictionary<ulong, EntityData>();
public StoredData()
{
}
}
class EntityData
{
public List<ulong> Share = new List<ulong>();
public Dictionary<string, List<ulong>> Quarry = new Dictionary<string, List<ulong>>();
public EntityData(){}
}
StoredData storedData;
#endregion
#region Initialization
void Init()
{
LoadDefaultConfig();
permission.RegisterPermission(PLPerm, this);
permission.RegisterPermission(AdmPerm, this);
permission.RegisterPermission(PlayerPerm, this);
permission.RegisterPermission(CorpsePerm, this);
permission.RegisterPermission(BackpackPerm, this);
permission.RegisterPermission(StoragePerm, this);
storedData = Interface.Oxide.DataFileSystem.ReadObject<StoredData>("PreventLooting");
}
void OnServerInitialized()
{
if(WipeDetected)
{
PrintWarning("Wipe detected! Clearing all share data!");
storedData.Data.Clear();
Interface.Oxide.DataFileSystem.WriteObject("PreventLooting", storedData);
}
}
void OnServerSave() => Interface.Oxide.DataFileSystem.WriteObject("PreventLooting", storedData);
void Unload() => Interface.Oxide.DataFileSystem.WriteObject("PreventLooting", storedData);
void OnNewSave(string filename) => WipeDetected = true;
#endregion
#region Configuration
protected override void LoadDefaultConfig()
{
Config["UsePermission"] = UsePermission = GetConfig("UsePermission", false);
Config["UseFriendsAPI"] = UseFriendsAPI = GetConfig("UseFriendsAPI", true);
Config["UseTeams"] = UseTeams = GetConfig("UseTeams", true);
Config["AdminCanLoot"] = AdminCanLoot = GetConfig("AdminCanLoot", true);
Config["CanAuthorizeCupboard"] = CanAuthCB = GetConfig("CanAuthorizeCupboard", true);
Config["CanLootPlayer"] = CanLootPl = GetConfig("CanLootPlayer", false);
Config["CanLootCorpse"] = CanLootCorpse = GetConfig("CanLootCorpse", false);
Config["CanLootEntity"] = CanLootEnt = GetConfig("CanLootEntity", false);
Config["CanRackedWeaponMount"] = CanRWMount = GetConfig("CanRackedWeaponMount", false);
Config["CanRackedWeaponSwap"] = CanRWSwap = GetConfig("CanRackedWeaponSwap", false);
Config["CanRackedWeaponTake"] = CanRWTake = GetConfig("CanRackedWeaponTake", false);
Config["CanRackedWeaponUnload"] = CanRWUnload = GetConfig("CanRackedWeaponUnload", false);
Config["CanRackedWeaponLoad"] = CanRWLoad = GetConfig("CanRackedWeaponLoad", false);
Config["CanLootBackpack"] = CanLootBackpack = GetConfig("CanLootBackpack", false);
Config["CanLootBackpackPlugin"] = CanLootBackpackPlugin = GetConfig("CanLootBackpackPlugin", false);
Config["CanPickup"] = CanPickup = GetConfig("CanPickup", false);
Config["CanOvenToggle"] = CanOvenToggle = GetConfig("CanOvenToggle", false);
Config["UseZoneManager"] = UseZoneManager = GetConfig("UseZoneManager", false);
Config["ZoneManagerIncludeMode"] = IncludeZoneMode = GetConfig("ZoneManagerIncludeMode", false);
Config["ZoneID"] = ZoneID = GetConfig("ZoneID", new List<object>{"12345678"});
Config["UseDynamicPVP"] = UseDynamicPVP = GetConfig("UseDynamicPVP", false);
Config["UseExcludeEntities"] = UseExcludeEntities = GetConfig("UseExcludeEntities", true);
Config["ExcludeEntities"] = ExcludeEntities = GetConfig("ExcludeEntities", new List<object>{"mailbox.deployed"});
Config["UseCupboard"] = UseCupboard = GetConfig("UseCupboard", false);
Config["UseCupboardInclude"] = UseCupboardInclude = GetConfig("UseCupboardInclude", new List<object>{"storage"});
Config["UseOnlyInCupboardRange"] = UseOnlyInCupboardRange = GetConfig("UseOnlyInCupboardRange", false);
Config["UseOnlyInCupboardRangeInclude"] = UseOnlyInCupboardRangeInclude = GetConfig("UseOnlyInCupboardRangeInclude", new List<object>{"storage"});
SaveConfig();
}
#endregion
#region Localization
void LoadDefaultMessages()
{
lang.RegisterMessages(new Dictionary<string, string>
{
["OnTryLootPlayer"] = "You can not loot players!",
["OnTryLootCorpse"] = "You can not loot corpses of players!",
["OnTryLootEntity"] = "You can not use this entity because it is not yours!",
["OnTryLootWeaponRack"] = "You can not use this weapon rack because it is not yours!",
["OnTryLootBackpack"] = "You can not open this backpack because it is not yours!",
["OnTryPickup"] = "You can not pickup this because it is not yours!",
["NoAccess"] = "This entity is not yours!",
["PlayerNotFound"] = "Player {0} not found!",
["ShareAll"] = "All players were given permission to use this entity!",
["SharePlayer"] = "The player {0} was given permission to use this entity!",
["NoShare"] = "No permissions have been found for this entity!",
["ListShare"] = "List of permissions for this entity:",
["EntityNotFound"] = "You are not standing in front of the entity or away from it!",
["HasShareAllList"] = "All players are allowed to use this entity!",
["ShareClear"] = "All permissions for this entity have been deleted!",
["HasShareAll"] = "All players already have permission to use this entity!",
["HasSharePlayer"] = "Player {0} already has permission to use this entity!",
["HasUnShareAll"] = "Permission to use this entity has not been issued to all players!",
["HasUnSharePlayer"] = "Player {0} has not been granted permission to use this entity!",
["WasUnShareAll"] = "All players have been removed permission for this entity!",
["WasUnSharePlayer"] = "The permission to use this entity has been removed from player {0}!",
["MultiplePlayerFind"]="Multiple players found:",
["OwnEntity"]="This object is yours!",
["NoPermission"]="You do not have enough rights to execute this command!",
["EntPrevent"] = "This entity is protected!",
["EntNoPrevent"] = "This entity is not protected!",
["OnTryOnOff"] = "You can not turn on or off this entity because it is not yours!",
["OnTryAuthCB"] = "You can not authorize in cupboard because it is not yours!",
}, this);
lang.RegisterMessages(new Dictionary<string, string>
{
["OnTryLootPlayer"] = "Вы не можете обворовывать игроков!",
["OnTryLootCorpse"] = "Вы не можете обворовывать трупы игроков!",
["OnTryLootEntity"] = "Вы не можете использовать этот объект, потому что он вам не принадлежит!",
["OnTryLootWeaponRack"] = "Вы не можете использовать эту оружейную стойку, потому что она вам не принадлежит!",
["OnTryLootBackpack"] = "Вы не можете открыть чужой рюкзак!",
["OnTryPickup"] = "Вы не можете взять чужое!",
["NoAccess"]="Этот объект не принадлежит вам!",
["PlayerNotFound"]="Игрок с именем {0} не найден!",
["ShareAll"]="Всем игрокам было выдано разрешение на использование этого объекта!",
["SharePlayer"]="Игроку {0} было выдано разрешение на использование этого объекта!",
["NoShare"]="Не найдено разрешений для этого объекта!",
["ListShare"]="Список разрешений для этого объекта:",
["EntityNotFound"]="Вы стоите не перед хранилищем или далеко от него!",
["HasShareAllList"]="Всем игрокам разрешено использовать этот объект!",
["ShareClear"]="Все разрешения для этого объекта были удалены!",
["HasShareAll"]="Все игроки уже имеют разрешение на использование этого объекта!",
["HasSharePlayer"]="Игрок {0} уже имеет разрешение на использование этого объекта!",
["HasUnShareAll"]="Разрешение на использование этого объекта не было выдано для всех игроков!",
["HasUnSharePlayer"]="Игроку {0} не было выдано разрешение на использование этого объекта!",
["WasUnShareAll"]="Всем игрокам было удалено разрешение на использование этого объекта!",
["WasUnSharePlayer"]="Игроку {0} было удалено разрешение на использование этого объекта!",
["MultiplePlayerFind"]="Найдено несколько игроков:",
["OwnEntity"]="Этот объект принадлежит вам!",
["NoPermission"]="У вас недостаточно прав для выполнения этой команды!",
["EntPrevent"]="Этот предмет защищен от воровства!",
["EntNoPrevent"]="Этот предмет не защищен от воровства!",
["OnTryOnOff"] = "Вы не можете включить или выключить этот объект, потому что он вам не принадлежит!",
["OnTryAuthCB"] = "Вы не можете авторизоваться в чужом шкафу, потому что он вам не принадлежит!",
}, this, "ru");
}
#endregion
#region Hooks
private object CanLootEntity(BasePlayer player, LootableCorpse corpse)
{
if(corpse == null || player == null) return null;
if(CanLootCorpse) return null;
if(CheckHelper(player, corpse as BaseEntity)) return null;
if(IsFriend(corpse.playerSteamID, player.userID)) return null;
if(UsePermission && !permission.UserHasPermission(corpse.playerSteamID.ToString(), CorpsePerm)) return null;
if(corpse.playerSteamID < 76561197960265728L || player.userID == corpse.playerSteamID) return null;
if(UseCupboard || UseOnlyInCupboardRange)
if(CheckAuthCupboard(corpse, player)) return null;
SendReply(player, lang.GetMessage("OnTryLootCorpse", this, player.UserIDString));
return true;
}
private void OnItemDropped(Item item, BaseEntity entity)
{
if (item.info.itemid == -907422733 || item.info.itemid == 2068884361)
{
entity.OwnerID = item.GetOwnerPlayer()?.userID ?? 0;
}
}
private object OnItemPickup(Item item, BasePlayer player)
{
if(item == null || player == null) return null;
BaseEntity entity = item?.GetWorldEntity();
if(CheckHelper(player, entity)) return null;
if(entity.OwnerID != 0 && entity.OwnerID != player.userID && !IsFriend(entity.OwnerID, player.userID))
{
if(item.info.itemid == -907422733 || item.info.itemid == 2068884361)
{
if(UseCupboard || UseOnlyInCupboardRange)
if(CheckAuthCupboard(entity, player)) return null;
SendReply(player, lang.GetMessage("OnTryPickup", this, player.UserIDString));
return false;
}
return null;
}
return null;
}
private void OnLootEntity(BasePlayer player, BaseEntity entity)
{
Item item = entity?.GetItem();
if(item == null || player == null) return;
if(CheckHelper(player, entity)) return;
if (item.info.itemid == -907422733 || item.info.itemid == 2068884361)
{
if(CanLootBackpack) return;
if(IsFriend(entity.OwnerID, player.userID)) return;
if(UsePermission && !permission.UserHasPermission(entity.OwnerID.ToString(), BackpackPerm)) return;
if(entity.OwnerID < 76561197960265728L || player.userID == entity.OwnerID) return;
if(UseCupboard || UseOnlyInCupboardRange)
if(CheckAuthCupboard(entity, player)) return;
NextFrame(() =>
{
player.inventory.loot.Clear();
player.inventory.loot.SendImmediate();
});
SendReply(player, lang.GetMessage("OnTryLootBackpack", this, player.UserIDString));
}
}
private object CanLootEntity(BasePlayer player, DroppedItemContainer container)
{
if(container == null || player == null) return null;
if(CanLootBackpack && CanLootBackpackPlugin) return null;
if(CheckHelper(player, container as BaseEntity)) return null;
if(((container as BaseEntity).name.Contains("item_drop_backpack") && !CanLootBackpack) || ((container as BaseEntity).name.Contains("droppedbackpack") && !CanLootBackpackPlugin))
{
if(IsFriend(container.playerSteamID, player.userID)) return null;
if(UsePermission && !permission.UserHasPermission(container.playerSteamID.ToString(), BackpackPerm)) return null;
if(container.playerSteamID < 76561197960265728L || player.userID == container.playerSteamID) return null;
if(UseCupboard || UseOnlyInCupboardRange)
if(CheckAuthCupboard(container, player)) return null;
SendReply(player, lang.GetMessage("OnTryLootBackpack", this, player.UserIDString));
return true;
}
return null;
}
private object CanLootPlayer(BasePlayer target, BasePlayer player)
{
if(target == null || player == null) return null;
if(CanLootPl) return null;
if(CheckHelper(player, target as BaseEntity)) return null;
if(IsFriend(target.userID, player.userID)) return null;
if(UsePermission && !permission.UserHasPermission(target.userID.ToString(), PlayerPerm)) return null;
if(player.userID == target.userID) return null;
if(UseCupboard || UseOnlyInCupboardRange)
if(CheckAuthCupboard(target, player)) return null;
SendReply(player, lang.GetMessage("OnTryLootPlayer", this, player.UserIDString));
return false;
}
private bool CheckHelper(BasePlayer player, BaseEntity entity)
{
if(entity == null || player == null) return true;
if(player.IsAdmin && AdminCanLoot) return true;
if(permission.UserHasPermission(player.userID.ToString(), AdmPerm)) return true;
if(UseZoneManager && ZoneManager != null)
{
if(CheckDynamicPVP(player)) return true;
if((string[])ZoneManager.Call("GetPlayerZoneIDs", player) != null)
{
if(!IncludeZoneMode)
{
foreach(var zoneID in ZoneID)
{
if((bool)ZoneManager.Call("isPlayerInZone", zoneID, player)) return true;
}
}
else
{
foreach(var zoneID in ZoneID)
{
if((bool)ZoneManager.Call("isPlayerInZone", zoneID, player)) return false;
}
return true;
}
}
}
if(entity is SupplyDrop) return true;
return false;
}
private bool CheckDynamicPVP(BasePlayer player)
{
if(UseDynamicPVP && DynamicPVP != null)
{
var Zones = (string[])ZoneManager.Call("GetPlayerZoneIDs", player);
foreach (var zoneID in Zones)
{
if((bool)DynamicPVP.Call("IsDynamicPVPZone", zoneID)) return true;
}
}
return false;
}
private object CanLootEntity(BasePlayer player, StorageContainer container)
{
if(container == null || player == null) return null;
if(CanLootEnt) return null;
BaseEntity entity = container as BaseEntity;
if(CheckHelper(player, entity)) return null;
BaseEntity childentity = entity;
entity = CheckParent(entity);
if(entity.OwnerID == player.userID) return null;
if(UsePermission && !permission.UserHasPermission(entity.OwnerID.ToString(), StoragePerm)) return null;
if(UseExcludeEntities)
{
if(ExcludeEntities.Contains(entity.ShortPrefabName)) return null;
}
if(IsVendingOpen(player, entity) || IsDropBoxOpen(player, entity)) return null;
if(IsFriend(entity.OwnerID, player.userID)) return null;
if(storedData.Data.ContainsKey(entity.net.ID.Value))
{
if(childentity == entity)
{
if(storedData.Data[entity.net.ID.Value].Share.Contains(player.userID) || storedData.Data[entity.net.ID.Value].Share.Contains(0)) return null;
}
else
{
if(storedData.Data[entity.net.ID.Value].Quarry.ContainsKey(childentity.ShortPrefabName))
if(storedData.Data[entity.net.ID.Value].Quarry[childentity.ShortPrefabName].Contains(player.userID) || storedData.Data[entity.net.ID.Value].Quarry[childentity.ShortPrefabName].Contains(0)) return null;
}
}
if(entity.OwnerID != player.userID && entity.OwnerID != 0)
{
if(UseCupboard || UseOnlyInCupboardRange)
if(CheckAuthCupboard(entity, player)) return null;
SendReply(player, lang.GetMessage("OnTryLootEntity", this, player.UserIDString));
return false;
}
return null;
}
private bool CheckRackedWeapon(BasePlayer player, BaseEntity entity)
{
if(CheckHelper(player, entity)) return true;
if(entity.OwnerID == player.userID) return true;
if(UsePermission && !permission.UserHasPermission(entity.OwnerID.ToString(), StoragePerm)) return true;
if(UseExcludeEntities)
{
if(ExcludeEntities.Contains(entity.ShortPrefabName)) return true;
}
if(IsFriend(entity.OwnerID, player.userID)) return true;
if(storedData.Data.ContainsKey(entity.net.ID.Value))
{
if(storedData.Data[entity.net.ID.Value].Share.Contains(player.userID) || storedData.Data[entity.net.ID.Value].Share.Contains(0)) return true;
}
if(entity.OwnerID != player.userID && entity.OwnerID != 0)
{
if(UseCupboard || UseOnlyInCupboardRange)
if(CheckAuthCupboard(entity, player)) return true;
SendReply(player, lang.GetMessage("OnTryLootWeaponRack", this, player.UserIDString));
return false;
}
return true;
}
private object OnRackedWeaponMount(Item weapon, BasePlayer player, WeaponRack rack)
{
if(rack == null || player == null || weapon == null) return null;
if(CanRWMount) return null;
BaseEntity entity = rack as BaseEntity;
if(CheckRackedWeapon(player, entity)) return null;
return false;
}
private object OnRackedWeaponSwap(Item weaponMounting, WeaponRackSlot weaponTaking, BasePlayer player, WeaponRack rack)
{
if(rack == null || player == null || weaponMounting == null) return null;
if(CanRWSwap) return null;
BaseEntity entity = rack as BaseEntity;
if(CheckRackedWeapon(player, entity)) return null;
return false;
}
private object OnRackedWeaponTake(Item weapon, BasePlayer player, WeaponRack rack)
{
if(rack == null || player == null || weapon == null) return null;
if(CanRWTake) return null;
BaseEntity entity = rack as BaseEntity;
if(CheckRackedWeapon(player, entity)) return null;
return false;
}
private object OnRackedWeaponUnload(Item weapon, BasePlayer player, WeaponRack rack)
{
if(rack == null || player == null || weapon == null) return null;
if(CanRWUnload) return null;
BaseEntity entity = rack as BaseEntity;
if(CheckRackedWeapon(player, entity)) return null;
return false;
}
private object OnRackedWeaponLoad(Item weapon, ItemDefinition ammoItem, BasePlayer player, WeaponRack rack)
{
if(rack == null || player == null || weapon == null) return null;
if(CanRWLoad) return null;
BaseEntity entity = rack as BaseEntity;
if(CheckRackedWeapon(player, entity)) return null;
return false;
}
private object OnOvenToggle(BaseOven oven, BasePlayer player)
{
if(oven == null || player == null) return null;
if(CanOvenToggle) return null;
BaseEntity entity = oven as BaseEntity;
if(CheckHelper(player, entity)) return null;
if(entity.OwnerID == player.userID) return null;
if(entity.OwnerID != 0 && entity.OwnerID != player.userID && !IsFriend(entity.OwnerID, player.userID))
{
if(UseCupboard || UseOnlyInCupboardRange)
if(CheckAuthCupboard(entity, player)) return null;
SendReply(player, lang.GetMessage("OnTryOnOff", this, player.UserIDString));
return false;
}
return null;
}
private object CanPickupEntity(BasePlayer player, BaseCombatEntity ent)
{
if(ent == null || player == null) return null;
if(CanPickup) return null;
BaseEntity entity = ent as BaseEntity;
if(CheckHelper(player, entity)) return null;
if(entity.OwnerID != 0 && entity.OwnerID != player.userID && !IsFriend(entity.OwnerID, player.userID))
{
if(UseCupboard || UseOnlyInCupboardRange)
if(CheckAuthCupboard(entity, player)) return null;
SendReply(player, lang.GetMessage("OnTryPickup", this, player.UserIDString));
return false;
}
return null;
}
private object OnCupboardAuthorize(BuildingPrivlidge privilege, BasePlayer player)
{
if(CanAuthCB) return null;
BaseEntity entity = privilege as BaseEntity;
if(CheckHelper(player, entity)) return null;
if(entity.OwnerID != 0 && entity.OwnerID != player.userID && !IsFriend(entity.OwnerID, player.userID))
{
SendReply(player, lang.GetMessage("OnTryAuthCB", this, player.UserIDString));
return false;
}
return null;
}
private BaseEntity CheckParent(BaseEntity entity)
{
if(entity.HasParent())
{
BaseEntity parententity = entity.GetParentEntity();
if(parententity is MiningQuarry)
{
entity.OwnerID=parententity.OwnerID;
entity=parententity;
}
}
return entity;
}
object CanAdministerVending(BasePlayer player, VendingMachine machine)
{
if(machine == null || player == null) return null;
if(CanLootEnt) return null;
BaseEntity entity = machine as BaseEntity;
if(CheckHelper(player, entity)) return null;
if(UsePermission && !permission.UserHasPermission(entity.OwnerID.ToString(), StoragePerm)) return null;
if(entity.OwnerID == player.userID) return null;
if(UseExcludeEntities)
{
if(ExcludeEntities.Contains(entity.ShortPrefabName)) return null;
}
if(IsFriend(entity.OwnerID, player.userID)) return null;
if(entity.OwnerID != player.userID && entity.OwnerID != 0)
{
if(UseCupboard || UseOnlyInCupboardRange)
if(CheckAuthCupboard(entity, player)) return null;
SendReply(player, lang.GetMessage("OnTryLootEntity", this, player.UserIDString));
return false;
}
return null;
}
bool IsVendingOpen(BasePlayer player, BaseEntity entity)
{
if(entity is VendingMachine)
{
VendingMachine shopFront = entity as VendingMachine;
if(shopFront.PlayerInfront(player)) return true;
return false;
}
return false;
}
bool IsDropBoxOpen(BasePlayer player, BaseEntity entity)
{
if(entity is DropBox)
{
DropBox dropboxFront = entity as DropBox;
if(dropboxFront.PlayerInfront(player)) return true;
return false;
}
return false;
}
bool IsFriend(ulong friendid, ulong playerid)
{
if(UseFriendsAPI && Friends != null)
{
var fr = Friends.CallHook("AreFriends", friendid, playerid);
if (fr != null && (bool)fr) return true;
}
if(UseTeams)
{
BasePlayer player = BasePlayer.FindByID(playerid);
if(player == null) return false;
if (player.currentTeam != (long)0)
{
RelationshipManager.PlayerTeam playerTeam = RelationshipManager.ServerInstance.FindTeam(player.currentTeam);
if(playerTeam == null) return false;
if(playerTeam.members.Contains(friendid)) return true;
}
}
return false;
}
bool FindEntityFromRay(BasePlayer player, out object success)
{
success = null;
RaycastHit hit;
if (!Physics.Raycast(player.eyes.HeadRay(), out hit, 2.2f))
return false;
success = hit.GetEntity();
return true;
}
bool CheckAuthCupboard(object ent, BasePlayer player)
{
BaseEntity entity = ent as BaseEntity;
ulong ownerid = 0;
string type = "";
if(ent is BaseCombatEntity)
if((ent as BaseCombatEntity).pickup.enabled) type = "pickup";
if(ent is StorageContainer || ent is MiningQuarry || ent is WeaponRack)
{
ownerid = entity.OwnerID;
type = "storage";
}
else if(ent is BasePlayer)
{
ownerid = (ent as BasePlayer).userID;
type = "player";
}
else if(ent is LootableCorpse)
{
ownerid = (ent as LootableCorpse).playerSteamID;
type = "corpse";
}
else if(ent is DroppedItemContainer)
{
ownerid = (ent as DroppedItemContainer).playerSteamID;
if(entity.name.Contains("item_drop_backpack")) type = "backpack";
else if (entity.name.Contains("droppedbackpack")) type = "backpackplugin";
}
BuildingPrivlidge bprev = player.GetBuildingPrivilege(new OBB(entity.transform.position, entity.transform.rotation, entity.bounds));
if(UseOnlyInCupboardRangeInclude.Contains(type) && bprev == null)
{
if(UseOnlyInCupboardRange) return true;
if(!UseOnlyInCupboardRange) return false;
}
if(UseCupboard && UseCupboardInclude.Contains(type) && bprev != null)
{
if(ownerid != 0)
{
if(bprev.IsAuthed(player) && bprev.authorizedPlayers.Any<ProtoBuf.PlayerNameID>((ProtoBuf.PlayerNameID x) => x.userid == ownerid)) return true;
}
else
{
if(bprev.IsAuthed(player)) return true;
}
}
return false;
}
private IPlayer CheckPlayer(BasePlayer player, string[] args)
{
var playerlist = covalence.Players.FindPlayers(args[0]).ToList();
if(playerlist.Count > 1)
{
var message="<color=#FF0000>"+lang.GetMessage("MultiplePlayerFind", this, player.UserIDString)+"</color>\n";
int i=0;
foreach(var pl in playerlist)
{
i++;
message+= string.Format("{0}. <color=#FFA500>{1}</color> ({2})\n\r", i, pl.Name, pl.Id);
}
SendReply(player, message);
return null;
}
var player0 = covalence.Players.FindPlayer(args[0]);
if(player0==null)
{
SendReply(player, string.Format(lang.GetMessage("PlayerNotFound", this, player.UserIDString), "<color=#FFA500>"+args[0]+"</color>"));
return null;
}
return player0;
}
#endregion
#region Commands
[ChatCommand("share")]
void Share(BasePlayer player, string command, string[] args)
{
if (UsePermission && !permission.UserHasPermission(player.UserIDString, PLPerm))
{
SendReply(player, lang.GetMessage("NoPermission", this, player.UserIDString));
return;
}
IPlayer player0 = null;
ulong ID;
if (args == null || args.Length <= 0) ID=0;
else
{
player0 = CheckPlayer(player, args);
if(player0 == null) return;
ID=Convert.ToUInt64(player0.Id);
}
object success;
if (FindEntityFromRay(player, out success))
{
if (success is StorageContainer)
{
BaseEntity entity = success as BaseEntity;
BaseEntity childentity = entity;
entity = CheckParent(entity);
if(entity.OwnerID == ID)
{
SendReply(player, lang.GetMessage("OwnEntity", this, player.UserIDString));
return;
}
if(entity.OwnerID != player.userID && (!player.IsAdmin || (player.IsAdmin && !AdminCanLoot)))
{
SendReply(player, lang.GetMessage("NoAccess", this, player.UserIDString));
return;
}
if(!storedData.Data.ContainsKey(entity.net.ID.Value))
{
var data = new EntityData();
storedData.Data.Add(entity.net.ID.Value, data);
if(childentity != entity)
{
data.Quarry = new Dictionary<string, List<ulong>>();
data.Quarry.Add(childentity.ShortPrefabName, new List<ulong>{ID});
}
else
{
data.Share = new List<ulong>();
data.Share.Add(ID);
}
if(ID==0) SendReply(player, lang.GetMessage("ShareAll", this, player.UserIDString));
else SendReply(player, string.Format(lang.GetMessage("SharePlayer", this, player.UserIDString), "<color=#FFA500>"+player0.Name+"</color>"));
}
else
{
if(childentity == entity)
{
if(storedData.Data[entity.net.ID.Value].Share.Contains(ID))
{
if(ID==0) SendReply(player, lang.GetMessage("HasShareAll", this, player.UserIDString));
else SendReply(player, string.Format(lang.GetMessage("HasSharePlayer", this, player.UserIDString), "<color=#FFA500>"+player0.Name+"</color>"));
}
else
{
storedData.Data[entity.net.ID.Value].Share.Add(ID);
if(ID==0) SendReply(player, lang.GetMessage("ShareAll", this, player.UserIDString));
else SendReply(player, string.Format(lang.GetMessage("SharePlayer", this, player.UserIDString), "<color=#FFA500>"+player0.Name+"</color>"));
}
}
else
{
if(!storedData.Data[entity.net.ID.Value].Quarry.ContainsKey(childentity.ShortPrefabName)) storedData.Data[entity.net.ID.Value].Quarry.Add(childentity.ShortPrefabName, new List<ulong>{});
if(storedData.Data[entity.net.ID.Value].Quarry[childentity.ShortPrefabName].Contains(ID))
{
if(ID==0) SendReply(player, lang.GetMessage("HasShareAll", this, player.UserIDString));
else SendReply(player, string.Format(lang.GetMessage("HasSharePlayer", this, player.UserIDString), "<color=#FFA500>"+player0.Name+"</color>"));
}
else
{
if(storedData.Data[entity.net.ID.Value].Quarry.ContainsKey(childentity.ShortPrefabName)) storedData.Data[entity.net.ID.Value].Quarry[childentity.ShortPrefabName].Add(ID);
else storedData.Data[entity.net.ID.Value].Quarry.Add(childentity.ShortPrefabName, new List<ulong>{ID});
if(ID==0) SendReply(player, lang.GetMessage("ShareAll", this, player.UserIDString));
else SendReply(player, string.Format(lang.GetMessage("SharePlayer", this, player.UserIDString), "<color=#FFA500>"+player0.Name+"</color>"));
}
}
}
}
else
{
SendReply(player, lang.GetMessage("EntityNotFound", this, player.UserIDString));
}
}
else
{
SendReply(player, lang.GetMessage("EntityNotFound", this, player.UserIDString));
}
}
[ChatCommand("unshare")]
void Unshare(BasePlayer player, string command, string[] args)
{
if (UsePermission && !permission.UserHasPermission(player.UserIDString, PLPerm))
{
SendReply(player, lang.GetMessage("NoPermission", this, player.UserIDString));
return;
}
IPlayer player0 = null;
ulong ID;
if (args == null || args.Length <= 0) ID=0;
else
{
player0 = CheckPlayer(player, args);
if(player0 == null) return;
ID=Convert.ToUInt64(player0.Id);
}
object success;
if (FindEntityFromRay(player, out success))
{
if (success is StorageContainer)
{
BaseEntity entity = success as BaseEntity;
BaseEntity childentity = entity;
entity = CheckParent(entity);
if(entity.OwnerID != player.userID && (!player.IsAdmin || (player.IsAdmin &&!AdminCanLoot)))
{
SendReply(player, lang.GetMessage("NoAccess", this, player.UserIDString));
return;
}
if(!storedData.Data.ContainsKey(entity.net.ID.Value))
{
SendReply(player, lang.GetMessage("NoShare", this, player.UserIDString));
}
else
{
if(childentity == entity)
{
if(!storedData.Data[entity.net.ID.Value].Share.Contains(ID))
{
if(ID==0) SendReply(player, lang.GetMessage("HasUnShareAll", this, player.UserIDString));
else SendReply(player, string.Format(lang.GetMessage("HasUnSharePlayer", this, player.UserIDString), "<color=#FFA500>"+player0.Name+"</color>"));
}
else
{
storedData.Data[entity.net.ID.Value].Share.Remove(ID);
if(storedData.Data[entity.net.ID.Value].Share.Count==0) storedData.Data.Remove(entity.net.ID.Value);
if(ID==0) SendReply(player, lang.GetMessage("WasUnShareAll", this, player.UserIDString));
else SendReply(player, string.Format(lang.GetMessage("WasUnSharePlayer", this, player.UserIDString), "<color=#FFA500>"+player0.Name+"</color>"));
}
}
else
{
if(!storedData.Data[entity.net.ID.Value].Quarry.ContainsKey(childentity.ShortPrefabName))
{
SendReply(player, lang.GetMessage("NoShare", this, player.UserIDString));
return;
}
if(!storedData.Data[entity.net.ID.Value].Quarry[childentity.ShortPrefabName].Contains(ID))
{
if(ID==0) SendReply(player, lang.GetMessage("HasUnShareAll", this, player.UserIDString));
else SendReply(player, string.Format(lang.GetMessage("HasUnSharePlayer", this, player.UserIDString), "<color=#FFA500>"+player0.Name+"</color>"));
}
else
{
storedData.Data[entity.net.ID.Value].Quarry[childentity.ShortPrefabName].Remove(ID);
if(storedData.Data[entity.net.ID.Value].Quarry[childentity.ShortPrefabName].Count==0) storedData.Data[entity.net.ID.Value].Quarry.Remove(childentity.ShortPrefabName);
if(ID==0) SendReply(player, lang.GetMessage("WasUnShareAll", this, player.UserIDString));
else SendReply(player, string.Format(lang.GetMessage("WasUnSharePlayer", this, player.UserIDString), "<color=#FFA500>"+player0.Name+"</color>"));
}
}
Sharelist(player);
}
}
else
{
SendReply(player, lang.GetMessage("EntityNotFound", this, player.UserIDString));
}
}
else
{
SendReply(player, lang.GetMessage("EntityNotFound", this, player.UserIDString));
}
}
[ChatCommand("sharelist")]
void Sharelist(BasePlayer player)
{
if (UsePermission && !permission.UserHasPermission(player.UserIDString, PLPerm))
{
SendReply(player, lang.GetMessage("NoPermission", this, player.UserIDString));
return;
}
object success;
if (FindEntityFromRay(player, out success))
{
if (success is StorageContainer)
{
BaseEntity entity = success as BaseEntity;
BaseEntity childentity = entity;
entity = CheckParent(entity);
if(entity.OwnerID != player.userID && (!player.IsAdmin || (player.IsAdmin &&!AdminCanLoot)))
{
SendReply(player, lang.GetMessage("NoAccess", this, player.UserIDString));
return;
}
if(!storedData.Data.ContainsKey(entity.net.ID.Value))
{
SendReply(player, lang.GetMessage("NoShare", this, player.UserIDString));
}
else
{
if(childentity == entity)
{
if(storedData.Data[entity.net.ID.Value].Share.Contains(0))
{
SendReply(player, lang.GetMessage("HasShareAllList", this, player.UserIDString));
return;
}
var message="<color=#FFFF00>"+lang.GetMessage("ListShare", this, player.UserIDString)+"</color>\n";
int i=0;
foreach(var share in storedData.Data[entity.net.ID.Value].Share)
{
i++;
message+= string.Format("{0}. <color=#00FF00>{1}</color> ({2})\n\r", i, covalence.Players.FindPlayer(share.ToString()).Name, covalence.Players.FindPlayer(share.ToString()).Id);
}
SendReply(player, message);
}
else
{
if(!storedData.Data[entity.net.ID.Value].Quarry.ContainsKey(childentity.ShortPrefabName))
{
SendReply(player, lang.GetMessage("NoShare", this, player.UserIDString));
return;
}
if(storedData.Data[entity.net.ID.Value].Quarry[childentity.ShortPrefabName].Contains(0))
{
SendReply(player, lang.GetMessage("HasShareAllList", this, player.UserIDString));
return;
}
var message="<color=#FFFF00>"+lang.GetMessage("ListShare", this, player.UserIDString)+"</color>\n";
int i=0;
foreach(var share in storedData.Data[entity.net.ID.Value].Quarry[childentity.ShortPrefabName])
{
i++;
message+= string.Format("{0}. <color=#00FF00>{1}</color> ({2})\n\r", i, covalence.Players.FindPlayer(share.ToString()).Name, covalence.Players.FindPlayer(share.ToString()).Id);
}
SendReply(player, message);
}
}
}
else
{
SendReply(player, lang.GetMessage("EntityNotFound", this, player.UserIDString));
}
}
else
{
SendReply(player, lang.GetMessage("EntityNotFound", this, player.UserIDString));
}
}
[ChatCommand("shareclear")]
void Shareclear(BasePlayer player)
{
if (UsePermission && !permission.UserHasPermission(player.UserIDString, PLPerm))
{
SendReply(player, lang.GetMessage("NoPermission", this, player.UserIDString));
return;
}
object success;
if (FindEntityFromRay(player, out success))
{
if (success is StorageContainer)
{
BaseEntity entity = success as BaseEntity;
BaseEntity childentity = entity;
entity = CheckParent(entity);
if(entity.OwnerID != player.userID && (!player.IsAdmin || (player.IsAdmin &&!AdminCanLoot)))
{
SendReply(player, lang.GetMessage("NoAccess", this, player.UserIDString));
return;
}
if(!storedData.Data.ContainsKey(entity.net.ID.Value))
{
SendReply(player, lang.GetMessage("NoShare", this, player.UserIDString));
}
else
{
if(childentity == entity)
{
storedData.Data[entity.net.ID.Value].Share.Clear();
if(storedData.Data[entity.net.ID.Value].Share.Count==0) storedData.Data.Remove(entity.net.ID.Value);
SendReply(player, lang.GetMessage("ShareClear", this, player.UserIDString));
}
else
{
if(!storedData.Data[entity.net.ID.Value].Quarry.ContainsKey(childentity.ShortPrefabName))
{
SendReply(player, lang.GetMessage("NoShare", this, player.UserIDString));
return;
}
storedData.Data[entity.net.ID.Value].Quarry[childentity.ShortPrefabName].Clear();
if(storedData.Data[entity.net.ID.Value].Quarry[childentity.ShortPrefabName].Count==0) storedData.Data[entity.net.ID.Value].Quarry.Remove(childentity.ShortPrefabName);
SendReply(player, lang.GetMessage("ShareClear", this, player.UserIDString));
}
}
}
else
{
SendReply(player, lang.GetMessage("EntityNotFound", this, player.UserIDString));
}
}
else
{
SendReply(player, lang.GetMessage("EntityNotFound", this, player.UserIDString));
}
}
[ChatCommand("checkit")]
void CheckBP(BasePlayer player)
{
if (UsePermission && !permission.UserHasPermission(player.UserIDString, PLPerm))
{
SendReply(player, lang.GetMessage("NoPermission", this, player.UserIDString));
return;
}
object success;
if (FindEntityFromRay(player, out success))
{
if (success is StorageContainer)
{
BaseEntity entity = success as BaseEntity;
entity = CheckParent(entity);
if(entity.OwnerID != player.userID && (!player.IsAdmin || (player.IsAdmin &&!AdminCanLoot)))
{
SendReply(player, lang.GetMessage("NoAccess", this, player.UserIDString));
return;
}
if(UseOnlyInCupboardRange)
{
BuildingPrivlidge bprev = player.GetBuildingPrivilege(new OBB(entity.transform.position, entity.transform.rotation, entity.bounds));
if(bprev == null) SendReply(player, "<color=#FF0000>"+lang.GetMessage("EntNoPrevent", this, player.UserIDString)+"</color>\n");
else SendReply(player, "<color=#CCFF00>"+lang.GetMessage("EntPrevent", this, player.UserIDString)+"</color>\n");
}
else SendReply(player, "<color=#CCFF00>"+lang.GetMessage("EntPrevent", this, player.UserIDString)+"</color>\n");
}
}
else
{
SendReply(player, lang.GetMessage("EntityNotFound", this, player.UserIDString));
}
}
#endregion
#region Helpers
T GetConfig<T>(string name, T defaultValue) => Config[name] == null ? defaultValue : (T) Convert.ChangeType(Config[name], typeof(T));
#endregion
}
}
Commands:
/share: Share permissions to an entity with another player or everyone.
/unshare: Remove sharing permissions from an entity.
/sharelist: List players who have been given access to an entity.
/shareclear: Clear all sharing permissions from an entity.
/checkit: Check if an entity is protected from unauthorized looting.
Usage Scenarios:
This plugin is perfect for server administrators who want to impose strict control over looting behaviors between players. By configuring permissions, administrators can ensure that only authorized players can loot specific entities, access storages, or perform sensitive actions, thereby enhancing security and fair play in the Rust environment.
If you have specific questions or need further explanation about any part of the script, feel free to let me know!
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Oxide.Core;
using Oxide.Core.Plugins;
using Oxide.Game.Rust.Cui;
using UnityEngine;
namespace Oxide.Plugins
{
[Info("IndustrialRecycler", "Marte6", "1.4.6")]
[Description("Automate recycling by attaching storage and adapters to recyclers.")]
class IndustrialRecycler : RustPlugin
{
#region PluginReferences
[PluginReference] Plugin Friends;
#endregion
#region Fields
private static IndustrialRecycler _instance;
private Configuration _config;
private const string RecyclerPrefabPath = "assets/bundled/prefabs/static/recycler_static.prefab";
private const string InputStoragePrefabPath = "assets/content/vehicles/boats/rowboat/subents/rowboat_storage.prefab";
private const string OutputStoragePrefabPath = "assets/prefabs/deployable/hot air balloon/subents/hab_storage.prefab";
private const string AdapterPrefabPath = "assets/prefabs/deployable/playerioents/industrialadaptors/storageadaptor.deployed.prefab";
private const string ItemName = "box.wooden.large";
private const string PermissionUseRecycler = "industrialrecycler.give";
private const string PermissionVip = "industrialrecycler.vip";
private const string PermissionAdmin = "industrialrecycler.admin";
private const string UiOverlayName = "IndustrialRecyclerMainPanel";
#endregion
#region Cache
private readonly Dictionary<ulong, ulong> _recyclerOwners = new();
private readonly HashSet<ulong> _recyclerItemContainers = new();
private readonly HashSet<ulong> _inputItemContainers = new();
private readonly HashSet<ulong> _storageAdapters = new();
private readonly HashSet<ulong> _playersWithUi = new();
#endregion
#region Game Hooks
private void Init()
{
permission.RegisterPermission(PermissionUseRecycler, this);
permission.RegisterPermission(PermissionVip, this);
permission.RegisterPermission(PermissionAdmin, this);
foreach (var command in _config.Commands)
{
cmd.AddChatCommand(command, this, nameof(CommandGetRecycler));
}
cmd.AddChatCommand("upgraderecycler", this, nameof(CommandUpgradeRecycler));
cmd.AddChatCommand("togglerecycler", this, nameof(ToggleRecyclerConfig));
cmd.AddConsoleCommand("industrialrecycler.openinput", this, nameof(OpenInputStorage));
cmd.AddConsoleCommand("industrialrecycler.openoutput", this, nameof(OpenOutputStorage));
}
private void OnServerInitialized()
{
_instance = this;
foreach (var recycler in UnityEngine.Object.FindObjectsOfType<Recycler>())
{
if (recycler.OwnerID != 0UL)
{
recycler.gameObject.AddComponent<RecyclerComponent>();
}
}
}
private void Unload()
{
foreach (var recyclerComponent in UnityEngine.Object.FindObjectsOfType<RecyclerComponent>())
{
UnityEngine.Object.Destroy(recyclerComponent);
}
foreach (var player in BasePlayer.activePlayerList)
{
CuiHelper.DestroyUi(player, UiOverlayName);
}
}
private object CanLootEntity(BasePlayer player, Recycler recycler)
{
if (!HasAccess(player, recycler))
{
player.ChatMessage(lang.GetMessage("NoAccess", this, player.UserIDString));
return false;
}
return null;
}
private object CanOpenStorage(BasePlayer player, StorageContainer container)
{
Recycler recycler = container.GetParentEntity() as Recycler;
if (recycler != null && !HasAccess(player, recycler))
{
player.ChatMessage(lang.GetMessage("NoAccess", this, player.UserIDString));
return false;
}
return null;
}
#endregion
#region Access Control
private bool HasAccess(BasePlayer player, BaseEntity entity)
{
ulong ownerId = entity.OwnerID;
if (ownerId == player.userID || permission.UserHasPermission(player.UserIDString, PermissionAdmin))
return true;
if (_config.AllowTeamAccess && player.currentTeam != 0)
{
var team = RelationshipManager.ServerInstance.FindTeam(player.currentTeam);
if (team != null && team.members.Contains(ownerId))
return true;
}
if (_config.AllowFriendsAccess && Friends != null)
{
bool areFriends = (bool)(Friends.CallHook("AreFriends", ownerId, player.userID) ?? false);
if (areFriends)
return true;
}
return false;
}
#endregion
#region UI
private void CreateUi(BasePlayer player, string recyclerId)
{
var container = new CuiElementContainer();
container.Add(
new CuiPanel
{
CursorEnabled = true,
Image =
{
Color = "1 1 1 0.15",
Sprite = "assets/content/ui/ui.background.transparent.radial.psd",
Material = "assets/content/ui/uibackgroundblur.mat",
},
RectTransform =
{
AnchorMin = _config.AnchorMin,
AnchorMax = _config.AnchorMax,
OffsetMin = "341.64 405.595",
OffsetMax = "554.76 505.605",
},
},
"Overlay",
UiOverlayName
);
container.Add(
new CuiElement
{
Name = "Text",
Parent = UiOverlayName,
Components =
{
new CuiTextComponent
{
Text = "INDUSTRIAL RECYCLER",
Font = "robotocondensed-bold.ttf",
FontSize = 17,
Align = TextAnchor.MiddleCenter,
Color = "1 1 1 1",
},
new CuiOutlineComponent { Color = "0 0 0 1", Distance = "1 1" },
new CuiRectTransformComponent
{
AnchorMin = "0.5 0.5",
AnchorMax = "0.5 0.5",
OffsetMin = "-86.493 0",
OffsetMax = "86.492 34.875",
},
},
}
);
container.Add(
new CuiButton
{
Button =
{
Color = "0.3960785 0.4666667 0.2627451 1",
Command = $"industrialrecycler.openinput {recyclerId}",
Close = UiOverlayName,
},
Text =
{
Text = lang.GetMessage("InputButton", this, player.UserIDString),
Font = "robotocondensed-regular.ttf",
FontSize = 18,
Align = TextAnchor.MiddleCenter,
Color = "1 1 1 1",
},
RectTransform =
{
AnchorMin = "0.5 0.5",
AnchorMax = "0.5 0.5",
OffsetMin = "-104.206 -49.58",
OffsetMax = "-2.394 -17.22",
},
},
UiOverlayName,
"Input"
);
container.Add(
new CuiButton
{
Button =
{
Color = "0.3960785 0.4666667 0.2627451 1",
Command = $"industrialrecycler.openoutput {recyclerId}",
Close = UiOverlayName,
},
Text =
{
Text = lang.GetMessage("OutputButton", this, player.UserIDString),
Font = "robotocondensed-regular.ttf",
FontSize = 18,
Align = TextAnchor.MiddleCenter,
Color = "1 1 1 1",
},
RectTransform =
{
AnchorMin = "0.5 0.5",
AnchorMax = "0.5 0.5",
OffsetMin = "1.994 -49.58",
OffsetMax = "103.806 -17.22",
},
},
UiOverlayName,
"Output"
);
container.Add(
new CuiButton
{
Button =
{
Color = "0.3960785 0.7666667 0.2627451 1",
Command = $"chat.say /togglerecycler",
Close = "ToggleConfig",
},
Text =
{
Text = lang.GetMessage("ToggleConfig", this),
Font = "robotocondensed-regular.ttf",
FontSize = 14,
Align = TextAnchor.MiddleCenter,
Color = "1 1 1 1",
},
RectTransform =
{
AnchorMin = "1 1",
AnchorMax = "1 1",
OffsetMin = "-110 -20",
OffsetMax = "0 0",
},
},
UiOverlayName,
"ToggleConfig"
);
CuiHelper.DestroyUi(player, UiOverlayName);
CuiHelper.AddUi(player, container);
}
private void OpenStorage(ConsoleSystem.Arg arg, bool isInput)
{
var player = arg.Player();
if (player == null)
{
return;
}
if (arg.Args.Length == 0)
{
return;
}
if (!uint.TryParse(arg.Args[0], out uint recyclerId))
{
return;
}
var networkableId = new NetworkableId(recyclerId);
var recycler = BaseNetworkable.serverEntities.Find(networkableId) as Recycler;
if (recycler != null && HasAccess(player, recycler))
{
var recyclerComponent = recycler.GetComponent<RecyclerComponent>();
if (recyclerComponent != null)
{
var storage = isInput ? recyclerComponent.InputStorage : recyclerComponent.OutputStorage;
player.inventory.loot.StartLootingEntity(storage, true);
player.inventory.loot.AddContainer(storage.inventory);
player.inventory.loot.SendImmediate();
player.ClientRPCPlayer(null, player, "RPC_OpenLootPanel", storage.panelName);
}
}
}
private void OpenInputStorage(ConsoleSystem.Arg arg)
{
OpenStorage(arg, true);
}
private void OpenOutputStorage(ConsoleSystem.Arg arg)
{
OpenStorage(arg, false);
}
#endregion
#region Main
private void CommandGetRecycler(BasePlayer player, string command, string[] args)
{
if (player == null)
return;
if (!permission.UserHasPermission(player.UserIDString, PermissionUseRecycler))
{
player.ChatMessage(lang.GetMessage("NoPermission", this, player.UserIDString));
return;
}
BasePlayer targetPlayer = player;
if (args != null && args.Length > 0)
{
targetPlayer = BasePlayer.Find(args[0]);
if (targetPlayer == null)
{
player.ChatMessage(lang.GetMessage("PlayerNotFound", this, player.UserIDString));
return;
}
}
if (GiveRecyclerItem(targetPlayer))
{
player.ChatMessage(lang.GetMessage("RecyclerGiven", this, player.UserIDString));
if (targetPlayer != player)
{
targetPlayer.ChatMessage(lang.GetMessage("RecyclerReceived", this, targetPlayer.UserIDString));
}
}
else
{
player.ChatMessage(lang.GetMessage("RecyclerNotGiven", this, player.UserIDString));
if (targetPlayer != player)
{
targetPlayer.ChatMessage(lang.GetMessage("RecyclerNotReceived", this, targetPlayer.UserIDString));
}
}
}
private bool GiveRecyclerItem(BasePlayer player)
{
var recyclerItem = ItemManager.CreateByName(ItemName, 1, _config.RecyclerSkinId);
if (recyclerItem == null)
return false;
recyclerItem.name = "Recycler";
return player.inventory.GiveItem(recyclerItem);
}
private void CommandUpgradeRecycler(BasePlayer player, string command, string[] args)
{
if (!permission.UserHasPermission(player.UserIDString, PermissionUseRecycler))
{
player.ChatMessage(lang.GetMessage("NoPermission", this, player.UserIDString));
return;
}
int maxRecyclers = _config.MaxRecyclersPerPlayer;
if (permission.UserHasPermission(player.UserIDString, PermissionAdmin))
{
maxRecyclers = int.MaxValue;
}
else if (permission.UserHasPermission(player.UserIDString, PermissionVip))
{
maxRecyclers = _config.MaxRecyclersVip;
}
if (_recyclerOwners.Count(entry => entry.Value == player.userID) >= maxRecyclers)
{
player.ChatMessage(lang.GetMessage("RecyclerLimitReached", this, player.UserIDString));
return;
}
if (!UpgradeToIndustrialRecycler(player))
{
player.ChatMessage(lang.GetMessage("NoRecyclerInView", this, player.UserIDString));
}
else
{
player.ChatMessage(lang.GetMessage("RecyclerUpgraded", this, player.UserIDString));
}
}
private Recycler FindRecyclerInView(BasePlayer player)
{
if (Physics.Raycast(player.eyes.HeadRay(), out RaycastHit hit, 5f))
{
BaseEntity entity = hit.GetEntity();
return entity as Recycler;
}
return null;
}
private bool InitializeRecyclerPlacement(BasePlayer player, BaseEntity baseEntity, int turn = 0)
{
var supportingFoundation = FindSupportingFoundation(baseEntity);
if (supportingFoundation == null)
return false;
var spawnedRecycler = SpawnRecyclerWithComponents(player, baseEntity, supportingFoundation, turn);
if (spawnedRecycler == null)
return false;
spawnedRecycler.gameObject.AddComponent<RecyclerComponent>();
return true;
}
private bool InitializeUpgradeRecycler(BasePlayer player, Recycler recycler, int turn = 0)
{
var spawnedRecycler = UpgradeRecyclerWithComponents(player, recycler, turn);
if (spawnedRecycler == null)
return false;
spawnedRecycler.gameObject.AddComponent<RecyclerComponent>();
return true;
}
private BuildingBlock FindSupportingFoundation(BaseEntity baseEntity)
{
Vector3 origin = baseEntity.transform.position + Vector3.up * 0.1f;
if (Physics.Raycast(origin, Vector3.down, out RaycastHit hitData, 4f, LayerMask.GetMask("Construction")))
{
return hitData.GetEntity() as BuildingBlock;
}
return null;
}
private Recycler SetupStorageAndAdapters(Recycler recycler, BasePlayer player)
{
Vector3 inputOffset,
inputAdapterOffset,
outputOffset,
outputAdapterOffset;
Quaternion inputRotation,
outputRotation,
inputAdapterRotation,
outputAdapterRotation;
if (_config.UseAlternativeAdapterConfig)
{
inputOffset = new Vector3(0.0f, 0.72f, 0.11f);
inputAdapterOffset = new Vector3(0.32f, -0.6f, -0.03f);
outputOffset = new Vector3(-0.4f, 0.8f, 0.2f);
outputAdapterOffset = new Vector3(-0.07f, 0.535f, 0.397f);
inputRotation = Quaternion.Euler(0, 180, 191);
outputRotation = Quaternion.Euler(169, 90, 180);
inputAdapterRotation = Quaternion.Euler(0, 0, 0);
outputAdapterRotation = Quaternion.Euler(180, 90, 0);
}
else
{
inputOffset = new Vector3(-1.0f, 0.72f, 0.31f);
inputAdapterOffset = new Vector3(0.00f, -0.15f, -0.25f);
outputOffset = new Vector3(-0.9f, 0.72f, -0.09f);
outputAdapterOffset = new Vector3(0.00f, 0.26f, -0.05f);
inputRotation = Quaternion.Euler(90, 90, 180);
outputRotation = Quaternion.Euler(180, 90, 180);
inputAdapterRotation = Quaternion.Euler(180, 90, 270);
outputAdapterRotation = Quaternion.Euler(0, 90, 0);
}
var inputStorage = SpawnEntity(InputStoragePrefabPath, recycler, player, inputOffset, inputRotation);
SpawnEntity(AdapterPrefabPath, inputStorage, player, inputAdapterOffset, inputAdapterRotation);
var outputStorage = SpawnEntity(OutputStoragePrefabPath, recycler, player, outputOffset, outputRotation);
SpawnEntity(AdapterPrefabPath, outputStorage, player, outputAdapterOffset, outputAdapterRotation);
return recycler;
}
private Recycler UpgradeRecyclerWithComponents(BasePlayer player, Recycler recycler, int turn = 0)
{
return SetupStorageAndAdapters(recycler, player);
}
private Recycler SpawnRecyclerWithComponents(BasePlayer player, BaseEntity baseEntity, BuildingBlock foundation, int turn = 0)
{
var recycler = SpawnEntity(RecyclerPrefabPath, foundation, player, baseEntity.transform.position, baseEntity.transform.rotation * Quaternion.Euler(0, turn, 0)) as Recycler;
if (recycler == null)
return null;
return SetupStorageAndAdapters(recycler, player);
}
private BaseEntity SpawnEntity(string prefabPath, BaseEntity parent, BasePlayer player, Vector3 position, Quaternion rotation)
{
var entity = GameManager.server.CreateEntity(prefabPath, Vector3.zero, Quaternion.identity, true);
if (entity == null)
return null;
entity.OwnerID = player.userID;
if (parent != null)
{
entity.SetParent(parent, true);
}
if (parent is BuildingBlock)
{
entity.transform.position = position;
entity.transform.rotation = rotation;
}
else
{
entity.transform.localPosition = position;
entity.transform.localRotation = rotation;
}
entity.Spawn();
entity.SendNetworkUpdateImmediate();
return entity;
}
private void ProcessRecyclerItems(RecyclerComponent recyclerComponent, Item item)
{
if (item.position < 6)
{
recyclerComponent.Recycler.StartRecycling();
}
else
{
if (!item.MoveToContainer(recyclerComponent.OutputStorage.inventory))
{
recyclerComponent.Recycler.StopRecycling();
}
}
}
private bool UpgradeToIndustrialRecycler(BasePlayer player)
{
if (Physics.Raycast(player.eyes.HeadRay(), out RaycastHit hit, 5f))
{
BaseEntity baseEntity = hit.GetEntity();
if (baseEntity is Recycler recycler && recycler.OwnerID == player.userID)
{
if (!InitializeUpgradeRecycler(player, baseEntity as Recycler, 90))
{
player.ChatMessage(lang.GetMessage("InvalidPlacement", this, player.UserIDString));
timer.Once(1, () => GiveRecyclerItem(player));
return false;
}
else
{
player.ChatMessage(lang.GetMessage("RecyclerPlaced", this, player.UserIDString));
}
return true;
}
}
return false;
}
private void ToggleRecyclerConfig(BasePlayer player, string command, string[] args)
{
if (!permission.UserHasPermission(player.UserIDString, PermissionUseRecycler))
{
player.ChatMessage(lang.GetMessage("NoPermission", this, player.UserIDString));
return;
}
Recycler recycler = FindRecyclerInView(player);
if (recycler == null)
{
player.ChatMessage(lang.GetMessage("NoRecyclerInView", this, player.UserIDString));
return;
}
var recyclerComponent = recycler.GetComponent<RecyclerComponent>();
if (recyclerComponent == null)
{
player.ChatMessage(lang.GetMessage("RecyclerComponentNotFound", this, player.UserIDString));
return;
}
recyclerComponent.ToggleConfig();
player.ChatMessage(lang.GetMessage("RecyclerConfigToggled", this, player.UserIDString));
}
#endregion
#region Configuration
private class Configuration
{
[JsonProperty("Commands")]
public List<string> Commands { get; set; }
[JsonProperty("Max Recyclers Per Player")]
public int MaxRecyclersPerPlayer { get; set; }
[JsonProperty("Max Recyclers Vip (industrialrecycler.vip)")]
public int MaxRecyclersVip { get; set; }
[JsonProperty("Recycler Item SkinId")]
public ulong RecyclerSkinId { get; set; }
[JsonProperty("AnchorMin")]
public string AnchorMin { get; set; }
[JsonProperty("AnchorMax")]
public string AnchorMax { get; set; }
[JsonProperty("Alternative Adapter Configuration")]
public bool UseAlternativeAdapterConfig { get; set; }
[JsonProperty("Hide Storage Containers")]
public bool HideStorageContainers { get; set; }
[JsonProperty("Only owner can access recycler")]
public bool OnlyOwnerAccess { get; set; }
[JsonProperty("Allow team members to access recycler")]
public bool AllowTeamAccess { get; set; }
[JsonProperty("Allow friends to access recycler")]
public bool AllowFriendsAccess { get; set; }
[JsonProperty("Version")]
public VersionNumber Version { get; set; }
}
protected override void LoadConfig()
{
base.LoadConfig();
try
{
_config = Config.ReadObject<Configuration>() ?? throw new Exception("Failed to read configuration file.");
bool configChanged = false;
if (_config.Version != Version)
{
_config.Version = Version;
configChanged = true;
}
if (string.IsNullOrEmpty(_config.AnchorMin))
{
_config.AnchorMin = "0.5 0";
configChanged = true;
}
if (string.IsNullOrEmpty(_config.AnchorMax))
{
_config.AnchorMax = "0.5 0";
configChanged = true;
}
if (!_config.UseAlternativeAdapterConfig)
{
_config.UseAlternativeAdapterConfig = false;
configChanged = true;
}
if (configChanged)
{
SaveConfig();
}
}
catch (Exception ex)
{
PrintError($"There was an error in your configuration file: {ex.Message}. Default values will be used.");
LoadDefaultConfig();
}
}
protected override void LoadDefaultConfig()
{
_config = GetDefaultConfig();
SaveConfig();
}
protected override void SaveConfig()
{
Config.WriteObject(_config, true);
}
private Configuration GetDefaultConfig()
{
return new Configuration
{
Commands = new List<string> { "getrecycler", "irecycler", "giverecycler" },
MaxRecyclersPerPlayer = 1,
MaxRecyclersVip = 2,
RecyclerSkinId = 3357927081,
AnchorMin = "0.5 0",
AnchorMax = "0.5 0",
UseAlternativeAdapterConfig = false,
HideStorageContainers = false,
OnlyOwnerAccess = true,
AllowTeamAccess = true,
AllowFriendsAccess = true,
Version = Version,
};
}
#endregion
#region Localization
protected override void LoadDefaultMessages()
{
lang.RegisterMessages(
new Dictionary<string, string>
{
["NoPermission"] = "You do not have permission to use this command.",
["RecyclerLimitReached"] = "You have reached the recycler limit.",
["InvalidPlacement"] = "The recycler must be placed on a construction block.",
["RecyclerPlaced"] = "Recycler placed successfully.",
["RecyclerPickedUp"] = "Recycler picked up, item returned to inventory.",
["RecyclerGiven"] = "Recycler given to your inventory.",
["RecyclerReceived"] = "You have received a recycler.",
["RecyclerNotGiven"] = "Failed to give recycler.",
["RecyclerNotReceived"] = "Failed to receive recycler.",
["NoRecyclerInView"] = "No recycler in sight to upgrade.",
["RecyclerComponentNotFound"] = "Recycler component not found.",
["RecyclerConfigToggled"] = "Recycler configuration toggled successfully.",
["PlayerNotFound"] = "The specified player could not be found.",
["ToggleConfig"] = "Toggle",
["InputButton"] = "Input",
["OutputButton"] = "Output",
["NoAccess"] = "You do not have access to this recycler.",
},
this
);
}
#endregion
#region Component
private class RecyclerComponent : MonoBehaviour
{
public Recycler Recycler { get; private set; }
public StorageContainer InputStorage { get; private set; }
public StorageContainer OutputStorage { get; private set; }
public int CurrentConfigState { get; private set; }
private const int MaxStorageCapacity = 48;
private const float TransferInterval = 10f;
private enum RecyclerConfig
{
Default = 1,
Alternative = 2,
}
private void Awake()
{
Recycler = GetComponent<Recycler>();
if (Recycler == null)
{
Debug.LogError("Recycler component is missing on this GameObject.");
enabled = false;
return;
}
// Start with a default known state
CurrentConfigState = (int)RecyclerConfig.Default;
InitializeRecyclerComponents();
}
private void InitializeRecyclerComponents()
{
foreach (MonoBehaviour mb in GetComponents<MonoBehaviour>())
{
var type = mb.GetType();
if (type != typeof(Recycler) && type != typeof(RecyclerComponent) && type.Name != "Ground_Watch")
{
Destroy(mb);
}
}
if (!ValidateStorageContainers())
{
Debug.LogError("Failed to validate storage containers.");
enabled = false;
return;
}
SetupRecycler();
RegisterEntities();
InvokeRepeating(nameof(HandleItemTransfers), 0f, TransferInterval);
}
private bool ValidateStorageContainers()
{
InputStorage = Recycler.children.OfType<StorageContainer>().FirstOrDefault(c => c?.name == InputStoragePrefabPath);
OutputStorage = Recycler.children.OfType<StorageContainer>().FirstOrDefault(c => c?.name == OutputStoragePrefabPath);
return InputStorage != null && OutputStorage != null;
}
private void RegisterEntities()
{
_instance._inputItemContainers.Add(InputStorage.inventory.uid.Value);
_instance._recyclerItemContainers.Add(Recycler.inventory.uid.Value);
var inputAdapter = InputStorage.children.OfType<IndustrialStorageAdaptor>().FirstOrDefault();
if (inputAdapter != null)
_instance._storageAdapters.Add(inputAdapter.net.ID.Value);
var outputAdapter = OutputStorage.children.OfType<IndustrialStorageAdaptor>().FirstOrDefault();
if (outputAdapter != null)
_instance._storageAdapters.Add(outputAdapter.net.ID.Value);
}
private void SetupRecycler()
{
if (Recycler == null || InputStorage == null || OutputStorage == null)
{
Debug.LogError("Attempted to setup recycler with null components.");
return;
}
_instance._recyclerOwners[Recycler.net.ID.Value] = Recycler.OwnerID;
InputStorage.inventory.capacity = MaxStorageCapacity;
OutputStorage.inventory.capacity = MaxStorageCapacity;
}
public void HandleItemTransfers()
{
int availableRecyclerSlots = 6 - Recycler.inventory.itemList.Count;
if (OutputStorage.inventory.IsFull())
{
Recycler.StopRecycling();
return;
}
TransferItemsFromRecyclerToOutput(ref availableRecyclerSlots);
TransferItemsFromInputToRecycler(ref availableRecyclerSlots);
if (availableRecyclerSlots < 6 && Recycler.inventory.itemList.Count > 0)
{
Recycler.StartRecycling();
}
}
private void TransferItemsFromRecyclerToOutput(ref int availableRecyclerSlots)
{
for (int slot = 6; slot < Recycler.inventory.capacity; slot++)
{
var itemInRecycler = Recycler.inventory.GetSlot(slot);
if (itemInRecycler != null && itemInRecycler.MoveToContainer(OutputStorage.inventory))
{
availableRecyclerSlots++;
}
}
}
private void TransferItemsFromInputToRecycler(ref int availableRecyclerSlots)
{
var inputItems = new List<Item>(InputStorage.inventory.itemList);
foreach (var item in inputItems)
{
if (item.info.Blueprint != null)
{
MoveItemToRecycler(item, ref availableRecyclerSlots);
}
else
{
item.MoveToContainer(OutputStorage.inventory);
}
}
}
private void MoveItemToRecycler(Item item, ref int availableRecyclerSlots)
{
if (availableRecyclerSlots <= 0)
return;
for (int slot = 0; slot < 6; slot++)
{
if (Recycler.inventory.GetSlot(slot) == null && item.MoveToContainer(Recycler.inventory, slot))
{
availableRecyclerSlots--;
break;
}
}
}
public void ToggleConfig()
{
CancelInvoke(nameof(HandleItemTransfers));
CurrentConfigState = (int)(CurrentConfigState == (int)RecyclerConfig.Default ? RecyclerConfig.Alternative : RecyclerConfig.Default);
List<(string Shortname, int Amount, float ConditionNormalized)> ExtractItemDetails(ItemContainer container) =>
container?.itemList?.Select(item => (item.info.shortname, item.amount, item.conditionNormalized)).ToList() ?? new List<(string, int, float)>();
var inputItemDetails = ExtractItemDetails(InputStorage.inventory);
var outputItemDetails = ExtractItemDetails(OutputStorage.inventory);
ClearExistingComponents();
UpdateAdapterPositions();
InitializeRecyclerComponents();
if (InputStorage == null || OutputStorage == null || Recycler == null)
{
Debug.LogError("As referências dos contêineres não foram atualizadas.");
return;
}
foreach (var (shortname, amount, condition) in inputItemDetails)
CreateAndMoveItem(shortname, amount, condition, InputStorage.inventory);
foreach (var (shortname, amount, condition) in outputItemDetails)
CreateAndMoveItem(shortname, amount, condition, OutputStorage.inventory);
}
private void CreateAndMoveItem(string shortname, int amount, float conditionNormalized, ItemContainer container)
{
var item = ItemManager.CreateByName(shortname, amount);
if (item != null)
{
item.conditionNormalized = conditionNormalized;
if (!item.MoveToContainer(container))
item.Remove();
}
}
private void UpdateAdapterPositions()
{
ClearExistingComponents();
Vector3 inputOffset,
outputOffset,
inputAdapterOffset,
outputAdapterOffset;
Quaternion inputRotation,
outputRotation,
inputAdapterRotation,
outputAdapterRotation;
if (CurrentConfigState == (int)RecyclerConfig.Default)
{
inputOffset = new Vector3(0.0f, 0.72f, 0.11f);
outputOffset = new Vector3(-0.4f, 0.8f, 0.2f);
inputAdapterOffset = new Vector3(0.32f, -0.6f, -0.03f);
outputAdapterOffset = new Vector3(-0.07f, 0.535f, 0.397f);
inputRotation = Quaternion.Euler(0, 180, 191);
outputRotation = Quaternion.Euler(169, 90, 180);
inputAdapterRotation = Quaternion.Euler(0, 0, 0);
outputAdapterRotation = Quaternion.Euler(180, 90, 0);
}
else
{
if (_instance._config.HideStorageContainers)
{
inputOffset = new Vector3(0.0f, 0.72f, 0.11f);
outputOffset = new Vector3(-0.4f, 0.72f, 0.2f);
inputAdapterOffset = new Vector3(0.836f, -0.3301f, 0.18f);
outputAdapterOffset = new Vector3(-0.227f, 0.33f, 0.434f);
inputRotation = Quaternion.Euler(0, 0, 180);
outputRotation = Quaternion.Euler(180, 90, 180);
inputAdapterRotation = Quaternion.Euler(0, 0, 0);
outputAdapterRotation = Quaternion.Euler(180, 90, 0);
}
else
{
inputOffset = new Vector3(-1.0f, 0.72f, 0.31f);
outputOffset = new Vector3(-0.9f, 0.72f, -0.09f);
inputAdapterOffset = new Vector3(0.00f, -0.15f, -0.25f);
outputAdapterOffset = new Vector3(0.00f, 0.26f, -0.05f);
inputRotation = Quaternion.Euler(90, 90, 180);
outputRotation = Quaternion.Euler(180, 90, 180);
inputAdapterRotation = Quaternion.Euler(180, 90, 270);
outputAdapterRotation = Quaternion.Euler(0, 90, 0);
}
}
BasePlayer ownerPlayer = BasePlayer.FindByID(Recycler.OwnerID);
if (ownerPlayer != null)
{
var inputStorage = _instance.SpawnEntity(InputStoragePrefabPath, Recycler, ownerPlayer, inputOffset, inputRotation) as StorageContainer;
if (inputStorage == null)
{
Debug.LogError("Failed to spawn input storage.");
return;
}
_instance.SpawnEntity(AdapterPrefabPath, inputStorage, ownerPlayer, inputAdapterOffset, inputAdapterRotation);
var outputStorage = _instance.SpawnEntity(OutputStoragePrefabPath, Recycler, ownerPlayer, outputOffset, outputRotation) as StorageContainer;
if (outputStorage == null)
{
Debug.LogError("Failed to spawn output storage.");
return;
}
_instance.SpawnEntity(AdapterPrefabPath, outputStorage, ownerPlayer, outputAdapterOffset, outputAdapterRotation);
}
}
private void ClearExistingComponents()
{
foreach (var child in Recycler.children.ToList())
{
if (child is StorageContainer || child is IndustrialStorageAdaptor)
{
child.Kill();
}
}
}
internal void DropItems()
{
var allItems = GatherAllItems();
DropItemsInBatches(allItems, MaxStorageCapacity);
}
private List<Item> GatherAllItems()
{
return InputStorage.inventory.itemList.Concat(OutputStorage.inventory.itemList).Concat(Recycler.inventory.itemList).ToList();
}
private void DropItemsInBatches(List<Item> items, int batchSize)
{
var recyclerPosition = Recycler.transform.position;
var recyclerRotation = Recycler.transform.rotation;
for (int i = 0; i < items.Count; i += batchSize)
{
var itemBatch = items.Skip(i).Take(batchSize).ToList();
SpawnDroppedItemContainer(recyclerPosition, recyclerRotation, itemBatch);
}
}
private DroppedItemContainer SpawnDroppedItemContainer(Vector3 position, Quaternion rotation, List<Item> itemsToDrop)
{
var containerPrefabPath = "assets/prefabs/misc/item drop/item_drop.prefab";
var droppedItemContainer = GameManager.server.CreateEntity(containerPrefabPath, position, rotation) as DroppedItemContainer;
if (droppedItemContainer == null)
return null;
InitializeItemContainer(droppedItemContainer, itemsToDrop);
droppedItemContainer.Spawn();
return droppedItemContainer;
}
private void InitializeItemContainer(DroppedItemContainer container, List<Item> items)
{
container.inventory = new ItemContainer();
container.inventory.ServerInitialize(null, items.Count);
container.inventory.GiveUID();
container.inventory.entityOwner = container;
foreach (var item in items)
{
item.MoveToContainer(container.inventory);
}
}
private void OnDestroy()
{
CancelInvoke(nameof(HandleItemTransfers));
}
}
#endregion
}
}
Key Changes and Additions:
Added Plugin Reference for Friends:
This allows the use of the Friends plugin to check if a player is considered a friend of the recycler owner.
Configuration Options:
Added AllowFriendsAccess configuration, enabling players to allow their friends to access their recyclers.
Access Control Implementation:
Implemented HasAccess method, which checks if a player is either the owner, a team member, or a friend.
Used this method in relevant hooks to restrict access based on these conditions.
Localization Update:
Added a message key "NoAccess", which is displayed when a player attempts to access a recycler they do not have permissions for.
This implementation uses the logic from PreventLooting to enable access control over recyclers, ensuring only authorized players, based on configuration and relations, can interact with them.
#region Cache
private readonly Dictionary<ulong, ulong> _recyclerOwners = new();
private readonly HashSet<ulong> _recyclerItemContainers = new();
private readonly HashSet<ulong> _inputItemContainers = new();
private readonly HashSet<ulong> _storageAdapters = new();
private readonly HashSet<ulong> _playersWithUi = new();
#endregion
#region Game Hooks
private void Init()
{
permission.RegisterPermission(PermissionUseRecycler, this);
permission.RegisterPermission(PermissionVip, this);
permission.RegisterPermission(PermissionAdmin, this);
foreach (var command in _config.Commands)
{
cmd.AddChatCommand(command, this, nameof(CommandGetRecycler));
}
cmd.AddChatCommand("upgraderecycler", this, nameof(CommandUpgradeRecycler));
cmd.AddChatCommand("togglerecycler", this, nameof(ToggleRecyclerConfig));
cmd.AddConsoleCommand("industrialrecycler.openinput", this, nameof(OpenInputStorage));
cmd.AddConsoleCommand("industrialrecycler.openoutput", this, nameof(OpenOutputStorage));
}
private void OnServerInitialized()
{
_instance = this;
foreach (var recycler in UnityEngine.Object.FindObjectsOfType<Recycler>())
{
if (recycler.OwnerID != 0UL)
{
recycler.gameObject.AddComponent<RecyclerComponent>();
}
}
}
private void Unload()
{
foreach (var recyclerComponent in UnityEngine.Object.FindObjectsOfType<RecyclerComponent>())
{
UnityEngine.Object.Destroy(recyclerComponent);
}
foreach (var player in BasePlayer.activePlayerList)
{
CuiHelper.DestroyUi(player, UiOverlayName);
}
}
private void OnItemAddedToContainer(ItemContainer container, Item item)
{
Recycler recycler = container.entityOwner as Recycler ?? container.entityOwner?.GetParentEntity() as Recycler;
if (recycler == null)
return;
var recyclerComponent = recycler.GetComponent<RecyclerComponent>();
if (recyclerComponent == null)
return;
bool isMainRecycler = container.entityOwner is Recycler;
ulong containerUid = container.uid.Value;
if (isMainRecycler && _recyclerItemContainers.Contains(containerUid))
{
ProcessRecyclerItems(recyclerComponent, item);
}
else if (!isMainRecycler && _inputItemContainers.Contains(containerUid))
{
recyclerComponent.HandleItemTransfers();
}
}
private void OnEntityBuilt(Planner planner, GameObject entityObject)
{
var player = planner?.GetOwnerPlayer();
var baseEntity = entityObject.GetComponent<BaseEntity>();
if (player == null || baseEntity == null || baseEntity.ShortPrefabName != ItemName || baseEntity.skinID != _config.RecyclerSkinId)
return;
int maxRecyclers = _config.MaxRecyclersPerPlayer;
if (permission.UserHasPermission(player.UserIDString, PermissionAdmin))
{
maxRecyclers = int.MaxValue;
}
else if (permission.UserHasPermission(player.UserIDString, PermissionVip))
{
maxRecyclers = _config.MaxRecyclersVip;
}
if (_recyclerOwners.Count(entry => entry.Value == player.userID) >= maxRecyclers)
{
player.ChatMessage(lang.GetMessage("RecyclerLimitReached", this, player.UserIDString));
timer.Once(1, () => GiveRecyclerItem(player));
NextTick(() => baseEntity?.Kill());
return;
}
if (!InitializeRecyclerPlacement(player, baseEntity))
{
player.ChatMessage(lang.GetMessage("InvalidPlacement", this, player.UserIDString));
timer.Once(1, () => GiveRecyclerItem(player));
}
else
{
player.ChatMessage(lang.GetMessage("RecyclerPlaced", this, player.UserIDString));
}
NextTick(() => baseEntity?.Kill());
}
private object CanPickupEntity(BasePlayer player, IndustrialStorageAdaptor adapter)
{
if (adapter?.net?.ID.Value != null && _storageAdapters.Contains(adapter.net.ID.Value))
{
adapter.GetParentEntity()?.GetParentEntity()?.Kill();
GiveRecyclerItem(player);
player.ChatMessage(lang.GetMessage("RecyclerPickedUp", this, player.UserIDString));
return false;
}
return null;
}
private object OnEntityKill(Recycler recycler)
{
if (!IsRecyclerOwned(recycler))
return null;
UnregisterRecyclerOwnership(recycler);
DropRecyclerItems(recycler);
return null;
}
private bool IsRecyclerOwned(Recycler recycler)
{
return recycler.OwnerID != 0UL && _recyclerOwners.ContainsKey(recycler.net.ID.Value);
}
private void UnregisterRecyclerOwnership(Recycler recycler)
{
_recyclerOwners.Remove(recycler.net.ID.Value);
}
private void DropRecyclerItems(Recycler recycler)
{
var recyclerComponent = recycler.GetComponent<RecyclerComponent>();
recyclerComponent?.DropItems();
}
void OnLootEntity(BasePlayer player, Recycler recycler)
{
if (recycler == null || player == null)
return;
if (recycler.OwnerID != 0UL && _recyclerOwners.ContainsKey(recycler.net.ID.Value))
{
_playersWithUi.Add(player.userID);
string recyclerId = recycler.net.ID.Value.ToString();
CreateUi(player, recyclerId);
}
}
private void OnPlayerLootEnd(PlayerLoot playerLoot)
{
BasePlayer player = playerLoot.GetComponentInParent<BasePlayer>();
if (player == null)
return;
if (_playersWithUi.Contains(player.userID))
{
_playersWithUi.Remove(player.userID);
CuiHelper.DestroyUi(player, UiOverlayName);
}
}
#endregion
#region UI
private void CreateUi(BasePlayer player, string recyclerId)
{
var container = new CuiElementContainer();
container.Add(
new CuiPanel
{
CursorEnabled = true,
Image =
{
Color = "1 1 1 0.15",
Sprite = "assets/content/ui/ui.background.transparent.radial.psd",
Material = "assets/content/ui/uibackgroundblur.mat",
},
RectTransform =
{
AnchorMin = _config.AnchorMin,
AnchorMax = _config.AnchorMax,
OffsetMin = "341.64 405.595",
OffsetMax = "554.76 505.605",
},
},
"Overlay",
UiOverlayName
);
container.Add(
new CuiElement
{
Name = "Text",
Parent = UiOverlayName,
Components =
{
new CuiTextComponent
{
Text = "INDUSTRIAL RECYCLER",
Font = "robotocondensed-bold.ttf",
FontSize = 17,
Align = TextAnchor.MiddleCenter,
Color = "1 1 1 1",
},
new CuiOutlineComponent { Color = "0 0 0 1", Distance = "1 1" },
new CuiRectTransformComponent
{
AnchorMin = "0.5 0.5",
AnchorMax = "0.5 0.5",
OffsetMin = "-86.493 0",
OffsetMax = "86.492 34.875",
},
},
}
);
container.Add(
new CuiButton
{
Button =
{
Color = "0.3960785 0.4666667 0.2627451 1",
Command = $"industrialrecycler.openinput {recyclerId}",
Close = UiOverlayName,
},
Text =
{
Text = lang.GetMessage("InputButton", this, player.UserIDString),
Font = "robotocondensed-regular.ttf",
FontSize = 18,
Align = TextAnchor.MiddleCenter,
Color = "1 1 1 1",
},
RectTransform =
{
AnchorMin = "0.5 0.5",
AnchorMax = "0.5 0.5",
OffsetMin = "-104.206 -49.58",
OffsetMax = "-2.394 -17.22",
},
},
UiOverlayName,
"Input"
);
container.Add(
new CuiButton
{
Button =
{
Color = "0.3960785 0.4666667 0.2627451 1",
Command = $"industrialrecycler.openoutput {recyclerId}",
Close = UiOverlayName,
},
Text =
{
Text = lang.GetMessage("OutputButton", this, player.UserIDString),
Font = "robotocondensed-regular.ttf",
FontSize = 18,
Align = TextAnchor.MiddleCenter,
Color = "1 1 1 1",
},
RectTransform =
{
AnchorMin = "0.5 0.5",
AnchorMax = "0.5 0.5",
OffsetMin = "1.994 -49.58",
OffsetMax = "103.806 -17.22",
},
},
UiOverlayName,
"Output"
);
container.Add(
new CuiButton
{
Button =
{
Color = "0.3960785 0.7666667 0.2627451 1",
Command = $"chat.say /togglerecycler",
Close = "ToggleConfig",
},
Text =
{
Text = lang.GetMessage("ToggleConfig", this),
Font = "robotocondensed-regular.ttf",
FontSize = 14,
Align = TextAnchor.MiddleCenter,
Color = "1 1 1 1",
},
RectTransform =
{
AnchorMin = "1 1",
AnchorMax = "1 1",
OffsetMin = "-110 -20",
OffsetMax = "0 0",
},
},
UiOverlayName,
"ToggleConfig"
);
CuiHelper.DestroyUi(player, UiOverlayName);
CuiHelper.AddUi(player, container);
}
private void OpenInputStorage(ConsoleSystem.Arg arg)
{
OpenStorage(arg, true);
}
private void OpenOutputStorage(ConsoleSystem.Arg arg)
{
OpenStorage(arg, false);
}
private void OpenStorage(ConsoleSystem.Arg arg, bool isInput)
{
var player = arg.Player();
if (player == null)
{
return;
}
if (arg.Args.Length == 0)
{
return;
}
if (!uint.TryParse(arg.Args[0], out uint recyclerId))
{
return;
}
var networkableId = new NetworkableId(recyclerId);
var recycler = BaseNetworkable.serverEntities.Find(networkableId) as Recycler;
if (recycler != null)
{
var recyclerComponent = recycler.GetComponent<RecyclerComponent>();
if (recyclerComponent != null)
{
var storage = isInput ? recyclerComponent.InputStorage : recyclerComponent.OutputStorage;
player.inventory.loot.StartLootingEntity(storage, true);
player.inventory.loot.AddContainer(storage.inventory);
player.inventory.loot.SendImmediate();
player.ClientRPCPlayer(null, player, "RPC_OpenLootPanel", storage.panelName);
}
}
}
#endregion
#region Main
private void CommandGetRecycler(BasePlayer player, string command, string[] args)
{
if (player == null)
return;
if (!permission.UserHasPermission(player.UserIDString, PermissionUseRecycler))
{
player.ChatMessage(lang.GetMessage("NoPermission", this, player.UserIDString));
return;
}
BasePlayer targetPlayer = player;
if (args != null && args.Length > 0)
{
targetPlayer = BasePlayer.Find(args[0]);
if (targetPlayer == null)
{
player.ChatMessage(lang.GetMessage("PlayerNotFound", this, player.UserIDString));
return;
}
}
if (GiveRecyclerItem(targetPlayer))
{
player.ChatMessage(lang.GetMessage("RecyclerGiven", this, player.UserIDString));
if (targetPlayer != player)
{
targetPlayer.ChatMessage(lang.GetMessage("RecyclerReceived", this, targetPlayer.UserIDString));
}
}
else
{
player.ChatMessage(lang.GetMessage("RecyclerNotGiven", this, player.UserIDString));
if (targetPlayer != player)
{
targetPlayer.ChatMessage(lang.GetMessage("RecyclerNotReceived", this, targetPlayer.UserIDString));
}
}
}
private bool GiveRecyclerItem(BasePlayer player)
{
var recyclerItem = ItemManager.CreateByName(ItemName, 1, _config.RecyclerSkinId);
if (recyclerItem == null)
return false;
recyclerItem.name = "Recycler";
return player.inventory.GiveItem(recyclerItem);
}
private void CommandUpgradeRecycler(BasePlayer player, string command, string[] args)
{
if (!permission.UserHasPermission(player.UserIDString, PermissionUseRecycler))
{
player.ChatMessage(lang.GetMessage("NoPermission", this, player.UserIDString));
return;
}
int maxRecyclers = _config.MaxRecyclersPerPlayer;
if (permission.UserHasPermission(player.UserIDString, PermissionAdmin))
{
maxRecyclers = int.MaxValue;
}
else if (permission.UserHasPermission(player.UserIDString, PermissionVip))
{
maxRecyclers = _config.MaxRecyclersVip;
}
if (_recyclerOwners.Count(entry => entry.Value == player.userID) >= maxRecyclers)
{
player.ChatMessage(lang.GetMessage("RecyclerLimitReached", this, player.UserIDString));
return;
}
if (!UpgradeToIndustrialRecycler(player))
{
player.ChatMessage(lang.GetMessage("NoRecyclerInView", this, player.UserIDString));
}
else
{
player.ChatMessage(lang.GetMessage("RecyclerUpgraded", this, player.UserIDString));
}
}
private Recycler FindRecyclerInView(BasePlayer player)
{
if (Physics.Raycast(player.eyes.HeadRay(), out RaycastHit hit, 5f))
{
BaseEntity entity = hit.GetEntity();
return entity as Recycler;
}
return null;
}
private bool InitializeRecyclerPlacement(BasePlayer player, BaseEntity baseEntity, int turn = 0)
{
var supportingFoundation = FindSupportingFoundation(baseEntity);
if (supportingFoundation == null)
return false;
var spawnedRecycler = SpawnRecyclerWithComponents(player, baseEntity, supportingFoundation, turn);
if (spawnedRecycler == null)
return false;
spawnedRecycler.gameObject.AddComponent<RecyclerComponent>();
return true;
}
private bool InitializeUpgradeRecycler(BasePlayer player, Recycler recycler, int turn = 0)
{
var spawnedRecycler = UpgradeRecyclerWithComponents(player, recycler, turn);
if (spawnedRecycler == null)
return false;
spawnedRecycler.gameObject.AddComponent<RecyclerComponent>();
return true;
}
private BuildingBlock FindSupportingFoundation(BaseEntity baseEntity)
{
Vector3 origin = baseEntity.transform.position + Vector3.up * 0.1f;
if (Physics.Raycast(origin, Vector3.down, out RaycastHit hitData, 4f, LayerMask.GetMask("Construction")))
{
return hitData.GetEntity() as BuildingBlock;
}
return null;
}
private Recycler SetupStorageAndAdapters(Recycler recycler, BasePlayer player)
{
Vector3 inputOffset,
inputAdapterOffset,
outputOffset,
outputAdapterOffset;
Quaternion inputRotation,
outputRotation,
inputAdapterRotation,
outputAdapterRotation;
if (_config.UseAlternativeAdapterConfig)
{
inputOffset = new Vector3(0.0f, 0.72f, 0.11f);
inputAdapterOffset = new Vector3(0.32f, -0.6f, -0.03f);
outputOffset = new Vector3(-0.4f, 0.8f, 0.2f);
outputAdapterOffset = new Vector3(-0.07f, 0.535f, 0.397f);
inputRotation = Quaternion.Euler(0, 180, 191);
outputRotation = Quaternion.Euler(169, 90, 180);
inputAdapterRotation = Quaternion.Euler(0, 0, 0);
outputAdapterRotation = Quaternion.Euler(180, 90, 0);
}
else
{
inputOffset = new Vector3(-1.0f, 0.72f, 0.31f);
inputAdapterOffset = new Vector3(0.00f, -0.15f, -0.25f);
outputOffset = new Vector3(-0.9f, 0.72f, -0.09f);
outputAdapterOffset = new Vector3(0.00f, 0.26f, -0.05f);
inputRotation = Quaternion.Euler(90, 90, 180);
outputRotation = Quaternion.Euler(180, 90, 180);
inputAdapterRotation = Quaternion.Euler(180, 90, 270);
outputAdapterRotation = Quaternion.Euler(0, 90, 0);
}
var inputStorage = SpawnEntity(InputStoragePrefabPath, recycler, player, inputOffset, inputRotation);
SpawnEntity(AdapterPrefabPath, inputStorage, player, inputAdapterOffset, inputAdapterRotation);
var outputStorage = SpawnEntity(OutputStoragePrefabPath, recycler, player, outputOffset, outputRotation);
SpawnEntity(AdapterPrefabPath, outputStorage, player, outputAdapterOffset, outputAdapterRotation);
return recycler;
}
private Recycler UpgradeRecyclerWithComponents(BasePlayer player, Recycler recycler, int turn = 0)
{
return SetupStorageAndAdapters(recycler, player);
}
private Recycler SpawnRecyclerWithComponents(BasePlayer player, BaseEntity baseEntity, BuildingBlock foundation, int turn = 0)
{
var recycler = SpawnEntity(RecyclerPrefabPath, foundation, player, baseEntity.transform.position, baseEntity.transform.rotation * Quaternion.Euler(0, turn, 0)) as Recycler;
if (recycler == null)
return null;
return SetupStorageAndAdapters(recycler, player);
}
private BaseEntity SpawnEntity(string prefabPath, BaseEntity parent, BasePlayer player, Vector3 position, Quaternion rotation)
{
var entity = GameManager.server.CreateEntity(prefabPath, Vector3.zero, Quaternion.identity, true);
if (entity == null)
return null;
entity.OwnerID = player.userID;
if (parent != null)
{
entity.SetParent(parent, true);
}
if (parent is BuildingBlock)
{
entity.transform.position = position;
entity.transform.rotation = rotation;
}
else
{
entity.transform.localPosition = position;
entity.transform.localRotation = rotation;
}
entity.Spawn();
entity.SendNetworkUpdateImmediate();
return entity;
}
private void ProcessRecyclerItems(RecyclerComponent recyclerComponent, Item item)
{
if (item.position < 6)
{
recyclerComponent.Recycler.StartRecycling();
}
else
{
if (!item.MoveToContainer(recyclerComponent.OutputStorage.inventory))
{
recyclerComponent.Recycler.StopRecycling();
}
}
}
private bool UpgradeToIndustrialRecycler(BasePlayer player)
{
if (Physics.Raycast(player.eyes.HeadRay(), out RaycastHit hit, 5f))
{
BaseEntity baseEntity = hit.GetEntity();
if (baseEntity is Recycler recycler && recycler.OwnerID == player.userID)
{
if (!InitializeUpgradeRecycler(player, baseEntity as Recycler, 90))
{
player.ChatMessage(lang.GetMessage("InvalidPlacement", this, player.UserIDString));
timer.Once(1, () => GiveRecyclerItem(player));
return false;
}
else
{
player.ChatMessage(lang.GetMessage("RecyclerPlaced", this, player.UserIDString));
}
return true;
}
}
return false;
}
private void ToggleRecyclerConfig(BasePlayer player, string command, string[] args)
{
if (!permission.UserHasPermission(player.UserIDString, PermissionUseRecycler))
{
player.ChatMessage(lang.GetMessage("NoPermission", this, player.UserIDString));
return;
}
Recycler recycler = FindRecyclerInView(player);
if (recycler == null)
{
player.ChatMessage(lang.GetMessage("NoRecyclerInView", this, player.UserIDString));
return;
}
var recyclerComponent = recycler.GetComponent<RecyclerComponent>();
if (recyclerComponent == null)
{
player.ChatMessage(lang.GetMessage("RecyclerComponentNotFound", this, player.UserIDString));
return;
}
recyclerComponent.ToggleConfig();
player.ChatMessage(lang.GetMessage("RecyclerConfigToggled", this, player.UserIDString));
}
#endregion
#region Configuration
private class Configuration
{
[JsonProperty("Commands")]
public List<string> Commands { get; set; }
[JsonProperty("Max Recyclers Per Player")]
public int MaxRecyclersPerPlayer { get; set; }
[JsonProperty("Max Recyclers Vip (industrialrecycler.vip)")]
public int MaxRecyclersVip { get; set; }
[JsonProperty("Recycler Item SkinId")]
public ulong RecyclerSkinId { get; set; }
[JsonProperty("AnchorMin")]
public string AnchorMin { get; set; }
[JsonProperty("AnchorMax")]
public string AnchorMax { get; set; }
[JsonProperty("Alternative Adapter Configuration")]
public bool UseAlternativeAdapterConfig { get; set; }
[JsonProperty("Hide Storage Containers")]
public bool HideStorageContainers { get; set; }
[JsonProperty("Version")]
public VersionNumber Version { get; set; }
}
protected override void LoadConfig()
{
base.LoadConfig();
try
{
_config = Config.ReadObject<Configuration>() ?? throw new Exception("Failed to read configuration file.");
bool configChanged = false;
if (_config.Version != Version)
{
_config.Version = Version;
configChanged = true;
}
if (string.IsNullOrEmpty(_config.AnchorMin))
{
_config.AnchorMin = "0.5 0";
configChanged = true;
}
if (string.IsNullOrEmpty(_config.AnchorMax))
{
_config.AnchorMax = "0.5 0";
configChanged = true;
}
if (!_config.UseAlternativeAdapterConfig)
{
_config.UseAlternativeAdapterConfig = false;
configChanged = true;
}
if (configChanged)
{
SaveConfig();
}
}
catch (Exception ex)
{
PrintError($"There was an error in your configuration file: {ex.Message}. Default values will be used.");
LoadDefaultConfig();
}
}
protected override void LoadDefaultConfig()
{
_config = GetDefaultConfig();
SaveConfig();
}
protected override void SaveConfig()
{
Config.WriteObject(_config, true);
}
private Configuration GetDefaultConfig()
{
return new Configuration
{
Commands = new List<string> { "getrecycler", "irecycler", "giverecycler" },
MaxRecyclersPerPlayer = 1,
MaxRecyclersVip = 2,
RecyclerSkinId = 3357927081,
AnchorMin = "0.5 0",
AnchorMax = "0.5 0",
UseAlternativeAdapterConfig = false,
HideStorageContainers = false,
Version = Version,
};
}
#endregion
#region Localization
protected override void LoadDefaultMessages()
{
lang.RegisterMessages(
new Dictionary<string, string>
{
["NoPermission"] = "You do not have permission to use this command.",
["RecyclerLimitReached"] = "You have reached the recycler limit.",
["InvalidPlacement"] = "The recycler must be placed on a construction block.",
["RecyclerPlaced"] = "Recycler placed successfully.",
["RecyclerPickedUp"] = "Recycler picked up, item returned to inventory.",
["RecyclerGiven"] = "Recycler given to your inventory.",
["RecyclerReceived"] = "You have received a recycler.",
["RecyclerNotGiven"] = "Failed to give recycler.",
["RecyclerNotReceived"] = "Failed to receive recycler.",
["NoRecyclerInView"] = "No recycler in sight to upgrade.",
["RecyclerComponentNotFound"] = "Recycler component not found.",
["RecyclerConfigToggled"] = "Recycler configuration toggled successfully.",
["PlayerNotFound"] = "The specified player could not be found.",
["ToggleConfig"] = "Toggle",
["InputButton"] = "Input",
["OutputButton"] = "Output",
},
this
);
lang.RegisterMessages(
new Dictionary<string, string>
{
["NoPermission"] = "Você não tem permissão para usar este comando.",
["RecyclerLimitReached"] = "Você atingiu o limite de recicladores.",
["InvalidPlacement"] = "O reciclador deve ser colocado sobre um bloco de construção.",
["RecyclerPlaced"] = "Reciclador colocado com sucesso.",
["RecyclerPickedUp"] = "Reciclador recolhido, item devolvido ao inventário.",
["RecyclerGiven"] = "Reciclador fornecido ao seu inventário.",
["RecyclerReceived"] = "Você recebeu um reciclador.",
["RecyclerNotGiven"] = "Falha ao fornecer o reciclador.",
["RecyclerNotReceived"] = "Falha ao receber o reciclador.",
["NoRecyclerInView"] = "Nenhum reciclador à vista para atualizar.",
["RecyclerComponentNotFound"] = "Componente de reciclador não encontrado.",
["RecyclerConfigToggled"] = "Configuração do reciclador alternada com sucesso.",
["PlayerNotFound"] = "O jogador especificado não pôde ser encontrado.",
["ToggleConfig"] = "Alterar",
["InputButton"] = "Entrada",
["OutputButton"] = "Saída",
},
this,
"pt-BR"
);
lang.RegisterMessages(
new Dictionary<string, string>
{
["NoPermission"] = "Sie haben keine Erlaubnis, diesen Befehl zu verwenden.",
["RecyclerLimitReached"] = "Sie haben die Grenze für Recycler erreicht.",
["InvalidPlacement"] = "Der Recycler muss auf einem Baublock platziert werden.",
["RecyclerPlaced"] = "Recycler erfolgreich platziert.",
["RecyclerPickedUp"] = "Recycler aufgenommen, Artikel in das Inventar zurückgegeben.",
["RecyclerGiven"] = "Recycler wurde Ihrem Inventar hinzugefügt.",
["RecyclerReceived"] = "Sie haben einen Recycler erhalten.",
["RecyclerNotGiven"] = "Recycle fehlerhaft vorhanden.",
["RecyclerNotReceived"] = "Falschen Empfang des Recyclers.",
["NoRecyclerInView"] = "Kein Recycler in Sicht, um aufzurüsten.",
["RecyclerComponentNotFound"] = "Recycler-Komponente nicht gefunden.",
["RecyclerConfigToggled"] = "Recycler-Konfiguration erfolgreich umgeschaltet.",
["PlayerNotFound"] = "Der angegebene Spieler konnte nicht gefunden werden.",
["ToggleConfig"] = "Umschalten",
["InputButton"] = "Eingang",
["OutputButton"] = "Ausgang",
},
this,
"de"
);
lang.RegisterMessages(
new Dictionary<string, string>
{
["NoPermission"] = "No tienes permiso para usar este comando.",
["RecyclerLimitReached"] = "Has alcanzado el límite de recicladores.",
["InvalidPlacement"] = "El reciclador debe colocarse en un bloque de construcción.",
["RecyclerPlaced"] = "Reciclador colocado con éxito.",
["RecyclerPickedUp"] = "Reciclador recogido, artículo devuelto al inventario.",
["RecyclerGiven"] = "Reciclador dado a tu inventario.",
["RecyclerReceived"] = "Has recibido un reciclador.",
["RecyclerNotGiven"] = "Fallo al dar el reciclador.",
["RecyclerNotReceived"] = "Fallo al recibir el reciclador.",
["NoRecyclerInView"] = "No hay reciclador a la vista para mejorar.",
["RecyclerComponentNotFound"] = "Componente de reciclador no encontrado.",
["RecyclerConfigToggled"] = "Configuración del reciclador alternada con éxito.",
["PlayerNotFound"] = "No se pudo encontrar al jugador especificado.",
["ToggleConfig"] = "Alternar",
["InputButton"] = "Entrada",
["OutputButton"] = "Salida",
},
this,
"es"
);
}
#endregion
#region Component
private class RecyclerComponent : MonoBehaviour
{
public Recycler Recycler { get; private set; }
public StorageContainer InputStorage { get; private set; }
public StorageContainer OutputStorage { get; private set; }
public int CurrentConfigState { get; private set; }
private const int MaxStorageCapacity = 48;
private const float TransferInterval = 10f;
private enum RecyclerConfig
{
Default = 1,
Alternative = 2,
}
private void Awake()
{
Recycler = GetComponent<Recycler>();
if (Recycler == null)
{
Debug.LogError("Recycler component is missing on this GameObject.");
enabled = false;
return;
}
// Start with a default known state
CurrentConfigState = (int)RecyclerConfig.Default;
InitializeRecyclerComponents();
}
private void InitializeRecyclerComponents()
{
foreach (MonoBehaviour mb in GetComponents<MonoBehaviour>())
{
var type = mb.GetType();
if (type != typeof(Recycler) && type != typeof(RecyclerComponent) && type.Name != "Ground_Watch")
{
Destroy(mb);
}
}
if (!ValidateStorageContainers())
{
Debug.LogError("Failed to validate storage containers.");
enabled = false;
return;
}
SetupRecycler();
RegisterEntities();
InvokeRepeating(nameof(HandleItemTransfers), 0f, TransferInterval);
}
private bool ValidateStorageContainers()
{
InputStorage = Recycler.children.OfType<StorageContainer>().FirstOrDefault(c => c?.name == InputStoragePrefabPath);
OutputStorage = Recycler.children.OfType<StorageContainer>().FirstOrDefault(c => c?.name == OutputStoragePrefabPath);
return InputStorage != null && OutputStorage != null;
}
private void RegisterEntities()
{
_instance._inputItemContainers.Add(InputStorage.inventory.uid.Value);
_instance._recyclerItemContainers.Add(Recycler.inventory.uid.Value);
var inputAdapter = InputStorage.children.OfType<IndustrialStorageAdaptor>().FirstOrDefault();
if (inputAdapter != null)
_instance._storageAdapters.Add(inputAdapter.net.ID.Value);
var outputAdapter = OutputStorage.children.OfType<IndustrialStorageAdaptor>().FirstOrDefault();
if (outputAdapter != null)
_instance._storageAdapters.Add(outputAdapter.net.ID.Value);
}
private void SetupRecycler()
{
if (Recycler == null || InputStorage == null || OutputStorage == null)
{
Debug.LogError("Attempted to setup recycler with null components.");
return;
}
_instance._recyclerOwners[Recycler.net.ID.Value] = Recycler.OwnerID;
InputStorage.inventory.capacity = MaxStorageCapacity;
OutputStorage.inventory.capacity = MaxStorageCapacity;
}
public void HandleItemTransfers()
{
int availableRecyclerSlots = 6 - Recycler.inventory.itemList.Count;
if (OutputStorage.inventory.IsFull())
{
Recycler.StopRecycling();
return;
}
TransferItemsFromRecyclerToOutput(ref availableRecyclerSlots);
TransferItemsFromInputToRecycler(ref availableRecyclerSlots);
if (availableRecyclerSlots < 6 && Recycler.inventory.itemList.Count > 0)
{
Recycler.StartRecycling();
}
}
private void TransferItemsFromRecyclerToOutput(ref int availableRecyclerSlots)
{
for (int slot = 6; slot < Recycler.inventory.capacity; slot++)
{
var itemInRecycler = Recycler.inventory.GetSlot(slot);
if (itemInRecycler != null && itemInRecycler.MoveToContainer(OutputStorage.inventory))
{
availableRecyclerSlots++;
}
}
}
private void TransferItemsFromInputToRecycler(ref int availableRecyclerSlots)
{
var inputItems = new List<Item>(InputStorage.inventory.itemList);
foreach (var item in inputItems)
{
if (item.info.Blueprint != null)
{
MoveItemToRecycler(item, ref availableRecyclerSlots);
}
else
{
item.MoveToContainer(OutputStorage.inventory);
}
}
}
private void MoveItemToRecycler(Item item, ref int availableRecyclerSlots)
{
if (availableRecyclerSlots <= 0)
return;
for (int slot = 0; slot < 6; slot++)
{
if (Recycler.inventory.GetSlot(slot) == null && item.MoveToContainer(Recycler.inventory, slot))
{
availableRecyclerSlots--;
break;
}
}
}
public void ToggleConfig()
{
CancelInvoke(nameof(HandleItemTransfers));
CurrentConfigState = (int)(CurrentConfigState == (int)RecyclerConfig.Default ? RecyclerConfig.Alternative : RecyclerConfig.Default);
List<(string Shortname, int Amount, float ConditionNormalized)> ExtractItemDetails(ItemContainer container) =>
container?.itemList?.Select(item => (item.info.shortname, item.amount, item.conditionNormalized)).ToList() ?? new List<(string, int, float)>();
var inputItemDetails = ExtractItemDetails(InputStorage.inventory);
var outputItemDetails = ExtractItemDetails(OutputStorage.inventory);
ClearExistingComponents();
UpdateAdapterPositions();
InitializeRecyclerComponents();
if (InputStorage == null || OutputStorage == null || Recycler == null)
{
Debug.LogError("As referências dos contêineres não foram atualizadas.");
return;
}
foreach (var (shortname, amount, condition) in inputItemDetails)
CreateAndMoveItem(shortname, amount, condition, InputStorage.inventory);
foreach (var (shortname, amount, condition) in outputItemDetails)
CreateAndMoveItem(shortname, amount, condition, OutputStorage.inventory);
}
private void CreateAndMoveItem(string shortname, int amount, float conditionNormalized, ItemContainer container)
{
var item = ItemManager.CreateByName(shortname, amount);
if (item != null)
{
item.conditionNormalized = conditionNormalized;
if (!item.MoveToContainer(container))
item.Remove();
}
}
private void UpdateAdapterPositions()
{
ClearExistingComponents();
Vector3 inputOffset,
outputOffset,
inputAdapterOffset,
outputAdapterOffset;
Quaternion inputRotation,
outputRotation,
inputAdapterRotation,
outputAdapterRotation;
if (CurrentConfigState == (int)RecyclerConfig.Default)
{
inputOffset = new Vector3(0.0f, 0.72f, 0.11f);
outputOffset = new Vector3(-0.4f, 0.8f, 0.2f);
inputAdapterOffset = new Vector3(0.32f, -0.6f, -0.03f);
outputAdapterOffset = new Vector3(-0.07f, 0.535f, 0.397f);
inputRotation = Quaternion.Euler(0, 180, 191);
outputRotation = Quaternion.Euler(169, 90, 180);
inputAdapterRotation = Quaternion.Euler(0, 0, 0);
outputAdapterRotation = Quaternion.Euler(180, 90, 0);
}
else
{
if (_instance._config.HideStorageContainers)
{
inputOffset = new Vector3(0.0f, 0.72f, 0.11f);
outputOffset = new Vector3(-0.4f, 0.72f, 0.2f);
inputAdapterOffset = new Vector3(0.836f, -0.3301f, 0.18f);
outputAdapterOffset = new Vector3(-0.227f, 0.33f, 0.434f);
inputRotation = Quaternion.Euler(0, 0, 180);
outputRotation = Quaternion.Euler(180, 90, 180);
inputAdapterRotation = Quaternion.Euler(0, 0, 0);
outputAdapterRotation = Quaternion.Euler(180, 90, 0);
}
else
{
inputOffset = new Vector3(-1.0f, 0.72f, 0.31f);
outputOffset = new Vector3(-0.9f, 0.72f, -0.09f);
inputAdapterOffset = new Vector3(0.00f, -0.15f, -0.25f);
outputAdapterOffset = new Vector3(0.00f, 0.26f, -0.05f);
inputRotation = Quaternion.Euler(90, 90, 180);
outputRotation = Quaternion.Euler(180, 90, 180);
inputAdapterRotation = Quaternion.Euler(180, 90, 270);
outputAdapterRotation = Quaternion.Euler(0, 90, 0);
}
}
BasePlayer ownerPlayer = BasePlayer.FindByID(Recycler.OwnerID);
if (ownerPlayer != null)
{
var inputStorage = _instance.SpawnEntity(InputStoragePrefabPath, Recycler, ownerPlayer, inputOffset, inputRotation) as StorageContainer;
if (inputStorage == null)
{
Debug.LogError("Failed to spawn input storage.");
return;
}
_instance.SpawnEntity(AdapterPrefabPath, inputStorage, ownerPlayer, inputAdapterOffset, inputAdapterRotation);
var outputStorage = _instance.SpawnEntity(OutputStoragePrefabPath, Recycler, ownerPlayer, outputOffset, outputRotation) as StorageContainer;
if (outputStorage == null)
{
Debug.LogError("Failed to spawn output storage.");
return;
}
_instance.SpawnEntity(AdapterPrefabPath, outputStorage, ownerPlayer, outputAdapterOffset, outputAdapterRotation);
}
}
private void ClearExistingComponents()
{
foreach (var child in Recycler.children.ToList())
{
if (child is StorageContainer || child is IndustrialStorageAdaptor)
{
child.Kill();
}
}
}
internal void DropItems()
{
var allItems = GatherAllItems();
DropItemsInBatches(allItems, MaxStorageCapacity);
}
private List<Item> GatherAllItems()
{
return InputStorage.inventory.itemList.Concat(OutputStorage.inventory.itemList).Concat(Recycler.inventory.itemList).ToList();
}
private void DropItemsInBatches(List<Item> items, int batchSize)
{
var recyclerPosition = Recycler.transform.position;
var recyclerRotation = Recycler.transform.rotation;
for (int i = 0; i < items.Count; i += batchSize)
{
var itemBatch = items.Skip(i).Take(batchSize).ToList();
SpawnDroppedItemContainer(recyclerPosition, recyclerRotation, itemBatch);
}
}
private DroppedItemContainer SpawnDroppedItemContainer(Vector3 position, Quaternion rotation, List<Item> itemsToDrop)
{
var containerPrefabPath = "assets/prefabs/misc/item drop/item_drop.prefab";
var droppedItemContainer = GameManager.server.CreateEntity(containerPrefabPath, position, rotation) as DroppedItemContainer;
if (droppedItemContainer == null)
return null;
InitializeItemContainer(droppedItemContainer, itemsToDrop);
droppedItemContainer.Spawn();
return droppedItemContainer;
}
private void InitializeItemContainer(DroppedItemContainer container, List<Item> items)
{
container.inventory = new ItemContainer();
container.inventory.ServerInitialize(null, items.Count);
container.inventory.GiveUID();
container.inventory.entityOwner = container;
foreach (var item in items)
{
item.MoveToContainer(container.inventory);
}
}
private void OnDestroy()
{
CancelInvoke(nameof(HandleItemTransfers));
}
}
#endregion
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Oxide.Core;
using Oxide.Core.Plugins;
using Oxide.Game.Rust.Cui;
using UnityEngine;
namespace Oxide.Plugins
{
[Info("IndustrialRecycler", "Marte6", "1.4.6")]
[Description("Automate recycling by attaching storage and adapters to recyclers.")]
class IndustrialRecycler : RustPlugin
{
#region PluginReferences
[PluginReference] Plugin Friends;
#endregion
#region Fields
private static IndustrialRecycler _instance;
private Configuration _config;
private const string RecyclerPrefabPath = "assets/bundled/prefabs/static/recycler_static.prefab";
private const string InputStoragePrefabPath = "assets/content/vehicles/boats/rowboat/subents/rowboat_storage.prefab";
private const string OutputStoragePrefabPath = "assets/prefabs/deployable/hot air balloon/subents/hab_storage.prefab";
private const string AdapterPrefabPath = "assets/prefabs/deployable/playerioents/industrialadaptors/storageadaptor.deployed.prefab";
private const string ItemName = "box.wooden.large";
private const string PermissionUseRecycler = "industrialrecycler.give";
private const string PermissionVip = "industrialrecycler.vip";
private const string PermissionAdmin = "industrialrecycler.admin";
private const string UiOverlayName = "IndustrialRecyclerMainPanel";
#endregion
#region Cache
private readonly Dictionary<ulong, ulong> _recyclerOwners = new();
private readonly HashSet<ulong> _recyclerItemContainers = new();
private readonly HashSet<ulong> _inputItemContainers = new();
private readonly HashSet<ulong> _storageAdapters = new();
private readonly HashSet<ulong> _playersWithUi = new();
#endregion
#region Game Hooks
private void Init()
{
permission.RegisterPermission(PermissionUseRecycler, this);
permission.RegisterPermission(PermissionVip, this);
permission.RegisterPermission(PermissionAdmin, this);
foreach (var command in _config.Commands)
{
cmd.AddChatCommand(command, this, nameof(CommandGetRecycler));
}
cmd.AddChatCommand("upgraderecycler", this, nameof(CommandUpgradeRecycler));
cmd.AddChatCommand("togglerecycler", this, nameof(ToggleRecyclerConfig));
cmd.AddConsoleCommand("industrialrecycler.openinput", this, nameof(OpenInputStorage));
cmd.AddConsoleCommand("industrialrecycler.openoutput", this, nameof(OpenOutputStorage));
}
private void OnServerInitialized()
{
_instance = this;
foreach (var recycler in UnityEngine.Object.FindObjectsOfType<Recycler>())
{
if (recycler.OwnerID != 0UL)
{
recycler.gameObject.AddComponent<RecyclerComponent>();
}
}
}
private void Unload()
{
foreach (var recyclerComponent in UnityEngine.Object.FindObjectsOfType<RecyclerComponent>())
{
UnityEngine.Object.Destroy(recyclerComponent);
}
foreach (var player in BasePlayer.activePlayerList)
{
CuiHelper.DestroyUi(player, UiOverlayName);
}
}
private void OnItemAddedToContainer(ItemContainer container, Item item)
{
Recycler recycler = container.entityOwner as Recycler ?? container.entityOwner?.GetParentEntity() as Recycler;
if (recycler == null)
return;
var recyclerComponent = recycler.GetComponent<RecyclerComponent>();
if (recyclerComponent == null)
return;
bool isMainRecycler = container.entityOwner is Recycler;
ulong containerUid = container.uid.Value;
if (isMainRecycler && _recyclerItemContainers.Contains(containerUid))
{
ProcessRecyclerItems(recyclerComponent, item);
}
else if (!isMainRecycler && _inputItemContainers.Contains(containerUid))
{
recyclerComponent.HandleItemTransfers();
}
}
private void OnEntityBuilt(Planner planner, GameObject entityObject)
{
var player = planner?.GetOwnerPlayer();
var baseEntity = entityObject.GetComponent<BaseEntity>();
if (player == null || baseEntity == null || baseEntity.ShortPrefabName != ItemName || baseEntity.skinID != _config.RecyclerSkinId)
return;
int maxRecyclers = _config.MaxRecyclersPerPlayer;
if (permission.UserHasPermission(player.UserIDString, PermissionAdmin))
{
maxRecyclers = int.MaxValue;
}
else if (permission.UserHasPermission(player.UserIDString, PermissionVip))
{
maxRecyclers = _config.MaxRecyclersVip;
}
if (_recyclerOwners.Count(entry => entry.Value == player.userID) >= maxRecyclers)
{
player.ChatMessage(lang.GetMessage("RecyclerLimitReached", this, player.UserIDString));
timer.Once(1, () => GiveRecyclerItem(player));
NextTick(() => baseEntity?.Kill());
return;
}
if (!InitializeRecyclerPlacement(player, baseEntity))
{
player.ChatMessage(lang.GetMessage("InvalidPlacement", this, player.UserIDString));
timer.Once(1, () => GiveRecyclerItem(player));
}
else
{
player.ChatMessage(lang.GetMessage("RecyclerPlaced", this, player.UserIDString));
}
NextTick(() => baseEntity?.Kill());
}
private object CanLootEntity(BasePlayer player, Recycler recycler)
{
if (!HasAccess(player, recycler))
{
player.ChatMessage(lang.GetMessage("NoAccess", this, player.UserIDString));
return false;
}
return null;
}
private object OnEntityKill(Recycler recycler)
{
if (!IsRecyclerOwned(recycler))
return null;
UnregisterRecyclerOwnership(recycler);
DropRecyclerItems(recycler);
return null;
}
private bool IsRecyclerOwned(Recycler recycler)
{
return recycler.OwnerID != 0UL && _recyclerOwners.ContainsKey(recycler.net.ID.Value);
}
private void UnregisterRecyclerOwnership(Recycler recycler)
{
_recyclerOwners.Remove(recycler.net.ID.Value);
}
private void DropRecyclerItems(Recycler recycler)
{
var recyclerComponent = recycler.GetComponent<RecyclerComponent>();
recyclerComponent?.DropItems();
}
private void OnLootEntity(BasePlayer player, Recycler recycler)
{
if (recycler == null || player == null || !HasAccess(player, recycler))
return;
if (recycler.OwnerID != 0UL && _recyclerOwners.ContainsKey(recycler.net.ID.Value))
{
_playersWithUi.Add(player.userID);
string recyclerId = recycler.net.ID.Value.ToString();
CreateUi(player, recyclerId);
}
}
private void OnPlayerLootEnd(PlayerLoot playerLoot)
{
BasePlayer player = playerLoot.GetComponentInParent<BasePlayer>();
if (player == null)
return;
if (_playersWithUi.Contains(player.userID))
{
_playersWithUi.Remove(player.userID);
CuiHelper.DestroyUi(player, UiOverlayName);
}
}
#endregion
#region Access Control
private bool HasAccess(BasePlayer player, BaseEntity entity)
{
ulong ownerId = entity.OwnerID;
if (ownerId == player.userID || permission.UserHasPermission(player.UserIDString, PermissionAdmin))
return true;
if (_config.AllowTeamAccess && player.currentTeam != 0)
{
var team = RelationshipManager.ServerInstance.FindTeam(player.currentTeam);
if (team != null && team.members.Contains(ownerId))
return true;
}
if (_config.AllowFriendsAccess && Friends != null)
{
bool areFriends = (bool)(Friends.CallHook("AreFriends", ownerId, player.userID) ?? false);
if (areFriends)
return true;
}
return false;
}
#endregion
#region UI
private void CreateUi(BasePlayer player, string recyclerId)
{
var container = new CuiElementContainer();
container.Add(
new CuiPanel
{
CursorEnabled = true,
Image =
{
Color = "1 1 1 0.15",
Sprite = "assets/content/ui/ui.background.transparent.radial.psd",
Material = "assets/content/ui/uibackgroundblur.mat",
},
RectTransform =
{
AnchorMin = _config.AnchorMin,
AnchorMax = _config.AnchorMax,
OffsetMin = "341.64 405.595",
OffsetMax = "554.76 505.605",
},
},
"Overlay",
UiOverlayName
);
container.Add(
new CuiElement
{
Name = "Text",
Parent = UiOverlayName,
Components =
{
new CuiTextComponent
{
Text = "INDUSTRIAL RECYCLER",
Font = "robotocondensed-bold.ttf",
FontSize = 17,
Align = TextAnchor.MiddleCenter,
Color = "1 1 1 1",
},
new CuiOutlineComponent { Color = "0 0 0 1", Distance = "1 1" },
new CuiRectTransformComponent
{
AnchorMin = "0.5 0.5",
AnchorMax = "0.5 0.5",
OffsetMin = "-86.493 0",
OffsetMax = "86.492 34.875",
},
},
}
);
container.Add(
new CuiButton
{
Button =
{
Color = "0.3960785 0.4666667 0.2627451 1",
Command = $"industrialrecycler.openinput {recyclerId}",
Close = UiOverlayName,
},
Text =
{
Text = lang.GetMessage("InputButton", this, player.UserIDString),
Font = "robotocondensed-regular.ttf",
FontSize = 18,
Align = TextAnchor.MiddleCenter,
Color = "1 1 1 1",
},
RectTransform =
{
AnchorMin = "0.5 0.5",
AnchorMax = "0.5 0.5",
OffsetMin = "-104.206 -49.58",
OffsetMax = "-2.394 -17.22",
},
},
UiOverlayName,
"Input"
);
container.Add(
new CuiButton
{
Button =
{
Color = "0.3960785 0.4666667 0.2627451 1",
Command = $"industrialrecycler.openoutput {recyclerId}",
Close = UiOverlayName,
},
Text =
{
Text = lang.GetMessage("OutputButton", this, player.UserIDString),
Font = "robotocondensed-regular.ttf",
FontSize = 18,
Align = TextAnchor.MiddleCenter,
Color = "1 1 1 1",
},
RectTransform =
{
AnchorMin = "0.5 0.5",
AnchorMax = "0.5 0.5",
OffsetMin = "1.994 -49.58",
OffsetMax = "103.806 -17.22",
},
},
UiOverlayName,
"Output"
);
container.Add(
new CuiButton
{
Button =
{
Color = "0.3960785 0.7666667 0.2627451 1",
Command = $"chat.say /togglerecycler",
Close = "ToggleConfig",
},
Text =
{
Text = lang.GetMessage("ToggleConfig", this),
Font = "robotocondensed-regular.ttf",
FontSize = 14,
Align = TextAnchor.MiddleCenter,
Color = "1 1 1 1",
},
RectTransform =
{
AnchorMin = "1 1",
AnchorMax = "1 1",
OffsetMin = "-110 -20",
OffsetMax = "0 0",
},
},
UiOverlayName,
"ToggleConfig"
);
CuiHelper.DestroyUi(player, UiOverlayName);
CuiHelper.AddUi(player, container);
}
private void OpenInputStorage(ConsoleSystem.Arg arg)
{
OpenStorage(arg, true);
}
private void OpenOutputStorage(ConsoleSystem.Arg arg)
{
OpenStorage(arg, false);
}
private void OpenStorage(ConsoleSystem.Arg arg, bool isInput)
{
var player = arg.Player();
if (player == null)
{
return;
}
if (arg.Args.Length == 0)
{
return;
}
if (!uint.TryParse(arg.Args[0], out uint recyclerId))
{
return;
}
var networkableId = new NetworkableId(recyclerId);
var recycler = BaseNetworkable.serverEntities.Find(networkableId) as Recycler;
if (recycler != null && HasAccess(player, recycler))
{
var recyclerComponent = recycler.GetComponent<RecyclerComponent>();
if (recyclerComponent != null)
{
var storage = isInput ? recyclerComponent.InputStorage : recyclerComponent.OutputStorage;
player.inventory.loot.StartLootingEntity(storage, true);
player.inventory.loot.AddContainer(storage.inventory);
player.inventory.loot.SendImmediate();
player.ClientRPCPlayer(null, player, "RPC_OpenLootPanel", storage.panelName);
}
}
}
#endregion
#region Main
private void CommandGetRecycler(BasePlayer player, string command, string[] args)
{
if (player == null)
return;
if (!permission.UserHasPermission(player.UserIDString, PermissionUseRecycler))
{
player.ChatMessage(lang.GetMessage("NoPermission", this, player.UserIDString));
return;
}
BasePlayer targetPlayer = player;
if (args != null && args.Length > 0)
{
targetPlayer = BasePlayer.Find(args[0]);
if (targetPlayer == null)
{
player.ChatMessage(lang.GetMessage("PlayerNotFound", this, player.UserIDString));
return;
}
}
if (GiveRecyclerItem(targetPlayer))
{
player.ChatMessage(lang.GetMessage("RecyclerGiven", this, player.UserIDString));
if (targetPlayer != player)
{
targetPlayer.ChatMessage(lang.GetMessage("RecyclerReceived", this, targetPlayer.UserIDString));
}
}
else
{
player.ChatMessage(lang.GetMessage("RecyclerNotGiven", this, player.UserIDString));
if (targetPlayer != player)
{
targetPlayer.ChatMessage(lang.GetMessage("RecyclerNotReceived", this, targetPlayer.UserIDString));
}
}
}
private bool GiveRecyclerItem(BasePlayer player)
{
var recyclerItem = ItemManager.CreateByName(ItemName, 1, _config.RecyclerSkinId);
if (recyclerItem == null)
return false;
recyclerItem.name = "Recycler";
return player.inventory.GiveItem(recyclerItem);
}
private void CommandUpgradeRecycler(BasePlayer player, string command, string[] args)
{
if (!permission.UserHasPermission(player.UserIDString, PermissionUseRecycler))
{
player.ChatMessage(lang.GetMessage("NoPermission", this, player.UserIDString));
return;
}
int maxRecyclers = _config.MaxRecyclersPerPlayer;
if (permission.UserHasPermission(player.UserIDString, PermissionAdmin))
{
maxRecyclers = int.MaxValue;
}
else if (permission.UserHasPermission(player.UserIDString, PermissionVip))
{
maxRecyclers = _config.MaxRecyclersVip;
}
if (_recyclerOwners.Count(entry => entry.Value == player.userID) >= maxRecyclers)
{
player.ChatMessage(lang.GetMessage("RecyclerLimitReached", this, player.UserIDString));
return;
}
if (!UpgradeToIndustrialRecycler(player))
{
player.ChatMessage(lang.GetMessage("NoRecyclerInView", this, player.UserIDString));
}
else
{
player.ChatMessage(lang.GetMessage("RecyclerUpgraded", this, player.UserIDString));
}
}
private Recycler FindRecyclerInView(BasePlayer player)
{
if (Physics.Raycast(player.eyes.HeadRay(), out RaycastHit hit, 5f))
{
BaseEntity entity = hit.GetEntity();
return entity as Recycler;
}
return null;
}
private bool InitializeRecyclerPlacement(BasePlayer player, BaseEntity baseEntity, int turn = 0)
{
var supportingFoundation = FindSupportingFoundation(baseEntity);
if (supportingFoundation == null)
return false;
var spawnedRecycler = SpawnRecyclerWithComponents(player, baseEntity, supportingFoundation, turn);
if (spawnedRecycler == null)
return false;
spawnedRecycler.gameObject.AddComponent<RecyclerComponent>();
return true;
}
private bool InitializeUpgradeRecycler(BasePlayer player, Recycler recycler, int turn = 0)
{
var spawnedRecycler = UpgradeRecyclerWithComponents(player, recycler, turn);
if (spawnedRecycler == null)
return false;
spawnedRecycler.gameObject.AddComponent<RecyclerComponent>();
return true;
}
private BuildingBlock FindSupportingFoundation(BaseEntity baseEntity)
{
Vector3 origin = baseEntity.transform.position + Vector3.up * 0.1f;
if (Physics.Raycast(origin, Vector3.down, out RaycastHit hitData, 4f, LayerMask.GetMask("Construction")))
{
return hitData.GetEntity() as BuildingBlock;
}
return null;
}
private Recycler SetupStorageAndAdapters(Recycler recycler, BasePlayer player)
{
Vector3 inputOffset,
inputAdapterOffset,
outputOffset,
outputAdapterOffset;
Quaternion inputRotation,
outputRotation,
inputAdapterRotation,
outputAdapterRotation;
if (_config.UseAlternativeAdapterConfig)
{
inputOffset = new Vector3(0.0f, 0.72f, 0.11f);
inputAdapterOffset = new Vector3(0.32f, -0.6f, -0.03f);
outputOffset = new Vector3(-0.4f, 0.8f, 0.2f);
outputAdapterOffset = new Vector3(-0.07f, 0.535f, 0.397f);
inputRotation = Quaternion.Euler(0, 180, 191);
outputRotation = Quaternion.Euler(169, 90, 180);
inputAdapterRotation = Quaternion.Euler(0, 0, 0);
outputAdapterRotation = Quaternion.Euler(180, 90, 0);
}
else
{
inputOffset = new Vector3(-1.0f, 0.72f, 0.31f);
inputAdapterOffset = new Vector3(0.00f, -0.15f, -0.25f);
outputOffset = new Vector3(-0.9f, 0.72f, -0.09f);
outputAdapterOffset = new Vector3(0.00f, 0.26f, -0.05f);
inputRotation = Quaternion.Euler(90, 90, 180);
outputRotation = Quaternion.Euler(180, 90, 180);
inputAdapterRotation = Quaternion.Euler(180, 90, 270);
outputAdapterRotation = Quaternion.Euler(0, 90, 0);
}
var inputStorage = SpawnEntity(InputStoragePrefabPath, recycler, player, inputOffset, inputRotation);
SpawnEntity(AdapterPrefabPath, inputStorage, player, inputAdapterOffset, inputAdapterRotation);
var outputStorage = SpawnEntity(OutputStoragePrefabPath, recycler, player, outputOffset, outputRotation);
SpawnEntity(AdapterPrefabPath, outputStorage, player, outputAdapterOffset, outputAdapterRotation);
return recycler;
}
private Recycler UpgradeRecyclerWithComponents(BasePlayer player, Recycler recycler, int turn = 0)
{
return SetupStorageAndAdapters(recycler, player);
}
private Recycler SpawnRecyclerWithComponents(BasePlayer player, BaseEntity baseEntity, BuildingBlock foundation, int turn = 0)
{
var recycler = SpawnEntity(RecyclerPrefabPath, foundation, player, baseEntity.transform.position, baseEntity.transform.rotation * Quaternion.Euler(0, turn, 0)) as Recycler;
if (recycler == null)
return null;
return SetupStorageAndAdapters(recycler, player);
}
private BaseEntity SpawnEntity(string prefabPath, BaseEntity parent, BasePlayer player, Vector3 position, Quaternion rotation)
{
var entity = GameManager.server.CreateEntity(prefabPath, Vector3.zero, Quaternion.identity, true);
if (entity == null)
return null;
entity.OwnerID = player.userID;
if (parent != null)
{
entity.SetParent(parent, true);
}
if (parent is BuildingBlock)
{
entity.transform.position = position;
entity.transform.rotation = rotation;
}
else
{
entity.transform.localPosition = position;
entity.transform.localRotation = rotation;
}
entity.Spawn();
entity.SendNetworkUpdateImmediate();
return entity;
}
private void ProcessRecyclerItems(RecyclerComponent recyclerComponent, Item item)
{
if (item.position < 6)
{
recyclerComponent.Recycler.StartRecycling();
}
else
{
if (!item.MoveToContainer(recyclerComponent.OutputStorage.inventory))
{
recyclerComponent.Recycler.StopRecycling();
}
}
}
private bool UpgradeToIndustrialRecycler(BasePlayer player)
{
if (Physics.Raycast(player.eyes.HeadRay(), out RaycastHit hit, 5f))
{
BaseEntity baseEntity = hit.GetEntity();
if (baseEntity is Recycler recycler && recycler.OwnerID == player.userID)
{
if (!InitializeUpgradeRecycler(player, baseEntity as Recycler, 90))
{
player.ChatMessage(lang.GetMessage("InvalidPlacement", this, player.UserIDString));
timer.Once(1, () => GiveRecyclerItem(player));
return false;
}
else
{
player.ChatMessage(lang.GetMessage("RecyclerPlaced", this, player.UserIDString));
}
return true;
}
}
return false;
}
private void ToggleRecyclerConfig(BasePlayer player, string command, string[] args)
{
if (!permission.UserHasPermission(player.UserIDString, PermissionUseRecycler))
{
player.ChatMessage(lang.GetMessage("NoPermission", this, player.UserIDString));
return;
}
Recycler recycler = FindRecyclerInView(player);
if (recycler == null)
{
player.ChatMessage(lang.GetMessage("NoRecyclerInView", this, player.UserIDString));
return;
}
var recyclerComponent = recycler.GetComponent<RecyclerComponent>();
if (recyclerComponent == null)
{
player.ChatMessage(lang.GetMessage("RecyclerComponentNotFound", this, player.UserIDString));
return;
}
recyclerComponent.ToggleConfig();
player.ChatMessage(lang.GetMessage("RecyclerConfigToggled", this, player.UserIDString));
}
#endregion
#region Configuration
private class Configuration
{
[JsonProperty("Commands")]
public List<string> Commands { get; set; }
[JsonProperty("Max Recyclers Per Player")]
public int MaxRecyclersPerPlayer { get; set; }
[JsonProperty("Max Recyclers Vip (industrialrecycler.vip)")]
public int MaxRecyclersVip { get; set; }
[JsonProperty("Recycler Item SkinId")]
public ulong RecyclerSkinId { get; set; }
[JsonProperty("AnchorMin")]
public string AnchorMin { get; set; }
[JsonProperty("AnchorMax")]
public string AnchorMax { get; set; }
[JsonProperty("Alternative Adapter Configuration")]
public bool UseAlternativeAdapterConfig { get; set; }
[JsonProperty("Hide Storage Containers")]
public bool HideStorageContainers { get; set; }
[JsonProperty("Only owner can access recycler")]
public bool OnlyOwnerAccess { get; set; }
[JsonProperty("Allow team members to access recycler")]
public bool AllowTeamAccess { get; set; }
[JsonProperty("Allow friends to access recycler")]
public bool AllowFriendsAccess { get; set; }
[JsonProperty("Version")]
public VersionNumber Version { get; set; }
}
protected override void LoadConfig()
{
base.LoadConfig();
try
{
_config = Config.ReadObject<Configuration>() ?? throw new Exception("Failed to read configuration file.");
bool configChanged = false;
if (_config.Version != Version)
{
_config.Version = Version;
configChanged = true;
}
if (string.IsNullOrEmpty(_config.AnchorMin))
{
_config.AnchorMin = "0.5 0";
configChanged = true;
}
if (string.IsNullOrEmpty(_config.AnchorMax))
{
_config.AnchorMax = "0.5 0";
configChanged = true;
}
if (!_config.UseAlternativeAdapterConfig)
{
_config.UseAlternativeAdapterConfig = false;
configChanged = true;
}
if (configChanged)
{
SaveConfig();
}
}
catch (Exception ex)
{
PrintError($"There was an error in your configuration file: {ex.Message}. Default values will be used.");
LoadDefaultConfig();
}
}
protected override void LoadDefaultConfig()
{
_config = GetDefaultConfig();
SaveConfig();
}
protected override void SaveConfig()
{
Config.WriteObject(_config, true);
}
private Configuration GetDefaultConfig()
{
return new Configuration
{
Commands = new List<string> { "getrecycler", "irecycler", "giverecycler" },
MaxRecyclersPerPlayer = 1,
MaxRecyclersVip = 2,
RecyclerSkinId = 3357927081,
AnchorMin = "0.5 0",
AnchorMax = "0.5 0",
UseAlternativeAdapterConfig = false,
HideStorageContainers = false,
OnlyOwnerAccess = true,
AllowTeamAccess = true,
AllowFriendsAccess = true,
Version = Version,
};
}
#endregion
#region Localization
protected override void LoadDefaultMessages()
{
lang.RegisterMessages(
new Dictionary<string, string>
{
["NoPermission"] = "You do not have permission to use this command.",
["RecyclerLimitReached"] = "You have reached the recycler limit.",
["InvalidPlacement"] = "The recycler must be placed on a construction block.",
["RecyclerPlaced"] = "Recycler placed successfully.",
["RecyclerPickedUp"] = "Recycler picked up, item returned to inventory.",
["RecyclerGiven"] = "Recycler given to your inventory.",
["RecyclerReceived"] = "You have received a recycler.",
["RecyclerNotGiven"] = "Failed to give recycler.",
["RecyclerNotReceived"] = "Failed to receive recycler.",
["NoRecyclerInView"] = "No recycler in sight to upgrade.",
["RecyclerComponentNotFound"] = "Recycler component not found.",
["RecyclerConfigToggled"] = "Recycler configuration toggled successfully.",
["PlayerNotFound"] = "The specified player could not be found.",
["ToggleConfig"] = "Toggle",
["InputButton"] = "Input",
["OutputButton"] = "Output",
["NoAccess"] = "You do not have access to this recycler.",
},
this
);
lang.RegisterMessages(
new Dictionary<string, string>
{
["NoPermission"] = "Você não tem permissão para usar este comando.",
["RecyclerLimitReached"] = "Você atingiu o limite de recicladores.",
["InvalidPlacement"] = "O reciclador deve ser colocado sobre um bloco de construção.",
["RecyclerPlaced"] = "Reciclador colocado com sucesso.",
["RecyclerPickedUp"] = "Reciclador recolhido, item devolvido ao inventário.",
["RecyclerGiven"] = "Reciclador fornecido ao seu inventário.",
["RecyclerReceived"] = "Você recebeu um reciclador.",
["RecyclerNotGiven"] = "Falha ao fornecer o reciclador.",
["RecyclerNotReceived"] = "Falha ao receber o reciclador.",
["NoRecyclerInView"] = "Nenhum reciclador à vista para atualizar.",
["RecyclerComponentNotFound"] = "Componente de reciclador não encontrado.",
["RecyclerConfigToggled"] = "Configuração do reciclador alternada com sucesso.",
["PlayerNotFound"] = "O jogador especificado não pôde ser encontrado.",
["ToggleConfig"] = "Alterar",
["InputButton"] = "Entrada",
["OutputButton"] = "Saída",
["NoAccess"] = "Você não tem acesso a este reciclador.",
},
this,
"pt-BR"
);
lang.RegisterMessages(
new Dictionary<string, string>
{
["NoPermission"] = "Sie haben keine Erlaubnis, diesen Befehl zu verwenden.",
["RecyclerLimitReached"] = "Sie haben die Grenze für Recycler erreicht.",
["InvalidPlacement"] = "Der Recycler muss auf einem Baublock platziert werden.",
["RecyclerPlaced"] = "Recycler erfolgreich platziert.",
["RecyclerPickedUp"] = "Recycler aufgenommen, Artikel in das Inventar zurückgegeben.",
["RecyclerGiven"] = "Recycler wurde Ihrem Inventar hinzugefügt.",
["RecyclerReceived"] = "Sie haben einen Recycler erhalten.",
["RecyclerNotGiven"] = "Recycle fehlerhaft vorhanden.",
["RecyclerNotReceived"] = "Falschen Empfang des Recyclers.",
["NoRecyclerInView"] = "Kein Recycler in Sicht, um aufzurüsten.",
["RecyclerComponentNotFound"] = "Recycler-Komponente nicht gefunden.",
["RecyclerConfigToggled"] = "Recycler-Konfiguration erfolgreich umgeschaltet.",
["PlayerNotFound"] = "Der angegebene Spieler konnte nicht gefunden werden.",
["ToggleConfig"] = "Umschalten",
["InputButton"] = "Eingang",
["OutputButton"] = "Ausgang",
["NoAccess"] = "Sie haben keinen Zugriff auf diesen Recycler.",
},
this,
"de"
);
lang.RegisterMessages(
new Dictionary<string, string>
{
["NoPermission"] = "No tienes permiso para usar este comando.",
["RecyclerLimitReached"] = "Has alcanzado el límite de recicladores.",
["InvalidPlacement"] = "El reciclador debe colocarse en un bloque de construcción.",
["RecyclerPlaced"] = "Reciclador colocado con éxito.",
["RecyclerPickedUp"] = "Reciclador recogido, artículo devuelto al inventario.",
["RecyclerGiven"] = "Reciclador dado a tu inventario.",
["RecyclerReceived"] = "Has recibido un reciclador.",
["RecyclerNotGiven"] = "Fallo al dar el reciclador.",
["RecyclerNotReceived"] = "Fallo al recibir el reciclador.",
["NoRecyclerInView"] = "No hay reciclador a la vista para mejorar.",
["RecyclerComponentNotFound"] = "Componente de reciclador no encontrado.",
["RecyclerConfigToggled"] = "Configuración del reciclador alternada con éxito.",
["PlayerNotFound"] = "No se pudo encontrar al jugador especificado.",
["ToggleConfig"] = "Alternar",
["InputButton"] = "Entrada",
["OutputButton"] = "Salida",
["NoAccess"] = "No tienes acceso a este reciclador.",
},
this,
"es"
);
}
#endregion
#region Component
private class RecyclerComponent : MonoBehaviour
{
public Recycler Recycler { get; private set; }
public StorageContainer InputStorage { get; private set; }
public StorageContainer OutputStorage { get; private set; }
public int CurrentConfigState { get; private set; }
private const int MaxStorageCapacity = 48;
private const float TransferInterval = 10f;
private enum RecyclerConfig
{
Default = 1,
Alternative = 2,
}
private void Awake()
{
Recycler = GetComponent<Recycler>();
if (Recycler == null)
{
Debug.LogError("Recycler component is missing on this GameObject.");
enabled = false;
return;
}
// Start with a default known state
CurrentConfigState = (int)RecyclerConfig.Default;
InitializeRecyclerComponents();
}
private void InitializeRecyclerComponents()
{
foreach (MonoBehaviour mb in GetComponents<MonoBehaviour>())
{
var type = mb.GetType();
if (type != typeof(Recycler) && type != typeof(RecyclerComponent) && type.Name != "Ground_Watch")
{
Destroy(mb);
}
}
if (!ValidateStorageContainers())
{
Debug.LogError("Failed to validate storage containers.");
enabled = false;
return;
}
SetupRecycler();
RegisterEntities();
InvokeRepeating(nameof(HandleItemTransfers), 0f, TransferInterval);
}
private bool ValidateStorageContainers()
{
InputStorage = Recycler.children.OfType<StorageContainer>().FirstOrDefault(c => c?.name == InputStoragePrefabPath);
OutputStorage = Recycler.children.OfType<StorageContainer>().FirstOrDefault(c => c?.name == OutputStoragePrefabPath);
return InputStorage != null && OutputStorage != null;
}
private void RegisterEntities()
{
_instance._inputItemContainers.Add(InputStorage.inventory.uid.Value);
_instance._recyclerItemContainers.Add(Recycler.inventory.uid.Value);
var inputAdapter = InputStorage.children.OfType<IndustrialStorageAdaptor>().FirstOrDefault();
if (inputAdapter != null)
_instance._storageAdapters.Add(inputAdapter.net.ID.Value);
var outputAdapter = OutputStorage.children.OfType<IndustrialStorageAdaptor>().FirstOrDefault();
if (outputAdapter != null)
_instance._storageAdapters.Add(outputAdapter.net.ID.Value);
}
private void SetupRecycler()
{
if (Recycler == null || InputStorage == null || OutputStorage == null)
{
Debug.LogError("Attempted to setup recycler with null components.");
return;
}
_instance._recyclerOwners[Recycler.net.ID.Value] = Recycler.OwnerID;
InputStorage.inventory.capacity = MaxStorageCapacity;
OutputStorage.inventory.capacity = MaxStorageCapacity;
}
public void HandleItemTransfers()
{
int availableRecyclerSlots = 6 - Recycler.inventory.itemList.Count;
if (OutputStorage.inventory.IsFull())
{
Recycler.StopRecycling();
return;
}
TransferItemsFromRecyclerToOutput(ref availableRecyclerSlots);
TransferItemsFromInputToRecycler(ref availableRecyclerSlots);
if (availableRecyclerSlots < 6 && Recycler.inventory.itemList.Count > 0)
{
Recycler.StartRecycling();
}
}
private void TransferItemsFromRecyclerToOutput(ref int availableRecyclerSlots)
{
for (int slot = 6; slot < Recycler.inventory.capacity; slot++)
{
var itemInRecycler = Recycler.inventory.GetSlot(slot);
if (itemInRecycler != null && itemInRecycler.MoveToContainer(OutputStorage.inventory))
{
availableRecyclerSlots++;
}
}
}
private void TransferItemsFromInputToRecycler(ref int availableRecyclerSlots)
{
var inputItems = new List<Item>(InputStorage.inventory.itemList);
foreach (var item in inputItems)
{
if (item.info.Blueprint != null)
{
MoveItemToRecycler(item, ref availableRecyclerSlots);
}
else
{
item.MoveToContainer(OutputStorage.inventory);
}
}
}
private void MoveItemToRecycler(Item item, ref int availableRecyclerSlots)
{
if (availableRecyclerSlots <= 0)
return;
for (int slot = 0; slot < 6; slot++)
{
if (Recycler.inventory.GetSlot(slot) == null && item.MoveToContainer(Recycler.inventory, slot))
{
availableRecyclerSlots--;
break;
}
}
}
public void ToggleConfig()
{
CancelInvoke(nameof(HandleItemTransfers));
CurrentConfigState = (int)(CurrentConfigState == (int)RecyclerConfig.Default ? RecyclerConfig.Alternative : RecyclerConfig.Default);
List<(string Shortname, int Amount, float ConditionNormalized)> ExtractItemDetails(ItemContainer container) =>
container?.itemList?.Select(item => (item.info.shortname, item.amount, item.conditionNormalized)).ToList() ?? new List<(string, int, float)>();
var inputItemDetails = ExtractItemDetails(InputStorage.inventory);
var outputItemDetails = ExtractItemDetails(OutputStorage.inventory);
ClearExistingComponents();
UpdateAdapterPositions();
InitializeRecyclerComponents();
if (InputStorage == null || OutputStorage == null || Recycler == null)
{
Debug.LogError("Storage references were not updated.");
return;
}
foreach (var (shortname, amount, condition) in inputItemDetails)
CreateAndMoveItem(shortname, amount, condition, InputStorage.inventory);
foreach (var (shortname, amount, condition) in outputItemDetails)
CreateAndMoveItem(shortname, amount, condition, OutputStorage.inventory);
}
private void CreateAndMoveItem(string shortname, int amount, float conditionNormalized, ItemContainer container)
{
var item = ItemManager.CreateByName(shortname, amount);
if (item != null)
{
item.conditionNormalized = conditionNormalized;
if (!item.MoveToContainer(container))
item.Remove();
}
}
private void UpdateAdapterPositions()
{
ClearExistingComponents();
Vector3 inputOffset,
outputOffset,
inputAdapterOffset,
outputAdapterOffset;
Quaternion inputRotation,
outputRotation,
inputAdapterRotation,
outputAdapterRotation;
if (CurrentConfigState == (int)RecyclerConfig.Default)
{
inputOffset = new Vector3(0.0f, 0.72f, 0.11f);
outputOffset = new Vector3(-0.4f, 0.8f, 0.2f);
inputAdapterOffset = new Vector3(0.32f, -0.6f, -0.03f);
outputAdapterOffset = new Vector3(-0.07f, 0.535f, 0.397f);
inputRotation = Quaternion.Euler(0, 180, 191);
outputRotation = Quaternion.Euler(169, 90, 180);
inputAdapterRotation = Quaternion.Euler(0, 0, 0);
outputAdapterRotation = Quaternion.Euler(180, 90, 0);
}
else
{
if (_instance._config.HideStorageContainers)
{
inputOffset = new Vector3(0.0f, 0.72f, 0.11f);
outputOffset = new Vector3(-0.4f, 0.72f, 0.2f);
inputAdapterOffset = new Vector3(0.836f, -0.3301f, 0.18f);
outputAdapterOffset = new Vector3(-0.227f, 0.33f, 0.434f);
inputRotation = Quaternion.Euler(0, 0, 180);
outputRotation = Quaternion.Euler(180, 90, 180);
inputAdapterRotation = Quaternion.Euler(0, 0, 0);
outputAdapterRotation = Quaternion.Euler(180, 90, 0);
}
else
{
inputOffset = new Vector3(-1.0f, 0.72f, 0.31f);
outputOffset = new Vector3(-0.9f, 0.72f, -0.09f);
inputAdapterOffset = new Vector3(0.00f, -0.15f, -0.25f);
outputAdapterOffset = new Vector3(0.00f, 0.26f, -0.05f);
inputRotation = Quaternion.Euler(90, 90, 180);
outputRotation = Quaternion.Euler(180, 90, 180);
inputAdapterRotation = Quaternion.Euler(180, 90, 270);
outputAdapterRotation = Quaternion.Euler(0, 90, 0);
}
}
BasePlayer ownerPlayer = BasePlayer.FindByID(Recycler.OwnerID);
if (ownerPlayer != null)
{
var inputStorage = _instance.SpawnEntity(InputStoragePrefabPath, Recycler, ownerPlayer, inputOffset, inputRotation) as StorageContainer;
if (inputStorage == null)
{
Debug.LogError("Failed to spawn input storage.");
return;
}
_instance.SpawnEntity(AdapterPrefabPath, inputStorage, ownerPlayer, inputAdapterOffset, inputAdapterRotation);
var outputStorage = _instance.SpawnEntity(OutputStoragePrefabPath, Recycler, ownerPlayer, outputOffset, outputRotation) as StorageContainer;
if (outputStorage == null)
{
Debug.LogError("Failed to spawn output storage.");
return;
}
_instance.SpawnEntity(AdapterPrefabPath, outputStorage, ownerPlayer, outputAdapterOffset, outputAdapterRotation);
}
}
private void ClearExistingComponents()
{
foreach (var child in Recycler.children.ToList())
{
if (child is StorageContainer || child is IndustrialStorageAdaptor)
{
child.Kill();
}
}
}
internal void DropItems()
{
var allItems = GatherAllItems();
DropItemsInBatches(allItems, MaxStorageCapacity);
}
private List<Item> GatherAllItems()
{
return InputStorage.inventory.itemList.Concat(OutputStorage.inventory.itemList).Concat(Recycler.inventory.itemList).ToList();
}
private void DropItemsInBatches(List<Item> items, int batchSize)
{
var recyclerPosition = Recycler.transform.position;
var recyclerRotation = Recycler.transform.rotation;
for (int i = 0; i < items.Count; i += batchSize)
{
var itemBatch = items.Skip(i).Take(batchSize).ToList();
SpawnDroppedItemContainer(recyclerPosition, recyclerRotation, itemBatch);
}
}
private DroppedItemContainer SpawnDroppedItemContainer(Vector3 position, Quaternion rotation, List<Item> itemsToDrop)
{
var containerPrefabPath = "assets/prefabs/misc/item drop/item_drop.prefab";
var droppedItemContainer = GameManager.server.CreateEntity(containerPrefabPath, position, rotation) as DroppedItemContainer;
if (droppedItemContainer == null)
return null;
InitializeItemContainer(droppedItemContainer, itemsToDrop);
droppedItemContainer.Spawn();
return droppedItemContainer;
}
private void InitializeItemContainer(DroppedItemContainer container, List<Item> items)
{
container.inventory = new ItemContainer();
container.inventory.ServerInitialize(null, items.Count);
container.inventory.GiveUID();
container.inventory.entityOwner = container;
foreach (var item in items)
{
item.MoveToContainer(container.inventory);
}
}
private void OnDestroy()
{
CancelInvoke(nameof(HandleItemTransfers));
}
}
#endregion
}
}
Note:
I've re-implemented the entire plugin, retaining its original structure, adding the necessary access control as previously discussed, and ensuring all methods and translations are present. The integrations allow access control based on ownership, team membership, and friendship.
The access control checks are applied in relevant hooks to restrict interaction with recyclers.
Ensure you have the Friends plugin installed and configured correctly to make use of the AllowFriendsAccess feature.
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Oxide.Core;
using Oxide.Core.Plugins;
using Oxide.Game.Rust.Cui;
using UnityEngine;
namespace Oxide.Plugins
{
[Info("IndustrialRecycler", "Marte6", "1.4.6")]
[Description("Automate recycling by attaching storage and adapters to recyclers.")]
class IndustrialRecycler : RustPlugin
{
#region PluginReferences
[PluginReference] Plugin Friends;
#endregion
#region Fields
private static IndustrialRecycler _instance;
private Configuration _config;
private const string RecyclerPrefabPath = "assets/bundled/prefabs/static/recycler_static.prefab";
private const string InputStoragePrefabPath = "assets/content/vehicles/boats/rowboat/subents/rowboat_storage.prefab";
private const string OutputStoragePrefabPath = "assets/prefabs/deployable/hot air balloon/subents/hab_storage.prefab";
private const string AdapterPrefabPath = "assets/prefabs/deployable/playerioents/industrialadaptors/storageadaptor.deployed.prefab";
private const string ItemName = "box.wooden.large";
private const string PermissionUseRecycler = "industrialrecycler.give";
private const string PermissionVip = "industrialrecycler.vip";
private const string PermissionAdmin = "industrialrecycler.admin";
private const string UiOverlayName = "IndustrialRecyclerMainPanel";
#endregion
#region Cache
private readonly Dictionary<ulong, ulong> _recyclerOwners = new();
private readonly HashSet<ulong> _recyclerItemContainers = new();
private readonly HashSet<ulong> _inputItemContainers = new();
private readonly HashSet<ulong> _storageAdapters = new();
private readonly HashSet<ulong> _playersWithUi = new();
#endregion
#region Game Hooks
private void Init()
{
permission.RegisterPermission(PermissionUseRecycler, this);
permission.RegisterPermission(PermissionVip, this);
permission.RegisterPermission(PermissionAdmin, this);
foreach (var command in _config.Commands)
{
cmd.AddChatCommand(command, this, nameof(CommandGetRecycler));
}
cmd.AddChatCommand("upgraderecycler", this, nameof(CommandUpgradeRecycler));
cmd.AddChatCommand("togglerecycler", this, nameof(ToggleRecyclerConfig));
cmd.AddConsoleCommand("industrialrecycler.openinput", this, nameof(OpenInputStorage));
cmd.AddConsoleCommand("industrialrecycler.openoutput", this, nameof(OpenOutputStorage));
}
private void OnServerInitialized()
{
_instance = this;
foreach (var recycler in UnityEngine.Object.FindObjectsOfType<Recycler>())
{
if (recycler.OwnerID != 0UL)
{
recycler.gameObject.AddComponent<RecyclerComponent>();
}
}
}
private void Unload()
{
foreach (var recyclerComponent in UnityEngine.Object.FindObjectsOfType<RecyclerComponent>())
{
UnityEngine.Object.Destroy(recyclerComponent);
}
foreach (var player in BasePlayer.activePlayerList)
{
CuiHelper.DestroyUi(player, UiOverlayName);
}
}
private void OnItemAddedToContainer(ItemContainer container, Item item)
{
Recycler recycler = container.entityOwner as Recycler ?? container.entityOwner?.GetParentEntity() as Recycler;
if (recycler == null)
return;
var recyclerComponent = recycler.GetComponent<RecyclerComponent>();
if (recyclerComponent == null)
return;
bool isMainRecycler = container.entityOwner is Recycler;
ulong containerUid = container.uid.Value;
if (isMainRecycler && _recyclerItemContainers.Contains(containerUid))
{
ProcessRecyclerItems(recyclerComponent, item);
}
else if (!isMainRecycler && _inputItemContainers.Contains(containerUid))
{
recyclerComponent.HandleItemTransfers();
}
}
private void OnEntityBuilt(Planner planner, GameObject entityObject)
{
var player = planner?.GetOwnerPlayer();
var baseEntity = entityObject.GetComponent<BaseEntity>();
if (player == null || baseEntity == null || baseEntity.ShortPrefabName != ItemName || baseEntity.skinID != _config.RecyclerSkinId)
return;
int maxRecyclers = _config.MaxRecyclersPerPlayer;
if (permission.UserHasPermission(player.UserIDString, PermissionAdmin))
{
maxRecyclers = int.MaxValue;
}
else if (permission.UserHasPermission(player.UserIDString, PermissionVip))
{
maxRecyclers = _config.MaxRecyclersVip;
}
if (_recyclerOwners.Count(entry => entry.Value == player.userID) >= maxRecyclers)
{
player.ChatMessage(lang.GetMessage("RecyclerLimitReached", this, player.UserIDString));
timer.Once(1, () => GiveRecyclerItem(player));
NextTick(() => baseEntity?.Kill());
return;
}
if (!InitializeRecyclerPlacement(player, baseEntity))
{
player.ChatMessage(lang.GetMessage("InvalidPlacement", this, player.UserIDString));
timer.Once(1, () => GiveRecyclerItem(player));
}
else
{
player.ChatMessage(lang.GetMessage("RecyclerPlaced", this, player.UserIDString));
}
NextTick(() => baseEntity?.Kill());
}
private object CanPickupEntity(BasePlayer player, IndustrialStorageAdaptor adapter)
{
if (adapter?.net?.ID.Value != null && _storageAdapters.Contains(adapter.net.ID.Value))
{
if (!HasAccess(player, adapter))
{
player.ChatMessage(lang.GetMessage("NoAccess", this, player.UserIDString));
return false;
}
adapter.GetParentEntity()?.GetParentEntity()?.Kill();
GiveRecyclerItem(player);
player.ChatMessage(lang.GetMessage("RecyclerPickedUp", this, player.UserIDString));
return false;
}
return null;
}
private object OnEntityKill(Recycler recycler)
{
if (!IsRecyclerOwned(recycler))
return null;
UnregisterRecyclerOwnership(recycler);
DropRecyclerItems(recycler);
return null;
}
private bool IsRecyclerOwned(Recycler recycler)
{
return recycler.OwnerID != 0UL && _recyclerOwners.ContainsKey(recycler.net.ID.Value);
}
private void UnregisterRecyclerOwnership(Recycler recycler)
{
_recyclerOwners.Remove(recycler.net.ID.Value);
}
private void DropRecyclerItems(Recycler recycler)
{
var recyclerComponent = recycler.GetComponent<RecyclerComponent>();
recyclerComponent?.DropItems();
}
private void OnLootEntity(BasePlayer player, Recycler recycler)
{
if (recycler == null || player == null || !HasAccess(player, recycler))
return;
if (recycler.OwnerID != 0UL && _recyclerOwners.ContainsKey(recycler.net.ID.Value))
{
_playersWithUi.Add(player.userID);
string recyclerId = recycler.net.ID.Value.ToString();
CreateUi(player, recyclerId);
}
}
private void OnPlayerLootEnd(PlayerLoot playerLoot)
{
BasePlayer player = playerLoot.GetComponentInParent<BasePlayer>();
if (player == null)
return;
if (_playersWithUi.Contains(player.userID))
{
_playersWithUi.Remove(player.userID);
CuiHelper.DestroyUi(player, UiOverlayName);
}
}
#endregion
#region Access Control
private bool HasAccess(BasePlayer player, BaseEntity entity)
{
ulong ownerId = entity.OwnerID;
if (ownerId == player.userID || permission.UserHasPermission(player.UserIDString, PermissionAdmin))
return true;
if (_config.AllowTeamAccess && player.currentTeam != 0)
{
var team = RelationshipManager.ServerInstance.FindTeam(player.currentTeam);
if (team != null && team.members.Contains(ownerId))
return true;
}
if (_config.AllowFriendsAccess && Friends != null)
{
bool areFriends = (bool)(Friends.CallHook("AreFriends", ownerId, player.userID) ?? false);
if (areFriends)
return true;
}
return false;
}
#endregion
#region UI
private void CreateUi(BasePlayer player, string recyclerId)
{
var container = new CuiElementContainer();
container.Add(
new CuiPanel
{
CursorEnabled = true,
Image =
{
Color = "1 1 1 0.15",
Sprite = "assets/content/ui/ui.background.transparent.radial.psd",
Material = "assets/content/ui/uibackgroundblur.mat",
},
RectTransform =
{
AnchorMin = _config.AnchorMin,
AnchorMax = _config.AnchorMax,
OffsetMin = "341.64 405.595",
OffsetMax = "554.76 505.605",
},
},
"Overlay",
UiOverlayName
);
container.Add(
new CuiElement
{
Name = "Text",
Parent = UiOverlayName,
Components =
{
new CuiTextComponent
{
Text = "INDUSTRIAL RECYCLER",
Font = "robotocondensed-bold.ttf",
FontSize = 17,
Align = TextAnchor.MiddleCenter,
Color = "1 1 1 1",
},
new CuiOutlineComponent { Color = "0 0 0 1", Distance = "1 1" },
new CuiRectTransformComponent
{
AnchorMin = "0.5 0.5",
AnchorMax = "0.5 0.5",
OffsetMin = "-86.493 0",
OffsetMax = "86.492 34.875",
},
},
}
);
container.Add(
new CuiButton
{
Button =
{
Color = "0.3960785 0.4666667 0.2627451 1",
Command = $"industrialrecycler.openinput {recyclerId}",
Close = UiOverlayName,
},
Text =
{
Text = lang.GetMessage("InputButton", this, player.UserIDString),
Font = "robotocondensed-regular.ttf",
FontSize = 18,
Align = TextAnchor.MiddleCenter,
Color = "1 1 1 1",
},
RectTransform =
{
AnchorMin = "0.5 0.5",
AnchorMax = "0.5 0.5",
OffsetMin = "-104.206 -49.58",
OffsetMax = "-2.394 -17.22",
},
},
UiOverlayName,
"Input"
);
container.Add(
new CuiButton
{
Button =
{
Color = "0.3960785 0.4666667 0.2627451 1",
Command = $"industrialrecycler.openoutput {recyclerId}",
Close = UiOverlayName,
},
Text =
{
Text = lang.GetMessage("OutputButton", this, player.UserIDString),
Font = "robotocondensed-regular.ttf",
FontSize = 18,
Align = TextAnchor.MiddleCenter,
Color = "1 1 1 1",
},
RectTransform =
{
AnchorMin = "0.5 0.5",
AnchorMax = "0.5 0.5",
OffsetMin = "1.994 -49.58",
OffsetMax = "103.806 -17.22",
},
},
UiOverlayName,
"Output"
);
container.Add(
new CuiButton
{
Button =
{
Color = "0.3960785 0.7666667 0.2627451 1",
Command = $"chat.say /togglerecycler",
Close = "ToggleConfig",
},
Text =
{
Text = lang.GetMessage("ToggleConfig", this),
Font = "robotocondensed-regular.ttf",
FontSize = 14,
Align = TextAnchor.MiddleCenter,
Color = "1 1 1 1",
},
RectTransform =
{
AnchorMin = "1 1",
AnchorMax = "1 1",
OffsetMin = "-110 -20",
OffsetMax = "0 0",
},
},
UiOverlayName,
"ToggleConfig"
);
CuiHelper.DestroyUi(player, UiOverlayName);
CuiHelper.AddUi(player, container);
}
private void OpenInputStorage(ConsoleSystem.Arg arg)
{
OpenStorage(arg, true);
}
private void OpenOutputStorage(ConsoleSystem.Arg arg)
{
OpenStorage(arg, false);
}
private void OpenStorage(ConsoleSystem.Arg arg, bool isInput)
{
var player = arg.Player();
if (player == null)
{
return;
}
if (arg.Args.Length == 0)
{
return;
}
if (!uint.TryParse(arg.Args[0], out uint recyclerId))
{
return;
}
var networkableId = new NetworkableId(recyclerId);
var recycler = BaseNetworkable.serverEntities.Find(networkableId) as Recycler;
if (recycler != null && HasAccess(player, recycler))
{
var recyclerComponent = recycler.GetComponent<RecyclerComponent>();
if (recyclerComponent != null)
{
var storage = isInput ? recyclerComponent.InputStorage : recyclerComponent.OutputStorage;
player.inventory.loot.StartLootingEntity(storage, true);
player.inventory.loot.AddContainer(storage.inventory);
player.inventory.loot.SendImmediate();
player.ClientRPCPlayer(null, player, "RPC_OpenLootPanel", storage.panelName);
}
}
}
#endregion
#region Main
private void CommandGetRecycler(BasePlayer player, string command, string[] args)
{
if (player == null)
return;
if (!permission.UserHasPermission(player.UserIDString, PermissionUseRecycler))
{
player.ChatMessage(lang.GetMessage("NoPermission", this, player.UserIDString));
return;
}
BasePlayer targetPlayer = player;
if (args != null && args.Length > 0)
{
targetPlayer = BasePlayer.Find(args[0]);
if (targetPlayer == null)
{
player.ChatMessage(lang.GetMessage("PlayerNotFound", this, player.UserIDString));
return;
}
}
if (GiveRecyclerItem(targetPlayer))
{
player.ChatMessage(lang.GetMessage("RecyclerGiven", this, player.UserIDString));
if (targetPlayer != player)
{
targetPlayer.ChatMessage(lang.GetMessage("RecyclerReceived", this, targetPlayer.UserIDString));
}
}
else
{
player.ChatMessage(lang.GetMessage("RecyclerNotGiven", this, player.UserIDString));
if (targetPlayer != player)
{
targetPlayer.ChatMessage(lang.GetMessage("RecyclerNotReceived", this, targetPlayer.UserIDString));
}
}
}
private bool GiveRecyclerItem(BasePlayer player)
{
var recyclerItem = ItemManager.CreateByName(ItemName, 1, _config.RecyclerSkinId);
if (recyclerItem == null)
return false;
recyclerItem.name = "Recycler";
return player.inventory.GiveItem(recyclerItem);
}
private void CommandUpgradeRecycler(BasePlayer player, string command, string[] args)
{
if (!permission.UserHasPermission(player.UserIDString, PermissionUseRecycler))
{
player.ChatMessage(lang.GetMessage("NoPermission", this, player.UserIDString));
return;
}
int maxRecyclers = _config.MaxRecyclersPerPlayer;
if (permission.UserHasPermission(player.UserIDString, PermissionAdmin))
{
maxRecyclers = int.MaxValue;
}
else if (permission.UserHasPermission(player.UserIDString, PermissionVip))
{
maxRecyclers = _config.MaxRecyclersVip;
}
if (_recyclerOwners.Count(entry => entry.Value == player.userID) >= maxRecyclers)
{
player.ChatMessage(lang.GetMessage("RecyclerLimitReached", this, player.UserIDString));
return;
}
if (!UpgradeToIndustrialRecycler(player))
{
player.ChatMessage(lang.GetMessage("NoRecyclerInView", this, player.UserIDString));
}
else
{
player.ChatMessage(lang.GetMessage("RecyclerUpgraded", this, player.UserIDString));
}
}
private Recycler FindRecyclerInView(BasePlayer player)
{
if (Physics.Raycast(player.eyes.HeadRay(), out RaycastHit hit, 5f))
{
BaseEntity entity = hit.GetEntity();
return entity as Recycler;
}
return null;
}
private bool InitializeRecyclerPlacement(BasePlayer player, BaseEntity baseEntity, int turn = 0)
{
var supportingFoundation = FindSupportingFoundation(baseEntity);
if (supportingFoundation == null)
return false;
var spawnedRecycler = SpawnRecyclerWithComponents(player, baseEntity, supportingFoundation, turn);
if (spawnedRecycler == null)
return false;
spawnedRecycler.gameObject.AddComponent<RecyclerComponent>();
return true;
}
private bool InitializeUpgradeRecycler(BasePlayer player, Recycler recycler, int turn = 0)
{
var spawnedRecycler = UpgradeRecyclerWithComponents(player, recycler, turn);
if (spawnedRecycler == null)
return false;
spawnedRecycler.gameObject.AddComponent<RecyclerComponent>();
return true;
}
private BuildingBlock FindSupportingFoundation(BaseEntity baseEntity)
{
Vector3 origin = baseEntity.transform.position + Vector3.up * 0.1f;
if (Physics.Raycast(origin, Vector3.down, out RaycastHit hitData, 4f, LayerMask.GetMask("Construction")))
{
return hitData.GetEntity() as BuildingBlock;
}
return null;
}
private Recycler SetupStorageAndAdapters(Recycler recycler, BasePlayer player)
{
Vector3 inputOffset,
inputAdapterOffset,
outputOffset,
outputAdapterOffset;
Quaternion inputRotation,
outputRotation,
inputAdapterRotation,
outputAdapterRotation;
if (_config.UseAlternativeAdapterConfig)
{
inputOffset = new Vector3(0.0f, 0.72f, 0.11f);
inputAdapterOffset = new Vector3(0.32f, -0.6f, -0.03f);
outputOffset = new Vector3(-0.4f, 0.8f, 0.2f);
outputAdapterOffset = new Vector3(-0.07f, 0.535f, 0.397f);
inputRotation = Quaternion.Euler(0, 180, 191);
outputRotation = Quaternion.Euler(169, 90, 180);
inputAdapterRotation = Quaternion.Euler(0, 0, 0);
outputAdapterRotation = Quaternion.Euler(180, 90, 0);
}
else
{
inputOffset = new Vector3(-1.0f, 0.72f, 0.31f);
inputAdapterOffset = new Vector3(0.00f, -0.15f, -0.25f);
outputOffset = new Vector3(-0.9f, 0.72f, -0.09f);
outputAdapterOffset = new Vector3(0.00f, 0.26f, -0.05f);
inputRotation = Quaternion.Euler(90, 90, 180);
outputRotation = Quaternion.Euler(180, 90, 180);
inputAdapterRotation = Quaternion.Euler(180, 90, 270);
outputAdapterRotation = Quaternion.Euler(0, 90, 0);
}
var inputStorage = SpawnEntity(InputStoragePrefabPath, recycler, player, inputOffset, inputRotation);
SpawnEntity(AdapterPrefabPath, inputStorage, player, inputAdapterOffset, inputAdapterRotation);
var outputStorage = SpawnEntity(OutputStoragePrefabPath, recycler, player, outputOffset, outputRotation);
SpawnEntity(AdapterPrefabPath, outputStorage, player, outputAdapterOffset, outputAdapterRotation);
return recycler;
}
private Recycler UpgradeRecyclerWithComponents(BasePlayer player, Recycler recycler, int turn = 0)
{
return SetupStorageAndAdapters(recycler, player);
}
private Recycler SpawnRecyclerWithComponents(BasePlayer player, BaseEntity baseEntity, BuildingBlock foundation, int turn = 0)
{
var recycler = SpawnEntity(RecyclerPrefabPath, foundation, player, baseEntity.transform.position, baseEntity.transform.rotation * Quaternion.Euler(0, turn, 0)) as Recycler;
if (recycler == null)
return null;
return SetupStorageAndAdapters(recycler, player);
}
private BaseEntity SpawnEntity(string prefabPath, BaseEntity parent, BasePlayer player, Vector3 position, Quaternion rotation)
{
var entity = GameManager.server.CreateEntity(prefabPath, Vector3.zero, Quaternion.identity, true);
if (entity == null)
return null;
entity.OwnerID = player.userID;
if (parent != null)
{
entity.SetParent(parent, true);
}
if (parent is BuildingBlock)
{
entity.transform.position = position;
entity.transform.rotation = rotation;
}
else
{
entity.transform.localPosition = position;
entity.transform.localRotation = rotation;
}
entity.Spawn();
entity.SendNetworkUpdateImmediate();
return entity;
}
private void ProcessRecyclerItems(RecyclerComponent recyclerComponent, Item item)
{
if (item.position < 6)
{
recyclerComponent.Recycler.StartRecycling();
}
else
{
if (!item.MoveToContainer(recyclerComponent.OutputStorage.inventory))
{
recyclerComponent.Recycler.StopRecycling();
}
}
}
private bool UpgradeToIndustrialRecycler(BasePlayer player)
{
if (Physics.Raycast(player.eyes.HeadRay(), out RaycastHit hit, 5f))
{
BaseEntity baseEntity = hit.GetEntity();
if (baseEntity is Recycler recycler && recycler.OwnerID == player.userID)
{
if (!InitializeUpgradeRecycler(player, baseEntity as Recycler, 90))
{
player.ChatMessage(lang.GetMessage("InvalidPlacement", this, player.UserIDString));
timer.Once(1, () => GiveRecyclerItem(player));
return false;
}
else
{
player.ChatMessage(lang.GetMessage("RecyclerPlaced", this, player.UserIDString));
}
return true;
}
}
return false;
}
private void ToggleRecyclerConfig(BasePlayer player, string command, string[] args)
{
if (!permission.UserHasPermission(player.UserIDString, PermissionUseRecycler))
{
player.ChatMessage(lang.GetMessage("NoPermission", this, player.UserIDString));
return;
}
Recycler recycler = FindRecyclerInView(player);
if (recycler == null)
{
player.ChatMessage(lang.GetMessage("NoRecyclerInView", this, player.UserIDString));
return;
}
var recyclerComponent = recycler.GetComponent<RecyclerComponent>();
if (recyclerComponent == null)
{
player.ChatMessage(lang.GetMessage("RecyclerComponentNotFound", this, player.UserIDString));
return;
}
recyclerComponent.ToggleConfig();
player.ChatMessage(lang.GetMessage("RecyclerConfigToggled", this, player.UserIDString));
}
#endregion
#region Configuration
private class Configuration
{
[JsonProperty("Commands")]
public List<string> Commands { get; set; }
[JsonProperty("Max Recyclers Per Player")]
public int MaxRecyclersPerPlayer { get; set; }
[JsonProperty("Max Recyclers Vip (industrialrecycler.vip)")]
public int MaxRecyclersVip { get; set; }
[JsonProperty("Recycler Item SkinId")]
public ulong RecyclerSkinId { get; set; }
[JsonProperty("AnchorMin")]
public string AnchorMin { get; set; }
[JsonProperty("AnchorMax")]
public string AnchorMax { get; set; }
[JsonProperty("Alternative Adapter Configuration")]
public bool UseAlternativeAdapterConfig { get; set; }
[JsonProperty("Hide Storage Containers")]
public bool HideStorageContainers { get; set; }
[JsonProperty("Only owner can access recycler")]
public bool OnlyOwnerAccess { get; set; }
[JsonProperty("Allow team members to access recycler")]
public bool AllowTeamAccess { get; set; }
[JsonProperty("Allow friends to access recycler")]
public bool AllowFriendsAccess { get; set; }
[JsonProperty("Version")]
public VersionNumber Version { get; set; }
}
protected override void LoadConfig()
{
base.LoadConfig();
try
{
_config = Config.ReadObject<Configuration>() ?? throw new Exception("Failed to read configuration file.");
bool configChanged = false;
if (_config.Version != Version)
{
_config.Version = Version;
configChanged = true;
}
if (string.IsNullOrEmpty(_config.AnchorMin))
{
_config.AnchorMin = "0.5 0";
configChanged = true;
}
if (string.IsNullOrEmpty(_config.AnchorMax))
{
_config.AnchorMax = "0.5 0";
configChanged = true;
}
if (!_config.UseAlternativeAdapterConfig)
{
_config.UseAlternativeAdapterConfig = false;
configChanged = true;
}
if (configChanged)
{
SaveConfig();
}
}
catch (Exception ex)
{
PrintError($"There was an error in your configuration file: {ex.Message}. Default values will be used.");
LoadDefaultConfig();
}
}
protected override void LoadDefaultConfig()
{
_config = GetDefaultConfig();
SaveConfig();
}
protected override void SaveConfig()
{
Config.WriteObject(_config, true);
}
private Configuration GetDefaultConfig()
{
return new Configuration
{
Commands = new List<string> { "getrecycler", "irecycler", "giverecycler" },
MaxRecyclersPerPlayer = 1,
MaxRecyclersVip = 2,
RecyclerSkinId = 3357927081,
AnchorMin = "0.5 0",
AnchorMax = "0.5 0",
UseAlternativeAdapterConfig = false,
HideStorageContainers = false,
OnlyOwnerAccess = true,
AllowTeamAccess = true,
AllowFriendsAccess = true,
Version = Version,
};
}
#endregion
#region Localization
protected override void LoadDefaultMessages()
{
lang.RegisterMessages(
new Dictionary<string, string>
{
["NoPermission"] = "You do not have permission to use this command.",
["RecyclerLimitReached"] = "You have reached the recycler limit.",
["InvalidPlacement"] = "The recycler must be placed on a construction block.",
["RecyclerPlaced"] = "Recycler placed successfully.",
["RecyclerPickedUp"] = "Recycler picked up, item returned to inventory.",
["RecyclerGiven"] = "Recycler given to your inventory.",
["RecyclerReceived"] = "You have received a recycler.",
["RecyclerNotGiven"] = "Failed to give recycler.",
["RecyclerNotReceived"] = "Failed to receive recycler.",
["NoRecyclerInView"] = "No recycler in sight to upgrade.",
["RecyclerComponentNotFound"] = "Recycler component not found.",
["RecyclerConfigToggled"] = "Recycler configuration toggled successfully.",
["PlayerNotFound"] = "The specified player could not be found.",
["ToggleConfig"] = "Toggle",
["InputButton"] = "Input",
["OutputButton"] = "Output",
["NoAccess"] = "You do not have access to this recycler.",
},
this
);
lang.RegisterMessages(
new Dictionary<string, string>
{
["NoPermission"] = "Você não tem permissão para usar este comando.",
["RecyclerLimitReached"] = "Você atingiu o limite de recicladores.",
["InvalidPlacement"] = "O reciclador deve ser colocado sobre um bloco de construção.",
["RecyclerPlaced"] = "Reciclador colocado com sucesso.",
["RecyclerPickedUp"] = "Reciclador recolhido, item devolvido ao inventário.",
["RecyclerGiven"] = "Reciclador fornecido ao seu inventário.",
["RecyclerReceived"] = "Você recebeu um reciclador.",
["RecyclerNotGiven"] = "Falha ao fornecer o reciclador.",
["RecyclerNotReceived"] = "Falha ao receber o reciclador.",
["NoRecyclerInView"] = "Nenhum reciclador à vista para atualizar.",
["RecyclerComponentNotFound"] = "Componente de reciclador não encontrado.",
["RecyclerConfigToggled"] = "Configuração do reciclador alternada com sucesso.",
["PlayerNotFound"] = "O jogador especificado não pôde ser encontrado.",
["ToggleConfig"] = "Alterar",
["InputButton"] = "Entrada",
["OutputButton"] = "Saída",
["NoAccess"] = "Você não tem acesso a este reciclador.",
},
this,
"pt-BR"
);
lang.RegisterMessages(
new Dictionary<string, string>
{
["NoPermission"] = "Sie haben keine Erlaubnis, diesen Befehl zu verwenden.",
["RecyclerLimitReached"] = "Sie haben die Grenze für Recycler erreicht.",
["InvalidPlacement"] = "Der Recycler muss auf einem Baublock platziert werden.",
["RecyclerPlaced"] = "Recycler erfolgreich platziert.",
["RecyclerPickedUp"] = "Recycler aufgenommen, Artikel in das Inventar zurückgegeben.",
["RecyclerGiven"] = "Recycler wurde Ihrem Inventar hinzugefügt.",
["RecyclerReceived"] = "Sie haben einen Recycler erhalten.",
["RecyclerNotGiven"] = "Recycle fehlerhaft vorhanden.",
["RecyclerNotReceived"] = "Falschen Empfang des Recyclers.",
["NoRecyclerInView"] = "Kein Recycler in Sicht, um aufzurüsten.",
["RecyclerComponentNotFound"] = "Recycler-Komponente nicht gefunden.",
["RecyclerConfigToggled"] = "Recycler-Konfiguration erfolgreich umgeschaltet.",
["PlayerNotFound"] = "Der angegebene Spieler konnte nicht gefunden werden.",
["ToggleConfig"] = "Umschalten",
["InputButton"] = "Eingang",
["OutputButton"] = "Ausgang",
["NoAccess"] = "Sie haben keinen Zugriff auf diesen Recycler.",
},
this,
"de"
);
lang.RegisterMessages(
new Dictionary<string, string>
{
["NoPermission"] = "No tienes permiso para usar este comando.",
["RecyclerLimitReached"] = "Has alcanzado el límite de recicladores.",
["InvalidPlacement"] = "El reciclador debe colocarse en un bloque de construcción.",
["RecyclerPlaced"] = "Reciclador colocado con éxito.",
["RecyclerPickedUp"] = "Reciclador recogido, artículo devuelto al inventario.",
["RecyclerGiven"] = "Reciclador dado a tu inventario.",
["RecyclerReceived"] = "Has recibido un reciclador.",
["RecyclerNotGiven"] = "Fallo al dar el reciclador.",
["RecyclerNotReceived"] = "Fallo al recibir el reciclador.",
["NoRecyclerInView"] = "No hay reciclador a la vista para mejorar.",
["RecyclerComponentNotFound"] = "Componente de reciclador no encontrado.",
["RecyclerConfigToggled"] = "Configuración del reciclador alternada con éxito.",
["PlayerNotFound"] = "No se pudo encontrar al jugador especificado.",
["ToggleConfig"] = "Alternar",
["InputButton"] = "Entrada",
["OutputButton"] = "Salida",
["NoAccess"] = "No tienes acceso a este reciclador.",
},
this,
"es"
);
}
#endregion
#region Component
private class RecyclerComponent : MonoBehaviour
{
public Recycler Recycler { get; private set; }
public StorageContainer InputStorage { get; private set; }
public StorageContainer OutputStorage { get; private set; }
public int CurrentConfigState { get; private set; }
private const int MaxStorageCapacity = 48;
private const float TransferInterval = 10f;
private enum RecyclerConfig
{
Default = 1,
Alternative = 2,
}
private void Awake()
{
Recycler = GetComponent<Recycler>();
if (Recycler == null)
{
Debug.LogError("Recycler component is missing on this GameObject.");
enabled = false;
return;
}
// Start with a default known state
CurrentConfigState = (int)RecyclerConfig.Default;
InitializeRecyclerComponents();
}
private void InitializeRecyclerComponents()
{
foreach (MonoBehaviour mb in GetComponents<MonoBehaviour>())
{
var type = mb.GetType();
if (type != typeof(Recycler) && type != typeof(RecyclerComponent) && type.Name != "Ground_Watch")
{
Destroy(mb);
}
}
if (!ValidateStorageContainers())
{
Debug.LogError("Failed to validate storage containers.");
enabled = false;
return;
}
SetupRecycler();
RegisterEntities();
InvokeRepeating(nameof(HandleItemTransfers), 0f, TransferInterval);
}
private bool ValidateStorageContainers()
{
InputStorage = Recycler.children.OfType<StorageContainer>().FirstOrDefault(c => c?.name == InputStoragePrefabPath);
OutputStorage = Recycler.children.OfType<StorageContainer>().FirstOrDefault(c => c?.name == OutputStoragePrefabPath);
return InputStorage != null && OutputStorage != null;
}
private void RegisterEntities()
{
_instance._inputItemContainers.Add(InputStorage.inventory.uid.Value);
_instance._recyclerItemContainers.Add(Recycler.inventory.uid.Value);
var inputAdapter = InputStorage.children.OfType<IndustrialStorageAdaptor>().FirstOrDefault();
if (inputAdapter != null)
_instance._storageAdapters.Add(inputAdapter.net.ID.Value);
var outputAdapter = OutputStorage.children.OfType<IndustrialStorageAdaptor>().FirstOrDefault();
if (outputAdapter != null)
_instance._storageAdapters.Add(outputAdapter.net.ID.Value);
}
private void SetupRecycler()
{
if (Recycler == null || InputStorage == null || OutputStorage == null)
{
Debug.LogError("Attempted to setup recycler with null components.");
return;
}
_instance._recyclerOwners[Recycler.net.ID.Value] = Recycler.OwnerID;
InputStorage.inventory.capacity = MaxStorageCapacity;
OutputStorage.inventory.capacity = MaxStorageCapacity;
}
public void HandleItemTransfers()
{
int availableRecyclerSlots = 6 - Recycler.inventory.itemList.Count;
if (OutputStorage.inventory.IsFull())
{
Recycler.StopRecycling();
return;
}
TransferItemsFromRecyclerToOutput(ref availableRecyclerSlots);
TransferItemsFromInputToRecycler(ref availableRecyclerSlots);
if (availableRecyclerSlots < 6 && Recycler.inventory.itemList.Count > 0)
{
Recycler.StartRecycling();
}
}
private void TransferItemsFromRecyclerToOutput(ref int availableRecyclerSlots)
{
for (int slot = 6; slot < Recycler.inventory.capacity; slot++)
{
var itemInRecycler = Recycler.inventory.GetSlot(slot);
if (itemInRecycler != null && itemInRecycler.MoveToContainer(OutputStorage.inventory))
{
availableRecyclerSlots++;
}
}
}
private void TransferItemsFromInputToRecycler(ref int availableRecyclerSlots)
{
var inputItems = new List<Item>(InputStorage.inventory.itemList);
foreach (var item in inputItems)
{
if (item.info.Blueprint != null)
{
MoveItemToRecycler(item, ref availableRecyclerSlots);
}
else
{
item.MoveToContainer(OutputStorage.inventory);
}
}
}
private void MoveItemToRecycler(Item item, ref int availableRecyclerSlots)
{
if (availableRecyclerSlots <= 0)
return;
for (int slot = 0; slot < 6; slot++)
{
if (Recycler.inventory.GetSlot(slot) == null && item.MoveToContainer(Recycler.inventory, slot))
{
availableRecyclerSlots--;
break;
}
}
}
public void ToggleConfig()
{
CancelInvoke(nameof(HandleItemTransfers));
CurrentConfigState = (int)(CurrentConfigState == (int)RecyclerConfig.Default ? RecyclerConfig.Alternative : RecyclerConfig.Default);
List<(string Shortname, int Amount, float ConditionNormalized)> ExtractItemDetails(ItemContainer container) =>
container?.itemList?.Select(item => (item.info.shortname, item.amount, item.conditionNormalized)).ToList() ?? new List<(string, int, float)>();
var inputItemDetails = ExtractItemDetails(InputStorage.inventory);
var outputItemDetails = ExtractItemDetails(OutputStorage.inventory);
ClearExistingComponents();
UpdateAdapterPositions();
InitializeRecyclerComponents();
if (InputStorage == null || OutputStorage == null || Recycler == null)
{
Debug.LogError("Storage references were not updated.");
return;
}
foreach (var (shortname, amount, condition) in inputItemDetails)
CreateAndMoveItem(shortname, amount, condition, InputStorage.inventory);
foreach (var (shortname, amount, condition) in outputItemDetails)
CreateAndMoveItem(shortname, amount, condition, OutputStorage.inventory);
}
private void CreateAndMoveItem(string shortname, int amount, float conditionNormalized, ItemContainer container)
{
var item = ItemManager.CreateByName(shortname, amount);
if (item != null)
{
item.conditionNormalized = conditionNormalized;
if (!item.MoveToContainer(container))
item.Remove();
}
}
private void UpdateAdapterPositions()
{
ClearExistingComponents();
Vector3 inputOffset,
outputOffset,
inputAdapterOffset,
outputAdapterOffset;
Quaternion inputRotation,
outputRotation,
inputAdapterRotation,
outputAdapterRotation;
if (CurrentConfigState == (int)RecyclerConfig.Default)
{
inputOffset = new Vector3(0.0f, 0.72f, 0.11f);
outputOffset = new Vector3(-0.4f, 0.8f, 0.2f);
inputAdapterOffset = new Vector3(0.32f, -0.6f, -0.03f);
outputAdapterOffset = new Vector3(-0.07f, 0.535f, 0.397f);
inputRotation = Quaternion.Euler(0, 180, 191);
outputRotation = Quaternion.Euler(169, 90, 180);
inputAdapterRotation = Quaternion.Euler(0, 0, 0);
outputAdapterRotation = Quaternion.Euler(180, 90, 0);
}
else
{
if (_instance._config.HideStorageContainers)
{
inputOffset = new Vector3(0.0f, 0.72f, 0.11f);
outputOffset = new Vector3(-0.4f, 0.72f, 0.2f);
inputAdapterOffset = new Vector3(0.836f, -0.3301f, 0.18f);
outputAdapterOffset = new Vector3(-0.227f, 0.33f, 0.434f);
inputRotation = Quaternion.Euler(0, 0, 180);
outputRotation = Quaternion.Euler(180, 90, 180);
inputAdapterRotation = Quaternion.Euler(0, 0, 0);
outputAdapterRotation = Quaternion.Euler(180, 90, 0);
}
else
{
inputOffset = new Vector3(-1.0f, 0.72f, 0.31f);
outputOffset = new Vector3(-0.9f, 0.72f, -0.09f);
inputAdapterOffset = new Vector3(0.00f, -0.15f, -0.25f);
outputAdapterOffset = new Vector3(0.00f, 0.26f, -0.05f);
inputRotation = Quaternion.Euler(90, 90, 180);
outputRotation = Quaternion.Euler(180, 90, 180);
inputAdapterRotation = Quaternion.Euler(180, 90, 270);
outputAdapterRotation = Quaternion.Euler(0, 90, 0);
}
}
BasePlayer ownerPlayer = BasePlayer.FindByID(Recycler.OwnerID);
if (ownerPlayer != null)
{
var inputStorage = _instance.SpawnEntity(InputStoragePrefabPath, Recycler, ownerPlayer, inputOffset, inputRotation) as StorageContainer;
if (inputStorage == null)
{
Debug.LogError("Failed to spawn input storage.");
return;
}
_instance.SpawnEntity(AdapterPrefabPath, inputStorage, ownerPlayer, inputAdapterOffset, inputAdapterRotation);
var outputStorage = _instance.SpawnEntity(OutputStoragePrefabPath, Recycler, ownerPlayer, outputOffset, outputRotation) as StorageContainer;
if (outputStorage == null)
{
Debug.LogError("Failed to spawn output storage.");
return;
}
_instance.SpawnEntity(AdapterPrefabPath, outputStorage, ownerPlayer, outputAdapterOffset, outputAdapterRotation);
}
}
private void ClearExistingComponents()
{
foreach (var child in Recycler.children.ToList())
{
if (child is StorageContainer || child is IndustrialStorageAdaptor)
{
child.Kill();
}
}
}
internal void DropItems()
{
var allItems = GatherAllItems();
DropItemsInBatches(allItems, MaxStorageCapacity);
}
private List<Item> GatherAllItems()
{
return InputStorage.inventory.itemList.Concat(OutputStorage.inventory.itemList).Concat(Recycler.inventory.itemList).ToList();
}
private void DropItemsInBatches(List<Item> items, int batchSize)
{
var recyclerPosition = Recycler.transform.position;
var recyclerRotation = Recycler.transform.rotation;
for (int i = 0; i < items.Count; i += batchSize)
{
var itemBatch = items.Skip(i).Take(batchSize).ToList();
SpawnDroppedItemContainer(recyclerPosition, recyclerRotation, itemBatch);
}
}
private DroppedItemContainer SpawnDroppedItemContainer(Vector3 position, Quaternion rotation, List<Item> itemsToDrop)
{
var containerPrefabPath = "assets/prefabs/misc/item drop/item_drop.prefab";
var droppedItemContainer = GameManager.server.CreateEntity(containerPrefabPath, position, rotation) as DroppedItemContainer;
if (droppedItemContainer == null)
return null;
InitializeItemContainer(droppedItemContainer, itemsToDrop);
droppedItemContainer.Spawn();
return droppedItemContainer;
}
private void InitializeItemContainer(DroppedItemContainer container, List<Item> items)
{
container.inventory = new ItemContainer();
container.inventory.ServerInitialize(null, items.Count);
container.inventory.GiveUID();
container.inventory.entityOwner = container;
foreach (var item in items)
{
item.MoveToContainer(container.inventory);
}
}
private void OnDestroy()
{
CancelInvoke(nameof(HandleItemTransfers));
}
}
#endregion
}
}
Key Updates:
CanPickupEntity Method: This method checks if the player has access to the adapter being picked up, preventing unauthorized pickups. If authorized, it kills the parent entity and gives the recycler item back to the player.
Access Control Logic: Ensures that only authorized entities (owner, friends, team members, admins) can interact with specific components or pick them up.
Please ensure to have the necessary plugins and configuration if you're using the Friends API to manage friendship checks for access rights.
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Oxide.Core;
using Oxide.Core.Plugins;
using Oxide.Game.Rust.Cui;
using UnityEngine;
namespace Oxide.Plugins
{
[Info("IndustrialRecycler", "Marte6", "1.4.6")]
[Description("Automate recycling by attaching storage and adapters to recyclers.")]
class IndustrialRecycler : RustPlugin
{
#region PluginReferences
[PluginReference] Plugin Friends;
#endregion
#region Fields
private static IndustrialRecycler _instance;
private Configuration _config;
private const string RecyclerPrefabPath = "assets/bundled/prefabs/static/recycler_static.prefab";
private const string InputStoragePrefabPath = "assets/content/vehicles/boats/rowboat/subents/rowboat_storage.prefab";
private const string OutputStoragePrefabPath = "assets/prefabs/deployable/hot air balloon/subents/hab_storage.prefab";
private const string AdapterPrefabPath = "assets/prefabs/deployable/playerioents/industrialadaptors/storageadaptor.deployed.prefab";
private const string ItemName = "box.wooden.large";
private const string PermissionUseRecycler = "industrialrecycler.give";
private const string PermissionVip = "industrialrecycler.vip";
private const string PermissionAdmin = "industrialrecycler.admin";
private const string UiOverlayName = "IndustrialRecyclerMainPanel";
#endregion
#region Cache
private readonly Dictionary<ulong, ulong> _recyclerOwners = new();
private readonly HashSet<ulong> _recyclerItemContainers = new();
private readonly HashSet<ulong> _inputItemContainers = new();
private readonly HashSet<ulong> _storageAdapters = new();
private readonly HashSet<ulong> _playersWithUi = new();
#endregion
#region Game Hooks
private void Init()
{
permission.RegisterPermission(PermissionUseRecycler, this);
permission.RegisterPermission(PermissionVip, this);
permission.RegisterPermission(PermissionAdmin, this);
foreach (var command in _config.Commands)
{
cmd.AddChatCommand(command, this, nameof(CommandGetRecycler));
}
cmd.AddChatCommand("upgraderecycler", this, nameof(CommandUpgradeRecycler));
cmd.AddChatCommand("togglerecycler", this, nameof(ToggleRecyclerConfig));
cmd.AddConsoleCommand("industrialrecycler.openinput", this, nameof(OpenInputStorage));
cmd.AddConsoleCommand("industrialrecycler.openoutput", this, nameof(OpenOutputStorage));
}
private void OnServerInitialized()
{
_instance = this;
foreach (var recycler in UnityEngine.Object.FindObjectsOfType<Recycler>())
{
if (recycler.OwnerID != 0UL)
{
recycler.gameObject.AddComponent<RecyclerComponent>();
}
}
}
private void Unload()
{
foreach (var recyclerComponent in UnityEngine.Object.FindObjectsOfType<RecyclerComponent>())
{
UnityEngine.Object.Destroy(recyclerComponent);
}
foreach (var player in BasePlayer.activePlayerList)
{
CuiHelper.DestroyUi(player, UiOverlayName);
}
}
private void OnItemAddedToContainer(ItemContainer container, Item item)
{
Recycler recycler = container.entityOwner as Recycler ?? container.entityOwner?.GetParentEntity() as Recycler;
if (recycler == null)
return;
var recyclerComponent = recycler.GetComponent<RecyclerComponent>();
if (recyclerComponent == null)
return;
bool isMainRecycler = container.entityOwner is Recycler;
ulong containerUid = container.uid.Value;
if (isMainRecycler && _recyclerItemContainers.Contains(containerUid))
{
ProcessRecyclerItems(recyclerComponent, item);
}
else if (!isMainRecycler && _inputItemContainers.Contains(containerUid))
{
recyclerComponent.HandleItemTransfers();
}
}
private void OnEntityBuilt(Planner planner, GameObject entityObject)
{
var player = planner?.GetOwnerPlayer();
var baseEntity = entityObject.GetComponent<BaseEntity>();
if (player == null || baseEntity == null || baseEntity.ShortPrefabName != ItemName || baseEntity.skinID != _config.RecyclerSkinId)
return;
int maxRecyclers = _config.MaxRecyclersPerPlayer;
if (permission.UserHasPermission(player.UserIDString, PermissionAdmin))
{
maxRecyclers = int.MaxValue;
}
else if (permission.UserHasPermission(player.UserIDString, PermissionVip))
{
maxRecyclers = _config.MaxRecyclersVip;
}
if (_recyclerOwners.Count(entry => entry.Value == player.userID) >= maxRecyclers)
{
player.ChatMessage(lang.GetMessage("RecyclerLimitReached", this, player.UserIDString));
timer.Once(1, () => GiveRecyclerItem(player));
NextTick(() => baseEntity?.Kill());
return;
}
if (!InitializeRecyclerPlacement(player, baseEntity))
{
player.ChatMessage(lang.GetMessage("InvalidPlacement", this, player.UserIDString));
timer.Once(1, () => GiveRecyclerItem(player));
}
else
{
player.ChatMessage(lang.GetMessage("RecyclerPlaced", this, player.UserIDString));
}
NextTick(() => baseEntity?.Kill());
}
private object CanPickupEntity(BasePlayer player, IndustrialStorageAdaptor adapter)
{
if (adapter?.net?.ID.Value != null && _storageAdapters.Contains(adapter.net.ID.Value))
{
if (!HasAccess(player, adapter))
{
player.ChatMessage(lang.GetMessage("NoAccess", this, player.UserIDString));
return false;
}
adapter.GetParentEntity()?.GetParentEntity()?.Kill();
GiveRecyclerItem(player);
player.ChatMessage(lang.GetMessage("RecyclerPickedUp", this, player.UserIDString));
return false;
}
return null;
}
private object CanLootStorage(BasePlayer player, StorageContainer storage)
{
Recycler recycler = storage.GetParentEntity() as Recycler;
if (recycler != null && !HasAccess(player, recycler))
{
player.ChatMessage(lang.GetMessage("NoAccess", this, player.UserIDString));
return false;
}
return null;
}
private object OnEntityKill(Recycler recycler)
{
if (!IsRecyclerOwned(recycler))
return null;
UnregisterRecyclerOwnership(recycler);
DropRecyclerItems(recycler);
return null;
}
private bool IsRecyclerOwned(Recycler recycler)
{
return recycler.OwnerID != 0UL && _recyclerOwners.ContainsKey(recycler.net.ID.Value);
}
private void UnregisterRecyclerOwnership(Recycler recycler)
{
_recyclerOwners.Remove(recycler.net.ID.Value);
}
private void DropRecyclerItems(Recycler recycler)
{
var recyclerComponent = recycler.GetComponent<RecyclerComponent>();
recyclerComponent?.DropItems();
}
private void OnLootEntity(BasePlayer player, Recycler recycler)
{
if (recycler == null || player == null || !HasAccess(player, recycler))
return;
if (recycler.OwnerID != 0UL && _recyclerOwners.ContainsKey(recycler.net.ID.Value))
{
_playersWithUi.Add(player.userID);
string recyclerId = recycler.net.ID.Value.ToString();
CreateUi(player, recyclerId);
}
}
private void OnPlayerLootEnd(PlayerLoot playerLoot)
{
BasePlayer player = playerLoot.GetComponentInParent<BasePlayer>();
if (player == null)
return;
if (_playersWithUi.Contains(player.userID))
{
_playersWithUi.Remove(player.userID);
CuiHelper.DestroyUi(player, UiOverlayName);
}
}
#endregion
#region Access Control
private bool HasAccess(BasePlayer player, BaseEntity entity)
{
ulong ownerId = entity.OwnerID;
if (ownerId == player.userID || permission.UserHasPermission(player.UserIDString, PermissionAdmin))
return true;
if (_config.AllowTeamAccess && player.currentTeam != 0)
{
var team = RelationshipManager.ServerInstance.FindTeam(player.currentTeam);
if (team != null && team.members.Contains(ownerId))
return true;
}
if (_config.AllowFriendsAccess && Friends != null)
{
bool areFriends = (bool)(Friends.CallHook("AreFriends", ownerId, player.userID) ?? false);
if (areFriends)
return true;
}
return false;
}
#endregion
#region UI
private void CreateUi(BasePlayer player, string recyclerId)
{
var container = new CuiElementContainer();
container.Add(
new CuiPanel
{
CursorEnabled = true,
Image =
{
Color = "1 1 1 0.15",
Sprite = "assets/content/ui/ui.background.transparent.radial.psd",
Material = "assets/content/ui/uibackgroundblur.mat",
},
RectTransform =
{
AnchorMin = _config.AnchorMin,
AnchorMax = _config.AnchorMax,
OffsetMin = "341.64 405.595",
OffsetMax = "554.76 505.605",
},
},
"Overlay",
UiOverlayName
);
container.Add(
new CuiElement
{
Name = "Text",
Parent = UiOverlayName,
Components =
{
new CuiTextComponent
{
Text = "INDUSTRIAL RECYCLER",
Font = "robotocondensed-bold.ttf",
FontSize = 17,
Align = TextAnchor.MiddleCenter,
Color = "1 1 1 1",
},
new CuiOutlineComponent { Color = "0 0 0 1", Distance = "1 1" },
new CuiRectTransformComponent
{
AnchorMin = "0.5 0.5",
AnchorMax = "0.5 0.5",
OffsetMin = "-86.493 0",
OffsetMax = "86.492 34.875",
},
},
}
);
container.Add(
new CuiButton
{
Button =
{
Color = "0.3960785 0.4666667 0.2627451 1",
Command = $"industrialrecycler.openinput {recyclerId}",
Close = UiOverlayName,
},
Text =
{
Text = lang.GetMessage("InputButton", this, player.UserIDString),
Font = "robotocondensed-regular.ttf",
FontSize = 18,
Align = TextAnchor.MiddleCenter,
Color = "1 1 1 1",
},
RectTransform =
{
AnchorMin = "0.5 0.5",
AnchorMax = "0.5 0.5",
OffsetMin = "-104.206 -49.58",
OffsetMax = "-2.394 -17.22",
},
},
UiOverlayName,
"Input"
);
container.Add(
new CuiButton
{
Button =
{
Color = "0.3960785 0.4666667 0.2627451 1",
Command = $"industrialrecycler.openoutput {recyclerId}",
Close = UiOverlayName,
},
Text =
{
Text = lang.GetMessage("OutputButton", this, player.UserIDString),
Font = "robotocondensed-regular.ttf",
FontSize = 18,
Align = TextAnchor.MiddleCenter,
Color = "1 1 1 1",
},
RectTransform =
{
AnchorMin = "0.5 0.5",
AnchorMax = "0.5 0.5",
OffsetMin = "1.994 -49.58",
OffsetMax = "103.806 -17.22",
},
},
UiOverlayName,
"Output"
);
container.Add(
new CuiButton
{
Button =
{
Color = "0.3960785 0.7666667 0.2627451 1",
Command = $"chat.say /togglerecycler",
Close = "ToggleConfig",
},
Text =
{
Text = lang.GetMessage("ToggleConfig", this),
Font = "robotocondensed-regular.ttf",
FontSize = 14,
Align = TextAnchor.MiddleCenter,
Color = "1 1 1 1",
},
RectTransform =
{
AnchorMin = "1 1",
AnchorMax = "1 1",
OffsetMin = "-110 -20",
OffsetMax = "0 0",
},
},
UiOverlayName,
"ToggleConfig"
);
CuiHelper.DestroyUi(player, UiOverlayName);
CuiHelper.AddUi(player, container);
}
private void OpenInputStorage(ConsoleSystem.Arg arg)
{
OpenStorage(arg, true);
}
private void OpenOutputStorage(ConsoleSystem.Arg arg)
{
OpenStorage(arg, false);
}
private void OpenStorage(ConsoleSystem.Arg arg, bool isInput)
{
var player = arg.Player();
if (player == null)
{
return;
}
if (arg.Args.Length == 0)
{
return;
}
if (!uint.TryParse(arg.Args[0], out uint recyclerId))
{
return;
}
var networkableId = new NetworkableId(recyclerId);
var recycler = BaseNetworkable.serverEntities.Find(networkableId) as Recycler;
if (recycler != null && HasAccess(player, recycler))
{
var recyclerComponent = recycler.GetComponent<RecyclerComponent>();
if (recyclerComponent != null)
{
var storage = isInput ? recyclerComponent.InputStorage : recyclerComponent.OutputStorage;
player.inventory.loot.StartLootingEntity(storage, true);
player.inventory.loot.AddContainer(storage.inventory);
player.inventory.loot.SendImmediate();
player.ClientRPCPlayer(null, player, "RPC_OpenLootPanel", storage.panelName);
}
}
}
#endregion
#region Main
private void CommandGetRecycler(BasePlayer player, string command, string[] args)
{
if (player == null)
return;
if (!permission.UserHasPermission(player.UserIDString, PermissionUseRecycler))
{
player.ChatMessage(lang.GetMessage("NoPermission", this, player.UserIDString));
return;
}
BasePlayer targetPlayer = player;
if (args != null && args.Length > 0)
{
targetPlayer = BasePlayer.Find(args[0]);
if (targetPlayer == null)
{
player.ChatMessage(lang.GetMessage("PlayerNotFound", this, player.UserIDString));
return;
}
}
if (GiveRecyclerItem(targetPlayer))
{
player.ChatMessage(lang.GetMessage("RecyclerGiven", this, player.UserIDString));
if (targetPlayer != player)
{
targetPlayer.ChatMessage(lang.GetMessage("RecyclerReceived", this, targetPlayer.UserIDString));
}
}
else
{
player.ChatMessage(lang.GetMessage("RecyclerNotGiven", this, player.UserIDString));
if (targetPlayer != player)
{
targetPlayer.ChatMessage(lang.GetMessage("RecyclerNotReceived", this, targetPlayer.UserIDString));
}
}
}
private bool GiveRecyclerItem(BasePlayer player)
{
var recyclerItem = ItemManager.CreateByName(ItemName, 1, _config.RecyclerSkinId);
if (recyclerItem == null)
return false;
recyclerItem.name = "Recycler";
return player.inventory.GiveItem(recyclerItem);
}
private void CommandUpgradeRecycler(BasePlayer player, string command, string[] args)
{
if (!permission.UserHasPermission(player.UserIDString, PermissionUseRecycler))
{
player.ChatMessage(lang.GetMessage("NoPermission", this, player.UserIDString));
return;
}
int maxRecyclers = _config.MaxRecyclersPerPlayer;
if (permission.UserHasPermission(player.UserIDString, PermissionAdmin))
{
maxRecyclers = int.MaxValue;
}
else if (permission.UserHasPermission(player.UserIDString, PermissionVip))
{
maxRecyclers = _config.MaxRecyclersVip;
}
if (_recyclerOwners.Count(entry => entry.Value == player.userID) >= maxRecyclers)
{
player.ChatMessage(lang.GetMessage("RecyclerLimitReached", this, player.UserIDString));
return;
}
if (!UpgradeToIndustrialRecycler(player))
{
player.ChatMessage(lang.GetMessage("NoRecyclerInView", this, player.UserIDString));
}
else
{
player.ChatMessage(lang.GetMessage("RecyclerUpgraded", this, player.UserIDString));
}
}
private Recycler FindRecyclerInView(BasePlayer player)
{
if (Physics.Raycast(player.eyes.HeadRay(), out RaycastHit hit, 5f))
{
BaseEntity entity = hit.GetEntity();
return entity as Recycler;
}
return null;
}
private bool InitializeRecyclerPlacement(BasePlayer player, BaseEntity baseEntity, int turn = 0)
{
var supportingFoundation = FindSupportingFoundation(baseEntity);
if (supportingFoundation == null)
return false;
var spawnedRecycler = SpawnRecyclerWithComponents(player, baseEntity, supportingFoundation, turn);
if (spawnedRecycler == null)
return false;
spawnedRecycler.gameObject.AddComponent<RecyclerComponent>();
return true;
}
private bool InitializeUpgradeRecycler(BasePlayer player, Recycler recycler, int turn = 0)
{
var spawnedRecycler = UpgradeRecyclerWithComponents(player, recycler, turn);
if (spawnedRecycler == null)
return false;
spawnedRecycler.gameObject.AddComponent<RecyclerComponent>();
return true;
}
private BuildingBlock FindSupportingFoundation(BaseEntity baseEntity)
{
Vector3 origin = baseEntity.transform.position + Vector3.up * 0.1f;
if (Physics.Raycast(origin, Vector3.down, out RaycastHit hitData, 4f, LayerMask.GetMask("Construction")))
{
return hitData.GetEntity() as BuildingBlock;
}
return null;
}
private Recycler SetupStorageAndAdapters(Recycler recycler, BasePlayer player)
{
Vector3 inputOffset,
inputAdapterOffset,
outputOffset,
outputAdapterOffset;
Quaternion inputRotation,
outputRotation,
inputAdapterRotation,
outputAdapterRotation;
if (_config.UseAlternativeAdapterConfig)
{
inputOffset = new Vector3(0.0f, 0.72f, 0.11f);
inputAdapterOffset = new Vector3(0.32f, -0.6f, -0.03f);
outputOffset = new Vector3(-0.4f, 0.8f, 0.2f);
outputAdapterOffset = new Vector3(-0.07f, 0.535f, 0.397f);
inputRotation = Quaternion.Euler(0, 180, 191);
outputRotation = Quaternion.Euler(169, 90, 180);
inputAdapterRotation = Quaternion.Euler(0, 0, 0);
outputAdapterRotation = Quaternion.Euler(180, 90, 0);
}
else
{
inputOffset = new Vector3(-1.0f, 0.72f, 0.31f);
inputAdapterOffset = new Vector3(0.00f, -0.15f, -0.25f);
outputOffset = new Vector3(-0.9f, 0.72f, -0.09f);
outputAdapterOffset = new Vector3(0.00f, 0.26f, -0.05f);
inputRotation = Quaternion.Euler(90, 90, 180);
outputRotation = Quaternion.Euler(180, 90, 180);
inputAdapterRotation = Quaternion.Euler(180, 90, 270);
outputAdapterRotation = Quaternion.Euler(0, 90, 0);
}
var inputStorage = SpawnEntity(InputStoragePrefabPath, recycler, player, inputOffset, inputRotation);
SpawnEntity(AdapterPrefabPath, inputStorage, player, inputAdapterOffset, inputAdapterRotation);
var outputStorage = SpawnEntity(OutputStoragePrefabPath, recycler, player, outputOffset, outputRotation);
SpawnEntity(AdapterPrefabPath, outputStorage, player, outputAdapterOffset, outputAdapterRotation);
return recycler;
}
private Recycler UpgradeRecyclerWithComponents(BasePlayer player, Recycler recycler, int turn = 0)
{
return SetupStorageAndAdapters(recycler, player);
}
private Recycler SpawnRecyclerWithComponents(BasePlayer player, BaseEntity baseEntity, BuildingBlock foundation, int turn = 0)
{
var recycler = SpawnEntity(RecyclerPrefabPath, foundation, player, baseEntity.transform.position, baseEntity.transform.rotation * Quaternion.Euler(0, turn, 0)) as Recycler;
if (recycler == null)
return null;
return SetupStorageAndAdapters(recycler, player);
}
private BaseEntity SpawnEntity(string prefabPath, BaseEntity parent, BasePlayer player, Vector3 position, Quaternion rotation)
{
var entity = GameManager.server.CreateEntity(prefabPath, Vector3.zero, Quaternion.identity, true);
if (entity == null)
return null;
entity.OwnerID = player.userID;
if (parent != null)
{
entity.SetParent(parent, true);
}
if (parent is BuildingBlock)
{
entity.transform.position = position;
entity.transform.rotation = rotation;
}
else
{
entity.transform.localPosition = position;
entity.transform.localRotation = rotation;
}
entity.Spawn();
entity.SendNetworkUpdateImmediate();
return entity;
}
private void ProcessRecyclerItems(RecyclerComponent recyclerComponent, Item item)
{
if (item.position < 6)
{
recyclerComponent.Recycler.StartRecycling();
}
else
{
if (!item.MoveToContainer(recyclerComponent.OutputStorage.inventory))
{
recyclerComponent.Recycler.StopRecycling();
}
}
}
private bool UpgradeToIndustrialRecycler(BasePlayer player)
{
if (Physics.Raycast(player.eyes.HeadRay(), out RaycastHit hit, 5f))
{
BaseEntity baseEntity = hit.GetEntity();
if (baseEntity is Recycler recycler && recycler.OwnerID == player.userID)
{
if (!InitializeUpgradeRecycler(player, baseEntity as Recycler, 90))
{
player.ChatMessage(lang.GetMessage("InvalidPlacement", this, player.UserIDString));
timer.Once(1, () => GiveRecyclerItem(player));
return false;
}
else
{
player.ChatMessage(lang.GetMessage("RecyclerPlaced", this, player.UserIDString));
}
return true;
}
}
return false;
}
private void ToggleRecyclerConfig(BasePlayer player, string command, string[] args)
{
if (!permission.UserHasPermission(player.UserIDString, PermissionUseRecycler))
{
player.ChatMessage(lang.GetMessage("NoPermission", this, player.UserIDString));
return;
}
Recycler recycler = FindRecyclerInView(player);
if (recycler == null)
{
player.ChatMessage(lang.GetMessage("NoRecyclerInView", this, player.UserIDString));
return;
}
var recyclerComponent = recycler.GetComponent<RecyclerComponent>();
if (recyclerComponent == null)
{
player.ChatMessage(lang.GetMessage("RecyclerComponentNotFound", this, player.UserIDString));
return;
}
recyclerComponent.ToggleConfig();
player.ChatMessage(lang.GetMessage("RecyclerConfigToggled", this, player.UserIDString));
}
#endregion
#region Configuration
private class Configuration
{
[JsonProperty("Commands")]
public List<string> Commands { get; set; }
[JsonProperty("Max Recyclers Per Player")]
public int MaxRecyclersPerPlayer { get; set; }
[JsonProperty("Max Recyclers Vip (industrialrecycler.vip)")]
public int MaxRecyclersVip { get; set; }
[JsonProperty("Recycler Item SkinId")]
public ulong RecyclerSkinId { get; set; }
[JsonProperty("AnchorMin")]
public string AnchorMin { get; set; }
[JsonProperty("AnchorMax")]
public string AnchorMax { get; set; }
[JsonProperty("Alternative Adapter Configuration")]
public bool UseAlternativeAdapterConfig { get; set; }
[JsonProperty("Hide Storage Containers")]
public bool HideStorageContainers { get; set; }
[JsonProperty("Only owner can access recycler")]
public bool OnlyOwnerAccess { get; set; }
[JsonProperty("Allow team members to access recycler")]
public bool AllowTeamAccess { get; set; }
[JsonProperty("Allow friends to access recycler")]
public bool AllowFriendsAccess { get; set; }
[JsonProperty("Version")]
public VersionNumber Version { get; set; }
}
protected override void LoadConfig()
{
base.LoadConfig();
try
{
_config = Config.ReadObject<Configuration>() ?? throw new Exception("Failed to read configuration file.");
bool configChanged = false;
if (_config.Version != Version)
{
_config.Version = Version;
configChanged = true;
}
if (string.IsNullOrEmpty(_config.AnchorMin))
{
_config.AnchorMin = "0.5 0";
configChanged = true;
}
if (string.IsNullOrEmpty(_config.AnchorMax))
{
_config.AnchorMax = "0.5 0";
configChanged = true;
}
if (!_config.UseAlternativeAdapterConfig)
{
_config.UseAlternativeAdapterConfig = false;
configChanged = true;
}
if (configChanged)
{
SaveConfig();
}
}
catch (Exception ex)
{
PrintError($"There was an error in your configuration file: {ex.Message}. Default values will be used.");
LoadDefaultConfig();
}
}
protected override void LoadDefaultConfig()
{
_config = GetDefaultConfig();
SaveConfig();
}
protected override void SaveConfig()
{
Config.WriteObject(_config, true);
}
private Configuration GetDefaultConfig()
{
return new Configuration
{
Commands = new List<string> { "getrecycler", "irecycler", "giverecycler" },
MaxRecyclersPerPlayer = 1,
MaxRecyclersVip = 2,
RecyclerSkinId = 3357927081,
AnchorMin = "0.5 0",
AnchorMax = "0.5 0",
UseAlternativeAdapterConfig = false,
HideStorageContainers = false,
OnlyOwnerAccess = true,
AllowTeamAccess = true,
AllowFriendsAccess = true,
Version = Version,
};
}
#endregion
#region Localization
protected override void LoadDefaultMessages()
{
lang.RegisterMessages(
new Dictionary<string, string>
{
["NoPermission"] = "You do not have permission to use this command.",
["RecyclerLimitReached"] = "You have reached the recycler limit.",
["InvalidPlacement"] = "The recycler must be placed on a construction block.",
["RecyclerPlaced"] = "Recycler placed successfully.",
["RecyclerPickedUp"] = "Recycler picked up, item returned to inventory.",
["RecyclerGiven"] = "Recycler given to your inventory.",
["RecyclerReceived"] = "You have received a recycler.",
["RecyclerNotGiven"] = "Failed to give recycler.",
["RecyclerNotReceived"] = "Failed to receive recycler.",
["NoRecyclerInView"] = "No recycler in sight to upgrade.",
["RecyclerComponentNotFound"] = "Recycler component not found.",
["RecyclerConfigToggled"] = "Recycler configuration toggled successfully.",
["PlayerNotFound"] = "The specified player could not be found.",
["ToggleConfig"] = "Toggle",
["InputButton"] = "Input",
["OutputButton"] = "Output",
["NoAccess"] = "You do not have access to this recycler.",
},
this
);
lang.RegisterMessages(
new Dictionary<string, string>
{
["NoPermission"] = "Você não tem permissão para usar este comando.",
["RecyclerLimitReached"] = "Você atingiu o limite de recicladores.",
["InvalidPlacement"] = "O reciclador deve ser colocado sobre um bloco de construção.",
["RecyclerPlaced"] = "Reciclador colocado com sucesso.",
["RecyclerPickedUp"] = "Reciclador recolhido, item devolvido ao inventário.",
["RecyclerGiven"] = "Reciclador fornecido ao seu inventário.",
["RecyclerReceived"] = "Você recebeu um reciclador.",
["RecyclerNotGiven"] = "Falha ao fornecer o reciclador.",
["RecyclerNotReceived"] = "Falha ao receber o reciclador.",
["NoRecyclerInView"] = "Nenhum reciclador à vista para atualizar.",
["RecyclerComponentNotFound"] = "Componente de reciclador não encontrado.",
["RecyclerConfigToggled"] = "Configuração do reciclador alternada com sucesso.",
["PlayerNotFound"] = "O jogador especificado não pôde ser encontrado.",
["ToggleConfig"] = "Alterar",
["InputButton"] = "Entrada",
["OutputButton"] = "Saída",
["NoAccess"] = "Você não tem acesso a este reciclador.",
},
this,
"pt-BR"
);
lang.RegisterMessages(
new Dictionary<string, string>
{
["NoPermission"] = "Sie haben keine Erlaubnis, diesen Befehl zu verwenden.",
["RecyclerLimitReached"] = "Sie haben die Grenze für Recycler erreicht.",
["InvalidPlacement"] = "Der Recycler muss auf einem Baublock platziert werden.",
["RecyclerPlaced"] = "Recycler erfolgreich platziert.",
["RecyclerPickedUp"] = "Recycler aufgenommen, Artikel in das Inventar zurückgegeben.",
["RecyclerGiven"] = "Recycler wurde Ihrem Inventar hinzugefügt.",
["RecyclerReceived"] = "Sie haben einen Recycler erhalten.",
["RecyclerNotGiven"] = "Recycle fehlerhaft vorhanden.",
["RecyclerNotReceived"] = "Falschen Empfang des Recyclers.",
["NoRecyclerInView"] = "Kein Recycler in Sicht, um aufzurüsten.",
["RecyclerComponentNotFound"] = "Recycler-Komponente nicht gefunden.",
["RecyclerConfigToggled"] = "Recycler-Konfiguration erfolgreich umgeschaltet.",
["PlayerNotFound"] = "Der angegebene Spieler konnte nicht gefunden werden.",
["ToggleConfig"] = "Umschalten",
["InputButton"] = "Eingang",
["OutputButton"] = "Ausgang",
["NoAccess"] = "Sie haben keinen Zugriff auf diesen Recycler.",
},
this,
"de"
);
lang.RegisterMessages(
new Dictionary<string, string>
{
["NoPermission"] = "No tienes permiso para usar este comando.",
["RecyclerLimitReached"] = "Has alcanzado el límite de recicladores.",
["InvalidPlacement"] = "El reciclador debe colocarse en un bloque de construcción.",
["RecyclerPlaced"] = "Reciclador colocado con éxito.",
["RecyclerPickedUp"] = "Reciclador recogido, artículo devuelto al inventario.",
["RecyclerGiven"] = "Reciclador dado a tu inventario.",
["RecyclerReceived"] = "Has recibido un reciclador.",
["RecyclerNotGiven"] = "Fallo al dar el reciclador.",
["RecyclerNotReceived"] = "Fallo al recibir el reciclador.",
["NoRecyclerInView"] = "No hay reciclador a la vista para mejorar.",
["RecyclerComponentNotFound"] = "Componente de reciclador no encontrado.",
["RecyclerConfigToggled"] = "Configuración del reciclador alternada con éxito.",
["PlayerNotFound"] = "No se pudo encontrar al jugador especificado.",
["ToggleConfig"] = "Alternar",
["InputButton"] = "Entrada",
["OutputButton"] = "Salida",
["NoAccess"] = "No tienes acceso a este reciclador.",
},
this,
"es"
);
}
#endregion
#region Component
private class RecyclerComponent : MonoBehaviour
{
public Recycler Recycler { get; private set; }
public StorageContainer InputStorage { get; private set; }
public StorageContainer OutputStorage { get; private set; }
public int CurrentConfigState { get; private set; }
private const int MaxStorageCapacity = 48;
private const float TransferInterval = 10f;
private enum RecyclerConfig
{
Default = 1,
Alternative = 2,
}
private void Awake()
{
Recycler = GetComponent<Recycler>();
if (Recycler == null)
{
Debug.LogError("Recycler component is missing on this GameObject.");
enabled = false;
return;
}
// Start with a default known state
CurrentConfigState = (int)RecyclerConfig.Default;
InitializeRecyclerComponents();
}
private void InitializeRecyclerComponents()
{
foreach (MonoBehaviour mb in GetComponents<MonoBehaviour>())
{
var type = mb.GetType();
if (type != typeof(Recycler) && type != typeof(RecyclerComponent) && type.Name != "Ground_Watch")
{
Destroy(mb);
}
}
if (!ValidateStorageContainers())
{
Debug.LogError("Failed to validate storage containers.");
enabled = false;
return;
}
SetupRecycler();
RegisterEntities();
InvokeRepeating(nameof(HandleItemTransfers), 0f, TransferInterval);
}
private bool ValidateStorageContainers()
{
InputStorage = Recycler.children.OfType<StorageContainer>().FirstOrDefault(c => c?.name == InputStoragePrefabPath);
OutputStorage = Recycler.children.OfType<StorageContainer>().FirstOrDefault(c => c?.name == OutputStoragePrefabPath);
return InputStorage != null && OutputStorage != null;
}
private void RegisterEntities()
{
_instance._inputItemContainers.Add(InputStorage.inventory.uid.Value);
_instance._recyclerItemContainers.Add(Recycler.inventory.uid.Value);
var inputAdapter = InputStorage.children.OfType<IndustrialStorageAdaptor>().FirstOrDefault();
if (inputAdapter != null)
_instance._storageAdapters.Add(inputAdapter.net.ID.Value);
var outputAdapter = OutputStorage.children.OfType<IndustrialStorageAdaptor>().FirstOrDefault();
if (outputAdapter != null)
_instance._storageAdapters.Add(outputAdapter.net.ID.Value);
}
private void SetupRecycler()
{
if (Recycler == null || InputStorage == null || OutputStorage == null)
{
Debug.LogError("Attempted to setup recycler with null components.");
return;
}
_instance._recyclerOwners[Recycler.net.ID.Value] = Recycler.OwnerID;
InputStorage.inventory.capacity = MaxStorageCapacity;
OutputStorage.inventory.capacity = MaxStorageCapacity;
}
public void HandleItemTransfers()
{
int availableRecyclerSlots = 6 - Recycler.inventory.itemList.Count;
if (OutputStorage.inventory.IsFull())
{
Recycler.StopRecycling();
return;
}
TransferItemsFromRecyclerToOutput(ref availableRecyclerSlots);
TransferItemsFromInputToRecycler(ref availableRecyclerSlots);
if (availableRecyclerSlots < 6 && Recycler.inventory.itemList.Count > 0)
{
Recycler.StartRecycling();
}
}
private void TransferItemsFromRecyclerToOutput(ref int availableRecyclerSlots)
{
for (int slot = 6; slot < Recycler.inventory.capacity; slot++)
{
var itemInRecycler = Recycler.inventory.GetSlot(slot);
if (itemInRecycler != null && itemInRecycler.MoveToContainer(OutputStorage.inventory))
{
availableRecyclerSlots++;
}
}
}
private void TransferItemsFromInputToRecycler(ref int availableRecyclerSlots)
{
var inputItems = new List<Item>(InputStorage.inventory.itemList);
foreach (var item in inputItems)
{
if (item.info.Blueprint != null)
{
MoveItemToRecycler(item, ref availableRecyclerSlots);
}
else
{
item.MoveToContainer(OutputStorage.inventory);
}
}
}
private void MoveItemToRecycler(Item item, ref int availableRecyclerSlots)
{
if (availableRecyclerSlots <= 0)
return;
for (int slot = 0; slot < 6; slot++)
{
if (Recycler.inventory.GetSlot(slot) == null && item.MoveToContainer(Recycler.inventory, slot))
{
availableRecyclerSlots--;
break;
}
}
}
public void ToggleConfig()
{
CancelInvoke(nameof(HandleItemTransfers));
CurrentConfigState = (int)(CurrentConfigState == (int)RecyclerConfig.Default ? RecyclerConfig.Alternative : RecyclerConfig.Default);
List<(string Shortname, int Amount, float ConditionNormalized)> ExtractItemDetails(ItemContainer container) =>
container?.itemList?.Select(item => (item.info.shortname, item.amount, item.conditionNormalized)).ToList() ?? new List<(string, int, float)>();
var inputItemDetails = ExtractItemDetails(InputStorage.inventory);
var outputItemDetails = ExtractItemDetails(OutputStorage.inventory);
ClearExistingComponents();
UpdateAdapterPositions();
InitializeRecyclerComponents();
if (InputStorage == null || OutputStorage == null || Recycler == null)
{
Debug.LogError("Storage references were not updated.");
return;
}
foreach (var (shortname, amount, condition) in inputItemDetails)
CreateAndMoveItem(shortname, amount, condition, InputStorage.inventory);
foreach (var (shortname, amount, condition) in outputItemDetails)
CreateAndMoveItem(shortname, amount, condition, OutputStorage.inventory);
}
private void CreateAndMoveItem(string shortname, int amount, float conditionNormalized, ItemContainer container)
{
var item = ItemManager.CreateByName(shortname, amount);
if (item != null)
{
item.conditionNormalized = conditionNormalized;
if (!item.MoveToContainer(container))
item.Remove();
}
}
private void UpdateAdapterPositions()
{
ClearExistingComponents();
Vector3 inputOffset,
outputOffset,
inputAdapterOffset,
outputAdapterOffset;
Quaternion inputRotation,
outputRotation,
inputAdapterRotation,
outputAdapterRotation;
if (CurrentConfigState == (int)RecyclerConfig.Default)
{
inputOffset = new Vector3(0.0f, 0.72f, 0.11f);
outputOffset = new Vector3(-0.4f, 0.8f, 0.2f);
inputAdapterOffset = new Vector3(0.32f, -0.6f, -0.03f);
outputAdapterOffset = new Vector3(-0.07f, 0.535f, 0.397f);
inputRotation = Quaternion.Euler(0, 180, 191);
outputRotation = Quaternion.Euler(169, 90, 180);
inputAdapterRotation = Quaternion.Euler(0, 0, 0);
outputAdapterRotation = Quaternion.Euler(180, 90, 0);
}
else
{
if (_instance._config.HideStorageContainers)
{
inputOffset = new Vector3(0.0f, 0.72f, 0.11f);
outputOffset = new Vector3(-0.4f, 0.72f, 0.2f);
inputAdapterOffset = new Vector3(0.836f, -0.3301f, 0.18f);
outputAdapterOffset = new Vector3(-0.227f, 0.33f, 0.434f);
inputRotation = Quaternion.Euler(0, 0, 180);
outputRotation = Quaternion.Euler(180, 90, 180);
inputAdapterRotation = Quaternion.Euler(0, 0, 0);
outputAdapterRotation = Quaternion.Euler(180, 90, 0);
}
else
{
inputOffset = new Vector3(-1.0f, 0.72f, 0.31f);
outputOffset = new Vector3(-0.9f, 0.72f, -0.09f);
inputAdapterOffset = new Vector3(0.00f, -0.15f, -0.25f);
outputAdapterOffset = new Vector3(0.00f, 0.26f, -0.05f);
inputRotation = Quaternion.Euler(90, 90, 180);
outputRotation = Quaternion.Euler(180, 90, 180);
inputAdapterRotation = Quaternion.Euler(180, 90, 270);
outputAdapterRotation = Quaternion.Euler(0, 90, 0);
}
}
BasePlayer ownerPlayer = BasePlayer.FindByID(Recycler.OwnerID);
if (ownerPlayer != null)
{
var inputStorage = _instance.SpawnEntity(InputStoragePrefabPath, Recycler, ownerPlayer, inputOffset, inputRotation) as StorageContainer;
if (inputStorage == null)
{
Debug.LogError("Failed to spawn input storage.");
return;
}
_instance.SpawnEntity(AdapterPrefabPath, inputStorage, ownerPlayer, inputAdapterOffset, inputAdapterRotation);
var outputStorage = _instance.SpawnEntity(OutputStoragePrefabPath, Recycler, ownerPlayer, outputOffset, outputRotation) as StorageContainer;
if (outputStorage == null)
{
Debug.LogError("Failed to spawn output storage.");
return;
}
_instance.SpawnEntity(AdapterPrefabPath, outputStorage, ownerPlayer, outputAdapterOffset, outputAdapterRotation);
}
}
private void ClearExistingComponents()
{
foreach (var child in Recycler.children.ToList())
{
if (child is StorageContainer || child is IndustrialStorageAdaptor)
{
child.Kill();
}
}
}
internal void DropItems()
{
var allItems = GatherAllItems();
DropItemsInBatches(allItems, MaxStorageCapacity);
}
private List<Item> GatherAllItems()
{
return InputStorage.inventory.itemList.Concat(OutputStorage.inventory.itemList).Concat(Recycler.inventory.itemList).ToList();
}
private void DropItemsInBatches(List<Item> items, int batchSize)
{
var recyclerPosition = Recycler.transform.position;
var recyclerRotation = Recycler.transform.rotation;
for (int i = 0; i < items.Count; i += batchSize)
{
var itemBatch = items.Skip(i).Take(batchSize).ToList();
SpawnDroppedItemContainer(recyclerPosition, recyclerRotation, itemBatch);
}
}
private DroppedItemContainer SpawnDroppedItemContainer(Vector3 position, Quaternion rotation, List<Item> itemsToDrop)
{
var containerPrefabPath = "assets/prefabs/misc/item drop/item_drop.prefab";
var droppedItemContainer = GameManager.server.CreateEntity(containerPrefabPath, position, rotation) as DroppedItemContainer;
if (droppedItemContainer == null)
return null;
InitializeItemContainer(droppedItemContainer, itemsToDrop);
droppedItemContainer.Spawn();
return droppedItemContainer;
}
private void InitializeItemContainer(DroppedItemContainer container, List<Item> items)
{
container.inventory = new ItemContainer();
container.inventory.ServerInitialize(null, items.Count);
container.inventory.GiveUID();
container.inventory.entityOwner = container;
foreach (var item in items)
{
item.MoveToContainer(container.inventory);
}
}
private void OnDestroy()
{
CancelInvoke(nameof(HandleItemTransfers));
}
}
#endregion
}
}
Explanation:
CanLootStorage Method: This method checks if a player has the necessary access to loot a storage container attached to the recycler. It uses the same HasAccess logic to verify player permissions based on owner, team, or friendship.
Integration with existing Hooks: This method ensures players can only interact with storage containers if they have the right permissions, thereby extending the control from the recycler to its attached storages as well.
These changes add a layer of access control to the storage interactions, consistent with the overall permission system you wanted to implement. Let me know if there's anything else you need!
Key Points:
Config Check: Before accessing a configuration setting, check if it exists using Config.ContainsKey. If it doesn't exist, assign a default value to ensure it's not null.
configChanged Variable: Track if any changes are made to the configuration object to decide if it should be saved back to the file.
LoadDefaultConfig Method: This method sets up the default configuration values. Ensure it properly reflects the default settings you wish to have, especially after updates or additions to your configuration structure.
Implementing these changes ensures that new settings are initialized with default values, even if they don't exist in an older configuration file. This approach provides a seamless transition to using new configuration options without errors.
Explanation:
Check for Null: Use checks for default (null) values within the _config object itself to see if a key was explicitly defined in the loaded configuration. If it’s null, it means it wasn’t defined in the JSON file.
Set Default Values: When keys are missing (indicated by null values), set them to your desired defaults and mark the configuration as having changed so it can be saved back to the file.
Ensure Proper Loading: When calling Config.ReadObject<Configuration>(), all objects and lists should be initialized to their default values in GetDefaultConfig() to prevent null references.
This approach is more straightforward and leverages the properties of your Configuration class for defaults, ensuring backward compatibility with previous configuration files.
Explanation:
Version Check: As you load the configuration, check if the version read from the config file (_config.Version) is null or less than the current plugin version. If it is, set a flag to reload the configuration with updated defaults.
Update Defaults: If configurations that are new to the plugin version are missing, assign them default values. This step is essential to ensure backward compatibility.
Use HasValue Method: Since we're working with nullable types for booleans (to handle the absence in older config files), HasValue is used to check whether these settings exist in the current configuration.
Save Changes: If any default values were set or changed, save the configuration back to the disk to preserve the new standard for future loads.
This ensures that whenever you increment your plugin version, configuration files are auto-updated with new settings and values, maintaining compatibility and ease of maintenance.