using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Facepunch;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Oxide.Core;
using Oxide.Core.Configuration;
using Oxide.Core.Plugins;
using Rust;
using UnityEngine;
using Random = UnityEngine.Random;
This code is a plugin for the video game Rust, designed to create "Dungeon Events". It allows server administrators to generate dungeons with NPCs, turrets, and loot containers, providing a mechanism for players to engage in challenges within these dungeons.
Key Components of the Plugin:
Plugin Metadata: Contains basic information about the plugin such as name, author, and version.
Configuration Handling: The plugin defines configuration data used to manage dungeons. This includes settings for dungeon tiers (Easy, Normal, Medium, Hard, Nightmare), loot odds, and various spawn settings. The configuration also supports logging options and various parameters for creating the dungeons.
Dungeon Management:
The plugin manages a list of active dungeons on the server, tracking their state, including NPCs and other entities.
Admin commands allow for dungeon creation, removal of inactive dungeons, and forced cleanup of all dungeon entities.
Timers: Several timers are utilized:
Auto-spawning dungeons at specified intervals.
Regular checks on the status of dungeons.
Timers for updating markers on the map.
Scanning for valid spawn points for new dungeons.
Entity Management:
The plugin controls the spawning of various entities (NPCs and turrets) within the dungeon based on certain configurations.
Manage loot distribution through storage containers.
Handle damage interactions between players and NPCs or turrets, to ensure appropriate game mechanics.
NPC Spawn Configuration: The plugin defines how NPCs should behave and what equipment they spawn with, with configurations differing across dungeon tiers.
Utility Methods:
Helper methods for logging, checking player status, validation of positions for spawning, and notifications to players.
Dungeons: Each dungeon is defined by its position, type, configuration, and a list of spawned entities.
Localization: Message handling for in-game notifications and commands, allowing for customization of player feedback.
Physics Checks: Functions for validating whether a spawn point is safe and free from obstructions or other unwanted interactions.
Summary:
User
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.5.4")]
[Description("Automate recycling by attaching storage and adapters to recyclers.")]
class IndustrialRecycler : RustPlugin
{
#region PluginReferences
[PluginReference]
Plugin Friends;
#endregion
code
Assistant
The provided code is a Rust plugin named "IndustrialRecycler" developed for the game Rust. This plugin automates the recycling process in the game by allowing players to attach storage containers and adapters to recyclers. Below is a breakdown of the key components, features, and functionality present in the plugin.
Overview of the Plugin
Purpose: The plugin automates recycling processes by enabling players to connect storage to recyclers. It allows industrial and standard recyclers to function more effectively with item transfer handled automatically.
Commands: Players can use various commands to interact with the recyclers, including commands to give recyclers to players, upgrade recyclers, and open input/output storage interfaces.
Configuration: The plugin supports a configuration system, allowing server administrators to customize commands, limits on the number of recyclers per player, and permissions.
Permissions: Different permissions are used to restrict actions, allowing roles such as admins and VIPs to enjoy enhanced capabilities.
Key Components
Initialization and Configuration (Init, LoadConfig, LoadDefaultConfig): The plugin registers necessary permissions and sets up commands during initialization. It loads the configuration from a file to set up the commands and limits.
UI Handling: The code involves creating a Custom User Interface (CUI) for players when they interact with a recycler. This UI includes options for opening input and output storage.
Game Hooks: The plugin hooks into various game events such as item addition, entity building, item looting, and entity killing to handle recycling functionality.
Recycler Management:
The plugin checks if a recycler is industrial or standard by examining its configuration and components.
It manages the creation and attachment of storage components to the recycler, ensuring proper functioning.
Storage Management:
It includes methods for handling item transfers between input and output storages, starting or stopping the recycling process based on item availability.
Access Control
Permission System: The code employs a comprehensive permission system to govern access—enabling only certain players (like the owner or those in the same team or friends) to interact with specific recyclers.
User
quero ajustar DungeonEvents, para em OnPortalUse, permitir somente usuário, time e amigos como noIndustrialRecycler
quero também no DungeonEvents, coloca o nome do player no marcador do mapa, quando ele entrar na dungeon
Assistant
Para ajustar o plugin DungeonEvents conforme sua solicitação, serão feitas duas alterações:
Restrições de acesso ao portal: Modificaremos o método OnPortalUse para permitir apenas o dono do portal, os membros do time e os amigos do jogador que tenta usar o portal.
Nome do jogador no marcador do mapa: Nós iremos modificar o sistema de marcação no momento em que um jogador entrar na dungeon para incluir o nome do jogador no marcador.
Aqui estão as implementações dessas alterações:
1. Ajustando o OnPortalUse para Restrições de Acesso
No método OnPortalUse, adicione a verificação de acesso para a dungeon, ajustando-a para permitir apenas os amigos, membros do time ou o proprietário do portal.
csharp
private object OnPortalUse(BasePlayer player, BasePortal portal)
{
ActiveDungeon dungeon = GetDungeonByPortal(portal);
if (dungeon == null)
{
return null;
}
if (!HasAccess(player, portal))
{
Puts($"Player {player.displayName} tried to enter a dungeon without access.");
player?.ChatMessage(Msg(player.UserIDString, "NoAccess"));
return false;
}
if (!dungeon.Spawned)
{
Puts($"Player {player.displayName} tried to enter a dungeon that is still spawning.");
player?.ChatMessage(Msg(player.UserIDString, "DungeonStillSpawningMessage"));
return false;
}
return null;
}
private bool HasAccess(BasePlayer player, BaseEntity entity)
{
ulong ownerId = entity.OwnerID;
if (ownerId == player.userID || permission.UserHasPermission(player.UserIDString, PermissionAdmin))
return true;
// Check team access
if (_config.AllowTeamAccess && player.currentTeam != 0)
{
var team = RelationshipManager.ServerInstance.FindTeam(player.currentTeam);
if (team != null && team.members.Contains(ownerId))
return true;
}
// Check friends access using the Friends plugin
if (_config.AllowFriendsAccess && Friends != null)
{
bool areFriends = (bool)(Friends.CallHook("AreFriends", ownerId, player.userID) ?? false);
if (areFriends)
return true;
}
return false;
}
User
qual seria uma frase melhor: Lock dungeon to first player to enter
Assistant
Uma sugestão para uma frase mais clara e impactante seria:
"Tranque a masmorra para o primeiro jogador que entrar."
Outra alternativa que transmite a mesma ideia:
"Restrinja o acesso à masmorra ao primeiro jogador que a acessar."
Ambas as opções são diretas e comunicam bem a ideia de que apenas o primeiro jogador que entrar terá acesso à masmorra.
User
em ingles, para usar em uma config, preciso que seja bem curta
Assistant
Here are a few concise phrases in English that you can use for configuration:
"Lock dungeon to the first player."
"Dungeon locked to first entrant."
"First player locks dungeon."
"Lock to first player who enters."
"First player to enter locks dungeon."
Each of these options is short and clear for configuration purposes.
User
now for those:
[JsonProperty("Lock dungeon to the first player")]
public bool LockDungeonToPlayer { get; set; } = true;
code
[JsonProperty("Allow team members to enter Dungeon")]
public bool AllowTeamAccess { get; set; } = true;
[JsonProperty("Allow friends to enter Dungeon")]
public bool AllowFriendsAccess { get; set; } = true;
Assistant
For your JSON properties, here are concise phrases that will fit nicely for configuration:
csharp
[JsonProperty("Lock dungeon to first player")]
public bool LockDungeonToFirstPlayer { get; set; } = true;
[JsonProperty("Allow team members to enter dungeon")]
public bool AllowTeamAccess { get; set; } = true;
[JsonProperty("Allow friends to enter dungeon")]
public bool AllowFriendsAccess { get; set; } = true;
If you want to make the JSON property names even shorter while retaining their meanings, you could modify them as follows:
csharp
[JsonProperty("Lock dungeon for first player")]
public bool LockDungeonToFirstPlayer { get; set; } = true;
[JsonProperty("Allow team members")]
public bool AllowTeamAccess { get; set; } = true;
[JsonProperty("Allow friends access")]
public bool AllowFriendsAccess { get; set; } = true;
These changes maintain the clarity of each configuration setting while making them more concise.
User
fix this:
["NoAccess"] = "You dont have permission to enter this Dungeon",
Assistant
To improve the grammatical accuracy and clarity of the sentence, it should read:
csharp
["NoAccess"] = "You don't have permission to enter this dungeon."
Here are the corrections made:
Changed "dont" to "don't" to include the proper contraction.
Changed "Dungeon" to "dungeon" to maintain consistency with standard usage; typically, common nouns like "dungeon" are not capitalized unless at the beginning of a sentence.
Added a period at the end for punctuation.
Final Corrected Line:
csharp
["NoAccess"] = "You don't have permission to enter this dungeon."
User
crie traduções para portugues do brasil, espanhol, alemão e russo: protected override void LoadDefaultMessages()
{
lang.RegisterMessages(
new Dictionary<string, string>
{
["NoInactiveDungeonsToRemove"] = "There are no inactive dungeons to remove.",
["NoDungeonsToRemove"] = "There are no dungeons to remove.",
["DungeonRemovedDetail"] = "Removed dungeon of tier {0} at grid {1}.",
["AttemptSpawnDungeons"] = "Attempting to spawn dungeons.",
["DungeonAppeared"] = "A {0} Dungeon has appeared at grid {1}!",
["DungeonSpawnFailed"] = "Could not find a valid location to spawn a new dungeon.",
["DungeonSpawnedSuccess"] = "Dungeon spawned successfully at grid {0}!",
["MaxActiveDungeonsReached"] = "Cannot spawn: Maximum number of active dungeons reached.",
["DungeonStillSpawningMessage"] = "The dungeon is still spawning. Please wait until it's ready before entering.",
["NoAccess"] = "You don't have permission to enter this dungeon.",
},
this
);
}
Assistant
Aqui estão as traduções para português do Brasil, espanhol, alemão e russo:
The expression permission.UserHasPermission(player.UserIDString, PermissionAdmin) already returns a boolean value (true or false) based on whether the user has permission or not. Therefore, the use of the null coalescing operator (??) is unnecessary here.
You can simply fix it by returning the permission check directly. Here's the corrected line of code:
Removing the ?? false ensures that if UserHasPermission returns false (when the player does not have the permission), it is directly returned. There is no need to coalesce with false since UserHasPermission cannot return null.
This change will improve the clarity of your code and adhere to its intended functionality.
User
esta correta essa lógica?
private bool CanEnter(BasePlayer player, ActiveDungeon activeDungeon)
{
if (!permission.UserHasPermission(player.UserIDString, PermissionEnter) || !permission.UserHasPermission(player.UserIDString, PermissionAdmin))
return false;
code
if (activeDungeon.OwnerID == 0UL)
{
activeDungeon.OwnerID = player.userID;
activeDungeon.OwnerName = player.displayName;
return true;
}
if (activeDungeon.OwnerID == player.userID)
return true;
if (_config.AllowTeam && player.currentTeam != 0UL)
{
var team = RelationshipManager.ServerInstance.FindTeam(player.currentTeam);
if (team != null && team.members.Contains(activeDungeon.OwnerID))
return true;
}
if (_config.AllowFriends && Friends != null)
{
bool areFriends = (bool)(Friends.CallHook("AreFriends", activeDungeon.OwnerID, player.userID) ?? false);
if (areFriends)
return true;
}
return permission.UserHasPermission(player.UserIDString, PermissionAdmin);
}
Assistant
A lógica apresentada no método CanEnter parece ter alguns problemas lógicos e pode ser ajustada para funcionar corretamente conforme sua intenção. Analisemos a lógica passo a passo e apresentemos um código corrigido.
Problemas Identificados
Verificação de Permissão: A condição atual if (!permission.UserHasPermission(player.UserIDString, PermissionEnter) || !permission.UserHasPermission(player.UserIDString, PermissionAdmin)) significa que o jogador deve ter tanto a permissão de entrar quanto a de admin. Se o jogador não for admin, ele não poderá entrar, mesmo que tenha a permissão de entrada. Essa lógica pode ser um erro, já que provavelmente você quer que o jogador possa entrar se ele tem a permissão de entrada ou a permissão de admin.
Definindo Proprietário: O método define o proprietário da dungeon como o jogador quando activeDungeon.OwnerID é 0UL. Isso é um comportamento que deve ser revisado, pois não está claro se isso é intencional em todas as circunstâncias de uso do método.
Verificação de Membro do Time: A checagem de parentesco no time deveria ser feita após verificar se o jogador é o proprietário ou não.
Retorno de Permissão de Admin: No final do método, fazer a verificação novamente da permissão admin é redundante, já que isso já foi verificado antes.
Lógica Corrigida
Aqui está uma versão revisada do método:
csharp
User
como eu faria aqui somente:
if (!permission.UserHasPermission(player.UserIDString, PermissionEnter) || !permission.UserHasPermission(player.UserIDString, PermissionAdmin))
return false;
Assistant
Se você deseja alterar a lógica da condição para que o jogador possa entrar se tiver a permissão de entradaoutiver a permissão de admin, você deve usar o operador && ao invés de ||. Assim, a condição correta seria:
csharp
if (!permission.UserHasPermission(player.UserIDString, PermissionEnter) && !permission.UserHasPermission(player.UserIDString, PermissionAdmin))
return false;
Explicação
Operador &&: O uso do operador && (E lógico) verifica se ambas as condições são falsas. Ou seja, a condição agora retorna false somente se o jogador não tiver a permissão de entrada enão for um administrador.
Comportamento Esperado: Assim, se um jogador tiver qualquer uma das permissões (PermissionEnter ou PermissionAdmin), o código não retornará false, permitindo que o jogador entre.
Versão Final
Aqui está a lógica completa com a modificação:
csharp
private bool CanEnter(BasePlayer player, ActiveDungeon activeDungeon)
{
// Permite a entrada se o jogador tem permissão para entrar ou é admin
if (!permission.UserHasPermission(player.UserIDString, PermissionEnter) && !permission.UserHasPermission(player.UserIDString, PermissionAdmin))
return false;
// Resto da lógica...
}
Essa é a abordagem correta para garantir que os jogadores possam acessar a dungeon se tiverem pelo menos uma das permissões necessárias.
User
essa lógica agora está correta?
private bool CanEnter(BasePlayer player, ActiveDungeon activeDungeon)
{
if (!permission.UserHasPermission(player.UserIDString, PermissionEnter) && !permission.UserHasPermission(player.UserIDString, PermissionAdmin))
return false;
code
if (activeDungeon.OwnerID == 0UL)
{
activeDungeon.OwnerID = player.userID;
activeDungeon.OwnerName = player.displayName;
return true;
}
if (activeDungeon.OwnerID == player.userID)
return true;
if (_config.AllowTeam && player.currentTeam != 0UL)
{
var team = RelationshipManager.ServerInstance.FindTeam(player.currentTeam);
if (team != null && team.members.Contains(activeDungeon.OwnerID))
return true;
}
if (_config.AllowFriends && Friends != null)
{
bool areFriends = (bool)(Friends.CallHook("AreFriends", activeDungeon.OwnerID, player.userID) ?? false);
if (areFriends)
return true;
}
return permission.UserHasPermission(player.UserIDString, PermissionAdmin);
}
Assistant
A lógica implementada no método CanEnter está quase correta, mas ainda há um pequeno detalhe que pode ser ajustado para melhorar a clareza e a funcionalidade. Vamos revisar a lógica passo a passo:
Revisão da Lógica:
Verificação de Permissões:
A condição if (!permission.UserHasPermission(player.UserIDString, PermissionEnter) && !permission.UserHasPermission(player.UserIDString, PermissionAdmin)) está correta. O jogador pode entrar se tiver a permissão para entrar ou se for um admin. Se nenhum dos dois, retorna false.
Definindo Proprietário:
Se a OwnerID da activeDungeon for 0UL, você define o jogador como o proprietário da masmorra e retorna true, permitindo a entrada. Isso parece correto.
Verificação do Proprietário:
A verificação se o jogador é o proprietário da dungeon (if (activeDungeon.OwnerID == player.userID)) também está correta e permitirá a entrada do proprietário.
Verificação de Team:
A lógica para permitir a entrada dos membros do time do proprietário está correta.
Verificação de Amizade:
A verificação se o jogador é amigo do proprietário da dungeon também parece correta, assumindo que o plugin de amigos está em uso.
Retorno de Permissão de Admin:
A última linha return permission.UserHasPermission(player.UserIDString, PermissionAdmin); é um pouco redundante. Essa linha retorna true ou false com base na permissão de admin, mas isso já foi verificado antes. Você pode removê-la, pois o método já retorna false caso nenhuma das condições de acesso anteriores seja atendida.
Código Corrigido
Com essas considerações, o método pode ser simplificado como segue:
csharp
User
e se no caso o player tiver permission.UserHasPermission(player.UserIDString, PermissionEnter)
mas a dungeon for acessada por outro player antes, ele não pode entrar, mas se for admin quero que possa
Assistant
Para atender à sua necessidade de forma a permitir que um jogador que possui PermissionEnter entre na dungeon apenas se a dungeon não tiver sido acessada por outro jogador, enquanto um jogador com o PermissionAdmin sempre terá acesso, você pode modificar a lógica da seguinte forma:
Lógica Atualizada
O código agora deve verificar se a dungeon já tem um proprietário. Se o proprietário é diferente do jogador atual e se o jogador não tem permissão de administrador, a entrada deve ser negada.
Aqui está a versão ajustada do método:
csharp
private bool CanEnter(BasePlayer player, ActiveDungeon activeDungeon)
{
// Se o jogador não for admin, verifica se ele tem permissão de entrada
if (!permission.UserHasPermission(player.UserIDString, PermissionAdmin))
{
// Se o jogador não tem permissão para entrar
if (!permission.UserHasPermission(player.UserIDString, PermissionEnter))
return false;
// Se a dungeon já tiver um proprietário diferente do jogador
if (activeDungeon.OwnerID != 0UL && activeDungeon.OwnerID != player.userID)
return false; // Não pode entrar, porque a dungeon já foi acessada por outro jogador
}
// Se não houver um proprietário, define o jogador como o proprietário da dungeon
if (activeDungeon.OwnerID == 0UL)
{
activeDungeon.OwnerID = player.userID;
activeDungeon.OwnerName = player.displayName;
return true;
}
// Permite entrada se o jogador for o dono
if (activeDungeon.OwnerID == player.userID)
return true;
// Permite entrada para membros do time do proprietário
if (_config.AllowTeam && player.currentTeam != 0UL)
{
var team = RelationshipManager.ServerInstance.FindTeam(player.currentTeam);
if (team != null && team.members.Contains(activeDungeon.OwnerID))
return true;
}
// Permite entrada para amigos do proprietário
if (_config.AllowFriends && Friends != null)
{
bool areFriends = (bool)(Friends.CallHook("AreFriends", activeDungeon.OwnerID, player.userID) ?? false);
if (areFriends)
return true;
}
// Se nenhuma condição foi atendida, o jogador não pode entrar
return false;
}
User
mas então, a minha lógica anteriar não estava correta?
code
private bool CanEnter(BasePlayer player, ActiveDungeon activeDungeon)
{
if (!permission.UserHasPermission(player.UserIDString, PermissionEnter) && !permission.UserHasPermission(player.UserIDString, PermissionAdmin))
return false;
if (activeDungeon.OwnerID == 0UL)
{
activeDungeon.OwnerID = player.userID;
activeDungeon.OwnerName = player.displayName;
return true;
}
if (activeDungeon.OwnerID == player.userID)
return true;
if (_config.AllowTeam && player.currentTeam != 0UL)
{
var team = RelationshipManager.ServerInstance.FindTeam(player.currentTeam);
if (team != null && team.members.Contains(activeDungeon.OwnerID))
return true;
}
if (_config.AllowFriends && Friends != null)
{
bool areFriends = (bool)(Friends.CallHook("AreFriends", activeDungeon.OwnerID, player.userID) ?? false);
if (areFriends)
return true;
}
return permission.UserHasPermission(player.UserIDString, PermissionAdmin);
}
Assistant
A lógica anterior que você apresentou não estava completamente correta para o cenário que você descreveu, onde um jogador deve ter a permissão de entrada, mas só pode acessar a dungeon se ainda não houver um proprietário definido (ou seja, se ninguém tiver acessado antes). Vamos revisar e explicar os pontos que podem ser melhorados.
Problemas na Lógica Anterior
Verificação de Permissão: A linha original:
csharp
if (!permission.UserHasPermission(player.UserIDString, PermissionEnter) && !permission.UserHasPermission(player.UserIDString, PermissionAdmin))
return false;
Esta lógica requer que um jogador tenha tanto a permissão de entrada quanto a de admin. Você desejava que o jogador pudesse entrar se tivesse uma das permissões, não ambas. Isso foi corrigido na sugestão.
Definindo Proprietário: Na sua versão, o código definia o proprietário da dungeon se OwnerID for 0UL, mas não havia uma verificação se outro jogador já havia acessado a dungeon. Isso significa que qualquer jogador poderia acessar a dungeon, mesmo que ela já tivesse um proprietário definido. A lógica precisava garantir que apenas o administrador ou o proprietário tivesse acesso, enquanto um jogador normal não poderia entrar se já houvesse um proprietário.
Redundância: Ao final, a persistência da verificação de permissão de admin na linha return permission.UserHasPermission(player.UserIDString, PermissionAdmin); é desnecessária, pois essa lógica já havia sido abordada anteriormente.
Revisão de Lógica Proposta
Com base nesses problemas, a nova lógica sugerida se tornou mais concisa e efetiva. Aqui está um resumo da lógica atualizada que resolve os problemas mencionados:
This plugin adds depth to Rust's gameplay by introducing an engaging dungeon mechanic. Server administrators can create an immersive experience for players, offering challenges in the form of enemy NPCs and valuable loot, facilitating a richer multiplayer environment. The organization into classes and methods, along with proper logging and configuration, showcases a structured approach to developing game plugins that enhance player involvement.
#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 PermissionToggle = "industrialrecycler.toggle";
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 Data
private bool IsRecyclerIndustrial(Recycler recycler)
{
return recycler.GetComponentsInChildren<StorageContainer>().Any(sc => sc.PrefabName == InputStoragePrefabPath || sc.PrefabName == OutputStoragePrefabPath);
}
#endregion
#region Game Hooks
private void Init()
{
permission.RegisterPermission(PermissionUseRecycler, this);
permission.RegisterPermission(PermissionVip, this);
permission.RegisterPermission(PermissionAdmin, this);
permission.RegisterPermission(PermissionToggle, this);
CustomizeCommands();
}
private void CustomizeCommands()
{
foreach (var command in _config.RecyclerCommands)
{
cmd.AddChatCommand(command, this, nameof(CommandGetRecycler));
}
foreach (var command in _config.StandardRecyclerCommands)
{
cmd.AddChatCommand(command, this, nameof(CommandGetStandardRecycler));
}
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));
cmd.AddConsoleCommand("giveindustrialrecycler", this, nameof(ConsoleCommandGiveRecycler));
cmd.AddConsoleCommand("givestandardrecycler", this, nameof(ConsoleCommandGiveStandardRecycler));
}
private void OnServerInitialized()
{
_instance = this;
foreach (var recycler in UnityEngine.Object.FindObjectsOfType<Recycler>())
{
if (recycler.OwnerID != 0UL && IsRecyclerIndustrial(recycler))
{
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)
return;
if (baseEntity.skinID != _config.RecyclerSkinId && baseEntity.skinID != _config.StandardRecyclerSkinId)
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, baseEntity.skinID == _config.StandardRecyclerSkinId));
NextTick(() => baseEntity?.Kill());
return;
}
if (!InitializeRecyclerPlacement(player, baseEntity))
{
player.ChatMessage(lang.GetMessage("InvalidPlacement", this, player.UserIDString));
timer.Once(1, () => GiveRecyclerItem(player, baseEntity.skinID == _config.StandardRecyclerSkinId));
}
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, false);
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 object CanLootEntity(BasePlayer player, Recycler recycler)
{
if (recycler.OwnerID != 0UL && _recyclerOwners.ContainsKey(recycler.net.ID.Value) && !HasAccess(player, recycler))
{
player.ChatMessage(lang.GetMessage("NoAccess", this, player.UserIDString));
return false;
}
return null;
}
private object CanLootEntity(BasePlayer player, StorageContainer storage)
{
Recycler recycler = storage.GetParentEntity() as Recycler;
if (recycler != null && recycler.OwnerID != 0UL && _recyclerOwners.ContainsKey(recycler.net.ID.Value) && !HasAccess(player, recycler))
{
player.ChatMessage(lang.GetMessage("NoAccess", this, player.UserIDString));
return false;
}
return null;
}
private void OnLootEntity(BasePlayer player, Recycler recycler)
{
if (recycler.OwnerID != 0UL && _recyclerOwners.ContainsKey(recycler.net.ID.Value) && IsRecyclerIndustrial(recycler))
{
_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);
}
}
object OnHammerHit(BasePlayer player, HitInfo hitInfo)
{
Recycler recycler = hitInfo?.HitEntity as Recycler;
if (recycler == null || recycler.OwnerID == 0)
return null;
if (!HasAccess(player, recycler))
{
player.ChatMessage(lang.GetMessage("NoAccess", this, player.UserIDString));
return null;
}
bool isIndustrial = IsRecyclerIndustrial(recycler);
DropRecyclerItems(recycler);
recycler.Kill();
GiveRecyclerItem(player, !isIndustrial);
player.ChatMessage(lang.GetMessage("RecyclerPickedUp", this, player.UserIDString));
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"
);
if (permission.UserHasPermission(player.UserIDString, PermissionToggle))
{
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 ConsoleCommandGiveRecycler(ConsoleSystem.Arg arg)
{
if (arg.Args.Length == 0)
{
return;
}
if (!ulong.TryParse(arg.Args[0], out ulong userId))
{
return;
}
var targetPlayer = BasePlayer.FindByID(userId);
if (targetPlayer == null)
{
Puts("Player Not Found");
return;
}
GiveRecyclerItem(targetPlayer, false);
}
private void ConsoleCommandGiveStandardRecycler(ConsoleSystem.Arg arg)
{
if (arg.Args.Length == 0)
{
return;
}
if (!ulong.TryParse(arg.Args[0], out ulong userId))
{
return;
}
var targetPlayer = BasePlayer.FindByID(userId);
if (targetPlayer == null)
{
Puts("Player Not Found");
return;
}
GiveRecyclerItem(targetPlayer, true);
}
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, false))
{
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, bool isStandard)
{
ulong skinId = isStandard ? _config.StandardRecyclerSkinId : _config.RecyclerSkinId;
var recyclerItem = ItemManager.CreateByName(ItemName, 1, skinId);
if (recyclerItem == null)
return false;
recyclerItem.name = isStandard ? "Standard Recycler" : "Industrial Recycler";
return player.inventory.GiveItem(recyclerItem);
}
private void CommandGetStandardRecycler(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, true))
{
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 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 Recycler SetupStandardRecycler(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;
recycler.OwnerID = player.userID;
_instance._recyclerOwners[recycler.net.ID.Value] = recycler.OwnerID;
return recycler;
}
private bool InitializeRecyclerPlacement(BasePlayer player, BaseEntity baseEntity, int turn = 0)
{
var supportingFoundation = FindSupportingFoundation(baseEntity);
if (supportingFoundation == null)
return false;
Recycler spawnedRecycler;
if (baseEntity.skinID == _config.StandardRecyclerSkinId)
{
spawnedRecycler = SetupStandardRecycler(player, baseEntity, supportingFoundation, turn);
}
else if (baseEntity.skinID == _config.RecyclerSkinId)
{
spawnedRecycler = SpawnRecyclerWithComponents(player, baseEntity, supportingFoundation, turn);
}
else
{
return false;
}
if (spawnedRecycler != null && baseEntity.skinID == _config.RecyclerSkinId)
{
spawnedRecycler.gameObject.AddComponent<RecyclerComponent>();
}
return spawnedRecycler != null;
}
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 && !IsRecyclerIndustrial(recycler))
{
if (!InitializeUpgradeRecycler(player, recycler, 90))
{
player.ChatMessage(lang.GetMessage("InvalidPlacement", this, player.UserIDString));
timer.Once(1, () => GiveRecyclerItem(player, true));
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, PermissionToggle))
{
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 Item Dropping
private void DropRecyclerItems(Recycler recycler)
{
if (recycler == null || recycler.inventory == null)
return;
List<Item> itemsToDrop;
var recyclerComponent = recycler.GetComponent<RecyclerComponent>();
if (recyclerComponent == null)
{
itemsToDrop = new List<Item>(recycler.inventory.itemList);
}
else
{
itemsToDrop = recyclerComponent.GatherAllItems();
}
Vector3 position = recycler.transform.position;
Quaternion rotation = recycler.transform.rotation;
foreach (var item in itemsToDrop)
{
item.RemoveFromContainer();
}
for (int i = 0; i < itemsToDrop.Count; i += 6)
{
var batch = itemsToDrop.Skip(i).Take(6).ToList();
SpawnDroppedItemContainer(position, rotation, batch);
}
}
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)
{
if (!item.MoveToContainer(container.inventory))
item.Remove();
}
}
#endregion
#region Configuration
private class Configuration
{
[JsonProperty("Recycler Commands")]
public List<string> RecyclerCommands { get; set; }
[JsonProperty("Standard Recycler Commands")]
public List<string> StandardRecyclerCommands { 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("Standard Recycler SkinId")]
public ulong StandardRecyclerSkinId { 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 == null || _config.Version < Version)
{
PrintWarning("Updating configuration file to new version.");
_config.Version = Version;
_config.OnlyOwnerAccess = true;
_config.AllowTeamAccess = true;
_config.AllowFriendsAccess = true;
_config.StandardRecyclerSkinId = 3363257468;
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.RecyclerCommands == null)
{
_config.RecyclerCommands = new List<string> { "irecycler", "giverecycler" };
configChanged = true;
}
if (_config.StandardRecyclerCommands == null)
{
_config.StandardRecyclerCommands = new List<string> { "getstandardrecycler" };
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();
}
}
protected override void LoadDefaultConfig()
{
_config = GetDefaultConfig();
SaveConfig();
}
protected override void SaveConfig()
{
Config.WriteObject(_config, true);
}
private Configuration GetDefaultConfig()
{
return new Configuration
{
RecyclerCommands = new List<string> { "getrecycler", "irecycler", "giverecycler" },
StandardRecyclerCommands = new List<string> { "getstandardrecycler" },
MaxRecyclersPerPlayer = 1,
MaxRecyclersVip = 2,
RecyclerSkinId = 3357927081,
StandardRecyclerSkinId = 3363257468,
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.",
["StandardRecyclerGiven"] = "Standard recycler added to your inventory.",
["StandardRecyclerNotGiven"] = "Failed to give standard 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.",
["StandardRecyclerGiven"] = "Reciclador padrão adicionado ao seu inventário.",
["StandardRecyclerNotGiven"] = "Falha ao fornecer o reciclador padrão.",
},
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.",
["StandardRecyclerGiven"] = "Standard-Recycler wurde Ihrem Inventar hinzugefügt.",
["StandardRecyclerNotGiven"] = "Standard-Recycler konnte nicht gegeben werden.",
},
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.",
["StandardRecyclerGiven"] = "Reciclador estándar añadido a tu inventario.",
["StandardRecyclerNotGiven"] = "Error al entregar el reciclador estándar.",
},
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 || !_instance.IsRecyclerIndustrial(Recycler))
{
enabled = false;
return;
}
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())
{
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)
{
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)
{
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)
{
return;
}
_instance.SpawnEntity(AdapterPrefabPath, inputStorage, ownerPlayer, inputAdapterOffset, inputAdapterRotation);
var outputStorage = _instance.SpawnEntity(OutputStoragePrefabPath, Recycler, ownerPlayer, outputOffset, outputRotation) as StorageContainer;
if (outputStorage == null)
{
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()
{
_instance.DropRecyclerItems(Recycler);
}
public List<Item> GatherAllItems()
{
if (InputStorage == null || InputStorage.inventory == null)
{
return new List<Item>();
}
if (OutputStorage == null || OutputStorage.inventory == null)
{
return new List<Item>();
}
if (Recycler == null || Recycler.inventory == null)
{
return new List<Item>();
}
return InputStorage.inventory.itemList.Concat(OutputStorage.inventory.itemList).Concat(Recycler.inventory.itemList).ToList();
}
private void OnDestroy()
{
CancelInvoke(nameof(HandleItemTransfers));
}
}
#endregion
}
}
Functionality
Giving Recyclers: Players can receive recyclers through specific commands, which are controlled by permissions.
Upgrading Recyclers: Players can upgrade existing recyclers to their industrial variants if they have the required permissions and items in view.
Storage Handling: For each recycler, the plugin maintains two storage containers: one for input items and the other for output items. These storage units interact with the recycler automatically.
Item Dropping: Upon removal or destruction of a recycler, the plugin ensures that all contained items are dropped or returned to the player's inventory.
Messaging: The plugin provides informative messages to players, informing them of errors, permissions, or actions taken regarding their recyclers.
Example Commands
/giverecycler: Give a recycler to a specified player.
/getstandardrecycler: Similar command for giving a standard recycler.
/upgraderecycler: Upgrade a standard recycler to an industrial recycler.
/togglerecycler: Toggle the configuration settings for the recycler.
Localization
The plugin includes localization support, allowing messages to be displayed in multiple languages, improving accessibility for players speaking different languages.
Conclusion
Overall, the "IndustrialRecycler" plugin enhances the gameplay experience in Rust by introducing automated recycling, improving efficiency for players, and providing a customizable and flexible system for server administrators. It showcases good programming practices such as modularization, the use of a permission system, and effective user feedback through messages and UI elements.
2. Colocando o Nome do Jogador no Marcador do Mapa
No método que cria os marcadores do mapa, você pode utilizar o nome do jogador no nome do marcador. Isso deve ser feito em NotifyPlayersOfNewDungeon.
csharp
private void NotifyPlayersOfNewDungeon(ActiveDungeon activeDungeon)
{
foreach (var player in BasePlayer.activePlayerList)
{
var message = Msg(player.UserIDString, "DungeonAppeared", activeDungeon.TierName, activeDungeon.Grid);
// Incluindo o nome do jogador no nome do marcador
var playerName = player.displayName;
var markerName = $"Dungeon: {activeDungeon.TierName} (by {playerName})";
// Substituir o código para criação do marcador para usar markerName
var vendingMarker = CreateMapMarker<VendingMachineMapMarker>(prefabVendingMarker, activeDungeon.Position);
vendingMarker.OwnerID = OwnerID;
vendingMarker.markerShopName = markerName; // Renomeado para incluir o jogador
vendingMarker.SendNetworkUpdate();
if (_configData.EnableShowToast)
{
player.ShowToast(GameTip.Styles.Blue_Normal, message);
}
}
}
Resumo das Alterações
O método OnPortalUse agora verifica se o jogador tem acesso ao portal com base em sua afiliação de equipe ou amizade.
No método NotifyPlayersOfNewDungeon, modificamos o nome do marcador para incluir o nome do jogador que acessou a dungeon.
Essas modificações garantirão que apenas usuários autorizados possam acessar as dungeons e apresentarão os marcadores do mapa de maneira mais informativa durante o jogo.
protected override void LoadDefaultMessages()
{
lang.RegisterMessages(
new Dictionary<string, string>
{
// English
["NoInactiveDungeonsToRemove"] = "There are no inactive dungeons to remove.",
["NoDungeonsToRemove"] = "There are no dungeons to remove.",
["DungeonRemovedDetail"] = "Removed dungeon of tier {0} at grid {1}.",
["AttemptSpawnDungeons"] = "Attempting to spawn dungeons.",
["DungeonAppeared"] = "A {0} Dungeon has appeared at grid {1}!",
["DungeonSpawnFailed"] = "Could not find a valid location to spawn a new dungeon.",
["DungeonSpawnedSuccess"] = "Dungeon spawned successfully at grid {0}!",
["MaxActiveDungeonsReached"] = "Cannot spawn: Maximum number of active dungeons reached.",
["DungeonStillSpawningMessage"] = "The dungeon is still spawning. Please wait until it's ready before entering.",
["NoAccess"] = "You don't have permission to enter this dungeon.",
// Portuguese (Brazil)
["NoInactiveDungeonsToRemove_pt"] = "Não há masmorras inativas para remover.",
["NoDungeonsToRemove_pt"] = "Não há masmorras para remover.",
["DungeonRemovedDetail_pt"] = "Masmorra de nível {0} removida na grade {1}.",
["AttemptSpawnDungeons_pt"] = "Tentando gerar masmorras.",
["DungeonAppeared_pt"] = "Uma masmorra {0} apareceu na grade {1}!",
["DungeonSpawnFailed_pt"] = "Não foi possível encontrar um local válido para gerar uma nova masmorra.",
["DungeonSpawnedSuccess_pt"] = "Masmorra gerada com sucesso na grade {0}!",
["MaxActiveDungeonsReached_pt"] = "Não é possível gerar: Número máximo de masmorras ativas atingido.",
["DungeonStillSpawningMessage_pt"] = "A masmorra ainda está sendo gerada. Por favor, aguarde até que esteja pronta antes de entrar.",
["NoAccess_pt"] = "Você não tem permissão para entrar nesta masmorra.",
// Spanish
["NoInactiveDungeonsToRemove_es"] = "No hay mazmorras inactivas para eliminar.",
["NoDungeonsToRemove_es"] = "No hay mazmorras para eliminar.",
["DungeonRemovedDetail_es"] = "Mazmorras de nivel {0} eliminada en la cuadrícula {1}.",
["AttemptSpawnDungeons_es"] = "Intentando generar mazmorras.",
["DungeonAppeared_es"] = "¡Una mazmorras {0} ha aparecido en la cuadrícula {1}!",
["DungeonSpawnFailed_es"] = "No se pudo encontrar un lugar válido para generar una nueva mazmorras.",
["DungeonSpawnedSuccess_es"] = "Mazmorras generada con éxito en la cuadrícula {0}!",
["MaxActiveDungeonsReached_es"] = "No se puede generar: Se alcanzó el número máximo de mazmorras activas.",
["DungeonStillSpawningMessage_es"] = "La mazmorras aún se está generando. Por favor, espera a que esté lista antes de entrar.",
["NoAccess_es"] = "No tienes permiso para entrar en esta mazmorras.",
// German
["NoInactiveDungeonsToRemove_de"] = "Es gibt keine inaktiven Verliese zu entfernen.",
["NoDungeonsToRemove_de"] = "Es gibt keine Verliese zu entfernen.",
["DungeonRemovedDetail_de"] = "Verlies der Stufe {0} bei Raster {1} entfernt.",
["AttemptSpawnDungeons_de"] = "Versuche, Verliese zu spawnen.",
["DungeonAppeared_de"] = "Ein {0} Verlies ist bei Raster {1} erschienen!",
["DungeonSpawnFailed_de"] = "Konnte keinen gültigen Standort für das Spawn eines neuen Verliese finden.",
["DungeonSpawnedSuccess_de"] = "Verlies erfolgreich bei Raster {0} gespawnt!",
["MaxActiveDungeonsReached_de"] = "Kann nicht spawnen: Maximale Anzahl aktiver Verliese erreicht.",
["DungeonStillSpawningMessage_de"] = "Das Verlies wird noch gespawnt. Bitte warten Sie, bis es bereit ist, bevor Sie eintreten.",
["NoAccess_de"] = "Sie haben keine Erlaubnis, dieses Verlies zu betreten.",
// Russian
["NoInactiveDungeonsToRemove_ru"] = "Нет неактивных подземелий для удаления.",
["NoDungeonsToRemove_ru"] = "Нет подземелий для удаления.",
["DungeonRemovedDetail_ru"] = "Удалено подземелье уровня {0} на сетке {1}.",
["AttemptSpawnDungeons_ru"] = "Попытка создать подземелья.",
["DungeonAppeared_ru"] = "Появилось подземелье {0} на сетке {1}!",
["DungeonSpawnFailed_ru"] = "Не удалось найти подходящее место для создания нового подземелья.",
["DungeonSpawnedSuccess_ru"] = "Подземелье успешно создано на сетке {0}!",
["MaxActiveDungeonsReached_ru"] = "Невозможно создать: Достигнуто максимальное количество активных подземелий.",
["DungeonStillSpawningMessage_ru"] = "Подземелье все еще создается. Пожалуйста, подождите, пока оно не будет готово, прежде чем входить.",
["NoAccess_ru"] = "У вас нет разрешения на вход в это подземелье.",
},
this
);
}
Resumo das Traduções:
O texto foi traduzido para os idiomas solicitados, mantendo o sentido original das mensagens.
As chaves de tradução foram criadas com sufixos (_pt, _es, _de, _ru) para cada idioma, permitindo a fácil identificação e utilização em diferentes configurações de idioma.
Sinta-se à vontade para ajustar qualquer uma das traduções de acordo com seu contexto específico ou preferências de estilo!
private bool CanEnter(BasePlayer player, ActiveDungeon activeDungeon)
{
// Permite a entrada se o jogador tem permissão ou é admin
if (permission.UserHasPermission(player.UserIDString, PermissionEnter) || permission.UserHasPermission(player.UserIDString, PermissionAdmin))
{
// Se a dungeon não tem dono, define o jogador como dono
if (activeDungeon.OwnerID == 0UL)
{
activeDungeon.OwnerID = player.userID;
activeDungeon.OwnerName = player.displayName;
return true;
}
// Permite entrada se o jogador for o dono
if (activeDungeon.OwnerID == player.userID)
return true;
// Permite a entrada se o jogador for membro do time do dono
if (_config.AllowTeam && player.currentTeam != 0UL)
{
var team = RelationshipManager.ServerInstance.FindTeam(player.currentTeam);
if (team != null && team.members.Contains(activeDungeon.OwnerID))
return true;
}
// Permite a entrada se o jogador for amigo do dono
if (_config.AllowFriends && Friends != null)
{
bool areFriends = (bool)(Friends.CallHook("AreFriends", activeDungeon.OwnerID, player.userID) ?? false);
if (areFriends)
return true;
}
}
// Retorna false se não atender a nenhuma das condições
return false;
}
Alterações Realizadas
Correção nas Verificações de Permissão: O jogador agora pode entrar se tiver a PermissionEnter ou PermissionAdmin.
Definindo Proprietário de forma Clara: Mantemos a lógica para definir o proprietário de forma consistente, apenas se OwnerID estiver definido como 0UL.
Reorganização da Lógica: A sequência das verificações foi alterada para melhor legibilidade e lógica.
Essa versão oferece um controle mais claro sobre as permissões e acesso às dungeons, permitindo que jogadores tenham um acesso mais flexível.
private bool CanEnter(BasePlayer player, ActiveDungeon activeDungeon)
{
// Verifica se o jogador tem permissão para entrar ou é admin
if (!permission.UserHasPermission(player.UserIDString, PermissionEnter) && !permission.UserHasPermission(player.UserIDString, PermissionAdmin))
return false;
// Se não houver um proprietário, define o jogador como o proprietário da dungeon
if (activeDungeon.OwnerID == 0UL)
{
activeDungeon.OwnerID = player.userID;
activeDungeon.OwnerName = player.displayName;
return true;
}
// Permite entrada se o jogador for o dono
if (activeDungeon.OwnerID == player.userID)
return true;
// Permite entrada para membros do time do proprietário
if (_config.AllowTeam && player.currentTeam != 0UL)
{
var team = RelationshipManager.ServerInstance.FindTeam(player.currentTeam);
if (team != null && team.members.Contains(activeDungeon.OwnerID))
return true;
}
// Permite entrada para amigos do proprietário
if (_config.AllowFriends && Friends != null)
{
bool areFriends = (bool)(Friends.CallHook("AreFriends", activeDungeon.OwnerID, player.userID) ?? false);
if (areFriends)
return true;
}
// Se nenhuma condição foi atendida, o jogador não pode entrar
return false;
}
Resumo
O método agora verifica se o jogador tem permissão de entrada ou é um admin, define o proprietário adequadamente e permite a entrada com base nas condições de equipe e amizade.
A verificação de permissões de admin foi removida da última linha, pois já é tratada anteriormente. As condições de acesso são agora mais claras e o fluxo do método é mais lógico.
Explicação das Alterações
Permissão de Admin: A primeira verificação agora se assegura de que, se o jogador não é um administrador, ele deve passar nas verificações de permissão para entrar.
Verificação de Proprietário: Nessa lógica, se a dungeon já tiver um proprietário (ou seja, OwnerID distinto de 0UL), o jogador só poderá entrar se ele for o proprietário ou se tiver a permissão de admin.
Regras de Acesso: Caso contrário, se o jogador com PermissionEnter tentar acessar a dungeon que já foi acessada por outro jogador, o acesso é negado.
Comportamento Final
Com essas modificações:
Apenas o primeiro jogador a acessar a dungeon se tornará o proprietário.
Um jogador não poderá entrar na dungeon se já houver um proprietário, a menos que seja um administrador.
Os membros da equipe e amigos poderão acessar, conforme configurado.
Essa lógica atende à sua solicitação de resguardar o acesso à dungeon, permitindo exceções apenas para administradores.
private bool CanEnter(BasePlayer player, ActiveDungeon activeDungeon)
{
// Permitir que jogadores admin e com permissão de entrada acessem
if (!permission.UserHasPermission(player.UserIDString, PermissionAdmin))
{
// Se não tem permissão para entrar e não é admin, negue a entrada
if (!permission.UserHasPermission(player.UserIDString, PermissionEnter))
return false;
// Se já houver um proprietário, negue a entrada
if (activeDungeon.OwnerID != 0UL && activeDungeon.OwnerID != player.userID)
return false; // Proprietário diferente impede a entrada
}
// Se não houver um proprietário, define o jogador como o proprietário
if (activeDungeon.OwnerID == 0UL)
{
activeDungeon.OwnerID = player.userID;
activeDungeon.OwnerName = player.displayName;
return true;
}
// Permitindo o acesso se o jogador for o proprietário
if (activeDungeon.OwnerID == player.userID)
return true;
// Permite a entrada se o jogador for membro do time do proprietário
if (_config.AllowTeam && player.currentTeam != 0UL)
{
var team = RelationshipManager.ServerInstance.FindTeam(player.currentTeam);
if (team != null && team.members.Contains(activeDungeon.OwnerID))
return true;
}
// Permite a entrada se o jogador for amigo do proprietário
if (_config.AllowFriends && Friends != null)
{
bool areFriends = (bool)(Friends.CallHook("AreFriends", activeDungeon.OwnerID, player.userID) ?? false);
if (areFriends)
return true;
}
// Se nenhuma condição foi atendida, o jogador não pode entrar
return false;
}
Conclusão
Correções Feitas: A lógica agora permite que jogadores entrem se não houver um proprietário atual (ou se forem o proprietário), ao mesmo tempo que ainda honra as permissões de admin.
Condições Claras: As condições agora estão organizadas de maneira que cada uma se encaixa na intenção do acesso à dungeon, permitindo uma experiência de jogo mais clara e justa.
Essa revisão melhora a segurança ao acessar as dungeons e permite que você atenda aos requisitos que você tinha em mente originalmente.