mirror of
https://github.com/Cubicake/RaycastedAntiESP.git
synced 2026-11-17 06:26:04 -05:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2d07b595d7 |
No files matched your search
+2
-2
@@ -3,7 +3,7 @@
|
||||
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
|
||||
patreon: # Replace with a single Patreon username
|
||||
open_collective: # Replace with a single Open Collective username
|
||||
ko_fi: #cubicake
|
||||
ko_fi: cubicake
|
||||
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
|
||||
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
|
||||
liberapay: # Replace with a single Liberapay username
|
||||
@@ -12,4 +12,4 @@ lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cl
|
||||
polar: # Replace with a single Polar username
|
||||
buy_me_a_coffee: # Replace with a single Buy Me a Coffee username
|
||||
thanks_dev: # Replace with a single thanks.dev username
|
||||
custom: ['https://cubi.games/donate/variable']# Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
|
||||
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
|
||||
@@ -122,5 +122,3 @@ run*/
|
||||
|
||||
# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
|
||||
!gradle-wrapper.jar
|
||||
# Libraries are supposed to be committed
|
||||
!libraries/*/*
|
||||
@@ -1 +0,0 @@
|
||||
extra["patchedConfigurateYaml"] = files("libraries/configurate-yaml/yaml-4.3.0-SNAPSHOT-cubi.jar")
|
||||
@@ -7,14 +7,11 @@
|
||||
*/
|
||||
|
||||
import java.time.Instant
|
||||
import org.gradle.api.file.FileCollection
|
||||
|
||||
plugins {
|
||||
id("java-library")
|
||||
}
|
||||
|
||||
val patchedConfigurateYaml = rootProject.extra["patchedConfigurateYaml"] as FileCollection
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
maven { url = uri("https://repo.codemc.io/repository/maven-releases/") }
|
||||
@@ -23,7 +20,7 @@ repositories {
|
||||
|
||||
dependencies {
|
||||
compileOnly("org.spongepowered:configurate-core:4.2.0")
|
||||
compileOnly(patchedConfigurateYaml)
|
||||
compileOnly("org.spongepowered:configurate-yaml:4.2.0")
|
||||
compileOnly("it.unimi.dsi:fastutil:8.5.18")
|
||||
|
||||
implementation(project(":locatables"))
|
||||
@@ -36,7 +33,6 @@ dependencies {
|
||||
testImplementation(project(":leafpile"))
|
||||
testImplementation(project(":logging"))
|
||||
testImplementation("org.spongepowered:configurate-core:4.2.0")
|
||||
testImplementation(patchedConfigurateYaml)
|
||||
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine")
|
||||
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
|
||||
testImplementation("it.unimi.dsi:fastutil:8.5.18")
|
||||
|
||||
+14
-10
@@ -8,15 +8,19 @@
|
||||
|
||||
package games.cubi.raycastedantiesp.core.config;
|
||||
|
||||
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
|
||||
import org.spongepowered.configurate.objectmapping.meta.Comment;
|
||||
import org.spongepowered.configurate.ConfigurationNode;
|
||||
|
||||
@ConfigSerializable
|
||||
public record BlockProcessorConfig(
|
||||
@Comment("Block processor implementation used by the plugin.")
|
||||
BlockProcessorMode mode,
|
||||
@Comment("Track every block rather than only tile entities.")
|
||||
boolean trackAllBlocks
|
||||
) implements Config {
|
||||
public static final BlockProcessorConfig DEFAULT = new BlockProcessorConfig(BlockProcessorMode.PACKETEVENTS, false);
|
||||
public record BlockProcessorConfig(BlockProcessorMode mode, boolean trackAllBlocks) implements Config {
|
||||
public static BlockProcessorConfig load(ConfigurationNode root) {
|
||||
ConfigurationNode node = ConfigReader.node(root, "block-processor");
|
||||
String modeName = ConfigReader.string(ConfigReader.node(node, "mode"), "block-processor.mode");
|
||||
BlockProcessorMode mode = BlockProcessorMode.fromString(modeName);
|
||||
if (mode == null) {
|
||||
throw new ConfigLoadException("block-processor.mode has unsupported value '" + modeName + "'");
|
||||
}
|
||||
return new BlockProcessorConfig(
|
||||
mode,
|
||||
ConfigReader.bool(ConfigReader.node(node, "track-all-blocks"), "block-processor.track-all-blocks")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -13,24 +13,19 @@ import games.cubi.raycastedantiesp.core.config.raycast.EntityConfig;
|
||||
import games.cubi.raycastedantiesp.core.config.raycast.PlayerConfig;
|
||||
import games.cubi.raycastedantiesp.core.config.raycast.SoundEffectsConfig;
|
||||
import games.cubi.raycastedantiesp.core.config.raycast.TileEntityConfig;
|
||||
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
|
||||
import org.spongepowered.configurate.objectmapping.meta.Setting;
|
||||
import org.spongepowered.configurate.ConfigurationNode;
|
||||
|
||||
@ConfigSerializable
|
||||
public record ChecksConfig(
|
||||
@Setting("player") PlayerConfig playerConfig,
|
||||
@Setting("entity") EntityConfig entityConfig,
|
||||
@Setting("tile-entity") TileEntityConfig tileEntityConfig,
|
||||
@Setting("sound-effects") SoundEffectsConfig soundEffectsConfig,
|
||||
@Setting("chunk-section") ChunkSectionConfig chunkSectionConfig
|
||||
) implements Config {
|
||||
public static final ChecksConfig DEFAULT = new ChecksConfig(
|
||||
PlayerConfig.DEFAULT,
|
||||
EntityConfig.DEFAULT,
|
||||
TileEntityConfig.DEFAULT,
|
||||
SoundEffectsConfig.DEFAULT,
|
||||
ChunkSectionConfig.DEFAULT
|
||||
);
|
||||
public record ChecksConfig(PlayerConfig playerConfig, EntityConfig entityConfig, TileEntityConfig tileEntityConfig, SoundEffectsConfig soundEffectsConfig, ChunkSectionConfig chunkSectionConfig) implements Config {
|
||||
public static ChecksConfig load(ConfigurationNode root) {
|
||||
ConfigurationNode checks = ConfigReader.node(root, "checks");
|
||||
return new ChecksConfig(
|
||||
PlayerConfig.load(ConfigReader.node(checks, "player"), "checks.player"),
|
||||
EntityConfig.load(ConfigReader.node(checks, "entity"), "checks.entity"),
|
||||
TileEntityConfig.load(ConfigReader.node(checks, "tile-entity"), "checks.tile-entity"),
|
||||
SoundEffectsConfig.load(ConfigReader.node(checks, "sound-effects"), "checks.sound-effects"),
|
||||
ChunkSectionConfig.load(ConfigReader.node(checks, "chunk-section"), "checks.chunk-section")
|
||||
);
|
||||
}
|
||||
|
||||
public boolean hasEnabledStatusChanges(ChecksConfig startup) {
|
||||
return playerConfig.enabled() != startup.playerConfig.enabled()
|
||||
|
||||
@@ -1,327 +0,0 @@
|
||||
package games.cubi.raycastedantiesp.core.config;
|
||||
|
||||
import org.spongepowered.configurate.CommentedConfigurationNode;
|
||||
import org.spongepowered.configurate.ConfigurationNode;
|
||||
import org.spongepowered.configurate.NodePath;
|
||||
import org.spongepowered.configurate.serialize.SerializationException;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* A mutable configuration under preparation, separate from the active runtime snapshot.
|
||||
* Used only during a load or edit; ConfigManager owns synchronization, persistence, and publication.
|
||||
*/
|
||||
final class ConfigCandidate {
|
||||
private final CommentedConfigurationNode node;
|
||||
private final CommentedConfigurationNode defaults;
|
||||
private final List<Repair> repairs = new ArrayList<>();
|
||||
private boolean dirty;
|
||||
|
||||
ConfigCandidate(CommentedConfigurationNode node, CommentedConfigurationNode defaults) {
|
||||
this.node = node;
|
||||
this.defaults = defaults;
|
||||
dirty |= ConfigMigration.migrate(node);
|
||||
dirty |= ConfigMapping.removeDuplicateHeader(node);
|
||||
mergeDefaults();
|
||||
}
|
||||
|
||||
CommentedConfigurationNode node() {
|
||||
return node;
|
||||
}
|
||||
|
||||
List<Repair> repairs() {
|
||||
return repairs;
|
||||
}
|
||||
|
||||
boolean isDirty() {
|
||||
return dirty;
|
||||
}
|
||||
|
||||
void markDirty() {
|
||||
dirty = true;
|
||||
}
|
||||
|
||||
boolean hasDefault(NodePath path) {
|
||||
return !defaults.node(path.array()).virtual();
|
||||
}
|
||||
|
||||
void mergeDefaults() {
|
||||
dirty |= mergeMissing(defaults, node);
|
||||
}
|
||||
|
||||
LoggingConfig parseLoggingConfig() {
|
||||
return deserializeWithRepairs(NodePath.path("logging"), LoggingConfig.class);
|
||||
}
|
||||
|
||||
RootConfig parseReadyConfig() {
|
||||
// Hiding sounds from hidden entities is currently unsupported; persist the false defaults.
|
||||
for (String section : List.of("player", "entity")) {
|
||||
repair(NodePath.path("checks", section, "hide-sounds-when-hidden"), "hiding sounds from hidden entities is currently unsupported");
|
||||
}
|
||||
int attemptsRemaining = Math.max(2, countLeaves(defaults) + 1);
|
||||
while (attemptsRemaining-- > 0) {
|
||||
RootConfig root = deserializeWithRepairs(NodePath.path(), RootConfig.class);
|
||||
if (!RootConfig.CURRENT_VERSION.equals(root.configVersion())) {
|
||||
throw ConfigMigration.unsupportedVersion(root.configVersion());
|
||||
}
|
||||
List<AbsoluteViolation> violations = validate(root);
|
||||
if (violations.isEmpty()) {
|
||||
canonicalizeEnums(root);
|
||||
return root;
|
||||
}
|
||||
|
||||
boolean repaired = false;
|
||||
for (AbsoluteViolation violation : violations) {
|
||||
repaired |= repair(violation.path, violation.message);
|
||||
}
|
||||
if (!repaired) {
|
||||
throw new ConfigLoadException("Configuration validation failed without a repairable default");
|
||||
}
|
||||
}
|
||||
throw new ConfigLoadException("Configuration could not be repaired after exhausting the available defaults");
|
||||
}
|
||||
|
||||
private void canonicalizeEnums(RootConfig root) {
|
||||
canonicalizeValue(NodePath.path("engine", "mode"), root.engineConfig().mode().getName());
|
||||
canonicalizeValue(NodePath.path("block-processor", "mode"), root.blockProcessorConfig().mode().getName());
|
||||
}
|
||||
|
||||
private void canonicalizeValue(NodePath path, String value) {
|
||||
ConfigurationNode target = node.node(path.array());
|
||||
if (!Objects.equals(target.raw(), value)) {
|
||||
target.raw(value);
|
||||
dirty = true;
|
||||
}
|
||||
}
|
||||
|
||||
private <T> T deserializeWithRepairs(NodePath mappingPath, Class<T> type) {
|
||||
int attemptsRemaining = Math.max(1, countLeaves(defaults.node(mappingPath.array())) + 1);
|
||||
while (attemptsRemaining-- > 0) {
|
||||
try {
|
||||
T value = node.node(mappingPath.array()).get(type);
|
||||
if (value == null) {
|
||||
throw new ConfigLoadException("Configuration mapper returned null for " + pathToString(mappingPath));
|
||||
}
|
||||
return value;
|
||||
} catch (SerializationException exception) {
|
||||
boolean repaired = false;
|
||||
for (SerializationException failure : leafFailures(exception)) {
|
||||
NodePath failurePath = normalizePath(failure.path(), mappingPath);
|
||||
repaired |= repair(failurePath, failure.rawMessage());
|
||||
}
|
||||
if (!repaired) {
|
||||
throw new ConfigLoadException("Invalid configuration at " + pathToString(mappingPath), exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new ConfigLoadException("Configuration at " + pathToString(mappingPath) + " could not be repaired");
|
||||
}
|
||||
|
||||
private List<AbsoluteViolation> validate(RootConfig root) {
|
||||
List<AbsoluteViolation> violations = new ArrayList<>();
|
||||
if (!root.blockProcessorConfig().trackAllBlocks() && root.checksConfig().chunkSectionConfig().enabled()) {
|
||||
violations.add(new AbsoluteViolation(
|
||||
NodePath.path("checks", "chunk-section", "enabled"),
|
||||
"must be false when block-processor.track-all-blocks is false"
|
||||
));
|
||||
}
|
||||
return violations;
|
||||
}
|
||||
|
||||
boolean repair(NodePath failedPath, String reason) {
|
||||
NodePath repairPath = findRepairPath(failedPath);
|
||||
if (repairPath == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
ConfigurationNode target = node.node(repairPath.array());
|
||||
ConfigurationNode replacement = defaults.node(repairPath.array());
|
||||
if (Objects.equals(target.raw(), replacement.raw())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
String existingComment = target instanceof CommentedConfigurationNode commented ? commented.comment() : null;
|
||||
target.from(replacement);
|
||||
copyComments(replacement, target);
|
||||
if (existingComment != null && target instanceof CommentedConfigurationNode commented) {
|
||||
commented.comment(existingComment);
|
||||
}
|
||||
dirty = true;
|
||||
repairs.add(new Repair(repairPath, reason, replacement.raw()));
|
||||
return true;
|
||||
}
|
||||
|
||||
private NodePath findRepairPath(NodePath failedPath) {
|
||||
Object[] parts = failedPath.array();
|
||||
for (int index = 0; index < parts.length; index++) {
|
||||
if (parts[index] instanceof Number) {
|
||||
parts = Arrays.copyOf(parts, index);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
for (int length = parts.length; length >= 0; length--) {
|
||||
NodePath candidate = NodePath.path(Arrays.copyOf(parts, length));
|
||||
if (!defaults.node(candidate.array()).virtual()) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private List<SerializationException> leafFailures(SerializationException root) {
|
||||
List<SerializationException> failures = new ArrayList<>();
|
||||
ArrayDeque<SerializationException> pending = new ArrayDeque<>();
|
||||
pending.add(root);
|
||||
while (!pending.isEmpty()) {
|
||||
SerializationException current = pending.removeFirst();
|
||||
boolean hasNested = false;
|
||||
for (Throwable suppressed : current.getSuppressed()) {
|
||||
if (suppressed instanceof SerializationException nested) {
|
||||
pending.addLast(nested);
|
||||
hasNested = true;
|
||||
}
|
||||
}
|
||||
if (!hasNested) {
|
||||
failures.add(current);
|
||||
}
|
||||
}
|
||||
return failures;
|
||||
}
|
||||
|
||||
private NodePath normalizePath(NodePath failurePath, NodePath mappingPath) {
|
||||
if (failurePath == null || failurePath.size() == 0) {
|
||||
return mappingPath;
|
||||
}
|
||||
if (startsWith(failurePath, mappingPath)) {
|
||||
return failurePath;
|
||||
}
|
||||
return mappingPath.plus(failurePath);
|
||||
}
|
||||
|
||||
private boolean startsWith(NodePath path, NodePath prefix) {
|
||||
if (prefix.size() > path.size()) {
|
||||
return false;
|
||||
}
|
||||
for (int index = 0; index < prefix.size(); index++) {
|
||||
if (!Objects.equals(path.get(index), prefix.get(index))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean mergeMissing(ConfigurationNode defaults, ConfigurationNode target) {
|
||||
if (target.virtual() || target.raw() == null && target.childrenMap().isEmpty() && target.childrenList().isEmpty()) {
|
||||
target.from(defaults);
|
||||
copyComments(defaults, target);
|
||||
return true;
|
||||
}
|
||||
|
||||
boolean changed = mergeComment(defaults, target);
|
||||
if (!defaults.childrenMap().isEmpty()) {
|
||||
Object raw = target.raw();
|
||||
if (target.childrenMap().isEmpty() && !(raw instanceof Map<?, ?>)) {
|
||||
return repair(target.path(), "expected a mapping");
|
||||
}
|
||||
for (Map.Entry<Object, ? extends ConfigurationNode> entry : defaults.childrenMap().entrySet()) {
|
||||
changed |= mergeMissing(entry.getValue(), target.node(entry.getKey()));
|
||||
}
|
||||
} else if (!defaults.childrenList().isEmpty() && target.isList()) {
|
||||
// Entries can be reordered or removed, so default comments must follow values rather than indices.
|
||||
Map<String, ConfigurationNode> commentedDefaults = new LinkedHashMap<>();
|
||||
for (ConfigurationNode child : defaults.childrenList()) {
|
||||
if (child.rawScalar() instanceof String value && child instanceof CommentedConfigurationNode commented && commented.comment() != null) {
|
||||
commentedDefaults.put(value, child);
|
||||
}
|
||||
}
|
||||
for (ConfigurationNode child : target.childrenList()) {
|
||||
if (child.rawScalar() instanceof String value) {
|
||||
ConfigurationNode defaultChild = commentedDefaults.get(value);
|
||||
if (defaultChild != null) {
|
||||
changed |= mergeComment(defaultChild, child);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
private boolean mergeComment(ConfigurationNode defaults, ConfigurationNode target) {
|
||||
if (!(defaults instanceof CommentedConfigurationNode defaultCommented) || !(target instanceof CommentedConfigurationNode targetCommented)) {
|
||||
return false;
|
||||
}
|
||||
if (targetCommented.comment() == null && defaultCommented.comment() != null) {
|
||||
targetCommented.comment(defaultCommented.comment());
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void copyComments(ConfigurationNode source, ConfigurationNode target) {
|
||||
if (source instanceof CommentedConfigurationNode sourceCommented
|
||||
&& target instanceof CommentedConfigurationNode targetCommented
|
||||
&& sourceCommented.comment() != null) {
|
||||
targetCommented.commentIfAbsent(sourceCommented.comment());
|
||||
}
|
||||
for (Map.Entry<Object, ? extends ConfigurationNode> entry : source.childrenMap().entrySet()) {
|
||||
copyComments(entry.getValue(), target.node(entry.getKey()));
|
||||
}
|
||||
List<? extends ConfigurationNode> sourceChildren = source.childrenList();
|
||||
List<? extends ConfigurationNode> targetChildren = target.childrenList();
|
||||
for (int index = 0; index < Math.min(sourceChildren.size(), targetChildren.size()); index++) {
|
||||
copyComments(sourceChildren.get(index), targetChildren.get(index));
|
||||
}
|
||||
}
|
||||
|
||||
private int countLeaves(ConfigurationNode node) {
|
||||
if (node.childrenMap().isEmpty() && node.childrenList().isEmpty()) {
|
||||
return 1;
|
||||
}
|
||||
int count = 0;
|
||||
for (ConfigurationNode child : node.childrenMap().values()) {
|
||||
count += countLeaves(child);
|
||||
}
|
||||
for (ConfigurationNode child : node.childrenList()) {
|
||||
count += countLeaves(child);
|
||||
}
|
||||
return Math.max(1, count);
|
||||
}
|
||||
|
||||
private static String pathToString(NodePath path) {
|
||||
if (path.size() == 0) {
|
||||
return "<root>";
|
||||
}
|
||||
StringBuilder result = new StringBuilder();
|
||||
for (Object part : path) {
|
||||
if (part instanceof Number) {
|
||||
result.append('[').append(part).append(']');
|
||||
} else {
|
||||
if (!result.isEmpty()) {
|
||||
result.append('.');
|
||||
}
|
||||
result.append(part);
|
||||
}
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
record Repair(NodePath path, String reason, Object defaultValue) {
|
||||
Repair {
|
||||
path = path.copy();
|
||||
}
|
||||
|
||||
String pathString() {
|
||||
return pathToString(path);
|
||||
}
|
||||
}
|
||||
|
||||
private record AbsoluteViolation(NodePath path, String message) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.config;
|
||||
|
||||
import org.spongepowered.configurate.ConfigurationNode;
|
||||
|
||||
public interface ConfigExtension<T extends Config> {
|
||||
Class<T> type();
|
||||
|
||||
T load(ConfigurationNode config, BlockProcessorConfig blockProcessorConfig);
|
||||
|
||||
default boolean requiresRestart(T startupConfig, T nextConfig) {
|
||||
return !startupConfig.equals(nextConfig);
|
||||
}
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
package games.cubi.raycastedantiesp.core.config;
|
||||
|
||||
import org.spongepowered.configurate.CommentedConfigurationNode;
|
||||
import org.spongepowered.configurate.loader.HeaderMode;
|
||||
import org.spongepowered.configurate.serialize.SerializationException;
|
||||
import org.spongepowered.configurate.yaml.NodeStyle;
|
||||
import org.spongepowered.configurate.yaml.YamlConfigurationLoader;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.AtomicMoveNotSupportedException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.Objects;
|
||||
|
||||
/** Owns YAML loading, default-node creation, and replacement of config.yml through a temporary file. */
|
||||
final class ConfigFile {
|
||||
private final Path dataFolder;
|
||||
private final Path configPath;
|
||||
private final YamlConfigurationLoader loader;
|
||||
|
||||
ConfigFile(Path dataFolder) {
|
||||
this.dataFolder = Objects.requireNonNull(dataFolder, "dataFolder");
|
||||
configPath = dataFolder.resolve("config.yml");
|
||||
loader = createLoader(configPath);
|
||||
}
|
||||
|
||||
private YamlConfigurationLoader createLoader(Path path) {
|
||||
return YamlConfigurationLoader.builder()
|
||||
.path(path)
|
||||
.nodeStyle(NodeStyle.BLOCK)
|
||||
.headerMode(HeaderMode.PRESERVE)
|
||||
.defaultOptions(ConfigMapping.options())
|
||||
.build();
|
||||
}
|
||||
|
||||
CommentedConfigurationNode createDefaultNode() {
|
||||
CommentedConfigurationNode defaults = loader.createNode();
|
||||
try {
|
||||
defaults.set(RootConfig.class, RootConfig.DEFAULT);
|
||||
} catch (SerializationException e) {
|
||||
throw new ConfigLoadException("Code-defined configuration defaults could not be serialized", e);
|
||||
}
|
||||
return defaults;
|
||||
}
|
||||
|
||||
CommentedConfigurationNode load() {
|
||||
try {
|
||||
Files.createDirectories(dataFolder);
|
||||
return Files.exists(configPath) ? loader.load() : loader.createNode();
|
||||
} catch (IOException e) {
|
||||
throw new ConfigLoadException("Failed to load config.yml", e);
|
||||
}
|
||||
}
|
||||
|
||||
void save(CommentedConfigurationNode node) {
|
||||
Path temporaryPath = null;
|
||||
try {
|
||||
temporaryPath = Files.createTempFile(dataFolder, "config-", ".yml.tmp");
|
||||
createLoader(temporaryPath).save(node);
|
||||
try {
|
||||
Files.move(temporaryPath, configPath, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||
} catch (AtomicMoveNotSupportedException exception) {
|
||||
Files.move(temporaryPath, configPath, StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
temporaryPath = null;
|
||||
} catch (IOException e) {
|
||||
throw new ConfigLoadException("Failed to save config.yml", e);
|
||||
} finally {
|
||||
if (temporaryPath != null) {
|
||||
try {
|
||||
Files.deleteIfExists(temporaryPath);
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,135 +16,106 @@ import games.cubi.raycastedantiesp.core.config.raycast.PlayerConfig;
|
||||
import games.cubi.raycastedantiesp.core.config.raycast.SoundEffectsConfig;
|
||||
import games.cubi.raycastedantiesp.core.config.raycast.TileEntityConfig;
|
||||
import games.cubi.utils.VarHandler;
|
||||
import org.spongepowered.configurate.CommentedConfigurationNode;
|
||||
import org.spongepowered.configurate.ConfigurationNode;
|
||||
import org.spongepowered.configurate.ConfigurateException;
|
||||
import org.spongepowered.configurate.NodePath;
|
||||
import org.spongepowered.configurate.serialize.SerializationException;
|
||||
import org.spongepowered.configurate.yaml.NodeStyle;
|
||||
import org.spongepowered.configurate.yaml.YamlConfigurationLoader;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.invoke.VarHandle;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* Coordinates startup, runtime edits, and publication of configuration snapshots.
|
||||
* ConfigCandidate prepares values and repairs; ConfigFile handles persistence.
|
||||
*/
|
||||
public class ConfigManager {
|
||||
private static volatile ConfigManager instance;
|
||||
private static final VarHandle INSTANCE = VarHandler.$tatic(ConfigManager.class, "instance", ConfigManager.class);
|
||||
private static final String REQUIRED_CONFIG_VERSION = "2.0";
|
||||
private static ConfigManager instance;
|
||||
|
||||
private final ConfigFile configFile;
|
||||
private final Supplier<InputStream> resourceSupplier;
|
||||
private final Path dataFolder;
|
||||
private final Path configPath;
|
||||
private final YamlConfigurationLoader loader;
|
||||
private final List<ConfigExtension<? extends Config>> extensions;
|
||||
|
||||
private volatile ActiveState activeState = new ActiveState(LoggingConfig.DEFAULT, null);
|
||||
private static final VarHandle ACTIVE_STATE = VarHandler.get(ConfigManager.class, "activeState", ActiveState.class);
|
||||
private ConfigurationNode config;
|
||||
private RootConfig startupConfig;
|
||||
private CommentedConfigurationNode configNode;
|
||||
private volatile RootConfig activeConfig; private static final VarHandle ACTIVE_CONFIG = VarHandler.get(ConfigManager.class, "activeConfig", RootConfig.class);
|
||||
|
||||
ConfigManager(Path dataFolder) {
|
||||
configFile = new ConfigFile(dataFolder);
|
||||
private ConfigManager(Supplier<InputStream> resourceSupplier, Path dataFolder, List<ConfigExtension<? extends Config>> extensions) {
|
||||
this.resourceSupplier = resourceSupplier;
|
||||
this.dataFolder = dataFolder;
|
||||
this.extensions = List.copyOf(extensions);
|
||||
this.configPath = dataFolder.resolve("config.yml");
|
||||
this.loader = YamlConfigurationLoader.builder()
|
||||
.path(configPath)
|
||||
.nodeStyle(NodeStyle.BLOCK)
|
||||
.build();
|
||||
load();
|
||||
}
|
||||
|
||||
public static synchronized ConfigManager initialiseConfigManager(Path dataFolder) {
|
||||
ConfigManager current = (ConfigManager) INSTANCE.getAcquire();
|
||||
if (current == null) {
|
||||
ConfigManager manager = new ConfigManager(dataFolder);
|
||||
INSTANCE.setRelease(manager);
|
||||
try {
|
||||
manager.loadLoggingConfig();
|
||||
} catch (RuntimeException exception) {
|
||||
INSTANCE.setRelease(null);
|
||||
throw exception;
|
||||
}
|
||||
current = manager;
|
||||
public static ConfigManager initialiseConfigManager(Supplier<InputStream> resourceSupplier, Path dataFolder, List<ConfigExtension<? extends Config>> extensions) {
|
||||
if (instance == null) {
|
||||
instance = new ConfigManager(resourceSupplier, dataFolder, extensions);
|
||||
}
|
||||
return current;
|
||||
return instance;
|
||||
}
|
||||
|
||||
public static ConfigManager get() {
|
||||
ConfigManager current = (ConfigManager) INSTANCE.getAcquire();
|
||||
if (current == null) {
|
||||
if (instance == null) {
|
||||
Logger.errorAndReturn(new RuntimeException("ConfigManager accessed before being initiated. Please report this."), 2, ConfigManager.class);
|
||||
}
|
||||
return current;
|
||||
return instance;
|
||||
}
|
||||
|
||||
public static LoggingConfig getLoggingConfigOrDefault() {
|
||||
ConfigManager current = (ConfigManager) INSTANCE.getAcquire();
|
||||
return current == null ? LoggingConfig.DEFAULT : current.getLoggingConfig();
|
||||
}
|
||||
|
||||
public synchronized void completeInitialLoad() {
|
||||
if (startupConfig != null) {
|
||||
throw new IllegalStateException("Configuration loading has already been completed");
|
||||
public void load() {
|
||||
ensureConfigFileExists();
|
||||
ConfigurationNode loaded = loadConfigNode();
|
||||
ConfigurationNode defaults = loadBundledDefaults();
|
||||
if (defaults != null && mergeMissing(defaults, loaded)) {
|
||||
saveConfigNode(loaded);
|
||||
}
|
||||
|
||||
ConfigCandidate candidate = prepare();
|
||||
RootConfig ready = candidate.parseReadyConfig();
|
||||
saveIfChanged(candidate);
|
||||
|
||||
startupConfig = ready;
|
||||
configNode = candidate.node();
|
||||
ACTIVE_STATE.setRelease(this, new ActiveState(ready.loggingConfig(), ready));
|
||||
logRepairs(candidate.repairs());
|
||||
RootConfig parsed = parse(loaded);
|
||||
validateReload(parsed);
|
||||
config = loaded;
|
||||
if (startupConfig == null) {
|
||||
startupConfig = parsed;
|
||||
}
|
||||
ACTIVE_CONFIG.setOpaque(this, parsed);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reloads the complete configuration. The active snapshot is replaced only after parsing and validation succeed.
|
||||
*/
|
||||
public synchronized void load() {
|
||||
requireReady();
|
||||
ConfigCandidate candidate = prepare();
|
||||
RootConfig ready = candidate.parseReadyConfig();
|
||||
saveIfChanged(candidate);
|
||||
configNode = candidate.node();
|
||||
logRepairs(candidate.repairs());
|
||||
validateReload(ready);
|
||||
ACTIVE_STATE.setRelease(this, new ActiveState(ready.loggingConfig(), ready));
|
||||
}
|
||||
|
||||
public synchronized SetConfigResult setConfigValue(String path, String rawValue) {
|
||||
requireReady();
|
||||
ConfigCandidate candidate = prepare();
|
||||
ConfigurationNode target = node(candidate.node(), path);
|
||||
public SetConfigResult setConfigValue(String path, String rawValue) {
|
||||
ConfigurationNode candidate = loadConfigNode();
|
||||
ConfigurationNode target = node(candidate, path);
|
||||
if (target.virtual()) {
|
||||
return SetConfigResult.invalid("Unknown config path: " + path);
|
||||
}
|
||||
|
||||
try {
|
||||
Object parsedValue = parseRawValue(rawValue);
|
||||
target.set(parsedValue);
|
||||
candidate.markDirty();
|
||||
NodePath targetPath = NodePath.path((Object[]) path.split("\\."));
|
||||
if (parsedValue == null && candidate.hasDefault(targetPath)) {
|
||||
candidate.repair(targetPath, "value cannot be null");
|
||||
}
|
||||
} catch (ConfigurateException e) {
|
||||
return SetConfigResult.invalid("Invalid YAML value: " + rawValue);
|
||||
}
|
||||
ConfigReader.setRaw(target, ConfigReader.parseRawValue(rawValue));
|
||||
|
||||
return applyCandidate(candidate, false);
|
||||
}
|
||||
|
||||
public synchronized SetConfigResult addConfigListValue(String path, String rawValue) {
|
||||
requireReady();
|
||||
public SetConfigResult addConfigListValue(String path, String rawValue) {
|
||||
return mutateConfigListValue(path, rawValue, ListMutation.ADD);
|
||||
}
|
||||
|
||||
public synchronized SetConfigResult removeConfigListValue(String path, String rawValue) {
|
||||
requireReady();
|
||||
public SetConfigResult removeConfigListValue(String path, String rawValue) {
|
||||
return mutateConfigListValue(path, rawValue, ListMutation.REMOVE);
|
||||
}
|
||||
|
||||
private SetConfigResult mutateConfigListValue(String path, String rawValue, ListMutation mutation) {
|
||||
ConfigCandidate candidate = prepare();
|
||||
ConfigurationNode target = node(candidate.node(), path);
|
||||
ConfigurationNode candidate = loadConfigNode();
|
||||
ConfigurationNode target = node(candidate, path);
|
||||
if (target.virtual()) {
|
||||
return SetConfigResult.invalid("Unknown config path: " + path);
|
||||
}
|
||||
@@ -157,13 +128,7 @@ public class ConfigManager {
|
||||
return SetConfigResult.invalid(path + " is not a list path");
|
||||
}
|
||||
|
||||
Object parsedValue;
|
||||
try {
|
||||
parsedValue = parseRawValue(rawValue);
|
||||
} catch (ConfigurateException e) {
|
||||
return SetConfigResult.invalid("Invalid YAML value: " + rawValue);
|
||||
}
|
||||
|
||||
Object parsedValue = ConfigReader.parseRawValue(rawValue);
|
||||
boolean changed = switch (mutation) {
|
||||
case ADD -> {
|
||||
if (values.contains(parsedValue)) {
|
||||
@@ -174,115 +139,113 @@ public class ConfigManager {
|
||||
}
|
||||
case REMOVE -> values.remove(parsedValue);
|
||||
};
|
||||
|
||||
if (!changed) {
|
||||
return SetConfigResult.invalid("No change made for " + path);
|
||||
}
|
||||
|
||||
try {
|
||||
target.set(values);
|
||||
candidate.markDirty();
|
||||
} catch (SerializationException e) {
|
||||
return SetConfigResult.invalid("Failed to update " + path);
|
||||
}
|
||||
ConfigReader.setRaw(target, values);
|
||||
return applyCandidate(candidate, true);
|
||||
}
|
||||
|
||||
private SetConfigResult applyCandidate(ConfigCandidate candidate, boolean allowRestartRequired) {
|
||||
candidate.mergeDefaults();
|
||||
RootConfig ready;
|
||||
private SetConfigResult applyCandidate(ConfigurationNode candidate, boolean allowRestartRequired) {
|
||||
RootConfig parsed;
|
||||
try {
|
||||
ready = candidate.parseReadyConfig();
|
||||
validateReload(ready);
|
||||
parsed = parse(candidate);
|
||||
validateReload(parsed);
|
||||
} catch (RestartRequiredException e) {
|
||||
if (!allowRestartRequired) {
|
||||
return SetConfigResult.invalid(e.getMessage());
|
||||
}
|
||||
saveIfChanged(candidate);
|
||||
configNode = candidate.node();
|
||||
logRepairs(candidate.repairs());
|
||||
return SetConfigResult.restartRequired(e.getMessage(), candidate.repairs());
|
||||
config = candidate;
|
||||
saveConfigNode(candidate);
|
||||
return SetConfigResult.restartRequired(e.getMessage());
|
||||
} catch (ConfigLoadException e) {
|
||||
return SetConfigResult.invalid(e.getMessage());
|
||||
}
|
||||
|
||||
saveIfChanged(candidate);
|
||||
configNode = candidate.node();
|
||||
ACTIVE_STATE.setRelease(this, new ActiveState(ready.loggingConfig(), ready));
|
||||
logRepairs(candidate.repairs());
|
||||
return SetConfigResult.ok(candidate.repairs());
|
||||
}
|
||||
|
||||
public LoggingConfig getLoggingConfig() {
|
||||
return ((ActiveState) ACTIVE_STATE.getAcquire(this)).loggingConfig;
|
||||
config = candidate;
|
||||
ACTIVE_CONFIG.setOpaque(this, parsed);
|
||||
saveConfigNode(candidate);
|
||||
return SetConfigResult.ok();
|
||||
}
|
||||
|
||||
public PlayerConfig getPlayerConfig() {
|
||||
return requireReady().checksConfig().playerConfig();
|
||||
return activeConfig().checksConfig().playerConfig();
|
||||
}
|
||||
|
||||
public EntityConfig getEntityConfig() {
|
||||
return requireReady().checksConfig().entityConfig();
|
||||
return activeConfig().checksConfig().entityConfig();
|
||||
}
|
||||
|
||||
public TileEntityConfig getTileEntityConfig() {
|
||||
return requireReady().checksConfig().tileEntityConfig();
|
||||
return activeConfig().checksConfig().tileEntityConfig();
|
||||
}
|
||||
|
||||
public SoundEffectsConfig getSoundEffectsConfig() {
|
||||
return requireReady().checksConfig().soundEffectsConfig();
|
||||
return activeConfig().checksConfig().soundEffectsConfig();
|
||||
}
|
||||
|
||||
public ChunkSectionConfig getChunkSectionConfig() {
|
||||
return requireReady().checksConfig().chunkSectionConfig();
|
||||
return activeConfig().checksConfig().chunkSectionConfig();
|
||||
}
|
||||
|
||||
public DebugConfig getDebugConfig() {
|
||||
return requireReady().debugConfig();
|
||||
RootConfig current = activeConfig();
|
||||
return current == null ? null : current.debugConfig();
|
||||
}
|
||||
|
||||
public UpdateConfig getUpdateConfig() {
|
||||
return requireReady().updateConfig();
|
||||
return activeConfig().updateConfig();
|
||||
}
|
||||
|
||||
public EngineConfig getEngineConfig() {
|
||||
return requireReady().engineConfig();
|
||||
return activeConfig().engineConfig();
|
||||
}
|
||||
|
||||
public BlockProcessorConfig getBlockProcessorConfig() {
|
||||
return requireReady().blockProcessorConfig();
|
||||
return activeConfig().blockProcessorConfig();
|
||||
}
|
||||
|
||||
public synchronized Map<String, Object> getConfigValues() {
|
||||
requireReady();
|
||||
public <T extends Config> T getExtensionConfig(Class<T> type) {
|
||||
return activeConfig().extensionConfig(type);
|
||||
}
|
||||
|
||||
private RootConfig activeConfig() {
|
||||
return (RootConfig) ACTIVE_CONFIG.getOpaque(this);
|
||||
}
|
||||
|
||||
public ConfigurationNode getConfigFile() {
|
||||
return config;
|
||||
}
|
||||
|
||||
public Map<String, Object> getConfigValues() {
|
||||
Map<String, Object> values = new LinkedHashMap<>();
|
||||
collectConfigValues(configNode, "", values);
|
||||
return Collections.unmodifiableMap(values);
|
||||
collectConfigValues(config, "", values);
|
||||
return values;
|
||||
}
|
||||
|
||||
void loadLoggingConfig() {
|
||||
ConfigCandidate candidate = prepare();
|
||||
LoggingConfig logging = candidate.parseLoggingConfig();
|
||||
saveIfChanged(candidate);
|
||||
configNode = candidate.node();
|
||||
ACTIVE_STATE.setRelease(this, new ActiveState(logging, null));
|
||||
logRepairs(candidate.repairs());
|
||||
}
|
||||
|
||||
private ConfigCandidate prepare() {
|
||||
return new ConfigCandidate(configFile.load(), configFile.createDefaultNode());
|
||||
}
|
||||
|
||||
private void saveIfChanged(ConfigCandidate candidate) {
|
||||
if (candidate.isDirty()) {
|
||||
configFile.save(candidate.node());
|
||||
private RootConfig parse(ConfigurationNode loaded) {
|
||||
String version = ConfigReader.string(ConfigReader.node(loaded, "config-version"), "config-version");
|
||||
if (!REQUIRED_CONFIG_VERSION.equals(version)) {
|
||||
throw new ConfigLoadException("Unsupported config-version '" + version + "'. RaycastedAntiESP requires config-version '2.0'.");
|
||||
}
|
||||
}
|
||||
|
||||
private Object parseRawValue(String rawValue) throws ConfigurateException {
|
||||
ConfigurationNode parsed = YamlConfigurationLoader.builder()
|
||||
.defaultOptions(ConfigMapping.options())
|
||||
.buildAndLoadString("value: " + rawValue);
|
||||
return parsed.node("value").raw();
|
||||
ChecksConfig checksConfig = ChecksConfig.load(loaded);
|
||||
EngineConfig engineConfig = EngineConfig.load(loaded);
|
||||
BlockProcessorConfig blockProcessorConfig = BlockProcessorConfig.load(loaded);
|
||||
DebugConfig debugConfig = DebugConfig.load(loaded);
|
||||
UpdateConfig updateConfig = UpdateConfig.load(loaded);
|
||||
Map<Class<? extends Config>, Config> extensionConfigs = new LinkedHashMap<>();
|
||||
for (ConfigExtension<? extends Config> extension : extensions) {
|
||||
extensionConfigs.put(extension.type(), extension.load(loaded, blockProcessorConfig));
|
||||
}
|
||||
|
||||
if (!blockProcessorConfig.trackAllBlocks() && checksConfig.chunkSectionConfig().enabled()) {
|
||||
throw new ConfigLoadException("checks.chunk-section.enabled must be false when block-processor.track-all-blocks is false");
|
||||
}
|
||||
|
||||
return new RootConfig(version, checksConfig, engineConfig, blockProcessorConfig, debugConfig, updateConfig, Map.copyOf(extensionConfigs));
|
||||
}
|
||||
|
||||
private void validateReload(RootConfig next) {
|
||||
@@ -298,34 +261,20 @@ public class ConfigManager {
|
||||
if (!next.checksConfig().entityConfig().excludedTypes().equals(startupConfig.checksConfig().entityConfig().excludedTypes())) {
|
||||
throw new RestartRequiredException("excluded entity types cannot be changed without a restart.");
|
||||
}
|
||||
if (!next.checksConfig().tileEntityConfig().excludedBlocks().equals(startupConfig.checksConfig().tileEntityConfig().excludedBlocks())) {
|
||||
throw new RestartRequiredException("excluded tile-entity blocks cannot be changed without a restart.");
|
||||
}
|
||||
if (next.checksConfig().hasEnabledStatusChanges(startupConfig.checksConfig())) {
|
||||
throw new RestartRequiredException("player and entity checks cannot be enabled or disabled without a restart.");
|
||||
}
|
||||
}
|
||||
|
||||
private RootConfig requireReady() {
|
||||
RootConfig ready = ((ActiveState) ACTIVE_STATE.getAcquire(this)).readyConfig;
|
||||
if (ready == null) {
|
||||
throw new IllegalStateException("Configuration is not available until completeInitialLoad has finished");
|
||||
}
|
||||
return ready;
|
||||
}
|
||||
|
||||
private void logRepairs(List<ConfigCandidate.Repair> repairs) {
|
||||
for (ConfigCandidate.Repair repair : repairs) {
|
||||
String reason = repair.reason() == null || repair.reason().isBlank() ? "invalid value" : repair.reason();
|
||||
String message = "Invalid config value at " + repair.pathString() + ": " + reason
|
||||
+ ". Replaced it with the default " + displayValue(repair.defaultValue()) + ".";
|
||||
Logger.warning(message, 4, ConfigManager.class);
|
||||
for (ConfigExtension<? extends Config> extension : extensions) {
|
||||
validateExtensionReload(extension, next);
|
||||
}
|
||||
}
|
||||
|
||||
private String displayValue(Object value) {
|
||||
String displayed = String.valueOf(value);
|
||||
return displayed.length() <= 160 ? displayed : displayed.substring(0, 157) + "...";
|
||||
private <T extends Config> void validateExtensionReload(ConfigExtension<T> extension, RootConfig next) {
|
||||
T startupExtensionConfig = startupConfig.extensionConfig(extension.type());
|
||||
T nextExtensionConfig = next.extensionConfig(extension.type());
|
||||
if (extension.requiresRestart(startupExtensionConfig, nextExtensionConfig)) {
|
||||
throw new RestartRequiredException("block-processor." + extension.type().getSimpleName() + " cannot be changed without a restart");
|
||||
}
|
||||
}
|
||||
|
||||
private void collectConfigValues(ConfigurationNode node, String path, Map<String, Object> values) {
|
||||
@@ -335,18 +284,190 @@ public class ConfigManager {
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!node.childrenList().isEmpty()) {
|
||||
values.put(path, node.childrenList().stream().map(ConfigurationNode::raw).toList());
|
||||
return;
|
||||
}
|
||||
|
||||
for (Map.Entry<Object, ? extends ConfigurationNode> entry : node.childrenMap().entrySet()) {
|
||||
String key = String.valueOf(entry.getKey());
|
||||
collectConfigValues(entry.getValue(), path.isEmpty() ? key : path + "." + key, values);
|
||||
String nextPath = path.isEmpty() ? key : path + "." + key;
|
||||
collectConfigValues(entry.getValue(), nextPath, values);
|
||||
}
|
||||
}
|
||||
|
||||
private void ensureConfigFileExists() {
|
||||
try {
|
||||
Files.createDirectories(dataFolder);
|
||||
if (!Files.exists(configPath)) {
|
||||
InputStream resource = resourceSupplier.get();
|
||||
if (resource != null) {
|
||||
try (resource) {
|
||||
Files.copy(resource, configPath);
|
||||
}
|
||||
} else {
|
||||
Files.createFile(configPath);
|
||||
}
|
||||
}
|
||||
ConfigMigrations.prependConfigDocumentationHeaderIfMissing(configPath);
|
||||
ConfigMigrations.migrateSoundEffectsEnabled(configPath);
|
||||
} catch (IOException e) {
|
||||
throw new ConfigLoadException("Failed to create config.yml", e);
|
||||
}
|
||||
}
|
||||
|
||||
private ConfigurationNode loadConfigNode() {
|
||||
try {
|
||||
return loader.load();
|
||||
} catch (IOException e) {
|
||||
throw new ConfigLoadException("Failed to load config.yml", e);
|
||||
}
|
||||
}
|
||||
|
||||
private ConfigurationNode loadBundledDefaults() {
|
||||
InputStream resource = resourceSupplier.get();
|
||||
if (resource == null) {
|
||||
return null;
|
||||
}
|
||||
try (resource) {
|
||||
return YamlConfigurationLoader.builder()
|
||||
.source(() -> new BufferedReader(new InputStreamReader(resource)))
|
||||
.build()
|
||||
.load();
|
||||
} catch (IOException e) {
|
||||
throw new ConfigLoadException("Failed to load bundled config defaults", e);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean mergeMissing(ConfigurationNode defaults, ConfigurationNode target) {
|
||||
if (target.virtual()) {
|
||||
target.from(defaults);
|
||||
return true;
|
||||
}
|
||||
|
||||
boolean changed = false;
|
||||
if (!defaults.childrenMap().isEmpty()) {
|
||||
for (Map.Entry<Object, ? extends ConfigurationNode> entry : defaults.childrenMap().entrySet()) {
|
||||
changed |= mergeMissing(entry.getValue(), target.node(entry.getKey()));
|
||||
}
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
private void saveConfigNode(ConfigurationNode node) {
|
||||
try {
|
||||
loader.save(node);
|
||||
} catch (IOException e) {
|
||||
throw new ConfigLoadException("Failed to save config.yml", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Temporary text-level config mutations. Remove this class when these migrations are no longer needed.
|
||||
*/
|
||||
private static final class ConfigMigrations {
|
||||
private static final Pattern YAML_KEY = Pattern.compile("^([ \\t]*)([^:#\\s][^:]*):.*$");
|
||||
private static final Pattern SOUND_EFFECTS_ENABLED_TRUE = Pattern.compile("^([ \\t]*enabled[ \\t]*:[ \\t]*)true([ \\t]*(?:#.*)?)$", Pattern.CASE_INSENSITIVE);
|
||||
|
||||
private ConfigMigrations() {
|
||||
}
|
||||
|
||||
private static void prependConfigDocumentationHeaderIfMissing(Path configPath) {
|
||||
try {
|
||||
String content = Files.readString(configPath);
|
||||
|
||||
if (content.startsWith("#")) {
|
||||
Logger.debug("Config starts with comment");
|
||||
return;
|
||||
}
|
||||
|
||||
Logger.debug("no starting comment");
|
||||
Files.writeString(configPath, "# An explanation of this configuration file and what all the options do can be found at https://raycastedantiesp.cubi.games/config/" + System.lineSeparator() + content);
|
||||
} catch (Exception e) {
|
||||
Logger.warning(e,3, ConfigManager.class);
|
||||
}
|
||||
}
|
||||
|
||||
@Temporary(forRemovalIn = "0.8.0")
|
||||
private static void migrateSoundEffectsEnabled(Path configPath) {
|
||||
try {
|
||||
String content = Files.readString(configPath, StandardCharsets.UTF_8);
|
||||
String migrated = replaceSoundEffectsEnabled(content);
|
||||
if (!content.equals(migrated)) {
|
||||
Files.writeString(configPath, migrated, StandardCharsets.UTF_8);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new ConfigLoadException("Failed to migrate sound-effects.enabled in config.yml", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static String replaceSoundEffectsEnabled(String content) {
|
||||
StringBuilder migrated = new StringBuilder(content.length());
|
||||
int lineStart = 0;
|
||||
int checksIndent = -1;
|
||||
int soundEffectsIndent = -1;
|
||||
boolean changed = false;
|
||||
|
||||
while (lineStart < content.length()) {
|
||||
int lineEnd = content.indexOf('\n', lineStart);
|
||||
boolean hasLineEnding = lineEnd >= 0;
|
||||
int contentEnd = hasLineEnding ? lineEnd : content.length();
|
||||
int lineContentEnd = contentEnd > lineStart && content.charAt(contentEnd - 1) == '\r'
|
||||
? contentEnd - 1 : contentEnd;
|
||||
String line = content.substring(lineStart, lineContentEnd);
|
||||
String lineEnding = content.substring(lineContentEnd, contentEnd) + (hasLineEnding ? "\n" : "");
|
||||
|
||||
Matcher key = YAML_KEY.matcher(line);
|
||||
if (key.matches()) {
|
||||
int indent = key.group(1).length();
|
||||
String name = key.group(2).trim();
|
||||
|
||||
if (checksIndent < 0) {
|
||||
if (name.equals("checks")) {
|
||||
checksIndent = indent;
|
||||
}
|
||||
} else if (indent <= checksIndent) {
|
||||
checksIndent = name.equals("checks") ? indent : -1;
|
||||
soundEffectsIndent = -1;
|
||||
} else if (soundEffectsIndent < 0) {
|
||||
if (name.equals("sound-effects")) {
|
||||
soundEffectsIndent = indent;
|
||||
}
|
||||
} else if (indent <= soundEffectsIndent) {
|
||||
soundEffectsIndent = name.equals("sound-effects") ? indent : -1;
|
||||
}
|
||||
}
|
||||
|
||||
if (soundEffectsIndent >= 0 && key.matches()
|
||||
&& key.group(2).trim().equals("enabled")
|
||||
&& key.group(1).length() > soundEffectsIndent) {
|
||||
Matcher enabled = SOUND_EFFECTS_ENABLED_TRUE.matcher(line);
|
||||
if (enabled.matches()) {
|
||||
line = enabled.group(1) + "false" + enabled.group(2);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
migrated.append(line).append(lineEnding);
|
||||
if (!hasLineEnding) {
|
||||
break;
|
||||
}
|
||||
lineStart = contentEnd + 1;
|
||||
}
|
||||
|
||||
return changed ? migrated.toString() : content;
|
||||
}
|
||||
|
||||
@Documented
|
||||
private @interface Temporary {
|
||||
String forRemovalIn();
|
||||
}
|
||||
}
|
||||
|
||||
private ConfigurationNode node(ConfigurationNode root, String path) {
|
||||
return root.node((Object[]) path.split("\\."));
|
||||
String[] parts = path.split("\\.");
|
||||
return ConfigReader.node(root, parts);
|
||||
}
|
||||
|
||||
private enum ListMutation {
|
||||
@@ -354,38 +475,23 @@ public class ConfigManager {
|
||||
REMOVE
|
||||
}
|
||||
|
||||
private record ActiveState(LoggingConfig loggingConfig, RootConfig readyConfig) {
|
||||
}
|
||||
|
||||
private static final class RestartRequiredException extends ConfigLoadException {
|
||||
private RestartRequiredException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
public record SetConfigResult(boolean success, boolean restartRequired, boolean repaired, String message) {
|
||||
private static SetConfigResult ok(List<ConfigCandidate.Repair> repairs) {
|
||||
if (repairs.isEmpty()) {
|
||||
return new SetConfigResult(true, false, false, "Config value updated.");
|
||||
}
|
||||
return new SetConfigResult(true, false, true, repairMessage(repairs));
|
||||
public record SetConfigResult(boolean success, boolean restartRequired, String message) {
|
||||
public static SetConfigResult ok() {
|
||||
return new SetConfigResult(true, false, "Config value updated.");
|
||||
}
|
||||
|
||||
private static SetConfigResult restartRequired(String message, List<ConfigCandidate.Repair> repairs) {
|
||||
String result = repairs.isEmpty() ? message : message + " " + repairMessage(repairs);
|
||||
return new SetConfigResult(true, true, !repairs.isEmpty(), result);
|
||||
public static SetConfigResult restartRequired(String message) {
|
||||
return new SetConfigResult(true, true, message);
|
||||
}
|
||||
|
||||
public static SetConfigResult invalid(String message) {
|
||||
return new SetConfigResult(false, false, false, message);
|
||||
}
|
||||
|
||||
private static String repairMessage(List<ConfigCandidate.Repair> repairs) {
|
||||
Set<String> paths = new LinkedHashSet<>();
|
||||
for (ConfigCandidate.Repair repair : repairs) {
|
||||
paths.add(repair.pathString());
|
||||
}
|
||||
return "Invalid values at " + String.join(", ", paths) + " were replaced with defaults.";
|
||||
return new SetConfigResult(false, false, message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,234 +0,0 @@
|
||||
package games.cubi.raycastedantiesp.core.config;
|
||||
|
||||
import games.cubi.raycastedantiesp.core.config.engine.EngineMode;
|
||||
import games.cubi.raycastedantiesp.core.config.raycast.BlockSelector;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.spongepowered.configurate.CommentedConfigurationNode;
|
||||
import org.spongepowered.configurate.ConfigurationOptions;
|
||||
import org.spongepowered.configurate.ConfigurationNode;
|
||||
import org.spongepowered.configurate.objectmapping.ObjectMapper;
|
||||
import org.spongepowered.configurate.serialize.SerializationException;
|
||||
import org.spongepowered.configurate.serialize.TypeSerializer;
|
||||
import org.spongepowered.configurate.serialize.TypeSerializerCollection;
|
||||
import org.spongepowered.configurate.util.NamingSchemes;
|
||||
|
||||
import java.lang.reflect.Type;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.BigInteger;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.LongFunction;
|
||||
|
||||
final class ConfigMapping {
|
||||
private static final String HEADER = "An explanation of this configuration file and what all the options do can be found at https://raycastedantiesp.cubi.games/config/";
|
||||
private static final String LEGACY_HEADER = "An explanation of this configuration file and what the options do can be found at https://raycastedantiesp.cubi.games/config/";
|
||||
private static final ConfigurationOptions OPTIONS = createOptions();
|
||||
|
||||
private ConfigMapping() {
|
||||
}
|
||||
|
||||
static ConfigurationOptions options() {
|
||||
return OPTIONS;
|
||||
}
|
||||
|
||||
static boolean removeDuplicateHeader(CommentedConfigurationNode node) {
|
||||
// Without a blank line, the legacy YAML header is loaded as a comment on config-version.
|
||||
CommentedConfigurationNode version = node.node("config-version");
|
||||
String comment = version.comment();
|
||||
if (comment == null) {
|
||||
return false;
|
||||
}
|
||||
var lines = comment.lines().toList();
|
||||
var remaining = lines.stream().filter(line -> {
|
||||
String normalized = line.strip().replace("https\\://", "https://");
|
||||
return !LEGACY_HEADER.equals(normalized) && !HEADER.equals(normalized);
|
||||
}).toList();
|
||||
if (remaining.size() == lines.size()) {
|
||||
return false;
|
||||
}
|
||||
String retainedComment = String.join("\n", remaining);
|
||||
version.comment(retainedComment.isBlank() ? null : retainedComment);
|
||||
return true;
|
||||
}
|
||||
|
||||
private static ConfigurationOptions createOptions() {
|
||||
ObjectMapper.Factory mapper = ObjectMapper.factoryBuilder()
|
||||
.defaultNamingScheme(NamingSchemes.LOWER_CASE_DASHED)
|
||||
.addProcessor(ListEntryComments.class, (annotation, type) -> {
|
||||
Map<String, String> comments = new HashMap<>();
|
||||
for (ListEntryComments.Entry entry : annotation.value()) {
|
||||
comments.put(entry.value(), entry.comment());
|
||||
}
|
||||
return (value, node) -> {
|
||||
for (ConfigurationNode child : node.childrenList()) {
|
||||
if (child.rawScalar() instanceof String entry && child instanceof CommentedConfigurationNode commented) {
|
||||
String comment = comments.get(entry);
|
||||
if (comment != null) {
|
||||
commented.commentIfAbsent(comment);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
})
|
||||
.addConstraint(ConfigRange.class, (annotation, type) -> value -> {
|
||||
if (!(value instanceof Number number)) {
|
||||
throw new SerializationException(type, "Expected a numeric value");
|
||||
}
|
||||
long numericValue = number.longValue();
|
||||
if (numericValue < annotation.min() || numericValue > annotation.max()) {
|
||||
throw new SerializationException(type, "Value must be between " + annotation.min() + " and " + annotation.max());
|
||||
}
|
||||
})
|
||||
.build();
|
||||
|
||||
TypeSerializer<String> stringSerializer = strictScalarSerializer(
|
||||
String.class,
|
||||
"a string",
|
||||
String.class::cast,
|
||||
value -> value
|
||||
);
|
||||
TypeSerializer<Boolean> booleanSerializer = strictScalarSerializer(
|
||||
Boolean.class,
|
||||
"a boolean",
|
||||
Boolean.class::cast,
|
||||
value -> value
|
||||
);
|
||||
TypeSerializer<Byte> byteSerializer = strictIntegerSerializer("a byte", Byte.MIN_VALUE, Byte.MAX_VALUE, value -> (byte) value);
|
||||
TypeSerializer<Short> shortSerializer = strictIntegerSerializer("a short", Short.MIN_VALUE, Short.MAX_VALUE, value -> (short) value);
|
||||
TypeSerializer<Integer> integerSerializer = strictIntegerSerializer("an integer", Integer.MIN_VALUE, Integer.MAX_VALUE, value -> (int) value);
|
||||
|
||||
TypeSerializerCollection serializers = TypeSerializerCollection.defaults().childBuilder()
|
||||
.registerExact(String.class, stringSerializer)
|
||||
.registerExact(boolean.class, booleanSerializer)
|
||||
.registerExact(Boolean.class, booleanSerializer)
|
||||
.registerExact(byte.class, byteSerializer)
|
||||
.registerExact(Byte.class, byteSerializer)
|
||||
.registerExact(short.class, shortSerializer)
|
||||
.registerExact(Short.class, shortSerializer)
|
||||
.registerExact(int.class, integerSerializer)
|
||||
.registerExact(Integer.class, integerSerializer)
|
||||
.registerExact(BlockSelector.class, blockSelectorSerializer())
|
||||
.registerExact(EngineMode.class, enumSerializer(EngineMode::fromString, EngineMode::getName))
|
||||
.registerExact(BlockProcessorMode.class, enumSerializer(BlockProcessorMode::fromString, BlockProcessorMode::getName))
|
||||
.registerAnnotatedObjects(mapper)
|
||||
.build();
|
||||
|
||||
return ConfigurationOptions.defaults()
|
||||
.header(HEADER)
|
||||
.serializers(serializers)
|
||||
.shouldCopyDefaults(true);
|
||||
}
|
||||
|
||||
private static <T> TypeSerializer<T> strictScalarSerializer(
|
||||
Class<T> type,
|
||||
String expected,
|
||||
Function<Object, T> reader,
|
||||
Function<T, Object> writer
|
||||
) {
|
||||
return new TypeSerializer<>() {
|
||||
@Override
|
||||
public T deserialize(@NotNull Type expectedType, @NotNull ConfigurationNode node) throws SerializationException {
|
||||
Object raw = node.rawScalar();
|
||||
if (!type.isInstance(raw)) {
|
||||
throw new SerializationException(expectedType, "Expected " + expected);
|
||||
}
|
||||
return reader.apply(raw);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void serialize(@NotNull Type expectedType, T value, @NotNull ConfigurationNode node) {
|
||||
node.raw(value == null ? null : writer.apply(value));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static <T extends Number> TypeSerializer<T> strictIntegerSerializer(String expected, long minimum, long maximum, LongFunction<T> converter) {
|
||||
return new TypeSerializer<>() {
|
||||
@Override
|
||||
public T deserialize(@NotNull Type expectedType, @NotNull ConfigurationNode node) throws SerializationException {
|
||||
Object raw = node.rawScalar();
|
||||
if (!(raw instanceof Number number)) {
|
||||
throw new SerializationException(expectedType, "Expected " + expected);
|
||||
}
|
||||
long value = exactLong(expectedType, number);
|
||||
if (value < minimum || value > maximum) {
|
||||
throw new SerializationException(expectedType, "Value is outside the supported range for " + expected);
|
||||
}
|
||||
return converter.apply(value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void serialize(@NotNull Type expectedType, T value, @NotNull ConfigurationNode node) {
|
||||
node.raw(value == null ? null : value.intValue());
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static long exactLong(Type expectedType, Number number) throws SerializationException {
|
||||
try {
|
||||
return switch (number) {
|
||||
case Byte ignored -> number.longValue();
|
||||
case Short ignored -> number.longValue();
|
||||
case Integer ignored -> number.longValue();
|
||||
case Long ignored -> number.longValue();
|
||||
case BigInteger value -> value.longValueExact();
|
||||
case BigDecimal value -> value.longValueExact();
|
||||
default -> exactLongFromFloatingPoint(expectedType, number.doubleValue());
|
||||
};
|
||||
} catch (ArithmeticException exception) {
|
||||
throw new SerializationException(expectedType, "Expected an integer", exception);
|
||||
}
|
||||
}
|
||||
|
||||
private static long exactLongFromFloatingPoint(Type expectedType, double value) throws SerializationException {
|
||||
if (!Double.isFinite(value) || Math.rint(value) != value || value < Long.MIN_VALUE || value > Long.MAX_VALUE) {
|
||||
throw new SerializationException(expectedType, "Expected an integer");
|
||||
}
|
||||
return (long) value;
|
||||
}
|
||||
|
||||
private static <T> TypeSerializer<T> enumSerializer(Function<String, T> parser, Function<T, String> writer) {
|
||||
return new TypeSerializer<>() {
|
||||
@Override
|
||||
public T deserialize(@NotNull Type expectedType, @NotNull ConfigurationNode node) throws SerializationException {
|
||||
Object raw = node.rawScalar();
|
||||
if (!(raw instanceof String string)) {
|
||||
throw new SerializationException(expectedType, "Expected a string");
|
||||
}
|
||||
T parsed = parser.apply(string);
|
||||
if (parsed == null) {
|
||||
throw new SerializationException(expectedType, "Unsupported value '" + string + "'");
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void serialize(@NotNull Type expectedType, T value, @NotNull ConfigurationNode node) {
|
||||
node.raw(value == null ? null : writer.apply(value));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static TypeSerializer<BlockSelector> blockSelectorSerializer() {
|
||||
return new TypeSerializer<>() {
|
||||
@Override
|
||||
public BlockSelector deserialize(@NotNull Type expectedType, @NotNull ConfigurationNode node) throws SerializationException {
|
||||
Object raw = node.rawScalar();
|
||||
if (!(raw instanceof String value)) {
|
||||
throw new SerializationException(expectedType, "Expected a namespaced block selector");
|
||||
}
|
||||
try {
|
||||
return BlockSelector.parse(value);
|
||||
} catch (IllegalArgumentException exception) {
|
||||
throw new SerializationException(expectedType, exception.getMessage(), exception);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void serialize(@NotNull Type expectedType, BlockSelector value, @NotNull ConfigurationNode node) {
|
||||
node.raw(value == null ? null : value.toString());
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
package games.cubi.raycastedantiesp.core.config;
|
||||
|
||||
import org.spongepowered.configurate.CommentedConfigurationNode;
|
||||
import org.spongepowered.configurate.ConfigurationNode;
|
||||
import org.spongepowered.configurate.ConfigurateException;
|
||||
import org.spongepowered.configurate.NodePath;
|
||||
import org.spongepowered.configurate.transformation.ConfigurationTransformation;
|
||||
import org.spongepowered.configurate.transformation.MoveStrategy;
|
||||
|
||||
/** Upgrades supported on-disk schemas before defaults are merged or objects are mapped. */
|
||||
final class ConfigMigration {
|
||||
private static final String PREVIOUS_CONFIG_VERSION = "2.0";
|
||||
private static final ConfigurationTransformation VERSION_2_1_TRANSFORMATION = createVersion21Transformation();
|
||||
|
||||
private ConfigMigration() {
|
||||
}
|
||||
|
||||
static boolean migrate(CommentedConfigurationNode node) {
|
||||
ConfigurationNode versionNode = node.node("config-version");
|
||||
Object rawVersion = versionNode.raw();
|
||||
if (rawVersion == null) {
|
||||
versionNode.raw(RootConfig.CURRENT_VERSION);
|
||||
return true;
|
||||
}
|
||||
if (!(rawVersion instanceof String version)) {
|
||||
throw new ConfigLoadException("config-version must be a string");
|
||||
}
|
||||
if (RootConfig.CURRENT_VERSION.equals(version)) {
|
||||
return false;
|
||||
}
|
||||
if (!PREVIOUS_CONFIG_VERSION.equals(version)) {
|
||||
throw unsupportedVersion(version);
|
||||
}
|
||||
|
||||
try {
|
||||
VERSION_2_1_TRANSFORMATION.apply(node);
|
||||
} catch (ConfigurateException e) {
|
||||
throw new ConfigLoadException("Failed to migrate config-version '" + PREVIOUS_CONFIG_VERSION + "' to '" + RootConfig.CURRENT_VERSION + "'", e);
|
||||
}
|
||||
versionNode.raw(RootConfig.CURRENT_VERSION);
|
||||
return true;
|
||||
}
|
||||
|
||||
static ConfigLoadException unsupportedVersion(String version) {
|
||||
return new ConfigLoadException(
|
||||
"Unsupported config-version '" + version + "'. RaycastedAntiESP requires config-version '"
|
||||
+ RootConfig.CURRENT_VERSION + "'."
|
||||
);
|
||||
}
|
||||
|
||||
private static ConfigurationTransformation createVersion21Transformation() {
|
||||
ConfigurationTransformation.Builder builder = ConfigurationTransformation.builder().moveStrategy(MoveStrategy.MERGE);
|
||||
addMove(builder, "info-level", "info", "level");
|
||||
addMove(builder, "info-exempted-classes", "info", "exempted-classes");
|
||||
addMove(builder, "warn-level", "warn", "level");
|
||||
addMove(builder, "warn-exempted-classes", "warn", "exempted-classes");
|
||||
addMove(builder, "error-level", "error", "level");
|
||||
addMove(builder, "error-exempted-classes", "error", "exempted-classes");
|
||||
builder.addAction(NodePath.path("block-processor", "packetevents"), (path, value) -> {
|
||||
value.raw(null);
|
||||
return null;
|
||||
});
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
private static void addMove(ConfigurationTransformation.Builder builder, String oldKey, String severity, String newKey) {
|
||||
builder.addAction(NodePath.path("debug", oldKey), (path, value) -> new Object[] {"logging", severity, newKey});
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
package games.cubi.raycastedantiesp.core.config;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Documented
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.RECORD_COMPONENT})
|
||||
public @interface ConfigRange {
|
||||
long min();
|
||||
|
||||
long max();
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.core.config;
|
||||
|
||||
import org.spongepowered.configurate.ConfigurationNode;
|
||||
import org.spongepowered.configurate.serialize.SerializationException;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.BigInteger;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public final class ConfigReader {
|
||||
private ConfigReader() {}
|
||||
|
||||
public static ConfigurationNode node(ConfigurationNode parent, String... path) {
|
||||
return parent.node((Object[]) path);
|
||||
}
|
||||
|
||||
public static String string(ConfigurationNode node, String path) {
|
||||
Object raw = node.raw();
|
||||
if (raw instanceof String value) {
|
||||
return value;
|
||||
}
|
||||
throw invalid(path, "string", raw);
|
||||
}
|
||||
|
||||
public static int integer(ConfigurationNode node, String path) {
|
||||
Object raw = node.raw();
|
||||
if (raw instanceof Number value) {
|
||||
return exactInteger(value, path, "integer");
|
||||
}
|
||||
throw invalid(path, "integer", raw);
|
||||
}
|
||||
|
||||
public static boolean bool(ConfigurationNode node, String path) {
|
||||
Object raw = node.raw();
|
||||
if (raw instanceof Boolean value) {
|
||||
return value;
|
||||
}
|
||||
throw invalid(path, "boolean", raw);
|
||||
}
|
||||
|
||||
public static List<String> stringList(ConfigurationNode node, String path) {
|
||||
if (node.virtual() || node.raw() == null) {
|
||||
return List.of();
|
||||
}
|
||||
if (node.childrenList().isEmpty()) {
|
||||
Object raw = node.raw();
|
||||
if (raw instanceof List<?> list && list.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
throw invalid(path, "list of strings", raw);
|
||||
}
|
||||
List<String> values = new ArrayList<>();
|
||||
for (ConfigurationNode child : node.childrenList()) {
|
||||
Object raw = child.raw();
|
||||
if (!(raw instanceof String value)) {
|
||||
throw invalid(path, "list of strings", raw);
|
||||
}
|
||||
values.add(value);
|
||||
}
|
||||
return List.copyOf(values);
|
||||
}
|
||||
|
||||
public static List<Integer> integerList(ConfigurationNode node, String path) {
|
||||
if (node.virtual() || node.raw() == null) {
|
||||
return List.of();
|
||||
}
|
||||
if (node.childrenList().isEmpty()) {
|
||||
Object raw = node.raw();
|
||||
if (raw instanceof List<?> list && list.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
throw invalid(path, "list of integers", raw);
|
||||
}
|
||||
List<Integer> values = new ArrayList<>();
|
||||
for (ConfigurationNode child : node.childrenList()) {
|
||||
Object raw = child.raw();
|
||||
if (!(raw instanceof Number value)) {
|
||||
throw invalid(path, "list of integers", raw);
|
||||
}
|
||||
int id = exactInteger(value, path, "list of integers");
|
||||
if (id < 0) {
|
||||
throw new ConfigLoadException(path + " cannot contain negative block state IDs: " + id);
|
||||
}
|
||||
values.add(id);
|
||||
}
|
||||
return List.copyOf(values);
|
||||
}
|
||||
|
||||
public static Object parseRawValue(String rawValue) {
|
||||
try {
|
||||
ConfigurationNode parsed = org.spongepowered.configurate.yaml.YamlConfigurationLoader.builder()
|
||||
.source(() -> new java.io.BufferedReader(new java.io.StringReader("value: " + rawValue)))
|
||||
.build()
|
||||
.load();
|
||||
return parsed.node("value").raw();
|
||||
} catch (java.io.IOException e) {
|
||||
throw new ConfigLoadException("Invalid YAML value: " + rawValue, e);
|
||||
}
|
||||
}
|
||||
|
||||
public static void setRaw(ConfigurationNode node, Object value) {
|
||||
try {
|
||||
node.set(value);
|
||||
} catch (SerializationException e) {
|
||||
throw new ConfigLoadException("Failed to set config value", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static ConfigLoadException invalid(String path, String expected, Object raw) {
|
||||
String actual = raw == null ? "null" : raw.getClass().getSimpleName();
|
||||
return new ConfigLoadException(path + " must be a " + expected + " but was " + actual);
|
||||
}
|
||||
|
||||
private static int exactInteger(Number value, String path, String expected) {
|
||||
try {
|
||||
return switch (value) {
|
||||
case Byte ignored -> value.intValue();
|
||||
case Short ignored -> value.intValue();
|
||||
case Integer ignored -> value.intValue();
|
||||
case Long longValue -> {
|
||||
if (longValue < Integer.MIN_VALUE || longValue > Integer.MAX_VALUE) {
|
||||
throw invalid(path, expected, value);
|
||||
}
|
||||
yield longValue.intValue();
|
||||
}
|
||||
case BigInteger bigInteger -> bigInteger.intValueExact();
|
||||
case BigDecimal bigDecimal -> bigDecimal.intValueExact();
|
||||
default -> exactIntegerFromFloatingPoint(value, path, expected);
|
||||
};
|
||||
} catch (ArithmeticException e) {
|
||||
throw invalid(path, expected, value);
|
||||
}
|
||||
}
|
||||
|
||||
private static int exactIntegerFromFloatingPoint(Number value, String path, String expected) {
|
||||
double doubleValue = value.doubleValue();
|
||||
if (!Double.isFinite(doubleValue)
|
||||
|| Math.rint(doubleValue) != doubleValue
|
||||
|| doubleValue < Integer.MIN_VALUE
|
||||
|| doubleValue > Integer.MAX_VALUE) {
|
||||
throw invalid(path, expected, value);
|
||||
}
|
||||
return (int) doubleValue;
|
||||
}
|
||||
}
|
||||
@@ -8,23 +8,78 @@
|
||||
|
||||
package games.cubi.raycastedantiesp.core.config;
|
||||
|
||||
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
|
||||
import org.spongepowered.configurate.objectmapping.meta.Comment;
|
||||
import org.spongepowered.configurate.ConfigurationNode;
|
||||
|
||||
@ConfigSerializable
|
||||
public record DebugConfig(
|
||||
@Comment("Show raycast debug particles.")
|
||||
boolean particles,
|
||||
@Comment("Record and report engine timing information.")
|
||||
boolean timings
|
||||
) implements Config {
|
||||
public static final DebugConfig DEFAULT = new DebugConfig(false, false);
|
||||
import java.util.List;
|
||||
|
||||
public record DebugConfig(byte infoLevel, List<String> infoExemptedClasses, byte warnLevel, List<String> warnExemptedClasses,
|
||||
byte errorLevel, List<String> errorExemptedClasses, boolean debugParticles, boolean timings) implements Config {
|
||||
|
||||
public static DebugConfig load(ConfigurationNode root) {
|
||||
ConfigurationNode node = ConfigReader.node(root, "debug");
|
||||
return new DebugConfig(
|
||||
level(ConfigReader.node(node, "info-level"), "debug.info-level"),
|
||||
ConfigReader.stringList(ConfigReader.node(node, "info-exempted-classes"), "debug.info-exempted-classes"),
|
||||
level(ConfigReader.node(node, "warn-level"), "debug.warn-level"),
|
||||
ConfigReader.stringList(ConfigReader.node(node, "warn-exempted-classes"), "debug.warn-exempted-classes"),
|
||||
level(ConfigReader.node(node, "error-level"), "debug.error-level"),
|
||||
ConfigReader.stringList(ConfigReader.node(node, "error-exempted-classes"), "debug.error-exempted-classes"),
|
||||
ConfigReader.bool(ConfigReader.node(node, "particles"), "debug.particles"),
|
||||
ConfigReader.bool(ConfigReader.node(node, "timings"), "debug.timings")
|
||||
);
|
||||
}
|
||||
|
||||
public byte getInfoLevel() {
|
||||
return infoLevel;
|
||||
}
|
||||
|
||||
public byte getWarnLevel() {
|
||||
return warnLevel;
|
||||
}
|
||||
|
||||
public byte getErrorLevel() {
|
||||
return errorLevel;
|
||||
}
|
||||
|
||||
public boolean showDebugParticles() {
|
||||
return particles;
|
||||
return debugParticles;
|
||||
}
|
||||
|
||||
public boolean recordTimings() {
|
||||
return timings;
|
||||
}
|
||||
|
||||
public boolean isExempted(Severity severity, Class<?>... sources) {
|
||||
List<String> exempted = switch (severity) {
|
||||
case INFO -> infoExemptedClasses;
|
||||
case WARN -> warnExemptedClasses;
|
||||
case ERROR -> errorExemptedClasses;
|
||||
};
|
||||
if (sources == null || exempted.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
for (Class<?> source : sources) {
|
||||
if (source == null) {
|
||||
continue;
|
||||
}
|
||||
if (exempted.contains(source.getSimpleName()) || exempted.contains(source.getName())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static byte level(ConfigurationNode node, String path) {
|
||||
int level = ConfigReader.integer(node, path);
|
||||
if (level < 0 || level > 10) {
|
||||
throw new ConfigLoadException(path + " must be between 0 and 10");
|
||||
}
|
||||
return (byte) level;
|
||||
}
|
||||
|
||||
public enum Severity {
|
||||
INFO,
|
||||
WARN,
|
||||
ERROR
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
package games.cubi.raycastedantiesp.core.config;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/** Adds comments to collection entries matched by their serialized string values, without replacing existing comments. */
|
||||
@Documented
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.RECORD_COMPONENT})
|
||||
public @interface ListEntryComments {
|
||||
Entry[] value();
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target({})
|
||||
@interface Entry {
|
||||
String value();
|
||||
|
||||
String comment();
|
||||
}
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
package games.cubi.raycastedantiesp.core.config;
|
||||
|
||||
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
|
||||
import org.spongepowered.configurate.objectmapping.meta.Comment;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@ConfigSerializable
|
||||
public record LogLevelConfig(
|
||||
@Comment("Messages above this level are suppressed. Set to 0 to suppress this severity.")
|
||||
@ConfigRange(min = 0, max = 10)
|
||||
byte level,
|
||||
@Comment("Simple or fully qualified class names whose messages should be suppressed.")
|
||||
List<String> exemptedClasses
|
||||
) implements Config {
|
||||
public static final LogLevelConfig DEFAULT = new LogLevelConfig((byte) 5, List.of());
|
||||
|
||||
public LogLevelConfig {
|
||||
exemptedClasses = List.copyOf(exemptedClasses);
|
||||
}
|
||||
|
||||
public boolean isExempted(Class<?>... sources) {
|
||||
if (sources == null || exemptedClasses.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
for (Class<?> source : sources) {
|
||||
if (source != null && (exemptedClasses.contains(source.getSimpleName()) || exemptedClasses.contains(source.getName()))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
package games.cubi.raycastedantiesp.core.config;
|
||||
|
||||
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
|
||||
|
||||
@ConfigSerializable
|
||||
public record LoggingConfig(LogLevelConfig info, LogLevelConfig warn, LogLevelConfig error) implements Config {
|
||||
public static final LoggingConfig DEFAULT = new LoggingConfig(LogLevelConfig.DEFAULT, LogLevelConfig.DEFAULT, LogLevelConfig.DEFAULT);
|
||||
|
||||
public LogLevelConfig forSeverity(Severity severity) {
|
||||
return switch (severity) {
|
||||
case INFO -> info;
|
||||
case WARN -> warn;
|
||||
case ERROR -> error;
|
||||
};
|
||||
}
|
||||
|
||||
public enum Severity {
|
||||
INFO,
|
||||
WARN,
|
||||
ERROR
|
||||
}
|
||||
}
|
||||
@@ -9,27 +9,12 @@
|
||||
package games.cubi.raycastedantiesp.core.config;
|
||||
|
||||
import games.cubi.raycastedantiesp.core.config.engine.EngineConfig;
|
||||
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
|
||||
import org.spongepowered.configurate.objectmapping.meta.Setting;
|
||||
|
||||
@ConfigSerializable
|
||||
public record RootConfig(
|
||||
String configVersion,
|
||||
@Setting("logging") LoggingConfig loggingConfig,
|
||||
@Setting("checks") ChecksConfig checksConfig,
|
||||
@Setting("engine") EngineConfig engineConfig,
|
||||
@Setting("block-processor") BlockProcessorConfig blockProcessorConfig,
|
||||
@Setting("debug") DebugConfig debugConfig,
|
||||
@Setting("updates") UpdateConfig updateConfig
|
||||
) implements Config {
|
||||
public static final String CURRENT_VERSION = "2.1";
|
||||
public static final RootConfig DEFAULT = new RootConfig(
|
||||
CURRENT_VERSION,
|
||||
LoggingConfig.DEFAULT,
|
||||
ChecksConfig.DEFAULT,
|
||||
EngineConfig.DEFAULT,
|
||||
BlockProcessorConfig.DEFAULT,
|
||||
DebugConfig.DEFAULT,
|
||||
UpdateConfig.DEFAULT
|
||||
);
|
||||
import java.util.Map;
|
||||
|
||||
public record RootConfig(String configVersion, ChecksConfig checksConfig, EngineConfig engineConfig, BlockProcessorConfig blockProcessorConfig, DebugConfig debugConfig, UpdateConfig updateConfig, Map<Class<? extends Config>, Config> extensionConfigs) implements Config {
|
||||
public <T extends Config> T extensionConfig(Class<T> type) {
|
||||
Config config = extensionConfigs.get(type);
|
||||
return type.cast(config);
|
||||
}
|
||||
}
|
||||
@@ -8,18 +8,19 @@
|
||||
|
||||
package games.cubi.raycastedantiesp.core.config;
|
||||
|
||||
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
|
||||
import org.spongepowered.configurate.objectmapping.meta.Comment;
|
||||
import org.spongepowered.configurate.ConfigurationNode;
|
||||
|
||||
@ConfigSerializable
|
||||
public record UpdateConfig(
|
||||
boolean checkRelease,
|
||||
boolean checkBeta,
|
||||
boolean checkAlpha,
|
||||
@Comment("When true, players with permission are notified; otherwise only the console is notified.")
|
||||
boolean notifyInGame
|
||||
) implements Config {
|
||||
public static final UpdateConfig DEFAULT = new UpdateConfig(true, true, true, true);
|
||||
public record UpdateConfig(boolean checkRelease, boolean checkBeta, boolean checkAlpha, boolean notifyInGame) implements Config {
|
||||
|
||||
public static UpdateConfig load(ConfigurationNode root) {
|
||||
ConfigurationNode node = ConfigReader.node(root, "updates");
|
||||
return new UpdateConfig(
|
||||
ConfigReader.bool(ConfigReader.node(node, "check-release"), "updates.check-release"),
|
||||
ConfigReader.bool(ConfigReader.node(node, "check-beta"), "updates.check-beta"),
|
||||
ConfigReader.bool(ConfigReader.node(node, "check-alpha"), "updates.check-alpha"),
|
||||
ConfigReader.bool(ConfigReader.node(node, "notify-in-game"), "updates.notify-in-game")
|
||||
);
|
||||
}
|
||||
|
||||
public boolean anyChannelEnabled() {
|
||||
return checkRelease || checkBeta || checkAlpha;
|
||||
|
||||
+11
-12
@@ -9,17 +9,16 @@
|
||||
package games.cubi.raycastedantiesp.core.config.engine;
|
||||
|
||||
import games.cubi.raycastedantiesp.core.config.Config;
|
||||
import games.cubi.raycastedantiesp.core.config.ConfigRange;
|
||||
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
|
||||
import org.spongepowered.configurate.objectmapping.meta.Comment;
|
||||
import org.spongepowered.configurate.objectmapping.meta.Setting;
|
||||
import games.cubi.raycastedantiesp.core.config.ConfigLoadException;
|
||||
import games.cubi.raycastedantiesp.core.config.ConfigReader;
|
||||
import org.spongepowered.configurate.ConfigurationNode;
|
||||
|
||||
@ConfigSerializable
|
||||
public record AsyncEngineConfig(
|
||||
@Setting("processing-threads")
|
||||
@Comment("Number of async processing threads. One is sufficient for hundreds of players.")
|
||||
@ConfigRange(min = 1, max = 64)
|
||||
int asyncProcessingThreads
|
||||
) implements Config {
|
||||
public static final AsyncEngineConfig DEFAULT = new AsyncEngineConfig(1);
|
||||
public record AsyncEngineConfig(int asyncProcessingThreads) implements Config {
|
||||
public static AsyncEngineConfig load(ConfigurationNode node) {
|
||||
int threads = ConfigReader.integer(ConfigReader.node(node, "processing-threads"), "engine.async.processing-threads");
|
||||
if (threads < 1) {
|
||||
throw new ConfigLoadException("engine.async.processing-threads must be at least 1");
|
||||
}
|
||||
return new AsyncEngineConfig(threads);
|
||||
}
|
||||
}
|
||||
+13
-8
@@ -9,15 +9,20 @@
|
||||
package games.cubi.raycastedantiesp.core.config.engine;
|
||||
|
||||
import games.cubi.raycastedantiesp.core.config.Config;
|
||||
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
|
||||
import org.spongepowered.configurate.objectmapping.meta.Setting;
|
||||
import games.cubi.raycastedantiesp.core.config.ConfigLoadException;
|
||||
import games.cubi.raycastedantiesp.core.config.ConfigReader;
|
||||
import org.spongepowered.configurate.ConfigurationNode;
|
||||
|
||||
@ConfigSerializable
|
||||
public record EngineConfig(
|
||||
EngineMode mode,
|
||||
@Setting("async") AsyncEngineConfig asyncConfig
|
||||
) implements Config {
|
||||
public static final EngineConfig DEFAULT = new EngineConfig(EngineMode.ASYNC, AsyncEngineConfig.DEFAULT);
|
||||
public record EngineConfig(EngineMode mode, AsyncEngineConfig asyncConfig) implements Config {
|
||||
public static EngineConfig load(ConfigurationNode root) {
|
||||
ConfigurationNode node = ConfigReader.node(root, "engine");
|
||||
String modeName = ConfigReader.string(ConfigReader.node(node, "mode"), "engine.mode");
|
||||
EngineMode mode = EngineMode.fromString(modeName);
|
||||
if (mode == null) {
|
||||
throw new ConfigLoadException("engine.mode has unsupported value '" + modeName + "'");
|
||||
}
|
||||
return new EngineConfig(mode, AsyncEngineConfig.load(ConfigReader.node(node, "async")));
|
||||
}
|
||||
|
||||
public EngineMode getMode() {
|
||||
return mode;
|
||||
|
||||
@@ -1,93 +0,0 @@
|
||||
package games.cubi.raycastedantiesp.core.config.raycast;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* A namespaced block key, optionally restricted by property values. Omitted properties match any value.
|
||||
*/
|
||||
public record BlockSelector(String value) {
|
||||
private static final Pattern NAMESPACE = Pattern.compile("[a-z0-9_.-]+");
|
||||
private static final Pattern PATH = Pattern.compile("[a-z0-9/._-]+");
|
||||
private static final Pattern PROPERTY = Pattern.compile("[a-z0-9_]+");
|
||||
|
||||
public BlockSelector {
|
||||
validate(value);
|
||||
}
|
||||
|
||||
public static BlockSelector parse(String input) {
|
||||
return new BlockSelector(input);
|
||||
}
|
||||
|
||||
public String blockKey() {
|
||||
int openingBracket = value.indexOf('[');
|
||||
return openingBracket < 0 ? value : value.substring(0, openingBracket);
|
||||
}
|
||||
|
||||
public boolean matchesAllStates() {
|
||||
return value.indexOf('[') < 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull String toString() {
|
||||
return value;
|
||||
}
|
||||
|
||||
private static void validate(String input) {
|
||||
Objects.requireNonNull(input, "value");
|
||||
int openingBracket = input.indexOf('[');
|
||||
if (openingBracket < 0) {
|
||||
if (input.indexOf(']') >= 0) {
|
||||
throw new IllegalArgumentException("Unexpected closing bracket in block selector");
|
||||
}
|
||||
validateBlockKey(input);
|
||||
return;
|
||||
}
|
||||
if (!input.endsWith("]") || input.indexOf('[', openingBracket + 1) >= 0
|
||||
|| input.indexOf(']', openingBracket) != input.length() - 1) {
|
||||
throw new IllegalArgumentException("Malformed block-state properties");
|
||||
}
|
||||
|
||||
String propertyText = input.substring(openingBracket + 1, input.length() - 1);
|
||||
if (propertyText.isEmpty()) {
|
||||
throw new IllegalArgumentException("Block-state properties cannot be empty");
|
||||
}
|
||||
|
||||
validateBlockKey(input.substring(0, openingBracket));
|
||||
Set<String> properties = new HashSet<>();
|
||||
for (String assignment : propertyText.split(",", -1)) {
|
||||
int equals = assignment.indexOf('=');
|
||||
if (equals <= 0 || equals != assignment.lastIndexOf('=') || equals == assignment.length() - 1) {
|
||||
throw new IllegalArgumentException("Invalid block-state property '" + assignment + "'");
|
||||
}
|
||||
String name = validateProperty(assignment.substring(0, equals), "property name");
|
||||
validateProperty(assignment.substring(equals + 1), "property value");
|
||||
if (!properties.add(name)) {
|
||||
throw new IllegalArgumentException("Duplicate block property '" + name + "'");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String validateBlockKey(String blockKey) {
|
||||
Objects.requireNonNull(blockKey, "blockKey");
|
||||
int separator = blockKey.indexOf(':');
|
||||
if (separator <= 0 || separator != blockKey.lastIndexOf(':') || separator == blockKey.length() - 1
|
||||
|| !NAMESPACE.matcher(blockKey.substring(0, separator)).matches()
|
||||
|| !PATH.matcher(blockKey.substring(separator + 1)).matches()) {
|
||||
throw new IllegalArgumentException("Invalid namespaced block key '" + blockKey + "'");
|
||||
}
|
||||
return blockKey;
|
||||
}
|
||||
|
||||
private static String validateProperty(String value, String description) {
|
||||
Objects.requireNonNull(value, description);
|
||||
if (!PROPERTY.matcher(value).matches()) {
|
||||
throw new IllegalArgumentException("Invalid block-state " + description + " '" + value + "'");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
}
|
||||
+11
-14
@@ -9,19 +9,16 @@
|
||||
package games.cubi.raycastedantiesp.core.config.raycast;
|
||||
|
||||
import games.cubi.raycastedantiesp.core.config.Config;
|
||||
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
|
||||
import org.spongepowered.configurate.objectmapping.meta.Comment;
|
||||
import games.cubi.raycastedantiesp.core.config.ConfigReader;
|
||||
import org.spongepowered.configurate.ConfigurationNode;
|
||||
|
||||
@ConfigSerializable
|
||||
public record ChunkSectionConfig(
|
||||
@Comment("Whether chunk sections are hidden when they cannot be seen. This feature is not implemented yet.")
|
||||
boolean enabled,
|
||||
@Comment("Maximum number of occluding blocks permitted by a successful raycast.")
|
||||
int maxOccludingCount,
|
||||
@Comment("Radius in chunks within which chunk sections are always visible.")
|
||||
int alwaysShowRadiusChunks,
|
||||
@Comment("Ticks between checks of visible chunk sections. -1 disables visible rechecks.")
|
||||
int visibleRecheckIntervalTicks
|
||||
) implements Config {
|
||||
public static final ChunkSectionConfig DEFAULT = new ChunkSectionConfig(false, 6, 2, -1);
|
||||
public record ChunkSectionConfig(boolean enabled, int maxOccludingCount, int alwaysShowRadiusChunks, int visibleRecheckIntervalTicks) implements Config {
|
||||
public static ChunkSectionConfig load(ConfigurationNode node, String path) {
|
||||
return new ChunkSectionConfig(
|
||||
ConfigReader.bool(ConfigReader.node(node, "enabled"), path + ".enabled"),
|
||||
ConfigReader.integer(ConfigReader.node(node, "max-occluding-count"), path + ".max-occluding-count"),
|
||||
ConfigReader.integer(ConfigReader.node(node, "always-show-radius-chunks"), path + ".always-show-radius-chunks"),
|
||||
ConfigReader.integer(ConfigReader.node(node, "visible-recheck-interval-ticks"), path + ".visible-recheck-interval-ticks")
|
||||
);
|
||||
}
|
||||
}
|
||||
+17
-72
@@ -8,84 +8,29 @@
|
||||
|
||||
package games.cubi.raycastedantiesp.core.config.raycast;
|
||||
|
||||
import games.cubi.raycastedantiesp.core.config.ListEntryComments;
|
||||
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
|
||||
import org.spongepowered.configurate.objectmapping.meta.Comment;
|
||||
import org.spongepowered.configurate.objectmapping.meta.Setting;
|
||||
import games.cubi.raycastedantiesp.core.config.ConfigReader;
|
||||
import org.spongepowered.configurate.ConfigurationNode;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
@ConfigSerializable
|
||||
public record EntityConfig(
|
||||
@Setting(nodeFromParent = true)
|
||||
RaycastSettings raycastSettings,
|
||||
@Comment("Suppress sounds produced by hidden entities.")
|
||||
boolean hideSoundsWhenHidden,
|
||||
@Comment("Retain hidden entities client-side instead of destroying them. This will cause a non-moving \"ghost player\" to persist until the real player is visible again, but can reduce network load around large mob farms or bases.")
|
||||
boolean keepClientEntityWhenHidden,
|
||||
@Comment("""
|
||||
Entity types that must always remain visible.
|
||||
public class EntityConfig extends RaycastConfig {
|
||||
private final Set<String> excludedTypes;
|
||||
|
||||
Falling blocks are also often used in custom mechanics, especially by plugins predating display entities. However, they occur in regular gameplay and can reveal information about hidden players, so they are not excluded by default. To exclude them, add minecraft:falling_block.
|
||||
private EntityConfig(RaycastConfig config, List<String> excludedTypes) {
|
||||
super(config.enabled(), config.hideSoundsWhenHidden(), config.getMaxOccludingCount(), config.getAlwaysShowRadius(),
|
||||
config.getRaycastRadius(), config.hideOnSpawnDistance(), config.getVisibleRecheckIntervalTicks(),
|
||||
config.keepClientEntityWhenHidden());
|
||||
this.excludedTypes = Set.copyOf(excludedTypes);
|
||||
}
|
||||
|
||||
Add further exclusions using the namespaced entity name accepted by the /summon command.
|
||||
""")
|
||||
@ListEntryComments({
|
||||
@ListEntryComments.Entry(value = "minecraft:arrow", comment =
|
||||
"Projectiles move very quickly, giving the raycast engine limited time to process them. "
|
||||
+ "This could leave players without enough time to dodge, so projectiles are always visible by default."),
|
||||
@ListEntryComments.Entry(value = "minecraft:area_effect_cloud", comment =
|
||||
"Potions and area-effect clouds can damage players even when not visible. "
|
||||
+ "A reasonable always-show-radius mitigates this, so exempting them is not always necessary. "
|
||||
+ "Servers where knowing the exact number of potions another player has used is an unfair advantage may want to remove these exclusions."),
|
||||
@ListEntryComments.Entry(value = "minecraft:potion", comment =
|
||||
"The minecraft:potion entity was removed in 1.21.5 and replaced by minecraft:splash_potion and minecraft:lingering_potion. "
|
||||
+ "On 1.21.4, remove the latter two entries; on 1.21.5 and newer, remove minecraft:potion instead."),
|
||||
@ListEntryComments.Entry(value = "minecraft:lightning_bolt", comment = "Lightning is short-lived and expected to be visible to players who cannot see the block being struck."),
|
||||
@ListEntryComments.Entry(value = "minecraft:ender_dragon", comment = "Boss entities are also always visible by default."),
|
||||
@ListEntryComments.Entry(value = "minecraft:block_display", comment =
|
||||
"Display, interaction, and mannequin entities are not normally seen in vanilla gameplay and are commonly used for custom mechanics. "
|
||||
+ "Removing these exclusions is likely to break plugins such as hologram or NPC plugins.")
|
||||
})
|
||||
Set<String> excludedTypes
|
||||
) implements RaycastConfig {
|
||||
public static final EntityConfig DEFAULT = new EntityConfig(
|
||||
new RaycastSettings(true, (byte) 3, (short) 8, (short) 92, (short) 24, (short) 5),
|
||||
false,
|
||||
false,
|
||||
new LinkedHashSet<>(List.of(
|
||||
"minecraft:arrow",
|
||||
"minecraft:spectral_arrow",
|
||||
"minecraft:fireball",
|
||||
"minecraft:dragon_fireball",
|
||||
"minecraft:small_fireball",
|
||||
"minecraft:firework_rocket",
|
||||
"minecraft:wither_skull",
|
||||
"minecraft:breeze_wind_charge",
|
||||
"minecraft:wind_charge",
|
||||
"minecraft:ender_pearl",
|
||||
"minecraft:evoker_fangs",
|
||||
"minecraft:shulker_bullet",
|
||||
"minecraft:area_effect_cloud",
|
||||
"minecraft:lingering_potion",
|
||||
"minecraft:splash_potion",
|
||||
"minecraft:potion",
|
||||
"minecraft:lightning_bolt",
|
||||
"minecraft:ender_dragon",
|
||||
"minecraft:wither",
|
||||
"minecraft:warden",
|
||||
"minecraft:block_display",
|
||||
"minecraft:text_display",
|
||||
"minecraft:item_display",
|
||||
"minecraft:interaction",
|
||||
"minecraft:mannequin"
|
||||
))
|
||||
);
|
||||
public static EntityConfig load(ConfigurationNode node, String path) {
|
||||
RaycastConfig config = RaycastConfig.load(node, path, true, true);
|
||||
List<String> excludedTypes = ConfigReader.stringList(ConfigReader.node(node, "excluded-types"), path + ".excluded-types");
|
||||
return new EntityConfig(config, excludedTypes);
|
||||
}
|
||||
|
||||
public EntityConfig {
|
||||
excludedTypes = Collections.unmodifiableSet(new LinkedHashSet<>(excludedTypes));
|
||||
public Set<String> excludedTypes() {
|
||||
return excludedTypes;
|
||||
}
|
||||
}
|
||||
+22
-20
@@ -8,25 +8,27 @@
|
||||
|
||||
package games.cubi.raycastedantiesp.core.config.raycast;
|
||||
|
||||
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
|
||||
import org.spongepowered.configurate.objectmapping.meta.Comment;
|
||||
import org.spongepowered.configurate.objectmapping.meta.Setting;
|
||||
import games.cubi.raycastedantiesp.core.config.ConfigReader;
|
||||
import org.spongepowered.configurate.ConfigurationNode;
|
||||
|
||||
@ConfigSerializable
|
||||
public record PlayerConfig(
|
||||
@Setting(nodeFromParent = true)
|
||||
RaycastSettings raycastSettings,
|
||||
@Comment("Suppress sounds produced by hidden players.")
|
||||
boolean hideSoundsWhenHidden,
|
||||
@Comment("Retain hidden players client-side instead of destroying their entities. This will cause a non-moving \"ghost player\" to persist until the real player is visible again.")
|
||||
boolean keepClientEntityWhenHidden,
|
||||
@Comment("Only raycast other players while the viewing player is sneaking.")
|
||||
boolean onlyCheckSneaking
|
||||
) implements RaycastConfig {
|
||||
public static final PlayerConfig DEFAULT = new PlayerConfig(
|
||||
new RaycastSettings(true, (byte) 3, (short) 8, (short) 128, (short) 24, (short) 5),
|
||||
false,
|
||||
false,
|
||||
true
|
||||
);
|
||||
public class PlayerConfig extends RaycastConfig {
|
||||
private final boolean onlyCheckSneaking;
|
||||
|
||||
private PlayerConfig(RaycastConfig config, boolean onlyCheckSneaking) {
|
||||
super(config.enabled(), config.hideSoundsWhenHidden(), config.getMaxOccludingCount(), config.getAlwaysShowRadius(),
|
||||
config.getRaycastRadius(), config.hideOnSpawnDistance(), config.getVisibleRecheckIntervalTicks(),
|
||||
config.keepClientEntityWhenHidden());
|
||||
this.onlyCheckSneaking = onlyCheckSneaking;
|
||||
}
|
||||
|
||||
public static PlayerConfig load(ConfigurationNode node, String path) {
|
||||
return new PlayerConfig(
|
||||
RaycastConfig.load(node, path, true, true),
|
||||
ConfigReader.bool(ConfigReader.node(node, "only-check-sneaking"), path + ".only-check-sneaking")
|
||||
);
|
||||
}
|
||||
|
||||
public boolean onlyCheckSneaking() {
|
||||
return onlyCheckSneaking;
|
||||
}
|
||||
}
|
||||
+92
-27
@@ -8,55 +8,120 @@
|
||||
|
||||
package games.cubi.raycastedantiesp.core.config.raycast;
|
||||
|
||||
import games.cubi.logs.Logger;
|
||||
import games.cubi.raycastedantiesp.core.config.Config;
|
||||
import games.cubi.raycastedantiesp.core.config.ConfigReader;
|
||||
import org.spongepowered.configurate.ConfigurationNode;
|
||||
|
||||
public interface RaycastConfig extends Config {
|
||||
RaycastSettings raycastSettings();
|
||||
public class RaycastConfig implements Config {
|
||||
private final boolean enabled;
|
||||
private final boolean hideSoundsWhenHidden;
|
||||
private final byte maxOccludingCount;
|
||||
private final short alwaysShowRadius;
|
||||
private final short raycastRadius;
|
||||
private final short hideOnSpawnDistance;
|
||||
private final short visibleRecheckIntervalTicks;
|
||||
private final boolean keepClientEntityWhenHidden;
|
||||
|
||||
default boolean enabled() {
|
||||
return raycastSettings().enabled();
|
||||
public final int alwaysShowRadiusSquared;
|
||||
public final int raycastRadiusSquared;
|
||||
public final int hideOnSpawnDistanceSquared;
|
||||
|
||||
public RaycastConfig(boolean enabled, boolean hideSoundsWhenHidden, int maxOccludingCount, int alwaysShowRadius,
|
||||
int raycastRadius, int hideOnSpawnDistance, int visibleRecheckIntervalTicks) {
|
||||
this(enabled, hideSoundsWhenHidden, maxOccludingCount, alwaysShowRadius, raycastRadius, hideOnSpawnDistance,
|
||||
visibleRecheckIntervalTicks, false);
|
||||
}
|
||||
|
||||
default boolean hideSoundsWhenHidden() {
|
||||
return false;
|
||||
public RaycastConfig(boolean enabled, boolean hideSoundsWhenHidden, int maxOccludingCount, int alwaysShowRadius,
|
||||
int raycastRadius, int hideOnSpawnDistance, int visibleRecheckIntervalTicks,
|
||||
boolean keepClientEntityWhenHidden) {
|
||||
this.enabled = enabled;
|
||||
this.hideSoundsWhenHidden = hideSoundsWhenHidden;
|
||||
this.maxOccludingCount = (byte) maxOccludingCount;
|
||||
this.alwaysShowRadius = (short) alwaysShowRadius;
|
||||
this.raycastRadius = (short) raycastRadius;
|
||||
this.hideOnSpawnDistance = (short) hideOnSpawnDistance;
|
||||
this.visibleRecheckIntervalTicks = (short) visibleRecheckIntervalTicks;
|
||||
this.keepClientEntityWhenHidden = keepClientEntityWhenHidden;
|
||||
|
||||
alwaysShowRadiusSquared = alwaysShowRadius * alwaysShowRadius;
|
||||
raycastRadiusSquared = raycastRadius * raycastRadius;
|
||||
hideOnSpawnDistanceSquared = hideOnSpawnDistance * hideOnSpawnDistance;
|
||||
}
|
||||
|
||||
default byte getMaxOccludingCount() {
|
||||
return raycastSettings().maxOccludingCount();
|
||||
protected static RaycastConfig load(ConfigurationNode node, String path, boolean hasHideSoundsWhenHidden) {
|
||||
return load(node, path, hasHideSoundsWhenHidden, false);
|
||||
}
|
||||
|
||||
default short getAlwaysShowRadius() {
|
||||
return raycastSettings().alwaysShowRadius();
|
||||
protected static RaycastConfig load(ConfigurationNode node, String path, boolean hasHideSoundsWhenHidden,
|
||||
boolean hasKeepClientEntityWhenHidden) {
|
||||
int maxOccludingCount = ConfigReader.integer(ConfigReader.node(node, "max-occluding-count"), path + ".max-occluding-count");
|
||||
if (maxOccludingCount < 0 || maxOccludingCount > Byte.MAX_VALUE) {
|
||||
Logger.warning(path + ".max-occluding-count must be between 0 and " + Byte.MAX_VALUE + " but was " + maxOccludingCount +". Defaulting to 3.", 4, RaycastConfig.class);
|
||||
maxOccludingCount = 3;
|
||||
}
|
||||
int alwaysShowRadius = ConfigReader.integer(ConfigReader.node(node, "always-show-radius"), path + ".always-show-radius");
|
||||
if (alwaysShowRadius < 0 || alwaysShowRadius > Short.MAX_VALUE) {
|
||||
Logger.warning(path + ".always-show-radius must be between 0 and " + Short.MAX_VALUE + " but was " + alwaysShowRadius +". Defaulting to 8.", 4, RaycastConfig.class);
|
||||
alwaysShowRadius = 8;
|
||||
}
|
||||
int raycastRadius = ConfigReader.integer(ConfigReader.node(node, "raycast-radius"), path + ".raycast-radius");
|
||||
if (raycastRadius < 0 || raycastRadius > Short.MAX_VALUE) {
|
||||
Logger.warning(path + ".raycast-radius must be between 0 and " + Short.MAX_VALUE + " but was " + raycastRadius +". Defaulting to 48.", 4, RaycastConfig.class);
|
||||
raycastRadius = 48;
|
||||
}
|
||||
int hideOnSpawnDistance = ConfigReader.integer(ConfigReader.node(node, "hide-on-spawn-distance"), path + ".hide-on-spawn-distance");
|
||||
if (hideOnSpawnDistance < 0 || hideOnSpawnDistance > Short.MAX_VALUE) {
|
||||
Logger.warning(path + ".hide-on-spawn-distance must be between 0 and " + Short.MAX_VALUE + " but was " + hideOnSpawnDistance +". Defaulting to 32.", 4, RaycastConfig.class);
|
||||
hideOnSpawnDistance = 32;
|
||||
}
|
||||
int visibleRecheckIntervalTicks = ConfigReader.integer(ConfigReader.node(node, "visible-recheck-interval-ticks"), path + ".visible-recheck-interval-ticks");
|
||||
if (visibleRecheckIntervalTicks < -1 || visibleRecheckIntervalTicks > Short.MAX_VALUE) {
|
||||
Logger.warning(path + ".visible-recheck-interval-ticks must be between -1 and " + Short.MAX_VALUE + " but was " + visibleRecheckIntervalTicks +". Defaulting to 5.", 4, RaycastConfig.class);
|
||||
visibleRecheckIntervalTicks = 5;
|
||||
}
|
||||
return new RaycastConfig(
|
||||
ConfigReader.bool(ConfigReader.node(node, "enabled"), path + ".enabled"),
|
||||
hasHideSoundsWhenHidden && ConfigReader.bool(ConfigReader.node(node, "hide-sounds-when-hidden"), path + ".hide-sounds-when-hidden"),
|
||||
maxOccludingCount,
|
||||
alwaysShowRadius,
|
||||
raycastRadius,
|
||||
hideOnSpawnDistance,
|
||||
visibleRecheckIntervalTicks,
|
||||
hasKeepClientEntityWhenHidden && ConfigReader.bool(ConfigReader.node(node, "keep-client-entity-when-hidden"), path + ".keep-client-entity-when-hidden")
|
||||
);
|
||||
}
|
||||
|
||||
default short getRaycastRadius() {
|
||||
return raycastSettings().raycastRadius();
|
||||
public boolean enabled() {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
default short hideOnSpawnDistance() {
|
||||
return raycastSettings().hideOnSpawnDistance();
|
||||
public boolean hideSoundsWhenHidden() {
|
||||
return hideSoundsWhenHidden;
|
||||
}
|
||||
|
||||
default short getVisibleRecheckIntervalTicks() {
|
||||
return raycastSettings().visibleRecheckIntervalTicks();
|
||||
public byte getMaxOccludingCount() {
|
||||
return maxOccludingCount;
|
||||
}
|
||||
|
||||
default boolean keepClientEntityWhenHidden() {
|
||||
return false;
|
||||
public short getAlwaysShowRadius() {
|
||||
return alwaysShowRadius;
|
||||
}
|
||||
|
||||
default int alwaysShowRadiusSquared() {
|
||||
int radius = getAlwaysShowRadius();
|
||||
return radius * radius;
|
||||
public short getRaycastRadius() {
|
||||
return raycastRadius;
|
||||
}
|
||||
|
||||
default int raycastRadiusSquared() {
|
||||
int radius = getRaycastRadius();
|
||||
return radius * radius;
|
||||
public short hideOnSpawnDistance() {
|
||||
return hideOnSpawnDistance;
|
||||
}
|
||||
|
||||
default int hideOnSpawnDistanceSquared() {
|
||||
int distance = hideOnSpawnDistance();
|
||||
return distance * distance;
|
||||
public short getVisibleRecheckIntervalTicks() {
|
||||
return visibleRecheckIntervalTicks;
|
||||
}
|
||||
|
||||
public boolean keepClientEntityWhenHidden() {
|
||||
return keepClientEntityWhenHidden;
|
||||
}
|
||||
}
|
||||
-27
@@ -1,27 +0,0 @@
|
||||
package games.cubi.raycastedantiesp.core.config.raycast;
|
||||
|
||||
import games.cubi.raycastedantiesp.core.config.ConfigRange;
|
||||
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
|
||||
import org.spongepowered.configurate.objectmapping.meta.Comment;
|
||||
|
||||
@ConfigSerializable
|
||||
public record RaycastSettings(
|
||||
@Comment("Whether this category is checked.")
|
||||
boolean enabled,
|
||||
@Comment("Maximum number of occluding blocks permitted by a successful raycast.")
|
||||
@ConfigRange(min = 0, max = Byte.MAX_VALUE)
|
||||
byte maxOccludingCount,
|
||||
@Comment("Distance in blocks within which targets are always visible.")
|
||||
@ConfigRange(min = 0, max = Short.MAX_VALUE)
|
||||
short alwaysShowRadius,
|
||||
@Comment("Maximum distance in blocks at which targets are raycasted.")
|
||||
@ConfigRange(min = 0, max = Short.MAX_VALUE)
|
||||
short raycastRadius,
|
||||
@Comment("Distance in blocks beyond which a newly spawned target starts hidden.")
|
||||
@ConfigRange(min = 0, max = Short.MAX_VALUE)
|
||||
short hideOnSpawnDistance,
|
||||
@Comment("Ticks between checks of visible targets. -1 keeps a shown target visible permanently.")
|
||||
@ConfigRange(min = -1, max = Short.MAX_VALUE)
|
||||
short visibleRecheckIntervalTicks
|
||||
) {
|
||||
}
|
||||
+10
-8
@@ -9,19 +9,21 @@
|
||||
package games.cubi.raycastedantiesp.core.config.raycast;
|
||||
|
||||
import games.cubi.raycastedantiesp.core.config.Config;
|
||||
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
|
||||
import org.spongepowered.configurate.objectmapping.meta.Comment;
|
||||
import games.cubi.raycastedantiesp.core.config.ConfigReader;
|
||||
import org.spongepowered.configurate.ConfigurationNode;
|
||||
|
||||
@ConfigSerializable
|
||||
public record SoundEffectsConfig(
|
||||
@Comment("Whether sounds should be hidden when their source cannot be seen. This feature is not implemented yet.")
|
||||
boolean enabled,
|
||||
@Comment("Maximum number of occluding blocks permitted by a successful sound raycast.")
|
||||
int maxOccludingCount,
|
||||
@Comment("Distance in blocks within which sounds are always played.")
|
||||
int alwaysPlayRadius,
|
||||
@Comment("Maximum distance in blocks at which sounds are raycasted.")
|
||||
int raycastRadius
|
||||
) implements Config {
|
||||
public static final SoundEffectsConfig DEFAULT = new SoundEffectsConfig(false, 3, 8, 48);
|
||||
public static SoundEffectsConfig load(ConfigurationNode node, String path) {
|
||||
return new SoundEffectsConfig(
|
||||
ConfigReader.bool(ConfigReader.node(node, "enabled"), path + ".enabled"),
|
||||
ConfigReader.integer(ConfigReader.node(node, "max-occluding-count"), path + ".max-occluding-count"),
|
||||
ConfigReader.integer(ConfigReader.node(node, "always-play-radius"), path + ".always-play-radius"),
|
||||
ConfigReader.integer(ConfigReader.node(node, "raycast-radius"), path + ".raycast-radius")
|
||||
);
|
||||
}
|
||||
}
|
||||
+8
-22
@@ -8,29 +8,15 @@
|
||||
|
||||
package games.cubi.raycastedantiesp.core.config.raycast;
|
||||
|
||||
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
|
||||
import org.spongepowered.configurate.objectmapping.meta.Comment;
|
||||
import org.spongepowered.configurate.objectmapping.meta.Setting;
|
||||
import org.spongepowered.configurate.ConfigurationNode;
|
||||
|
||||
import java.util.List;
|
||||
public class TileEntityConfig extends RaycastConfig {
|
||||
private TileEntityConfig(RaycastConfig config) {
|
||||
super(config.enabled(), false, config.getMaxOccludingCount(), config.getAlwaysShowRadius(),
|
||||
config.getRaycastRadius(), config.hideOnSpawnDistance(), config.getVisibleRecheckIntervalTicks());
|
||||
}
|
||||
|
||||
@ConfigSerializable
|
||||
public record TileEntityConfig(
|
||||
@Setting(nodeFromParent = true)
|
||||
RaycastSettings raycastSettings,
|
||||
@Comment("Blocks that should not be managed as tile entities. Use namespaced block keys.\n"
|
||||
+ "\"minecraft:chest\" matches every chest state.\n"
|
||||
+ "\"minecraft:chest[waterlogged=true]\" matches all waterlogged chests, regardless of facing or chest type.\n"
|
||||
+ "Omitted properties are wildcards. All specified properties must match. Specify every property to select one exact state.\n"
|
||||
+ "A block is excluded if any list entry matches. Changes require a server restart.")
|
||||
List<BlockSelector> excludedBlocks
|
||||
) implements RaycastConfig {
|
||||
public static final TileEntityConfig DEFAULT = new TileEntityConfig(
|
||||
new RaycastSettings(true, (byte) 3, (short) 8, (short) 64, (short) 24, (short) -1),
|
||||
List.of(BlockSelector.parse("minecraft:beacon"))
|
||||
);
|
||||
|
||||
public TileEntityConfig {
|
||||
excludedBlocks = List.copyOf(excludedBlocks);
|
||||
public static TileEntityConfig load(ConfigurationNode node, String path) {
|
||||
return new TileEntityConfig(RaycastConfig.load(node, path, false));
|
||||
}
|
||||
}
|
||||
@@ -386,8 +386,6 @@ public abstract class AsyncEngine implements Engine {
|
||||
|
||||
private void checkEntities(PlayerData player, Locatable playerLocation, EntityConfig entityConfig, boolean debugParticles, BlockView blockView, int currentTick, int worldEpoch, TickTimingBatch timings) {
|
||||
EntityView<?> entityView = player.entityView();
|
||||
int alwaysShowRadiusSquared = entityConfig.alwaysShowRadiusSquared();
|
||||
int raycastRadiusSquared = entityConfig.raycastRadiusSquared();
|
||||
|
||||
int checked = entityView.forEachNeedingRecheckEntity(entityConfig.getVisibleRecheckIntervalTicks(), currentTick, !(timings instanceof TickTimingBatchNoOp), worldEpoch, entity -> {
|
||||
if (entity.glowing()) {
|
||||
@@ -399,7 +397,7 @@ public abstract class AsyncEngine implements Engine {
|
||||
}
|
||||
|
||||
timings.incrementEntityRaycasts();
|
||||
boolean canSee = RaycastUtil.raycastUnrolledAccumulated(entityConfig.getMaxOccludingCount(), alwaysShowRadiusSquared, raycastRadiusSquared, debugParticles, entity.getYOffset(), blockView, playerLocation, entity, particleSpawner);
|
||||
boolean canSee = RaycastUtil.raycastUnrolledAccumulated(entityConfig.getMaxOccludingCount(), entityConfig.alwaysShowRadiusSquared, entityConfig.raycastRadiusSquared, debugParticles, entity.getYOffset(), blockView, playerLocation, entity, particleSpawner);
|
||||
entityView.setVisibility(entity, canSee, currentTick, worldEpoch);
|
||||
});
|
||||
timings.addEntityChecked(checked);
|
||||
@@ -407,8 +405,6 @@ public abstract class AsyncEngine implements Engine {
|
||||
|
||||
private void checkPlayers(PlayerData player, Locatable playerLocation, PlayerConfig playerConfig, boolean debugParticles, BlockView blockView, int currentTick, int worldEpoch, TickTimingBatch timings) {
|
||||
EntityView<?> playerView = player.playerView();
|
||||
int alwaysShowRadiusSquared = playerConfig.alwaysShowRadiusSquared();
|
||||
int raycastRadiusSquared = playerConfig.raycastRadiusSquared();
|
||||
|
||||
int checked = playerView.forEachNeedingRecheckEntity(playerConfig.getVisibleRecheckIntervalTicks(), currentTick, !(timings instanceof TickTimingBatchNoOp), worldEpoch, otherPlayer -> {
|
||||
if (otherPlayer.glowing() || (playerConfig.onlyCheckSneaking() && !otherPlayer.sneaking())) {
|
||||
@@ -419,7 +415,7 @@ public abstract class AsyncEngine implements Engine {
|
||||
return;
|
||||
}
|
||||
timings.incrementPlayerRaycasts();
|
||||
boolean canSee = RaycastUtil.raycastUnrolledAccumulated(playerConfig.getMaxOccludingCount(), alwaysShowRadiusSquared, raycastRadiusSquared, debugParticles, 1.5f, blockView, playerLocation, otherPlayer, particleSpawner);
|
||||
boolean canSee = RaycastUtil.raycastUnrolledAccumulated(playerConfig.getMaxOccludingCount(), playerConfig.alwaysShowRadiusSquared, playerConfig.raycastRadiusSquared, debugParticles, 1.5f, blockView, playerLocation, otherPlayer, particleSpawner);
|
||||
playerView.setVisibility(otherPlayer, canSee, currentTick, worldEpoch);
|
||||
});
|
||||
timings.addPlayerChecked(checked);
|
||||
@@ -439,16 +435,14 @@ public abstract class AsyncEngine implements Engine {
|
||||
|
||||
private void checkTileEntities(PlayerData player, Locatable playerLocation, TileEntityConfig tileEntityConfig, boolean debugParticles, BlockView blockView, int currentTick, int worldEpoch, TickTimingBatch timings) {
|
||||
long modeToken = blockView.tileEntityCheckModeToken();
|
||||
int alwaysShowRadiusSquared = tileEntityConfig.alwaysShowRadiusSquared();
|
||||
int raycastRadiusSquared = tileEntityConfig.raycastRadiusSquared();
|
||||
int checked = blockView.updateVisibilityForEachNeedingRecheck(tileEntityConfig.getVisibleRecheckIntervalTicks(), currentTick, modeToken, worldEpoch, tileEntityLocation -> {
|
||||
|
||||
if (playerLocation.distanceSquared(tileEntityLocation) > raycastRadiusSquared) {
|
||||
if (playerLocation.distanceSquared(tileEntityLocation) > (double) tileEntityConfig.getRaycastRadius() * tileEntityConfig.getRaycastRadius()) {
|
||||
timings.incrementTileRadiusSkipped();
|
||||
return BlockView.VisibilityResolver.HIDE;
|
||||
}
|
||||
timings.incrementTileRaycasts();
|
||||
boolean canSee = RaycastUtil.raycastUnrolledAccumulated(tileEntityConfig.getMaxOccludingCount(), alwaysShowRadiusSquared, raycastRadiusSquared, debugParticles, 0, blockView, playerLocation, tileEntityLocation, particleSpawner);
|
||||
boolean canSee = RaycastUtil.raycastUnrolledAccumulated(tileEntityConfig.getMaxOccludingCount(), tileEntityConfig.alwaysShowRadiusSquared, tileEntityConfig.raycastRadiusSquared, debugParticles, 0, blockView, playerLocation, tileEntityLocation, particleSpawner);
|
||||
return canSee ? BlockView.VisibilityResolver.SHOW : BlockView.VisibilityResolver.HIDE;
|
||||
});
|
||||
timings.addTileChecked(checked);
|
||||
|
||||
@@ -54,6 +54,29 @@ public class RaycastUtil {
|
||||
return rayAdvancer.occluded <= maxOccluding;
|
||||
}
|
||||
|
||||
/**
|
||||
* A very fast, low-accuracy raycast
|
||||
*/
|
||||
public static int fastRaycastDirection(int maxOccluding, final BlockView snap, final Spatial start,
|
||||
final double dirX, final double dirY, final double dirZ, final int maxSteps) {
|
||||
double startX = start.x();
|
||||
double startY = start.y();
|
||||
double startZ = start.z();
|
||||
|
||||
final RayAdvancer rayAdvancer = new RayAdvancer(startX, startY, startZ, RayDirection.ofDirection(dirX, dirY, dirZ), snap);
|
||||
int remainingSteps = maxSteps;
|
||||
|
||||
while (remainingSteps >= 4) {
|
||||
rayAdvancer.advance();
|
||||
rayAdvancer.advance();
|
||||
rayAdvancer.advance();
|
||||
rayAdvancer.advance();
|
||||
remainingSteps -= 4;
|
||||
if (rayAdvancer.occluded > maxOccluding) return (maxSteps - remainingSteps);
|
||||
}
|
||||
return maxSteps;
|
||||
}
|
||||
|
||||
private static sealed class RayAdvancer extends RayPosition permits DebugRayAdvancer {
|
||||
private final RayDirection direction;
|
||||
private final BlockView blockView;
|
||||
@@ -159,6 +182,10 @@ public class RaycastUtil {
|
||||
return new RayDirection(endX - startX, endY - startY, endZ - startZ);
|
||||
}
|
||||
|
||||
private static RayDirection ofDirection(double x, double y, double z) {
|
||||
return new RayDirection(x, y, z);
|
||||
}
|
||||
|
||||
private double getLengthSquared() {
|
||||
return x * x + y * y + z * z;
|
||||
}
|
||||
|
||||
+1
-14
@@ -127,7 +127,7 @@ public abstract class PacketEntityViewController<P> {
|
||||
Locatable ownLocation = playerData.ownLocation();
|
||||
boolean staleOwnLocation = ownLocation == null || ownLocation.world() == null || !ownLocation.world().equals(world);
|
||||
double distanceSquared = staleOwnLocation ? Double.POSITIVE_INFINITY : ownLocation.distanceSquared(entity);
|
||||
if (distanceSquared > config.hideOnSpawnDistanceSquared()) {
|
||||
if (distanceSquared > config.hideOnSpawnDistanceSquared) {
|
||||
entity.setVisible(false);
|
||||
entity.setClientVisible(false);
|
||||
if (isPlayer) {
|
||||
@@ -153,19 +153,6 @@ public abstract class PacketEntityViewController<P> {
|
||||
return cancelIfEnabledAndHidden(entityID, playerData);
|
||||
}
|
||||
|
||||
protected boolean handleCollectItem(int collectedEntityID, int collectorEntityID, PlayerData playerData) {
|
||||
// Pickup animations do not imply removal; full pickups have a separate destroy packet.
|
||||
return collectItemEndpointHidden(collectedEntityID, playerData) || collectItemEndpointHidden(collectorEntityID, playerData);
|
||||
}
|
||||
|
||||
private boolean collectItemEndpointHidden(int entityID, PlayerData playerData) {
|
||||
if (EntityBypassRegistry.isBypassed(entityID)) {
|
||||
return false;
|
||||
}
|
||||
NettyEntity<?> entity = playerData.entityFromID(entityID);
|
||||
return entity != null && !entity.isSelfEntity() && (!entity.clientVisible());
|
||||
}
|
||||
|
||||
@Packet(Packet.Packets.ENTITY_EVENT)
|
||||
protected boolean handleEntityEvent(int entityID, PlayerData playerData) {
|
||||
return cancelIfEnabledAndHidden(entityID, playerData);
|
||||
|
||||
@@ -1,461 +0,0 @@
|
||||
package games.cubi.raycastedantiesp.core.config;
|
||||
|
||||
import games.cubi.raycastedantiesp.core.config.engine.EngineMode;
|
||||
import games.cubi.raycastedantiesp.core.config.raycast.BlockSelector;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.spongepowered.configurate.CommentedConfigurationNode;
|
||||
import org.spongepowered.configurate.NodePath;
|
||||
import org.spongepowered.configurate.loader.HeaderMode;
|
||||
import org.spongepowered.configurate.serialize.SerializationException;
|
||||
import org.spongepowered.configurate.yaml.NodeStyle;
|
||||
import org.spongepowered.configurate.yaml.YamlConfigurationLoader;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.attribute.FileTime;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class ConfigManagerTest {
|
||||
@TempDir
|
||||
Path directory;
|
||||
|
||||
@Test
|
||||
void freshConfigLoadsInTwoPhasesFromCodeDefaults() {
|
||||
ConfigManager manager = new ConfigManager(directory);
|
||||
|
||||
assertEquals(LoggingConfig.DEFAULT, manager.getLoggingConfig());
|
||||
assertFalse(Files.exists(configPath()));
|
||||
manager.loadLoggingConfig();
|
||||
|
||||
assertEquals(RootConfig.DEFAULT.loggingConfig(), manager.getLoggingConfig());
|
||||
assertThrows(IllegalStateException.class, manager::getDebugConfig);
|
||||
assertThrows(IllegalStateException.class, manager::getConfigValues);
|
||||
|
||||
manager.completeInitialLoad();
|
||||
|
||||
assertEquals(RootConfig.DEFAULT.debugConfig(), manager.getDebugConfig());
|
||||
assertEquals(RootConfig.DEFAULT.engineConfig(), manager.getEngineConfig());
|
||||
assertEquals(RootConfig.DEFAULT.checksConfig().playerConfig(), manager.getPlayerConfig());
|
||||
assertTrue(Files.isRegularFile(configPath()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void lateCompletionCanOnlyRunOnce() {
|
||||
ConfigManager manager = earlyManager();
|
||||
|
||||
manager.completeInitialLoad();
|
||||
|
||||
assertThrows(IllegalStateException.class, manager::completeInitialLoad);
|
||||
}
|
||||
|
||||
@Test
|
||||
void malformedSectionsUseTheirDefaultsWithoutLosingOtherOverrides() throws IOException {
|
||||
CommentedConfigurationNode node = defaultNode();
|
||||
boolean particles = !RootConfig.DEFAULT.debugConfig().particles();
|
||||
node.node("logging").raw("invalid");
|
||||
node.node("updates").raw(List.of("invalid"));
|
||||
node.node("checks", "player").comment("User-authored comment").raw("invalid");
|
||||
node.node("debug", "particles").raw(particles);
|
||||
saveNode(node);
|
||||
|
||||
ConfigManager manager = earlyManager();
|
||||
assertEquals(LoggingConfig.DEFAULT, manager.getLoggingConfig());
|
||||
manager.completeInitialLoad();
|
||||
|
||||
assertEquals(UpdateConfig.DEFAULT, manager.getUpdateConfig());
|
||||
assertEquals(RootConfig.DEFAULT.checksConfig().playerConfig(), manager.getPlayerConfig());
|
||||
assertEquals(particles, manager.getDebugConfig().particles());
|
||||
assertEquals("User-authored comment", loadNode().node("checks", "player").comment());
|
||||
}
|
||||
|
||||
@Test
|
||||
void commandRepairsScalarAndListSectionsBeforePublishing() {
|
||||
ConfigManager manager = earlyManager();
|
||||
manager.completeInitialLoad();
|
||||
|
||||
for (String path : List.of("logging", "updates", "checks.player")) {
|
||||
for (String rawValue : List.of("invalid", "[invalid]")) {
|
||||
ConfigManager.SetConfigResult result = manager.setConfigValue(path, rawValue);
|
||||
|
||||
assertTrue(result.success(), path + ": " + rawValue);
|
||||
assertTrue(result.repaired(), path + ": " + rawValue);
|
||||
assertEquals(LoggingConfig.DEFAULT, manager.getLoggingConfig());
|
||||
assertEquals(UpdateConfig.DEFAULT, manager.getUpdateConfig());
|
||||
assertEquals(RootConfig.DEFAULT.checksConfig().playerConfig(), manager.getPlayerConfig());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidValueAndCrossFieldViolationRepairOnlyTheirFields() throws IOException {
|
||||
ConfigManager manager = earlyManager();
|
||||
CommentedConfigurationNode node = loadNode();
|
||||
Object unrelatedValue = node.node("updates", "notify-in-game").raw();
|
||||
node.node("block-processor", "track-all-blocks").raw(false);
|
||||
node.node("checks", "chunk-section", "enabled").raw(true);
|
||||
saveNode(node);
|
||||
|
||||
manager.completeInitialLoad();
|
||||
ConfigManager.SetConfigResult result = manager.setConfigValue("engine.async.processing-threads", "0");
|
||||
|
||||
assertTrue(result.success());
|
||||
assertTrue(result.repaired());
|
||||
assertEquals(RootConfig.DEFAULT.engineConfig().asyncConfig(), manager.getEngineConfig().asyncConfig());
|
||||
assertEquals(RootConfig.DEFAULT.checksConfig().chunkSectionConfig().enabled(), manager.getChunkSectionConfig().enabled());
|
||||
assertEquals(unrelatedValue, loadNode().node("updates", "notify-in-game").raw());
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidListElementResetsItsListWithoutLosingOtherOverrides() throws IOException {
|
||||
ConfigManager manager = earlyManager();
|
||||
CommentedConfigurationNode node = loadNode();
|
||||
boolean onlyCheckSneaking = !RootConfig.DEFAULT.checksConfig().playerConfig().onlyCheckSneaking();
|
||||
node.node("checks", "entity", "excluded-types").raw(List.of(1));
|
||||
node.node("checks", "player", "only-check-sneaking").raw(onlyCheckSneaking);
|
||||
saveNode(node);
|
||||
|
||||
manager.completeInitialLoad();
|
||||
|
||||
assertEquals(RootConfig.DEFAULT.checksConfig().entityConfig().excludedTypes(), manager.getEntityConfig().excludedTypes());
|
||||
assertEquals(onlyCheckSneaking, manager.getPlayerConfig().onlyCheckSneaking());
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidBlockSelectorResetsItsListWithoutLosingOtherOverrides() throws IOException {
|
||||
ConfigManager manager = earlyManager();
|
||||
CommentedConfigurationNode node = loadNode();
|
||||
boolean onlyCheckSneaking = !RootConfig.DEFAULT.checksConfig().playerConfig().onlyCheckSneaking();
|
||||
node.node("checks", "tile-entity", "excluded-blocks").raw(List.of("minecraft:chest[]"));
|
||||
node.node("checks", "player", "only-check-sneaking").raw(onlyCheckSneaking);
|
||||
saveNode(node);
|
||||
|
||||
manager.completeInitialLoad();
|
||||
|
||||
assertEquals(RootConfig.DEFAULT.checksConfig().tileEntityConfig().excludedBlocks(), manager.getTileEntityConfig().excludedBlocks());
|
||||
assertEquals(onlyCheckSneaking, manager.getPlayerConfig().onlyCheckSneaking());
|
||||
}
|
||||
|
||||
@Test
|
||||
void excludedBlockMutationIsSavedForRestartWithoutChangingActiveSnapshot() throws IOException {
|
||||
ConfigManager manager = earlyManager();
|
||||
manager.completeInitialLoad();
|
||||
BlockSelector added = BlockSelector.parse("example:block");
|
||||
|
||||
ConfigManager.SetConfigResult result = manager.addConfigListValue("checks.tile-entity.excluded-blocks", added.toString());
|
||||
|
||||
assertTrue(result.success());
|
||||
assertTrue(result.restartRequired());
|
||||
assertEquals(RootConfig.DEFAULT.checksConfig().tileEntityConfig().excludedBlocks(), manager.getTileEntityConfig().excludedBlocks());
|
||||
assertTrue(loadNode().node("checks", "tile-entity", "excluded-blocks").getList(String.class).contains(added.toString()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void migrationPrefersExistingDestinationAndPreservesUnrelatedValues() throws IOException {
|
||||
CommentedConfigurationNode node = defaultNode();
|
||||
byte destinationLevel = differentValidLevel(RootConfig.DEFAULT.loggingConfig().info().level());
|
||||
byte legacyLevel = differentValidLevel(destinationLevel);
|
||||
boolean soundEnabled = !RootConfig.DEFAULT.checksConfig().soundEffectsConfig().enabled();
|
||||
String unknownValue = "preserve-me";
|
||||
node.node("config-version").raw("2.0");
|
||||
node.node("logging", "info", "level").raw(destinationLevel);
|
||||
node.node("debug", "info-level").raw(legacyLevel);
|
||||
node.node("checks", "sound-effects", "enabled").raw(soundEnabled);
|
||||
node.node("checks", "tile-entity", "excluded-blocks").raw(null);
|
||||
node.node("unknown-setting").raw(unknownValue);
|
||||
node.node("block-processor", "packetevents", "tile-entity-exempted-ids").raw(List.of(1));
|
||||
saveNode(node);
|
||||
|
||||
ConfigManager manager = earlyManager();
|
||||
manager.completeInitialLoad();
|
||||
CommentedConfigurationNode migrated = loadNode();
|
||||
|
||||
assertEquals(destinationLevel, manager.getLoggingConfig().info().level());
|
||||
assertEquals(soundEnabled, manager.getSoundEffectsConfig().enabled());
|
||||
assertEquals(RootConfig.CURRENT_VERSION, migrated.node("config-version").getString());
|
||||
assertTrue(migrated.node("debug", "info-level").virtual());
|
||||
assertTrue(migrated.node("block-processor", "packetevents").virtual());
|
||||
assertEquals(
|
||||
RootConfig.DEFAULT.checksConfig().tileEntityConfig().excludedBlocks().stream().map(BlockSelector::toString).toList(),
|
||||
migrated.node("checks", "tile-entity", "excluded-blocks").getList(String.class)
|
||||
);
|
||||
assertEquals(unknownValue, migrated.node("unknown-setting").getString());
|
||||
|
||||
String afterMigration = Files.readString(configPath());
|
||||
manager.load();
|
||||
assertEquals(afterMigration, Files.readString(configPath()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void acceptedEnumSpellingsArePersistedCanonically() throws IOException {
|
||||
CommentedConfigurationNode node = defaultNode();
|
||||
node.node("engine", "mode").raw("SiMpLe");
|
||||
node.node("block-processor", "mode").raw(
|
||||
RootConfig.DEFAULT.blockProcessorConfig().mode().getName().toUpperCase(java.util.Locale.ROOT)
|
||||
);
|
||||
saveNode(node);
|
||||
|
||||
ConfigManager manager = earlyManager();
|
||||
manager.completeInitialLoad();
|
||||
CommentedConfigurationNode canonical = loadNode();
|
||||
|
||||
assertEquals(EngineMode.ASYNC, manager.getEngineConfig().mode());
|
||||
assertEquals(EngineMode.ASYNC.getName(), canonical.node("engine", "mode").raw());
|
||||
assertEquals(
|
||||
RootConfig.DEFAULT.blockProcessorConfig().mode().getName(),
|
||||
canonical.node("block-processor", "mode").raw()
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidScalarShapeAndEnumUseTheirFieldDefaults() {
|
||||
ConfigManager manager = earlyManager();
|
||||
manager.completeInitialLoad();
|
||||
|
||||
ConfigManager.SetConfigResult scalarResult = manager.setConfigValue("debug.timings", "{invalid: shape}");
|
||||
ConfigManager.SetConfigResult enumResult = manager.setConfigValue("engine.mode", "definitely-invalid");
|
||||
|
||||
assertTrue(scalarResult.success());
|
||||
assertTrue(scalarResult.repaired());
|
||||
assertEquals(RootConfig.DEFAULT.debugConfig().timings(), manager.getDebugConfig().timings());
|
||||
assertTrue(enumResult.success());
|
||||
assertTrue(enumResult.repaired());
|
||||
assertEquals(RootConfig.DEFAULT.engineConfig().mode(), manager.getEngineConfig().mode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void commandSectionsFillMissingFieldsAndNullUsesTheFieldDefault() {
|
||||
ConfigManager manager = earlyManager();
|
||||
manager.completeInitialLoad();
|
||||
boolean particles = !RootConfig.DEFAULT.debugConfig().particles();
|
||||
|
||||
ConfigManager.SetConfigResult sectionResult = manager.setConfigValue(
|
||||
"debug",
|
||||
"{particles: " + particles + "}"
|
||||
);
|
||||
ConfigManager.SetConfigResult nullResult = manager.setConfigValue("updates.notify-in-game", "null");
|
||||
|
||||
assertTrue(sectionResult.success());
|
||||
assertEquals(particles, manager.getDebugConfig().particles());
|
||||
assertEquals(RootConfig.DEFAULT.debugConfig().timings(), manager.getDebugConfig().timings());
|
||||
assertTrue(nullResult.success());
|
||||
assertTrue(nullResult.repaired());
|
||||
assertEquals(RootConfig.DEFAULT.updateConfig().notifyInGame(), manager.getUpdateConfig().notifyInGame());
|
||||
}
|
||||
|
||||
@Test
|
||||
void fatalReloadRetainsActiveSnapshotAndDoesNotRewriteFile() throws IOException {
|
||||
ConfigManager manager = earlyManager();
|
||||
manager.completeInitialLoad();
|
||||
LoggingConfig activeLogging = manager.getLoggingConfig();
|
||||
CommentedConfigurationNode node = loadNode();
|
||||
String unsupportedVersion = RootConfig.CURRENT_VERSION + "-future";
|
||||
node.node("config-version").raw(unsupportedVersion);
|
||||
saveNode(node);
|
||||
String beforeReload = Files.readString(configPath());
|
||||
|
||||
assertThrows(ConfigLoadException.class, manager::load);
|
||||
|
||||
assertEquals(activeLogging, manager.getLoggingConfig());
|
||||
assertEquals(beforeReload, Files.readString(configPath()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void commandCannotPublishAnUnsupportedVersion() throws IOException {
|
||||
ConfigManager manager = earlyManager();
|
||||
manager.completeInitialLoad();
|
||||
String beforeMutation = Files.readString(configPath());
|
||||
|
||||
ConfigManager.SetConfigResult result = manager.setConfigValue(
|
||||
"config-version",
|
||||
"'" + RootConfig.CURRENT_VERSION + "-future'"
|
||||
);
|
||||
|
||||
assertFalse(result.success());
|
||||
assertEquals(beforeMutation, Files.readString(configPath()));
|
||||
assertEquals(RootConfig.CURRENT_VERSION, manager.getConfigValues().get("config-version"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void malformedYamlIsNotOverwritten() throws IOException {
|
||||
String malformed = "invalid: [";
|
||||
Files.writeString(configPath(), malformed);
|
||||
ConfigManager manager = new ConfigManager(directory);
|
||||
|
||||
assertThrows(ConfigLoadException.class, manager::loadLoggingConfig);
|
||||
assertEquals(malformed, Files.readString(configPath()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingMappedCommentsArePersisted() throws IOException {
|
||||
CommentedConfigurationNode node = defaultNode();
|
||||
CommentedPath expected = firstComment(node, NodePath.path());
|
||||
clearComments(node);
|
||||
saveNode(node);
|
||||
|
||||
ConfigManager manager = earlyManager();
|
||||
manager.completeInitialLoad();
|
||||
|
||||
assertEquals(expected.comment(), loadNode().node(expected.path().array()).comment());
|
||||
}
|
||||
|
||||
@Test
|
||||
void freshConfigWritesGuidanceAboveIndividualEntries() throws IOException {
|
||||
ConfigManager manager = earlyManager();
|
||||
manager.completeInitialLoad();
|
||||
CommentedConfigurationNode defaults = defaultNode().node("checks", "entity", "excluded-types");
|
||||
CommentedConfigurationNode saved = loadNode().node("checks", "entity", "excluded-types");
|
||||
List<String> lines = Files.readAllLines(configPath()).stream().map(String::strip).toList();
|
||||
|
||||
assertEquals(defaults.raw(), saved.raw());
|
||||
for (int index = 0; index < defaults.childrenList().size(); index++) {
|
||||
String comment = defaults.node(index).comment();
|
||||
assertEquals(comment, saved.node(index).comment());
|
||||
if (comment != null) {
|
||||
String[] commentLines = comment.split("\\R");
|
||||
int line = lines.indexOf("# " + commentLines[commentLines.length - 1]);
|
||||
assertTrue(line >= 0);
|
||||
assertEquals("- " + defaults.node(index).getString(), lines.get(line + 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingEntryCommentsArePersistedWithoutOtherChanges() throws IOException {
|
||||
CommentedConfigurationNode node = defaultNode();
|
||||
CommentedConfigurationNode list = node.node("checks", "entity", "excluded-types");
|
||||
for (CommentedConfigurationNode child : list.childrenList()) {
|
||||
child.comment(null);
|
||||
}
|
||||
saveNode(node);
|
||||
|
||||
ConfigManager manager = earlyManager();
|
||||
manager.completeInitialLoad();
|
||||
CommentedConfigurationNode defaults = defaultNode().node("checks", "entity", "excluded-types");
|
||||
CommentedConfigurationNode saved = loadNode().node("checks", "entity", "excluded-types");
|
||||
|
||||
assertEquals(defaults.raw(), saved.raw());
|
||||
for (int index = 0; index < defaults.childrenList().size(); index++) {
|
||||
assertEquals(defaults.node(index).comment(), saved.node(index).comment());
|
||||
}
|
||||
|
||||
String content = Files.readString(configPath());
|
||||
Files.setLastModifiedTime(configPath(), FileTime.fromMillis(1_000));
|
||||
FileTime modified = Files.getLastModifiedTime(configPath());
|
||||
manager.load();
|
||||
assertEquals(content, Files.readString(configPath()));
|
||||
assertEquals(modified, Files.getLastModifiedTime(configPath()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void entryCommentMergePreservesReorderedSubsetAndUserComments() throws IOException {
|
||||
CommentedConfigurationNode node = defaultNode();
|
||||
CommentedConfigurationNode list = node.node("checks", "entity", "excluded-types");
|
||||
List<String> values = List.of("minecraft:block_display", "minecraft:arrow", "example:custom", "minecraft:potion", "minecraft:wither");
|
||||
list.raw(values);
|
||||
clearComments(list);
|
||||
list.comment("Existing consolidated guidance");
|
||||
list.node(1).comment("User-authored projectile guidance");
|
||||
list.node(2).comment("User-authored custom entry guidance");
|
||||
saveNode(node);
|
||||
|
||||
ConfigManager manager = earlyManager();
|
||||
manager.completeInitialLoad();
|
||||
CommentedConfigurationNode saved = loadNode().node("checks", "entity", "excluded-types");
|
||||
CommentedConfigurationNode defaults = defaultNode().node("checks", "entity", "excluded-types");
|
||||
|
||||
assertEquals(values, saved.getList(String.class));
|
||||
assertEquals("Existing consolidated guidance", saved.comment());
|
||||
assertEquals("User-authored projectile guidance", saved.node(1).comment());
|
||||
assertEquals("User-authored custom entry guidance", saved.node(2).comment());
|
||||
assertNull(saved.node(4).comment());
|
||||
for (CommentedConfigurationNode child : defaults.childrenList()) {
|
||||
if (values.get(0).equals(child.getString())) {
|
||||
assertEquals(child.comment(), saved.node(0).comment());
|
||||
} else if (values.get(3).equals(child.getString())) {
|
||||
assertEquals(child.comment(), saved.node(3).comment());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private ConfigManager earlyManager() {
|
||||
ConfigManager manager = new ConfigManager(directory);
|
||||
manager.loadLoggingConfig();
|
||||
return manager;
|
||||
}
|
||||
|
||||
private Path configPath() {
|
||||
return directory.resolve("config.yml");
|
||||
}
|
||||
|
||||
private CommentedConfigurationNode defaultNode() {
|
||||
CommentedConfigurationNode node = YamlConfigurationLoader.builder()
|
||||
.defaultOptions(ConfigMapping.options())
|
||||
.build()
|
||||
.createNode();
|
||||
try {
|
||||
node.set(RootConfig.class, RootConfig.DEFAULT);
|
||||
} catch (SerializationException e) {
|
||||
throw new AssertionError("Code defaults must serialize", e);
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
private CommentedConfigurationNode loadNode() throws IOException {
|
||||
return loader().load();
|
||||
}
|
||||
|
||||
private void saveNode(CommentedConfigurationNode node) throws IOException {
|
||||
loader().save(node);
|
||||
}
|
||||
|
||||
private YamlConfigurationLoader loader() {
|
||||
return YamlConfigurationLoader.builder()
|
||||
.path(configPath())
|
||||
.nodeStyle(NodeStyle.BLOCK)
|
||||
.headerMode(HeaderMode.PRESERVE)
|
||||
.defaultOptions(ConfigMapping.options())
|
||||
.build();
|
||||
}
|
||||
|
||||
private byte differentValidLevel(byte level) {
|
||||
return level == 0 ? (byte) 1 : (byte) 0;
|
||||
}
|
||||
|
||||
private CommentedPath firstComment(CommentedConfigurationNode node, NodePath path) {
|
||||
if (node.comment() != null) {
|
||||
return new CommentedPath(path, node.comment());
|
||||
}
|
||||
for (var entry : node.childrenMap().entrySet()) {
|
||||
CommentedPath found = firstComment(
|
||||
(CommentedConfigurationNode) entry.getValue(),
|
||||
path.plus(NodePath.path(entry.getKey()))
|
||||
);
|
||||
if (found != null) {
|
||||
return found;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void clearComments(CommentedConfigurationNode node) {
|
||||
node.comment(null);
|
||||
for (var child : node.childrenMap().values()) {
|
||||
clearComments((CommentedConfigurationNode) child);
|
||||
}
|
||||
for (var child : node.childrenList()) {
|
||||
clearComments((CommentedConfigurationNode) child);
|
||||
}
|
||||
}
|
||||
|
||||
private record CommentedPath(NodePath path, String comment) {
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,167 +0,0 @@
|
||||
package games.cubi.raycastedantiesp.core.config;
|
||||
|
||||
import games.cubi.raycastedantiesp.core.config.engine.EngineMode;
|
||||
import games.cubi.raycastedantiesp.core.config.raycast.BlockSelector;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.spongepowered.configurate.CommentedConfigurationNode;
|
||||
import org.spongepowered.configurate.NodePath;
|
||||
import org.spongepowered.configurate.objectmapping.ConfigSerializable;
|
||||
import org.spongepowered.configurate.objectmapping.meta.Comment;
|
||||
import org.spongepowered.configurate.serialize.SerializationException;
|
||||
import org.spongepowered.configurate.yaml.YamlConfigurationLoader;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class ConfigMappingTest {
|
||||
@Test
|
||||
void codeDefaultsRoundTripThroughObjectMapper() throws SerializationException {
|
||||
CommentedConfigurationNode node = mappedDefaults();
|
||||
|
||||
assertEquals(RootConfig.DEFAULT, node.get(RootConfig.class));
|
||||
assertEquals(RootConfig.DEFAULT.engineConfig().mode().getName(), node.node("engine", "mode").raw());
|
||||
assertInstanceOf(String.class, node.node("engine", "mode").raw());
|
||||
assertNotNull(node.node("checks", "player", "enabled").comment());
|
||||
assertEquals(
|
||||
List.copyOf(RootConfig.DEFAULT.checksConfig().entityConfig().excludedTypes()),
|
||||
node.node("checks", "entity", "excluded-types").getList(String.class)
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void excludedTypesIncludesDetailedGuidance() throws SerializationException {
|
||||
CommentedConfigurationNode list = mappedDefaults().node("checks", "entity", "excluded-types");
|
||||
String comment = list.comment();
|
||||
|
||||
assertNotNull(comment);
|
||||
assertTrue(comment.contains("minecraft:falling_block"));
|
||||
assertTrue(comment.contains("/summon command"));
|
||||
Map<String, String> guidance = Map.of(
|
||||
"minecraft:arrow", "Projectiles move very quickly",
|
||||
"minecraft:area_effect_cloud", "Potions and area-effect clouds",
|
||||
"minecraft:potion", "minecraft:potion entity was removed in 1.21.5",
|
||||
"minecraft:lightning_bolt", "Lightning is short-lived",
|
||||
"minecraft:ender_dragon", "Boss entities",
|
||||
"minecraft:block_display", "hologram or NPC plugins"
|
||||
);
|
||||
for (CommentedConfigurationNode child : list.childrenList()) {
|
||||
String expected = guidance.get(child.getString());
|
||||
if (expected == null) {
|
||||
assertNull(child.comment());
|
||||
} else {
|
||||
assertNotNull(child.comment());
|
||||
assertTrue(child.comment().contains(expected));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void entryCommentsWorkOnAnotherListByValue(@TempDir Path directory) throws IOException {
|
||||
YamlConfigurationLoader loader = YamlConfigurationLoader.builder()
|
||||
.path(directory.resolve("list-comments.yml"))
|
||||
.defaultOptions(ConfigMapping.options())
|
||||
.build();
|
||||
CommentedConfigurationNode node = loader.createNode();
|
||||
CommentedList value = new CommentedList(List.of("second", "custom", "first"));
|
||||
node.set(CommentedList.class, value);
|
||||
|
||||
CommentedConfigurationNode list = node.node("values");
|
||||
assertEquals(value.values(), list.getList(String.class));
|
||||
assertEquals("Second entry", list.node(0).comment());
|
||||
assertNull(list.node(1).comment());
|
||||
assertEquals("First entry", list.node(2).comment());
|
||||
list.node(1).comment("User-authored entry comment");
|
||||
|
||||
loader.save(node);
|
||||
CommentedConfigurationNode loaded = loader.load();
|
||||
|
||||
assertEquals(value, loaded.get(CommentedList.class));
|
||||
assertEquals("Second entry", loaded.node("values", 0).comment());
|
||||
assertEquals("User-authored entry comment", loaded.node("values", 1).comment());
|
||||
assertEquals("First entry", loaded.node("values", 2).comment());
|
||||
}
|
||||
|
||||
@Test
|
||||
void engineAliasReadsButCanonicalNameWrites() throws SerializationException {
|
||||
CommentedConfigurationNode node = CommentedConfigurationNode.root(ConfigMapping.options());
|
||||
node.raw("simple");
|
||||
|
||||
assertEquals(EngineMode.ASYNC, node.get(EngineMode.class));
|
||||
|
||||
node.set(EngineMode.class, EngineMode.ASYNC);
|
||||
assertEquals(EngineMode.ASYNC.getName(), node.raw());
|
||||
}
|
||||
|
||||
@Test
|
||||
void blockSelectorsRoundTripWithoutFillingOmittedProperties() throws SerializationException {
|
||||
CommentedConfigurationNode node = CommentedConfigurationNode.root(ConfigMapping.options());
|
||||
for (String value : List.of("minecraft:chest", "minecraft:chest[waterlogged=true]", "minecraft:chest[facing=north,type=single,waterlogged=false]", "example:block[type=left,facing=north]")) {
|
||||
node.raw(value);
|
||||
|
||||
BlockSelector selector = node.get(BlockSelector.class);
|
||||
node.set(BlockSelector.class, selector);
|
||||
|
||||
assertEquals(value, node.raw());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void annotationConstraintReportsTheMappedFieldPath() throws SerializationException {
|
||||
CommentedConfigurationNode node = mappedDefaults();
|
||||
NodePath expectedPath = NodePath.path("engine", "async", "processing-threads");
|
||||
node.node(expectedPath.array()).raw(0);
|
||||
|
||||
SerializationException exception = assertThrows(SerializationException.class, () -> node.get(RootConfig.class));
|
||||
|
||||
assertEquals(expectedPath, exception.path());
|
||||
}
|
||||
|
||||
@Test
|
||||
void yamlLoaderRoundTripsMappedAndUserComments(@TempDir Path directory) throws IOException {
|
||||
Path path = directory.resolve("comments.yml");
|
||||
YamlConfigurationLoader loader = YamlConfigurationLoader.builder()
|
||||
.path(path)
|
||||
.defaultOptions(ConfigMapping.options())
|
||||
.build();
|
||||
CommentedConfigurationNode node = loader.createNode();
|
||||
node.set(CommentedValue.class, new CommentedValue("mapped"));
|
||||
node.node("unknown").comment("User-authored comment").raw("preserved");
|
||||
|
||||
loader.save(node);
|
||||
CommentedConfigurationNode loaded = loader.load();
|
||||
|
||||
assertEquals("Mapped comment", loaded.node("value").comment());
|
||||
assertEquals("User-authored comment", loaded.node("unknown").comment());
|
||||
}
|
||||
|
||||
private CommentedConfigurationNode mappedDefaults() throws SerializationException {
|
||||
CommentedConfigurationNode node = CommentedConfigurationNode.root(ConfigMapping.options());
|
||||
node.set(RootConfig.class, RootConfig.DEFAULT);
|
||||
return node;
|
||||
}
|
||||
|
||||
@ConfigSerializable
|
||||
private record CommentedValue(@Comment("Mapped comment") String value) {
|
||||
}
|
||||
|
||||
@ConfigSerializable
|
||||
private record CommentedList(
|
||||
@ListEntryComments({
|
||||
@ListEntryComments.Entry(value = "first", comment = "First entry"),
|
||||
@ListEntryComments.Entry(value = "second", comment = "Second entry"),
|
||||
@ListEntryComments.Entry(value = "absent", comment = "Absent entry")
|
||||
})
|
||||
List<String> values
|
||||
) {
|
||||
}
|
||||
}
|
||||
-38
@@ -1,38 +0,0 @@
|
||||
package games.cubi.raycastedantiesp.core.config.raycast;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class BlockSelectorTest {
|
||||
@Test
|
||||
void blockKeySelectsAllStates() {
|
||||
BlockSelector selector = BlockSelector.parse("example:block");
|
||||
|
||||
assertEquals("example:block", selector.blockKey());
|
||||
assertTrue(selector.matchesAllStates());
|
||||
assertEquals("example:block", selector.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void propertySelectorPreservesItsText() {
|
||||
BlockSelector selector = BlockSelector.parse("example:block[type=left,facing=north]");
|
||||
|
||||
assertFalse(selector.matchesAllStates());
|
||||
assertEquals("example:block", selector.blockKey());
|
||||
assertEquals("example:block[type=left,facing=north]", selector.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void malformedSelectorsAreRejected() {
|
||||
assertThrows(IllegalArgumentException.class, () -> BlockSelector.parse("block"));
|
||||
assertThrows(IllegalArgumentException.class, () -> BlockSelector.parse("Example:block"));
|
||||
assertThrows(IllegalArgumentException.class, () -> BlockSelector.parse("example:block[]"));
|
||||
assertThrows(IllegalArgumentException.class, () -> BlockSelector.parse("example:block[type]"));
|
||||
assertThrows(IllegalArgumentException.class, () -> BlockSelector.parse("example:block[type=left,type=right]"));
|
||||
assertThrows(IllegalArgumentException.class, () -> BlockSelector.parse("example:block[type=left"));
|
||||
}
|
||||
}
|
||||
+45
-23
@@ -9,44 +9,66 @@
|
||||
package games.cubi.raycastedantiesp.core.config.raycast;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.spongepowered.configurate.BasicConfigurationNode;
|
||||
import org.spongepowered.configurate.ConfigurationNode;
|
||||
import org.spongepowered.configurate.serialize.SerializationException;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class RaycastConfigTest {
|
||||
@Test
|
||||
void variantSettingsRemainIndependent() {
|
||||
PlayerConfig defaults = PlayerConfig.DEFAULT;
|
||||
PlayerConfig changed = new PlayerConfig(
|
||||
defaults.raycastSettings(),
|
||||
!defaults.hideSoundsWhenHidden(),
|
||||
!defaults.keepClientEntityWhenHidden(),
|
||||
!defaults.onlyCheckSneaking()
|
||||
);
|
||||
void playerAndEntityRetentionSettingsLoadIndependently() throws SerializationException {
|
||||
PlayerConfig playerConfig = PlayerConfig.load(entityNode(true), "checks.player");
|
||||
EntityConfig entityConfig = EntityConfig.load(entityNode(false), "checks.entity");
|
||||
|
||||
assertNotEquals(defaults.hideSoundsWhenHidden(), changed.hideSoundsWhenHidden());
|
||||
assertNotEquals(defaults.keepClientEntityWhenHidden(), changed.keepClientEntityWhenHidden());
|
||||
assertNotEquals(defaults.onlyCheckSneaking(), changed.onlyCheckSneaking());
|
||||
assertEquals(defaults.raycastSettings(), changed.raycastSettings());
|
||||
assertTrue(playerConfig.keepClientEntityWhenHidden());
|
||||
assertFalse(playerConfig.onlyCheckSneaking());
|
||||
assertFalse(entityConfig.keepClientEntityWhenHidden());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tileEntityUsesInterfaceDefaultsForUnsupportedSettings() {
|
||||
TileEntityConfig config = TileEntityConfig.DEFAULT;
|
||||
void playerSneakingOnlySettingLoadsIndependently() throws SerializationException {
|
||||
ConfigurationNode node = entityNode(true);
|
||||
node.node("only-check-sneaking").set(true);
|
||||
|
||||
PlayerConfig playerConfig = PlayerConfig.load(node, "checks.player");
|
||||
|
||||
assertTrue(playerConfig.onlyCheckSneaking());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tileEntityConfigDoesNotRequireOrEnableClientRetention() throws SerializationException {
|
||||
TileEntityConfig config = TileEntityConfig.load(baseNode(), "checks.tile-entity");
|
||||
|
||||
assertFalse(config.hideSoundsWhenHidden());
|
||||
assertFalse(config.keepClientEntityWhenHidden());
|
||||
}
|
||||
|
||||
@Test
|
||||
void squaredDistancesAreDerivedFromConfiguredDistances() {
|
||||
RaycastConfig config = EntityConfig.DEFAULT;
|
||||
void legacyConstructorKeepsDestroyBehaviorWhileNewOverloadCanRetain() {
|
||||
RaycastConfig legacy = new RaycastConfig(true, true, 3, 8, 48, 24, 5);
|
||||
RaycastConfig retaining = new RaycastConfig(true, true, 3, 8, 48, 24, 5, true);
|
||||
|
||||
assertEquals((int) config.getAlwaysShowRadius() * config.getAlwaysShowRadius(), config.alwaysShowRadiusSquared());
|
||||
assertEquals((int) config.getRaycastRadius() * config.getRaycastRadius(), config.raycastRadiusSquared());
|
||||
assertEquals((int) config.hideOnSpawnDistance() * config.hideOnSpawnDistance(), config.hideOnSpawnDistanceSquared());
|
||||
assertTrue(config.raycastRadiusSquared() >= 0);
|
||||
assertFalse(legacy.keepClientEntityWhenHidden());
|
||||
assertTrue(retaining.keepClientEntityWhenHidden());
|
||||
}
|
||||
|
||||
private static ConfigurationNode entityNode(boolean keepClientEntityWhenHidden) throws SerializationException {
|
||||
ConfigurationNode node = baseNode();
|
||||
node.node("hide-sounds-when-hidden").set(true);
|
||||
node.node("keep-client-entity-when-hidden").set(keepClientEntityWhenHidden);
|
||||
node.node("only-check-sneaking").set(false);
|
||||
return node;
|
||||
}
|
||||
|
||||
private static ConfigurationNode baseNode() throws SerializationException {
|
||||
ConfigurationNode node = BasicConfigurationNode.root();
|
||||
node.node("enabled").set(true);
|
||||
node.node("max-occluding-count").set(3);
|
||||
node.node("always-show-radius").set(8);
|
||||
node.node("raycast-radius").set(48);
|
||||
node.node("hide-on-spawn-distance").set(24);
|
||||
node.node("visible-recheck-interval-ticks").set(5);
|
||||
return node;
|
||||
}
|
||||
}
|
||||
@@ -31,7 +31,7 @@ class RaycastUtilTest {
|
||||
Locatable start = new ImmutableLocatableImpl(world, 0, 0, 0);
|
||||
RecordingParticleSpawner particles = new RecordingParticleSpawner();
|
||||
|
||||
assertTrue(RaycastUtil.raycastUnrolledAccumulated(1, 0, 10, true, 0, emptyBlockView(), start, new ImmutableSpatialImpl(2, 0, 0), particles));
|
||||
assertTrue(RaycastUtil.raycast(start, new ImmutableSpatialImpl(2, 0, 0), 1, 0, 10, true, emptyBlockView(), 1, particles));
|
||||
assertEquals(List.of(world), particles.worlds);
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ class RaycastUtilTest {
|
||||
Locatable start = new ImmutableLocatableImpl(world, 0.5, 0.5, 0.5);
|
||||
RecordingParticleSpawner particles = new RecordingParticleSpawner();
|
||||
|
||||
assertTrue(RaycastUtil.raycastUnrolledAccumulated(1, 0, 10, true, 0, emptyBlockView(), start, new ImmutableBlockSpatialImpl(3, 0, 0), particles));
|
||||
assertTrue(RaycastUtil.raycast(start, new ImmutableBlockSpatialImpl(3, 0, 0), 1, 0, 10, true, emptyBlockView(), 1, particles));
|
||||
assertEquals(0.5, particles.positions.getFirst().y());
|
||||
assertEquals(0.5, particles.positions.getFirst().z());
|
||||
}
|
||||
@@ -65,13 +65,8 @@ class RaycastUtilTest {
|
||||
|
||||
@Override
|
||||
public void spawnParticleAt(UUID world, Spatial spatial, Colour colour) {
|
||||
spawnParticleAt(world, spatial.x(), spatial.y(), spatial.z(), colour);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void spawnParticleAt(UUID world, double x, double y, double z, Colour colour) {
|
||||
worlds.add(world);
|
||||
positions.add(new ImmutableSpatialImpl(x, y, z));
|
||||
positions.add(new ImmutableSpatialImpl(spatial.x(), spatial.y(), spatial.z()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
The binary in this folder is a compiled version of the source code at https://github.com/Cubicake/Configurate
|
||||
The fork adds commented yaml support from [Tim203](https://github.com/Tim203/Configurate) (the same as in Geyser's configurate),
|
||||
plus some minor additions from myself, with updates from [SpongePowered](https://github.com/spongepowered/configurate) merged.
|
||||
|
||||
For now, I am directly committing the binary because I cannot be bothered to host it as a Maven artifact.
|
||||
|
||||
The current version is commit [`a999454`](https://github.com/Cubicake/Configurate/commit/a999454d4020c1437bc42527c657adcc0663d9e9) from https://github.com/Cubicake/Configurate
|
||||
Binary file not shown.
+1
-1
Submodule locatables updated: 97ff3c29dc...48791f944f.
+1
-1
Submodule logging updated: dff71173aa...a7ee968069.
@@ -27,8 +27,8 @@ dependencies {
|
||||
compileOnly(project(":leafpile"))
|
||||
|
||||
compileOnly("com.github.retrooper:packetevents-api:2.12.0")
|
||||
compileOnly("org.spongepowered:configurate-core:4.2.0")
|
||||
compileOnly("it.unimi.dsi:fastutil:8.5.18")
|
||||
compileOnly("org.jetbrains:annotations:24.0.1")
|
||||
|
||||
testImplementation(platform("org.junit:junit-bom:5.10.2"))
|
||||
testImplementation("org.junit.jupiter:junit-jupiter-api")
|
||||
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
* Copyright © 2026 Cubicake.
|
||||
* This file is part of RaycastedAntiESP. RaycastedAntiESP is free software: you can redistribute it and/or
|
||||
* modify it under the terms of the GNU Affero General Public License v3.0 only, which can be accessed at
|
||||
* https://www.gnu.org/licenses/agpl-3.0.html. See README.md for warranty disclaimer and further information.
|
||||
*/
|
||||
|
||||
package games.cubi.raycastedantiesp.packetevents.config;
|
||||
|
||||
import games.cubi.raycastedantiesp.core.config.BlockProcessorConfig;
|
||||
import games.cubi.raycastedantiesp.core.config.Config;
|
||||
import games.cubi.raycastedantiesp.core.config.ConfigExtension;
|
||||
import games.cubi.raycastedantiesp.core.config.ConfigLoadException;
|
||||
import games.cubi.raycastedantiesp.core.config.ConfigReader;
|
||||
import org.spongepowered.configurate.ConfigurationNode;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record PacketEventsBlockProcessorConfig(List<Integer> tileEntityExemptedIds, List<Integer> tileEntityForceIncludedIds) implements Config {
|
||||
public static final ConfigExtension<PacketEventsBlockProcessorConfig> EXTENSION = new ConfigExtension<>() {
|
||||
@Override
|
||||
public Class<PacketEventsBlockProcessorConfig> type() {
|
||||
return PacketEventsBlockProcessorConfig.class;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PacketEventsBlockProcessorConfig load(ConfigurationNode config, BlockProcessorConfig blockProcessorConfig) {
|
||||
ConfigurationNode node = ConfigReader.node(config, "block-processor", "packetevents");
|
||||
PacketEventsBlockProcessorConfig packetEventsConfig = new PacketEventsBlockProcessorConfig(
|
||||
ConfigReader.integerList(ConfigReader.node(node, "tile-entity-exempted-ids"), "block-processor.packetevents.tile-entity-exempted-ids"),
|
||||
ConfigReader.integerList(ConfigReader.node(node, "tile-entity-force-included-ids"), "block-processor.packetevents.tile-entity-force-included-ids")
|
||||
);
|
||||
if (!blockProcessorConfig.trackAllBlocks() && !packetEventsConfig.tileEntityForceIncludedIds().isEmpty()) {
|
||||
throw new ConfigLoadException("block-processor.packetevents.tile-entity-force-included-ids must be empty when block-processor.track-all-blocks is false");
|
||||
}
|
||||
return packetEventsConfig;
|
||||
}
|
||||
};
|
||||
}
|
||||
+1
-1
@@ -301,7 +301,7 @@ public abstract class PacketEventsBlockViewController implements PacketListener
|
||||
if (playerLocation == null || playerLocation.world() == null || !playerLocation.world().equals(packetWorld)) {
|
||||
return false;
|
||||
}
|
||||
return location.distanceSquared(playerLocation) <= tileEntityConfig.hideOnSpawnDistanceSquared();
|
||||
return location.distanceSquared(playerLocation) <= tileEntityConfig.hideOnSpawnDistanceSquared;
|
||||
}
|
||||
|
||||
private WrapperPlayServerBlockEntityData buildBlockEntityDataPacket(BlockSpatial location, PacketEventsTileEntityReplayData replayData) {
|
||||
|
||||
-5
@@ -173,11 +173,6 @@ public abstract class PacketEventsEntityViewController extends PacketEntityViewC
|
||||
if (!isBypassed(packet.getEntityId()) && handleEntityAnimation(packet.getEntityId(), playerData) == REQUIRE_EVENT_CANCELLATION)
|
||||
event.setCancelled(true);
|
||||
}
|
||||
case PacketType.Play.Server.COLLECT_ITEM -> {
|
||||
WrapperPlayServerCollectItem packet = new WrapperPlayServerCollectItem(event);
|
||||
if (handleCollectItem(packet.getCollectedEntityId(), packet.getCollectorEntityId(), playerData) == REQUIRE_EVENT_CANCELLATION)
|
||||
event.setCancelled(true);
|
||||
}
|
||||
case PacketType.Play.Server.ENTITY_STATUS -> {
|
||||
WrapperPlayServerEntityStatus packet = new WrapperPlayServerEntityStatus(event);
|
||||
if (!isBypassed(packet.getEntityId()) && handleEntityEvent(packet.getEntityId(), playerData) == REQUIRE_EVENT_CANCELLATION)
|
||||
|
||||
@@ -7,7 +7,6 @@
|
||||
*/
|
||||
|
||||
import java.time.Instant
|
||||
import org.gradle.api.file.FileCollection
|
||||
import org.gradle.jvm.toolchain.JavaToolchainService
|
||||
|
||||
plugins {
|
||||
@@ -17,8 +16,6 @@ plugins {
|
||||
id("com.gradleup.shadow") version "9.4.0"
|
||||
}
|
||||
|
||||
val patchedConfigurateYaml = rootProject.extra["patchedConfigurateYaml"] as FileCollection
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
maven { url = uri("https://repo.codemc.io/repository/maven-releases/") }
|
||||
@@ -32,7 +29,7 @@ dependencies {
|
||||
//paperweight.paperDevBundle("26.2.build.+")
|
||||
compileOnly("com.github.retrooper:packetevents-spigot:2.12.0")
|
||||
compileOnly("org.spongepowered:configurate-core:4.2.0")
|
||||
implementation(patchedConfigurateYaml)
|
||||
compileOnly("org.spongepowered:configurate-yaml:4.2.0")
|
||||
|
||||
compileOnly("de.oliver:FancyHolograms:2.9.1")
|
||||
compileOnly("de.oliver:FancyNpcs:2.9.2")
|
||||
@@ -161,10 +158,6 @@ tasks.shadowJar {
|
||||
"org.bstats",
|
||||
"games.cubi.libs.raycastedantiesp.bstats"
|
||||
)
|
||||
relocate(
|
||||
"org.spongepowered.configurate.yaml",
|
||||
"games.cubi.libs.raycastedantiesp.configurate.yaml"
|
||||
)
|
||||
minimize {} // get rid of leafpile bloat
|
||||
archiveBaseName.set("RaycastedAntiESP")
|
||||
archiveClassifier.set("")
|
||||
|
||||
+26
-11
@@ -11,8 +11,7 @@ package games.cubi.raycastedantiesp.paper;
|
||||
import games.cubi.logs.CheckPreviousLogForError;
|
||||
import games.cubi.logs.PlatformLogger;
|
||||
import games.cubi.raycastedantiesp.core.config.ConfigManager;
|
||||
import games.cubi.raycastedantiesp.core.config.LogLevelConfig;
|
||||
import games.cubi.raycastedantiesp.core.config.LoggingConfig;
|
||||
import games.cubi.raycastedantiesp.core.config.DebugConfig;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Range;
|
||||
@@ -81,11 +80,21 @@ public class PaperLoggerAdapter implements PlatformLogger {
|
||||
* Note that by default the log levels are at 5, so any logs which should appear normally should be at 1-5. Additionally, loggers which fire several times a tick should be at 10, once a tick at 9, and loggers firing frequently at 6-8
|
||||
* */
|
||||
|
||||
private LoggingConfig.Severity getConfigSeverity(Level severity) {
|
||||
private int getLevel(Level severity, DebugConfig debug) {
|
||||
return switch (severity) {
|
||||
case INFO -> LoggingConfig.Severity.INFO;
|
||||
case WARN -> LoggingConfig.Severity.WARN;
|
||||
case ERROR -> LoggingConfig.Severity.ERROR;
|
||||
case INFO -> debug.getInfoLevel();
|
||||
case WARN -> debug.getWarnLevel();
|
||||
case ERROR -> debug.getErrorLevel();
|
||||
default -> 1;
|
||||
};
|
||||
}
|
||||
|
||||
private DebugConfig.Severity getDebugSeverity(Level severity) {
|
||||
return switch (severity) {
|
||||
case INFO -> DebugConfig.Severity.INFO;
|
||||
case WARN -> DebugConfig.Severity.WARN;
|
||||
case ERROR -> DebugConfig.Severity.ERROR;
|
||||
default -> DebugConfig.Severity.ERROR;
|
||||
};
|
||||
}
|
||||
/**
|
||||
@@ -135,13 +144,19 @@ public class PaperLoggerAdapter implements PlatformLogger {
|
||||
}
|
||||
|
||||
private void forwardLog(String message, Level severity, int level, Class<?>... source) {
|
||||
ConfigManager configManager = RaycastedAntiESP.getConfigManager();
|
||||
if (LOG_TO_FILE) {
|
||||
queueFileLog(PlatformLogger.constructFileLogMessage(message, severity, level, source), severity);
|
||||
}
|
||||
LoggingConfig logging = ConfigManager.getLoggingConfigOrDefault();
|
||||
LogLevelConfig levelConfig = logging.forSeverity(getConfigSeverity(severity));
|
||||
if (levelConfig.isExempted(source) || levelConfig.level() < level) {
|
||||
return;
|
||||
if (configManager != null && configManager.getDebugConfig() != null) {
|
||||
DebugConfig debug = configManager.getDebugConfig();
|
||||
|
||||
if (debug.isExempted(getDebugSeverity(severity), source)) {
|
||||
return;
|
||||
}
|
||||
if (getLevel(severity, debug) < level) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
message = source != null ? PlatformLogger.constructMessage(message, source) : message;
|
||||
@@ -229,4 +244,4 @@ public class PaperLoggerAdapter implements PlatformLogger {
|
||||
logger.severe("Failed to write queued log messages to " + logFilePath + ": " + exception.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+8
-6
@@ -14,7 +14,7 @@ import games.cubi.raycastedantiesp.paper.commands.AttributionBrigadier;
|
||||
import games.cubi.raycastedantiesp.paper.commands.RaycastedAntiESPCommandBrigadier;
|
||||
import games.cubi.raycastedantiesp.paper.config.PaperEntityTypeExclusionResolver;
|
||||
import games.cubi.raycastedantiesp.paper.engine.PaperAsyncEngine;
|
||||
import games.cubi.raycastedantiesp.paper.config.PaperBlockSelectorMatcher;
|
||||
import games.cubi.raycastedantiesp.packetevents.config.PacketEventsBlockProcessorConfig;
|
||||
import games.cubi.raycastedantiesp.packetevents.view.PacketEventsBlockView;
|
||||
import games.cubi.raycastedantiesp.packetevents.view.PacketEventsEntityView;
|
||||
import games.cubi.raycastedantiesp.core.view.ViewRegistry;
|
||||
@@ -42,6 +42,7 @@ import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Set;
|
||||
import java.util.function.IntSupplier;
|
||||
import java.util.List;
|
||||
|
||||
public final class RaycastedAntiESP extends JavaPlugin implements CommandExecutor {
|
||||
private static ConfigManager config;
|
||||
@@ -69,7 +70,11 @@ public final class RaycastedAntiESP extends JavaPlugin implements CommandExecuto
|
||||
|
||||
@Override
|
||||
public void onLoad() {
|
||||
config = ConfigManager.initialiseConfigManager(getDataFolder().toPath());
|
||||
config = ConfigManager.initialiseConfigManager(
|
||||
() -> getResource("config.yml"),
|
||||
getDataFolder().toPath(),
|
||||
List.of(PacketEventsBlockProcessorConfig.EXTENSION)
|
||||
);
|
||||
Plugin packetEvents = Bukkit.getPluginManager().getPlugin("packetevents");
|
||||
if (packetEvents == null) {
|
||||
throw new IllegalStateException("PacketEvents is required but was not found.");
|
||||
@@ -87,11 +92,8 @@ public final class RaycastedAntiESP extends JavaPlugin implements CommandExecuto
|
||||
else {
|
||||
currentTickSupplier = new PaperTicker();
|
||||
}
|
||||
config.completeInitialLoad();
|
||||
PaperEntityTypeExclusionResolver.resolveAndInitialise(config.getEntityConfig().excludedTypes());
|
||||
PacketEventsPaperBlockInfoResolver blockInfoResolver = new PacketEventsPaperBlockInfoResolver(
|
||||
new PaperBlockSelectorMatcher(config.getTileEntityConfig().excludedBlocks())
|
||||
);
|
||||
PacketEventsPaperBlockInfoResolver blockInfoResolver = new PacketEventsPaperBlockInfoResolver();
|
||||
boolean trackAllBlocks = config.getBlockProcessorConfig().trackAllBlocks();
|
||||
ViewRegistry.initialise(worldEpoch -> new PacketEventsBlockView(blockInfoResolver, trackAllBlocks, worldEpoch), PacketEventsEntityView::createEntityView, PacketEventsEntityView::createPlayerView);
|
||||
PacketEventsCommonViewController.initialise(new PaperPacketEventsCommonViewController(currentTickSupplier));
|
||||
|
||||
+6
-13
@@ -24,6 +24,7 @@ import games.cubi.raycastedantiesp.core.view.BlockView;
|
||||
import games.cubi.raycastedantiesp.core.view.EntityView;
|
||||
import games.cubi.raycastedantiesp.paper.RaycastedAntiESP;
|
||||
import games.cubi.raycastedantiesp.paper.UpdateChecker;
|
||||
import games.cubi.raycastedantiesp.paper.packets.PacketEventsPaperBlockInfoResolver;
|
||||
|
||||
import games.cubi.raycastedantiesp.paper.utils.PaperScheduler;
|
||||
import io.github.retrooper.packetevents.util.SpigotConversionUtil;
|
||||
@@ -39,7 +40,6 @@ import net.strokkur.commands.permission.Permission;
|
||||
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.bukkit.entity.Player;
|
||||
@@ -120,6 +120,11 @@ public class RaycastedAntiESPCommand {
|
||||
UpdateChecker.checkForUpdates(RaycastedAntiESP.get(), sender);
|
||||
}
|
||||
|
||||
@Executes("print-block-ids")
|
||||
void printBlockIDsCommand() {
|
||||
PacketEventsPaperBlockInfoResolver.get.iterateBlockIDs(true);
|
||||
}
|
||||
|
||||
private void sendConfigMutationResult(CommandSender sender, ConfigManager.SetConfigResult result, String action, String key, String value) {
|
||||
if (!result.success()) {
|
||||
sender.sendRichMessage("<red>Invalid config change: <white>" + result.message());
|
||||
@@ -128,8 +133,6 @@ public class RaycastedAntiESPCommand {
|
||||
sender.sendRichMessage("<white>" + action + " <green>" + value + "<white> for <green>" + key);
|
||||
if (result.restartRequired()) {
|
||||
sender.sendRichMessage("<yellow>This change was saved but requires a restart: <white>" + result.message());
|
||||
} else if (result.repaired()) {
|
||||
sender.sendRichMessage("<yellow>" + result.message());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -330,16 +333,6 @@ public class RaycastedAntiESPCommand {
|
||||
|
||||
@Executes("entity-id")
|
||||
void getFromEntityID(int entityID, CommandSender sender) {
|
||||
sender.sendRichMessage("<white>Searching Bukkit for entity id " + entityID + ":");
|
||||
boolean foundBukkit = false;
|
||||
for (World world : Bukkit.getWorlds()) {
|
||||
Entity bukkitEntity = SpigotConversionUtil.getEntityById(world, entityID);
|
||||
if (bukkitEntity != null) {
|
||||
sendBukkitEntityData(sender, bukkitEntity);
|
||||
foundBukkit = true;
|
||||
}
|
||||
}
|
||||
if (!foundBukkit) sender.sendRichMessage("<red> Could not find entity via Bukkit.");
|
||||
sender.sendRichMessage("<white>Searching all connected player views for entity ID " + entityID + ":");
|
||||
int matches = 0;
|
||||
for (PlayerData playerData : PlayerRegistry.get().getPlayerDataArray()) {
|
||||
|
||||
-53
@@ -1,53 +0,0 @@
|
||||
package games.cubi.raycastedantiesp.paper.config;
|
||||
|
||||
import games.cubi.logs.Logger;
|
||||
import games.cubi.raycastedantiesp.core.config.raycast.BlockSelector;
|
||||
import org.bukkit.NamespacedKey;
|
||||
import org.bukkit.Registry;
|
||||
import org.bukkit.block.BlockType;
|
||||
import org.bukkit.block.data.BlockData;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
/** Resolves core block selectors through the block registry without exposing processor state IDs. */
|
||||
public final class PaperBlockSelectorMatcher implements Predicate<BlockData> {
|
||||
private final List<BlockData> parsedSelectors;
|
||||
|
||||
public PaperBlockSelectorMatcher(List<BlockSelector> selectors) {
|
||||
Objects.requireNonNull(selectors, "selectors");
|
||||
List<BlockData> resolvedSelectors = new ArrayList<>();
|
||||
for (BlockSelector selector : selectors) {
|
||||
NamespacedKey key = NamespacedKey.fromString(selector.blockKey());
|
||||
BlockType blockType = key == null ? null : Registry.BLOCK.get(key);
|
||||
if (blockType == null) {
|
||||
warnUnresolved(selector);
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
resolvedSelectors.add(blockType.createBlockData(selector.toString().substring(selector.blockKey().length())));
|
||||
} catch (IllegalArgumentException exception) {
|
||||
warnUnresolved(selector);
|
||||
}
|
||||
}
|
||||
parsedSelectors = List.copyOf(resolvedSelectors);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean test(BlockData blockData) {
|
||||
for (BlockData selector : parsedSelectors) {
|
||||
// The parsed selector must be the argument so omitted properties remain wildcards.
|
||||
if (blockData.matches(selector)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void warnUnresolved(BlockSelector selector) {
|
||||
Logger.warning("Unknown block selector '" + selector + "' in checks.tile-entity.excluded-blocks; ignoring it on this server.", 4,
|
||||
PaperBlockSelectorMatcher.class);
|
||||
}
|
||||
}
|
||||
+44
-26
@@ -11,37 +11,56 @@ package games.cubi.raycastedantiesp.paper.packets;
|
||||
import com.github.retrooper.packetevents.protocol.world.states.WrappedBlockState;
|
||||
import games.cubi.logs.Logger;
|
||||
import games.cubi.raycastedantiesp.core.chunks.BlockInfoResolver;
|
||||
import games.cubi.raycastedantiesp.packetevents.config.PacketEventsBlockProcessorConfig;
|
||||
import games.cubi.raycastedantiesp.paper.RaycastedAntiESP;
|
||||
import io.github.retrooper.packetevents.util.SpigotConversionUtil;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.block.TileState;
|
||||
import org.bukkit.block.data.BlockData;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
public class PacketEventsPaperBlockInfoResolver implements BlockInfoResolver {
|
||||
private final boolean[] occlusionArray;
|
||||
/** Raw Bukkit TileState capability, before plugin config overrides. */
|
||||
private final boolean[] rawTileEntityArray;
|
||||
/** Anti-ESP managed tile entity state, after configured exclusions. */
|
||||
/** Anti-ESP managed tile entity state, after exemptions and force-includes. */
|
||||
private final boolean[] tileEntityArray;
|
||||
|
||||
public PacketEventsPaperBlockInfoResolver(Predicate<BlockData> excludedBlocks) {
|
||||
BlockInfoArrays result = iterateBlockStates(Objects.requireNonNull(excludedBlocks, "excludedBlocks"));
|
||||
occlusionArray = result.occluding;
|
||||
rawTileEntityArray = result.rawTileEntity;
|
||||
tileEntityArray = result.managedTileEntity;
|
||||
public static PacketEventsPaperBlockInfoResolver get;
|
||||
|
||||
public PacketEventsPaperBlockInfoResolver() {
|
||||
get = this;
|
||||
boolean[][] result = iterateBlockIDs(false);
|
||||
occlusionArray = result[0];
|
||||
rawTileEntityArray = result[1];
|
||||
tileEntityArray = Arrays.copyOf(rawTileEntityArray, rawTileEntityArray.length);
|
||||
PacketEventsBlockProcessorConfig config = RaycastedAntiESP.getConfigManager().getExtensionConfig(PacketEventsBlockProcessorConfig.class);
|
||||
if (config != null) {
|
||||
for (int blockStateId : config.tileEntityExemptedIds()) {
|
||||
if (blockStateId >= 0 && blockStateId < tileEntityArray.length) {
|
||||
tileEntityArray[blockStateId] = false;
|
||||
}
|
||||
}
|
||||
for (int blockStateId : config.tileEntityForceIncludedIds()) {
|
||||
if (blockStateId >= 0 && blockStateId < tileEntityArray.length) {
|
||||
tileEntityArray[blockStateId] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private BlockInfoArrays iterateBlockStates(Predicate<BlockData> excludedBlocks) {
|
||||
/**
|
||||
* @return Boolean array with two nested boolean arrays. <code>boolean[0]</code> returns the occlusion status array, <code>boolean[1]</code> returns the tile entity status array. Both arrays are indexed by block state ID. Air blocks and invalid IDs are treated as non-occluding and non-tile-entity, and trailing air IDs are ignored to save memory.
|
||||
*/
|
||||
public boolean[][] iterateBlockIDs(boolean materialToIDMode) {
|
||||
boolean run = true;
|
||||
int airs = 0;
|
||||
int lastNonAirID = 0;
|
||||
Map<Integer, Boolean> occlusion = new HashMap<>(111000); //Tests show 30,000 block IDs in 1.21.11, and we scan forwards for 80k air ids just in case, so 111k is enough. This is a pointless micro optimization but why not
|
||||
Map<Integer, Boolean> rawTileEntity = new HashMap<>(111000);
|
||||
Map<Integer, Boolean> managedTileEntity = new HashMap<>(111000);
|
||||
Map<Integer, Boolean> tileEntity = new HashMap<>(111000);
|
||||
int iterator = 0;
|
||||
while (run) {
|
||||
BlockData blockData = SpigotConversionUtil.toBukkitBlockData(WrappedBlockState.getByGlobalId(iterator));
|
||||
@@ -63,27 +82,29 @@ public class PacketEventsPaperBlockInfoResolver implements BlockInfoResolver {
|
||||
lastNonAirID = iterator;
|
||||
}
|
||||
boolean occluding = material != Material.BARRIER && material.isOccluding();
|
||||
if (materialToIDMode && material != Material.AIR) {
|
||||
Logger.info(blockData.getAsString() + iterator + occluding,1);
|
||||
}
|
||||
occlusion.put(iterator, occluding);
|
||||
try {
|
||||
boolean isTileEntity = blockData.createBlockState() instanceof TileState;
|
||||
rawTileEntity.put(iterator, isTileEntity);
|
||||
managedTileEntity.put(iterator, isTileEntity && !excludedBlocks.test(blockData));
|
||||
if (blockData.createBlockState() instanceof TileState) {
|
||||
//Logger.debug("tile at" + iterator + " is tile entity" + material.name());
|
||||
tileEntity.put(iterator, true);
|
||||
} else {
|
||||
tileEntity.put(iterator, false);
|
||||
}
|
||||
} catch (Exception a) {
|
||||
rawTileEntity.put(iterator, false);
|
||||
managedTileEntity.put(iterator, false);
|
||||
tileEntity.put(iterator, false);
|
||||
// will sometimes inconsistently happen, just ignore it ig?
|
||||
}
|
||||
iterator++;
|
||||
}
|
||||
boolean[] occlusionArray = new boolean[lastNonAirID + 1];
|
||||
boolean[] rawTileEntityArray = new boolean[lastNonAirID + 1];
|
||||
boolean[] managedTileEntityArray = new boolean[lastNonAirID + 1];
|
||||
boolean[][] result = new boolean[2][lastNonAirID + 1];
|
||||
for (int i = 0; i < (lastNonAirID + 1) /*Ignore the trailing airs*/; i++) {
|
||||
occlusionArray[i] = occlusion.get(i);
|
||||
rawTileEntityArray[i] = rawTileEntity.get(i);
|
||||
managedTileEntityArray[i] = managedTileEntity.get(i);
|
||||
result[0][i] = occlusion.get(i);
|
||||
result[1][i] = tileEntity.get(i);
|
||||
}
|
||||
return new BlockInfoArrays(occlusionArray, rawTileEntityArray, managedTileEntityArray);
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -117,7 +138,4 @@ public class PacketEventsPaperBlockInfoResolver implements BlockInfoResolver {
|
||||
private boolean[] dumpTileEntityArray() {
|
||||
return tileEntityArray;
|
||||
}
|
||||
|
||||
private record BlockInfoArrays(boolean[] occluding, boolean[] rawTileEntity, boolean[] managedTileEntity) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
# An explanation of this configuration file and what the options do can be found at https://raycastedantiesp.cubi.games/config/
|
||||
config-version: '2.0'
|
||||
checks:
|
||||
player:
|
||||
enabled: true
|
||||
hide-sounds-when-hidden: true
|
||||
max-occluding-count: 3
|
||||
always-show-radius: 8
|
||||
raycast-radius: 128
|
||||
hide-on-spawn-distance: 24
|
||||
visible-recheck-interval-ticks: 5 # -1 disables visible rechecks. When set to -1, once an entity is shown by any mechanism, it will be permanently visible.
|
||||
keep-client-entity-when-hidden: false
|
||||
only-check-sneaking: true
|
||||
entity:
|
||||
enabled: true
|
||||
hide-sounds-when-hidden: true
|
||||
max-occluding-count: 3
|
||||
always-show-radius: 8
|
||||
raycast-radius: 92
|
||||
hide-on-spawn-distance: 24
|
||||
visible-recheck-interval-ticks: 5 # -1 disables visible rechecks. When set to -1, once an entity is shown by any mechanism, it will be permanently visible.
|
||||
keep-client-entity-when-hidden: false
|
||||
excluded-types:
|
||||
# Projectiles move very quickly, giving limited time for the raycast engine to process them. This could cause the player not to have enough time to dodge the projectile, so they are always visible by default.
|
||||
- minecraft:arrow
|
||||
- minecraft:spectral_arrow
|
||||
- minecraft:fireball
|
||||
- minecraft:dragon_fireball
|
||||
- minecraft:small_fireball
|
||||
- minecraft:firework_rocket
|
||||
- minecraft:wither_skull
|
||||
- minecraft:breeze_wind_charge
|
||||
- minecraft:wind_charge
|
||||
- minecraft:ender_pearl
|
||||
- minecraft:evoker_fangs
|
||||
- minecraft:shulker_bullet
|
||||
|
||||
# Potions and area effect clouds can damage players even if not visible. A reasonable always-show-radius mitigates these issues, so exempting these entities is not necessary.
|
||||
# If your server relies on potion pvp where knowing the exact number of potions someone else has used is an unfair advantage, you may want to un-exempt these entities.
|
||||
- minecraft:area_effect_cloud
|
||||
- minecraft:lingering_potion
|
||||
- minecraft:splash_potion
|
||||
- minecraft:potion # Note: the "potion" entity was removed in 1.21.5 and replaced with "splash_potion" and "lingering_potion". If you are on 1.21.4, you can comment out the above two entry. If you are on 1.21.5+ you should instead comment out this entry.
|
||||
|
||||
# Lightning is short-lived and expected to be visible to people who cannot see the block being struck.
|
||||
- minecraft:lightning_bolt
|
||||
|
||||
- minecraft:ender_dragon
|
||||
- minecraft:wither
|
||||
- minecraft:warden
|
||||
|
||||
# These entities are not seen in normal gameplay, and are usually part of custom mechanics.
|
||||
# If you un-exempt these entities, it is likely that other plugins (such as hologram or NPC plugins) will break.
|
||||
- minecraft:block_display
|
||||
- minecraft:text_display
|
||||
- minecraft:item_display
|
||||
- minecraft:interaction
|
||||
- minecraft:mannequin
|
||||
# Falling blocks are often used in custom mechanics, especially by plugins made before display entities were added to the game.
|
||||
# Therefore, exempting them can make sense. However, falling blocks also occur in regular gameplay,
|
||||
# and can provide insight about players which are not visible.
|
||||
# Therefore, falling blocks are not exempted by default.
|
||||
#- minecraft:falling_block
|
||||
|
||||
# You can add more excluded types using the name for the entity which would be used by the /summon <entity> command, adding "- <entity>" to the list above.
|
||||
tile-entity:
|
||||
enabled: true
|
||||
max-occluding-count: 3
|
||||
always-show-radius: 8
|
||||
raycast-radius: 64
|
||||
hide-on-spawn-distance: 24
|
||||
visible-recheck-interval-ticks: -1 # -1 disables visible rechecks. When set to -1, once an entity is shown by any mechanism, it will be permanently visible.
|
||||
sound-effects:
|
||||
enabled: false
|
||||
max-occluding-count: 3
|
||||
always-play-radius: 8
|
||||
raycast-radius: 48
|
||||
chunk-section:
|
||||
enabled: false
|
||||
max-occluding-count: 6
|
||||
always-show-radius-chunks: 2
|
||||
visible-recheck-interval-ticks: -1
|
||||
engine:
|
||||
mode: async
|
||||
async:
|
||||
processing-threads: 1 # 1 thread is sufficient for hundreds of players, I do not recommend increasing this value blindly.
|
||||
netty:
|
||||
block-processor:
|
||||
mode: packetevents
|
||||
track-all-blocks: false
|
||||
packetevents:
|
||||
tile-entity-exempted-ids:
|
||||
#- 9779 - Beacon ID on 1.21.11. To see what the beacon ID is for your server version, run the command "/antiesp print-block-ids". This will dump a massive list of all the block ID to block name mappings in the console. Search your logs for "beacon" (or whatever other tile entity you'd like to exempt) and add the associated ID here
|
||||
tile-entity-force-included-ids:
|
||||
debug:
|
||||
info-level: 5
|
||||
info-exempted-classes:
|
||||
warn-level: 5
|
||||
warn-exempted-classes:
|
||||
error-level: 5
|
||||
error-exempted-classes:
|
||||
particles: false
|
||||
timings: false
|
||||
updates:
|
||||
check-release: true
|
||||
check-beta: true
|
||||
check-alpha: true
|
||||
notify-in-game: true # When false, update checks only notify the console. When true, players with the correct permission are notified.
|
||||
Reference in new issue
Block a user