From 92f40c36b86bc47da84e4ef03b96d71f0b40df52 Mon Sep 17 00:00:00 2001 From: gnembon Date: Tue, 11 Jun 2019 02:08:50 -0300 Subject: [PATCH 1/7] settings system --- src/main/java/carpet/CarpetServer.java | 13 + src/main/java/carpet/CarpetSettings.java | 44 ++-- .../java/carpet/commands/ParcetCommand.java | 209 ++++++++++++++++ src/main/java/carpet/settings/ParsedRule.java | 170 +++++++++++++ src/main/java/carpet/settings/Rule.java | 58 +++++ .../java/carpet/settings/RuleCategory.java | 13 + src/main/java/carpet/settings/Settings.java | 84 +++++++ .../java/carpet/settings/SettingsManager.java | 230 ++++++++++++++++++ src/main/java/carpet/settings/Validator.java | 63 +++++ 9 files changed, 863 insertions(+), 21 deletions(-) create mode 100644 src/main/java/carpet/commands/ParcetCommand.java create mode 100644 src/main/java/carpet/settings/ParsedRule.java create mode 100644 src/main/java/carpet/settings/Rule.java create mode 100644 src/main/java/carpet/settings/RuleCategory.java create mode 100644 src/main/java/carpet/settings/Settings.java create mode 100644 src/main/java/carpet/settings/SettingsManager.java create mode 100644 src/main/java/carpet/settings/Validator.java diff --git a/src/main/java/carpet/CarpetServer.java b/src/main/java/carpet/CarpetServer.java index 22f088c6..7c9d6cec 100644 --- a/src/main/java/carpet/CarpetServer.java +++ b/src/main/java/carpet/CarpetServer.java @@ -10,6 +10,7 @@ import carpet.commands.DistanceCommand; import carpet.commands.DrawCommand; import carpet.commands.InfoCommand; import carpet.commands.LogCommand; +import carpet.commands.ParcetCommand; import carpet.commands.PerimeterInfoCommand; import carpet.commands.PlayerCommand; import carpet.commands.ScriptCommand; @@ -18,6 +19,8 @@ import carpet.commands.TickCommand; import carpet.helpers.TickSpeed; import carpet.logging.LoggerRegistry; import carpet.script.CarpetScriptServer; +import carpet.settings.Settings; +import carpet.settings.SettingsManager; import carpet.utils.HUDController; import com.mojang.brigadier.CommandDispatcher; import net.minecraft.server.command.ServerCommandSource; @@ -28,12 +31,21 @@ public class CarpetServer // static for now - easier to handle all around the co public static final Random rand = new Random((int)((2>>16)*Math.random())); public static MinecraftServer minecraft_server; public static CarpetScriptServer scriptServer; + public static SettingsManager settingsManager; + static { + SettingsManager.parseSettingsClass(Settings.class); + //... + } public static void init(MinecraftServer server) //aka constructor of this static singleton class { CarpetServer.minecraft_server = server; } public static void onServerLoaded(MinecraftServer server) { + //new + settingsManager = new SettingsManager(server); + + //old CarpetSettings.apply_settings_from_conf(server); scriptServer = new CarpetScriptServer(); } @@ -65,6 +77,7 @@ public class CarpetServer // static for now - easier to handle all around the co PerimeterInfoCommand.register(dispatcher); DrawCommand.register(dispatcher); ScriptCommand.register(dispatcher); + ParcetCommand.register(dispatcher); //TestCommand.register(dispatcher); } diff --git a/src/main/java/carpet/CarpetSettings.java b/src/main/java/carpet/CarpetSettings.java index 13a49e68..2a619272 100644 --- a/src/main/java/carpet/CarpetSettings.java +++ b/src/main/java/carpet/CarpetSettings.java @@ -7,6 +7,7 @@ import net.minecraft.server.MinecraftServer; import net.minecraft.server.command.ServerCommandSource; import net.minecraft.server.dedicated.DedicatedServer; import net.minecraft.server.network.ServerPlayerEntity; +import org.apache.commons.lang3.tuple.Pair; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -214,19 +215,19 @@ public class CarpetSettings public static void apply_settings_from_conf(MinecraftServer server) { - Map conf = read_conf(server); - boolean is_locked = locked; + Pair,Boolean> conf = read_conf(server); locked = false; - if (is_locked) + if (conf.getRight()) { LOG.info("[CM]: Carpet Mod is locked by the administrator"); + disable_commands_by_default(); } - for (String key: conf.keySet()) + for (String key: conf.getLeft().keySet()) { - set(server.getCommandSource(), key, conf.get(key)); - LOG.info("[CM]: loaded setting "+key+" as "+conf.get(key)+" from carpet.conf"); + set(server.getCommandSource(), key, conf.getLeft().get(key)); + LOG.info("[CM]: loaded setting "+key+" as "+conf.getLeft().get(key)+" from carpet.conf"); } - locked = is_locked; + locked = conf.getRight(); } private static void disable_commands_by_default() { @@ -239,21 +240,21 @@ public class CarpetSettings } } - private static Map read_conf(MinecraftServer server) + private static Pair,Boolean> read_conf(MinecraftServer server) { try { File settings_file = server.getLevelStorage().resolveFile(server.getLevelName(), "carpet.conf"); BufferedReader b = new BufferedReader(new FileReader(settings_file)); String line = ""; + boolean confLocked = false; Map result = new HashMap(); while ((line = b.readLine()) != null) { line = line.replaceAll("\\r|\\n", ""); if ("locked".equalsIgnoreCase(line)) { - disable_commands_by_default(); - locked = true; + confLocked = true; } String[] fields = line.split("\\s+",2); if (fields.length > 1) @@ -272,16 +273,16 @@ public class CarpetSettings } } b.close(); - return result; + return Pair.of(result, confLocked); } catch(FileNotFoundException e) { - return new HashMap<>(); + return Pair.of(new HashMap<>(), false); } catch (IOException e) { e.printStackTrace(); - return new HashMap<>(); + return Pair.of(new HashMap<>(), false); } } @@ -311,9 +312,10 @@ public class CarpetSettings if (locked) return false; if (settings_store.containsKey(setting_name)) { - Map conf = read_conf(source.getMinecraftServer()); - conf.put(setting_name, string_value); - write_conf(source.getMinecraftServer(), conf); + Pair,Boolean> conf = read_conf(source.getMinecraftServer()); + conf.getLeft().put(setting_name, string_value); + write_conf(source.getMinecraftServer(), conf.getLeft()); // this may feels weird, but if conf + // is locked, it will never reach this point. set(source, setting_name,string_value); return true; } @@ -325,9 +327,9 @@ public class CarpetSettings if (locked) return false; if (settings_store.containsKey(setting_name)) { - Map conf = read_conf(source.getMinecraftServer()); - conf.remove(setting_name); - write_conf(source.getMinecraftServer(), conf); + Pair,Boolean> conf = read_conf(source.getMinecraftServer()); + conf.getLeft().remove(setting_name); + write_conf(source.getMinecraftServer(), conf.getLeft()); set(source, setting_name,get(setting_name).getDefault()); return true; } @@ -386,7 +388,7 @@ public class CarpetSettings public static CarpetSettingEntry[] find_nondefault(MinecraftServer server) { ArrayList res = new ArrayList(); - Map defaults = read_conf(server); + Map defaults = read_conf(server).getLeft(); for (String rule: settings_store.keySet().stream().sorted().collect(Collectors.toList())) { if (!settings_store.get(rule).isDefault() || defaults.containsKey(rule)) @@ -400,7 +402,7 @@ public class CarpetSettings { ArrayList res = new ArrayList(); if (locked) return res.toArray(new CarpetSettingEntry[0]); - Map defaults = read_conf(server); + Map defaults = read_conf(server).getLeft(); for (String rule: settings_store.keySet().stream().sorted().collect(Collectors.toList())) { if (defaults.containsKey(rule)) diff --git a/src/main/java/carpet/commands/ParcetCommand.java b/src/main/java/carpet/commands/ParcetCommand.java new file mode 100644 index 00000000..a614c7bb --- /dev/null +++ b/src/main/java/carpet/commands/ParcetCommand.java @@ -0,0 +1,209 @@ +package carpet.commands; + +import carpet.CarpetServer; +import carpet.CarpetSettings; +import carpet.settings.ParsedRule; +import carpet.settings.RuleCategory; +import carpet.settings.SettingsManager; +import carpet.utils.Messenger; +import com.mojang.brigadier.CommandDispatcher; +import com.mojang.brigadier.arguments.StringArgumentType; +import com.mojang.brigadier.builder.LiteralArgumentBuilder; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import net.minecraft.server.command.ServerCommandSource; +import net.minecraft.server.command.CommandManager; +import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.text.BaseText; +import net.minecraft.text.Text; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.stream.Collectors; + +import static net.minecraft.server.command.CommandManager.argument; +import static net.minecraft.server.command.CommandManager.literal; +import static net.minecraft.server.command.CommandSource.suggestMatching; + +public class ParcetCommand +{ + public static void register(CommandDispatcher dispatcher) + { + LiteralArgumentBuilder literalargumentbuilder = literal("parcet").requires((player) -> + player.hasPermissionLevel(2) && !CarpetServer.settingsManager.locked); + + literalargumentbuilder.executes((context)->listAllSettings(context.getSource())). + then(literal("list"). + executes( (c) -> listSettings(c.getSource(), + "All CarpetMod Settings", + SettingsManager.getRules())). + then(literal("defaults"). + executes( (c)-> listSettings(c.getSource(), + "Current CarpetMod Startup Settings from carpet.conf", + CarpetServer.settingsManager.findStartupOverrides()))). + then(argument("tag",StringArgumentType.word()). + suggests( (c, b)->suggestMatching(Arrays.stream(RuleCategory.values()).map(r -> r.lowerCase), b)). + executes( (c) -> listSettings(c.getSource(), + String.format("CarpetMod Settings matching \"%s\"", StringArgumentType.getString(c, "tag")), + CarpetServer.settingsManager.getRulesMatching(StringArgumentType.getString(c, "tag")))))); + + for (ParsedRule rule: SettingsManager.getRules()) + { + literalargumentbuilder.then(literal(rule.name).executes( (context) -> + displayRuleMenu(context.getSource(),rule))); + literalargumentbuilder.then(literal("removeDefault"). + requires(s -> !CarpetServer.settingsManager.locked). + then(literal(rule.name).executes((context) -> + removeDefault(context.getSource(), rule)))); + literalargumentbuilder.then(literal(rule.name). + requires(s -> !CarpetServer.settingsManager.locked). + then(argument("value", StringArgumentType.word()). + suggests((c, b)-> suggestMatching(rule.options,b)). + executes((context) -> + setRule(context.getSource(), rule, StringArgumentType.getString(context, "value"))))); + literalargumentbuilder.then(literal("setDefault"). + requires(s -> !CarpetServer.settingsManager.locked). + then(literal(rule.name). + then(argument("value", StringArgumentType.word()). + suggests((c, b)-> suggestMatching(rule.options,b)). + executes((context) -> + setDefault(context.getSource(), rule, StringArgumentType.getString(context, "value")))))); + } + dispatcher.register(literalargumentbuilder); + } + + private static int displayRuleMenu(ServerCommandSource source, ParsedRule rule) + { + PlayerEntity player; + try + { + player = source.getPlayer(); + } + catch (CommandSyntaxException e) + { + Messenger.m(source, "w "+rule.name +" is set to: ","wb "+rule.getAsString()); + return 1; + } + + Messenger.m(player, ""); + Messenger.m(player, "wb "+rule.name,"!/carpet "+rule.name,"^g refresh"); + Messenger.m(player, "w "+rule.description); + + rule.extraInfo.forEach(s -> Messenger.m(player, "g "+s)); + + List tags = new ArrayList<>(); + tags.add(Messenger.c("w Tags: ")); + for (String t: Arrays.stream(RuleCategory.values()).sorted().map(c -> c.lowerCase).collect(Collectors.toList())) + { + tags.add(Messenger.c("c ["+t+"]", "^g list all "+t+" settings","!/carpet list "+t)); + tags.add(Messenger.c("w , ")); + } + tags.remove(tags.size()-1); + Messenger.m(player, tags.toArray(new Object[0])); + + Messenger.m(player, "w Current value: ",String.format("%s %s (%s value)",rule.getBoolValue()?"lb":"nb", rule.getAsString(),rule.isDefault()?"default":"modified")); + List options = new ArrayList<>(); + options.add(Messenger.c("w Options: ", "y [ ")); + for (String o: rule.options) + { + options.add(makeSetRuleButton(rule, o, false)); + options.add(Messenger.c("w ")); + } + options.remove(options.size()-1); + options.add(Messenger.c("y ]")); + Messenger.m(player, options.toArray(new Object[0])); + + return 1; + } + + private static int setRule(ServerCommandSource source, ParsedRule rule, String newValue) + { + if (rule.set(source, newValue) != null) + Messenger.m(source, "w "+rule.toString()+", ", "c [change permanently?]", + "^w Click to keep the settings in carpet.conf to save across restarts", + "?/carpet setDefault "+rule.name+" "+rule.getAsString()); + return 1; + } + private static int setDefault(ServerCommandSource source, ParsedRule rule, String defaultValue) + { + CarpetServer.settingsManager.setDefaultRule(source, rule.name, defaultValue); + Messenger.m(source ,"gi rule "+ rule.name+" will now default to "+ defaultValue); + return 1; + } + private static int removeDefault(ServerCommandSource source, ParsedRule rule) + { + CarpetServer.settingsManager.removeDefaultRule(source, rule.name); + Messenger.m(source ,"gi rule "+ rule.name+" defaults to Vanilla"); + return 1; + } + + + private static BaseText displayInteractiveSetting(ParsedRule rule) + { + List args = new ArrayList<>(); + args.add("w - "+rule.name+" "); + args.add("!/carpet "+rule.name); + args.add("^y "+rule.description); + for (String option: rule.options) + { + args.add(makeSetRuleButton(rule, option, true)); + args.add("w "); + } + args.remove(args.size()-1); + return Messenger.c(args.toArray(new Object[0])); + } + + private static BaseText makeSetRuleButton(ParsedRule rule, String option, boolean brackets) { + String color = ""; + if (option.equals(rule.defaultAsString) && !brackets) color += "u"; + color += option.equals(rule.getAsString()) ? "bl" : "y"; + String baseText = color + (brackets ? " [" : " ") + option + (brackets ? "]" : ""); + if (CarpetServer.settingsManager.locked) { + return Messenger.c(baseText, "^g Settings are locked"); + } + return Messenger.c(baseText, "^g Switch to " + option, "?/carpet " + rule.name + " " + option); + } + + private static int listSettings(ServerCommandSource source, String title, Collection> settings_list) + { + try + { + PlayerEntity player = source.getPlayer(); + Messenger.m(player,String.format("wb %s:",title)); + settings_list.forEach(e -> Messenger.m(player,displayInteractiveSetting(e))); + + } + catch (CommandSyntaxException e) + { + Messenger.m(source, "w s:"+title); + settings_list.forEach(r -> Messenger.m(source, "w - "+ r.toString())); + } + return 1; + } + private static int listAllSettings(ServerCommandSource source) + { + listSettings(source, "Current CarpetMod Settings", CarpetServer.settingsManager.getNonDefault()); + + Messenger.m(source, "Carpet Mod version: "+ CarpetSettings.carpetVersion); + try + { + PlayerEntity player = source.getPlayer(); + List tags = new ArrayList<>(); + tags.add("w Browse Categories:\n"); + for (String t : Arrays.stream(RuleCategory.values()).map(r -> r.lowerCase).collect(Collectors.toList())) + { + tags.add("c [" + t+"]"); + tags.add("^g list all " + t + " settings"); + tags.add("!/carpet list " + t); + tags.add("w "); + } + tags.remove(tags.size() - 1); + Messenger.m(player, tags.toArray(new Object[0])); + } + catch (CommandSyntaxException e) + { + } + return 1; + } +} diff --git a/src/main/java/carpet/settings/ParsedRule.java b/src/main/java/carpet/settings/ParsedRule.java new file mode 100644 index 00000000..224b2895 --- /dev/null +++ b/src/main/java/carpet/settings/ParsedRule.java @@ -0,0 +1,170 @@ +package carpet.settings; + +import carpet.utils.Messenger; +import com.google.common.collect.ImmutableList; +import net.minecraft.server.command.ServerCommandSource; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Locale; + +public final class ParsedRule implements Comparable { + public final Rule rule; + public final Field field; + + public final String name; + public final String description; + public final ImmutableList extraInfo; + public final ImmutableList categories; + public final ImmutableList options; + public boolean isStrict; + public final Class type; + public final List> validators; + public final T defaultValue; + public final String defaultAsString; + + public static T callConstructor(Class cls) { + try { + Constructor constr = cls.getDeclaredConstructor(); + constr.setAccessible(true); + return constr.newInstance(); + } catch (ReflectiveOperationException e) { + throw new RuntimeException(e); + } + } + + ParsedRule(Field field, Rule rule) { + this.rule = rule; + this.field = field; + this.name = rule.name().isEmpty() ? field.getName() : rule.name(); + this.type = (Class) field.getType(); + this.description = rule.desc(); + this.isStrict = rule.strict(); + this.extraInfo = ImmutableList.copyOf(rule.extra()); + this.categories = ImmutableList.copyOf(rule.category()); + this.validators = new ArrayList<>(); + for (Class v : rule.validate()) + { + this.validators.add((Validator) callConstructor(v)); + } + if (categories.contains(RuleCategory.COMMANDS)) + this.validators.add(callConstructor(Validator._COMMAND.class)); + + this.defaultValue = get(); + this.defaultAsString = convertToString(this.defaultValue); + if (this.type == boolean.class) { + this.isStrict = true; // it has no sense otherwise + this.options = ImmutableList.of("true", "false"); + } else if (this.type.isEnum()) { + this.isStrict = true; // it has no sense otherwise + this.options = Arrays.stream(this.type.getEnumConstants()).map(e -> ((Enum) e).name().toLowerCase(Locale.ROOT)).collect(ImmutableList.toImmutableList()); + } else { + this.options = ImmutableList.copyOf(rule.options()); + } + if (isStrict) + this.validators.add(callConstructor(Validator._STRICT.class)); + } + + + public ParsedRule set(ServerCommandSource source, String value) { + //if locked - prevent + if (type == String.class) + { + return set(source, (T) value, value); + } + else if (type == boolean.class) + { + return set(source, (T) (Object) Boolean.parseBoolean(value), value); + } + else if (type == int.class) + { + return set(source, (T) (Object) Integer.parseInt(value), value); + } + else if (type.isEnum()) + { + String ucValue = value.toUpperCase(Locale.ROOT); + return set(source, (T) (Object) Enum.valueOf((Class) type, ucValue), value); + } + else + { + Messenger.m(source, "r Unknown type " + type.getSimpleName()); + return null; + } + } + + public ParsedRule set(ServerCommandSource source, T value, String stringValue) { + try { + for (Validator validator : this.validators) + { + boolean allowed = validator.validate(source, this, value, stringValue); + if (!allowed) + { + Messenger.m(source, "r Wrong value for " + name + ": " + stringValue); + return null; + } + } + this.field.set(null, value); + + } + catch (IllegalAccessException e) + { + Messenger.m(source, "r Unable to access setting for "+name); + } + return this; + } + + public T get() { + try { + return (T) this.field.get(null); + } catch (IllegalAccessException e) { + throw new IllegalStateException(e); + } + } + + public String getAsString() { + return convertToString(get()); + } + + public boolean getBoolValue() { + if (type == boolean.class) return (Boolean) get(); + if (type.isAssignableFrom(Number.class)) return ((Number) get()).doubleValue() > 0; + return false; + } + + public boolean isDefault() { + return defaultValue.equals(get()); + } + + public void resetToDefault(ServerCommandSource source) { + set(source, defaultValue, defaultAsString); + } + + + private static String convertToString(Object value) { + if (value instanceof Enum) return ((Enum) value).name().toLowerCase(Locale.ROOT); + return value.toString(); + } + + @Override + public boolean equals(Object obj) { + return obj.getClass() == ParsedRule.class && ((ParsedRule) obj).name.equals(this.name); + } + + @Override + public int hashCode() { + return this.name.hashCode(); + } + + @Override + public int compareTo(ParsedRule o) { + return this.name.compareTo(o.name); + } + + @Override + public String toString() { + return this.name + ": " + getAsString(); + } +} diff --git a/src/main/java/carpet/settings/Rule.java b/src/main/java/carpet/settings/Rule.java new file mode 100644 index 00000000..f49854c9 --- /dev/null +++ b/src/main/java/carpet/settings/Rule.java @@ -0,0 +1,58 @@ +package carpet.settings; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Any field in this class annotated with this class is interpreted as a carpet rule. + * The field must be static and have a type of one of: + * - boolean + * - int + * - double + * - String + * - a subclass of Enum + * The default value of the rule will be the initial value of the field. + */ +@Target(ElementType.FIELD) +@Retention(RetentionPolicy.RUNTIME) +@interface Rule { + /** + * The rule name, by default the same as the field name + */ + String name() default ""; // default same as field name + + /** + * A description of the rule + */ + String desc(); + + /** + * Extra information about the rule + */ + String[] extra() default {}; + + /** + * A list of categories the rule is in + */ + RuleCategory[] category(); + + /** + * Options to select in menu. + * Inferred for booleans and enums. Otherwise, must be present. + */ + String[] options() default {}; + + /** + * if a rule is not strict - can take any value, otherwise it needs to match + * any of the options + * For enums, its always strict + */ + boolean strict() default true; + + /** + * The class of the validator checked when the rule is changed. + */ + Class[] validate() default {}; +} diff --git a/src/main/java/carpet/settings/RuleCategory.java b/src/main/java/carpet/settings/RuleCategory.java new file mode 100644 index 00000000..990701aa --- /dev/null +++ b/src/main/java/carpet/settings/RuleCategory.java @@ -0,0 +1,13 @@ +package carpet.settings; + +import java.util.Locale; + +public enum RuleCategory { + BUGFIX, SURVIVAL, CREATIVE, EXPERIMENTAL, OPTIMIZATIONS, FEATURE, COMMANDS ; + + public final String lowerCase; + + RuleCategory() { + this.lowerCase = this.name().toLowerCase(Locale.ROOT); + } +} diff --git a/src/main/java/carpet/settings/Settings.java b/src/main/java/carpet/settings/Settings.java new file mode 100644 index 00000000..00228776 --- /dev/null +++ b/src/main/java/carpet/settings/Settings.java @@ -0,0 +1,84 @@ +package carpet.settings; + +import static carpet.settings.RuleCategory.BUGFIX; +import static carpet.settings.RuleCategory.COMMANDS; +import static carpet.settings.RuleCategory.CREATIVE; +import static carpet.settings.RuleCategory.EXPERIMENTAL; +import static carpet.settings.RuleCategory.FEATURE; +import static carpet.settings.RuleCategory.OPTIMIZATIONS; +import static carpet.settings.RuleCategory.SURVIVAL; + +public class Settings +{ + @Rule( + desc = "Fixes server crashing supposedly on falling behind 60s in ONE tick, yeah bs.", + extra = "Fixed 1.12 watchdog crash in 1.13 pre-releases, reintroduced with 1.13, GG.", + category = BUGFIX, + validate = Validator.WIP.class + ) + public static boolean watchdogCrashFix = false; + + @Rule( + desc = "Enables /c and /s commands to quickly switch between camera and survival modes", + extra = "/c and /s commands are available to all players regardless of their permission levels", + category = COMMANDS + ) + public static boolean commandCameramode = true; + + @Rule(desc = "fill/clone/setblock and structure blocks cause block updates", category = CREATIVE) + public static boolean fillUpdates = true; + + @Rule( + desc = "Customizable fill/clone volume limit", + options = {"32768", "250000", "1000000"}, + validate = Validator.POSITIVE_NUMBER.class, + category = CREATIVE + ) + public static int fillLimit = 32768; + + @Rule( + desc = "Hoppers pointing to wool will count items passing through them", + extra = { + "Enables /counter command, and actions while placing red and green carpets on wool blocks", + "Use /counter reset to reset the counter, and /counter to query", + "In survival, place green carpet on same color wool to query, red to reset the counters", + "Counters are global and shared between players, 16 channels available", + "Items counted are destroyed, count up to one stack per tick per hopper" + }, + category = COMMANDS + ) + public static boolean hopperCounters = false; + + @Rule(desc = "Explosions won't destroy blocks", category = CREATIVE) + public static boolean explosionNoBlockDamage = false; + + @Rule( + desc = "Silverfish drop a gravel item when breaking out of a block", + category = {FEATURE, EXPERIMENTAL} + ) + public static boolean silverFishDropGravel = false; + + @Rule(desc = "Shulkers will respawn in end cities", category = {FEATURE, EXPERIMENTAL}) + public static boolean shulkerSpawningInEndCities = false; + + @Rule( + desc = "Portals won't let a creative player go through instantly", + extra = "Holding obsidian in either hand won't let you through at all", + category = CREATIVE + ) + public static boolean portalCreativeDelay = false; + + @Rule(desc = "Pistons can push block entities, like hoppers, chests etc.", category = {FEATURE, EXPERIMENTAL}) + public static boolean movableTileEntities = false; + + @Rule( + desc = "Empty shulker boxes can stack to 64 when dropped on the ground", + extra = "To move them around between inventories, use shift click to move entire stacks", + category = SURVIVAL + ) + public static boolean stackableShulkerBoxes = false; + + @Rule(desc = "Optimizes spawning", category = {OPTIMIZATIONS, EXPERIMENTAL}) + public static boolean lagFreeSpawning = false; + +} diff --git a/src/main/java/carpet/settings/SettingsManager.java b/src/main/java/carpet/settings/SettingsManager.java new file mode 100644 index 00000000..34b8941a --- /dev/null +++ b/src/main/java/carpet/settings/SettingsManager.java @@ -0,0 +1,230 @@ +package carpet.settings; + +import carpet.CarpetSettings; +import com.google.common.collect.ImmutableList; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.command.ServerCommandSource; +import net.minecraft.server.network.ServerPlayerEntity; +import org.apache.commons.lang3.tuple.Pair; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.io.*; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +public class SettingsManager { + private static final Logger LOG = LogManager.getLogger(); + private static Map> rules = new HashMap<>(); + public boolean locked; + MinecraftServer server; + + public SettingsManager(MinecraftServer server) + { + this.server = server; + loadConfigurationFromConf(); + } + + + public static void parseSettingsClass(Class settingsClass) + { + for (Field f : settingsClass.getDeclaredFields()) + { + Rule rule = f.getAnnotation(Rule.class); + if (rule == null) continue; + ParsedRule parsed = new ParsedRule(f, rule); + CarpetSettings.LOG.error("REGISTERED RULE: "+parsed.name); + rules.put(parsed.name, parsed); + } + } + + + public ParsedRule getRule(String name) { + return rules.get(name); + } + + public static Collection> getRules() { + CarpetSettings.LOG.error("grabbing rules"); + List> r = rules.values().stream().sorted().collect(Collectors.toList()); + CarpetSettings.LOG.error("Got: "+r.size()+" rules"); + return r; + } + + public Collection> findStartupOverrides() + { + Set defaults = readSettingsFromConf().getLeft().keySet(); + return rules.values().stream().filter(r -> defaults.contains(r.name)). + sorted().collect(Collectors.toList()); + } + + + public Collection> getNonDefault() { + return rules.values().stream().filter(r -> !r.isDefault()).sorted().collect(Collectors.toList()); + } + + private File getFile() { + return server.getLevelStorage().resolveFile(server.getLevelName(), "carpet.conf"); + } + + public void disableBooleanFromCategory(RuleCategory category) { + for (ParsedRule rule : rules.values()) { + if (rule.type != boolean.class || !rule.categories.contains(category)) continue; + ((ParsedRule) rule).set(server.getCommandSource(), false, "false"); + } + } + + + + private void writeSettingsToConf(Map values) + { + if (locked) return; + try + { + FileWriter fw = new FileWriter(getFile()); + for (String key: values.keySet()) + { + fw.write(key+" "+values.get(key)+"\n"); + } + fw.close(); + } + catch (IOException e) + { + e.printStackTrace(); + LOG.error("[CM]: failed write the carpet.conf"); + } + ///todo is it really needed? resendCommandTree(); + } + + public void notifyPlayersCommandsChanged() + { + if (server.getPlayerManager() == null) + { + return; + } + for (ServerPlayerEntity entityplayermp : server.getPlayerManager().getPlayerList()) + { + server.getCommandManager().sendCommandTree(entityplayermp); + } + } + + private void loadConfigurationFromConf() + { + for (ParsedRule rule : rules.values()) rule.resetToDefault(server.getCommandSource()); + Pair,Boolean> conf = readSettingsFromConf(); + locked = false; + if (conf.getRight()) + { + LOG.info("[CM]: Carpet Mod is locked by the administrator"); + disableBooleanFromCategory(RuleCategory.COMMANDS); + } + for (String key: conf.getLeft().keySet()) + { + if (rules.get(key).set(server.getCommandSource(), conf.getLeft().get(key)) != null) + LOG.info("[CM]: loaded setting "+key+" as "+conf.getLeft().get(key)+" from carpet.conf"); + } + locked = conf.getRight(); + } + + + public Pair,Boolean> readSettingsFromConf() + { + try + { + BufferedReader reader = new BufferedReader(new FileReader(getFile())); + String line = ""; + boolean confLocked = false; + Map result = new HashMap(); + while ((line = reader.readLine()) != null) + { + line = line.replaceAll("\\r|\\n", ""); + if ("locked".equalsIgnoreCase(line)) + { + confLocked = true; + } + String[] fields = line.split("\\s+",2); + if (fields.length > 1) + { + if (!rules.containsKey(fields[0])) + { + LOG.error("[CM]: Setting " + fields[0] + " is not a valid - ignoring..."); + continue; + } + ParsedRule rule = rules.get(fields[0]); + + + + if (!(rule.options.contains(fields[1])) && rule.isStrict) + { + LOG.error("[CM]: The value of " + fields[1] + " for " + fields[0] + " is not valid - ignoring..."); + continue; + } + result.put(fields[0],fields[1]); + + } + } + reader.close(); + return Pair.of(result, confLocked); + } + catch(FileNotFoundException e) + { + return Pair.of(new HashMap<>(), false); + } + catch (IOException e) + { + e.printStackTrace(); + return Pair.of(new HashMap<>(), false); + } + } + + // stores different defaults in the file + public boolean setDefaultRule(ServerCommandSource source, String settingName, String stringValue) + { + if (locked) return false; + if (rules.containsKey(settingName)) + { + Pair,Boolean> conf = readSettingsFromConf(); + conf.getLeft().put(settingName, stringValue); + writeSettingsToConf(conf.getLeft()); // this may feels weird, but if conf + // is locked, it will never reach this point. + rules.get(settingName).set(source,stringValue); + return true; + } + return false; + } + // removes overrides of the default values in the file + public boolean removeDefaultRule(ServerCommandSource source, String settingName) + { + if (locked) return false; + if (rules.containsKey(settingName)) + { + Pair,Boolean> conf = readSettingsFromConf(); + conf.getLeft().remove(settingName); + writeSettingsToConf(conf.getLeft()); + rules.get(settingName).resetToDefault(source); + return true; + } + return false; + } + + public Collection> getRulesMatching(Predicate> predicate) { + return rules.values().stream().filter(predicate).collect(ImmutableList.toImmutableList()); + } + + public Collection> getRulesMatching(String search) { + String lcSearch = search.toLowerCase(Locale.ROOT); + return getRulesMatching(rule -> { + if (rule.name.toLowerCase(Locale.ROOT).contains(lcSearch)) return true; + for (RuleCategory c : rule.categories) if (c.lowerCase.equals(search)) return true; + return false; + }); + } +} diff --git a/src/main/java/carpet/settings/Validator.java b/src/main/java/carpet/settings/Validator.java new file mode 100644 index 00000000..9ab287ab --- /dev/null +++ b/src/main/java/carpet/settings/Validator.java @@ -0,0 +1,63 @@ +package carpet.settings; + +import carpet.CarpetServer; +import carpet.utils.Messenger; +import net.minecraft.server.command.ServerCommandSource; + +import java.util.Locale; + +public abstract class Validator { + /** + * Validate the new value of a rule + * @return true if valid, false if new rule invalid. + */ + abstract boolean validate(ServerCommandSource source, ParsedRule currentRule, T newValue, String string); + + + public static class POSITIVE_NUMBER extends Validator { + @Override + public boolean validate(ServerCommandSource source, ParsedRule currentRule, T newValue, String string) { + return newValue.doubleValue() > 0; + } + } + + public static class _COMMAND extends Validator { + @Override + public boolean validate(ServerCommandSource source, ParsedRule currentRule, T newValue, String string) { + if (CarpetServer.settingsManager != null) + CarpetServer.settingsManager.notifyPlayersCommandsChanged(); + return true; + } + } + + public static class WIP extends Validator { + @Override + public boolean validate(ServerCommandSource source, ParsedRule currentRule, T newValue, String string) { + if (source != null) + try + { + Messenger.m(source, "r Work in progress - limited or no functionality available for "+currentRule.name); + } + catch (NullPointerException ignored) { } + return true; + } + } + public static class _STRICT extends Validator { + @Override + public boolean validate(ServerCommandSource source, ParsedRule currentRule, T newValue, String string) { + if (!currentRule.options.contains(string.toLowerCase(Locale.ROOT))) + { + if (source != null) + try + { + Messenger.m(source, "r Valid options: " + currentRule.options.toString()); + } + catch (NullPointerException ignored) + { + } + return false; + } + return true; + } + } +} From f05c661fbfab693fc9060c01a5e8355a5b8d3983 Mon Sep 17 00:00:00 2001 From: gnembon Date: Tue, 11 Jun 2019 12:27:26 -0300 Subject: [PATCH 2/7] categories not an enum, so its easier to extend. Validators can modify value. --- .../java/carpet/commands/ParcetCommand.java | 11 ++------ src/main/java/carpet/settings/ParsedRule.java | 28 +++++++++++-------- src/main/java/carpet/settings/Rule.java | 6 ++-- .../java/carpet/settings/RuleCategory.java | 17 ++++++----- src/main/java/carpet/settings/Settings.java | 15 ++++++++-- .../java/carpet/settings/SettingsManager.java | 20 ++++++------- src/main/java/carpet/settings/Validator.java | 22 ++++++++------- 7 files changed, 65 insertions(+), 54 deletions(-) diff --git a/src/main/java/carpet/commands/ParcetCommand.java b/src/main/java/carpet/commands/ParcetCommand.java index a614c7bb..083c1766 100644 --- a/src/main/java/carpet/commands/ParcetCommand.java +++ b/src/main/java/carpet/commands/ParcetCommand.java @@ -3,7 +3,6 @@ package carpet.commands; import carpet.CarpetServer; import carpet.CarpetSettings; import carpet.settings.ParsedRule; -import carpet.settings.RuleCategory; import carpet.settings.SettingsManager; import carpet.utils.Messenger; import com.mojang.brigadier.CommandDispatcher; @@ -11,16 +10,12 @@ import com.mojang.brigadier.arguments.StringArgumentType; import com.mojang.brigadier.builder.LiteralArgumentBuilder; import com.mojang.brigadier.exceptions.CommandSyntaxException; import net.minecraft.server.command.ServerCommandSource; -import net.minecraft.server.command.CommandManager; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.text.BaseText; -import net.minecraft.text.Text; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.List; -import java.util.stream.Collectors; import static net.minecraft.server.command.CommandManager.argument; import static net.minecraft.server.command.CommandManager.literal; @@ -43,7 +38,7 @@ public class ParcetCommand "Current CarpetMod Startup Settings from carpet.conf", CarpetServer.settingsManager.findStartupOverrides()))). then(argument("tag",StringArgumentType.word()). - suggests( (c, b)->suggestMatching(Arrays.stream(RuleCategory.values()).map(r -> r.lowerCase), b)). + suggests( (c, b)->suggestMatching(SettingsManager.getCategories(), b)). executes( (c) -> listSettings(c.getSource(), String.format("CarpetMod Settings matching \"%s\"", StringArgumentType.getString(c, "tag")), CarpetServer.settingsManager.getRulesMatching(StringArgumentType.getString(c, "tag")))))); @@ -94,7 +89,7 @@ public class ParcetCommand List tags = new ArrayList<>(); tags.add(Messenger.c("w Tags: ")); - for (String t: Arrays.stream(RuleCategory.values()).sorted().map(c -> c.lowerCase).collect(Collectors.toList())) + for (String t: SettingsManager.getCategories()) { tags.add(Messenger.c("c ["+t+"]", "^g list all "+t+" settings","!/carpet list "+t)); tags.add(Messenger.c("w , ")); @@ -191,7 +186,7 @@ public class ParcetCommand PlayerEntity player = source.getPlayer(); List tags = new ArrayList<>(); tags.add("w Browse Categories:\n"); - for (String t : Arrays.stream(RuleCategory.values()).map(r -> r.lowerCase).collect(Collectors.toList())) + for (String t : SettingsManager.getCategories()) { tags.add("c [" + t+"]"); tags.add("^g list all " + t + " settings"); diff --git a/src/main/java/carpet/settings/ParsedRule.java b/src/main/java/carpet/settings/ParsedRule.java index 224b2895..674dd137 100644 --- a/src/main/java/carpet/settings/ParsedRule.java +++ b/src/main/java/carpet/settings/ParsedRule.java @@ -1,5 +1,6 @@ package carpet.settings; +import carpet.CarpetServer; import carpet.utils.Messenger; import com.google.common.collect.ImmutableList; import net.minecraft.server.command.ServerCommandSource; @@ -12,13 +13,11 @@ import java.util.List; import java.util.Locale; public final class ParsedRule implements Comparable { - public final Rule rule; public final Field field; - public final String name; public final String description; public final ImmutableList extraInfo; - public final ImmutableList categories; + public final ImmutableList categories; public final ImmutableList options; public boolean isStrict; public final Class type; @@ -37,7 +36,6 @@ public final class ParsedRule implements Comparable { } ParsedRule(Field field, Rule rule) { - this.rule = rule; this.field = field; this.name = rule.name().isEmpty() ? field.getName() : rule.name(); this.type = (Class) field.getType(); @@ -52,16 +50,20 @@ public final class ParsedRule implements Comparable { } if (categories.contains(RuleCategory.COMMANDS)) this.validators.add(callConstructor(Validator._COMMAND.class)); - this.defaultValue = get(); this.defaultAsString = convertToString(this.defaultValue); - if (this.type == boolean.class) { + if (this.type == boolean.class) + { this.isStrict = true; // it has no sense otherwise this.options = ImmutableList.of("true", "false"); - } else if (this.type.isEnum()) { + } + else if (this.type.isEnum()) + { this.isStrict = true; // it has no sense otherwise this.options = Arrays.stream(this.type.getEnumConstants()).map(e -> ((Enum) e).name().toLowerCase(Locale.ROOT)).collect(ImmutableList.toImmutableList()); - } else { + } + else + { this.options = ImmutableList.copyOf(rule.options()); } if (isStrict) @@ -70,7 +72,8 @@ public final class ParsedRule implements Comparable { public ParsedRule set(ServerCommandSource source, String value) { - //if locked - prevent + if (CarpetServer.settingsManager.locked) + return null; if (type == String.class) { return set(source, (T) value, value); @@ -95,12 +98,12 @@ public final class ParsedRule implements Comparable { } } - public ParsedRule set(ServerCommandSource source, T value, String stringValue) { + ParsedRule set(ServerCommandSource source, T value, String stringValue) { try { for (Validator validator : this.validators) { - boolean allowed = validator.validate(source, this, value, stringValue); - if (!allowed) + value = validator.validate(source, this, value, stringValue); + if (value == null) { Messenger.m(source, "r Wrong value for " + name + ": " + stringValue); return null; @@ -112,6 +115,7 @@ public final class ParsedRule implements Comparable { catch (IllegalAccessException e) { Messenger.m(source, "r Unable to access setting for "+name); + return null; } return this; } diff --git a/src/main/java/carpet/settings/Rule.java b/src/main/java/carpet/settings/Rule.java index f49854c9..62a54bab 100644 --- a/src/main/java/carpet/settings/Rule.java +++ b/src/main/java/carpet/settings/Rule.java @@ -36,7 +36,7 @@ import java.lang.annotation.Target; /** * A list of categories the rule is in */ - RuleCategory[] category(); + String[] category(); /** * Options to select in menu. @@ -47,9 +47,9 @@ import java.lang.annotation.Target; /** * if a rule is not strict - can take any value, otherwise it needs to match * any of the options - * For enums, its always strict + * For enums, its always strict, same for booleans - no need to set that for them. */ - boolean strict() default true; + boolean strict() default false; /** * The class of the validator checked when the rule is changed. diff --git a/src/main/java/carpet/settings/RuleCategory.java b/src/main/java/carpet/settings/RuleCategory.java index 990701aa..fbb952bc 100644 --- a/src/main/java/carpet/settings/RuleCategory.java +++ b/src/main/java/carpet/settings/RuleCategory.java @@ -1,13 +1,12 @@ package carpet.settings; -import java.util.Locale; +public class RuleCategory { + public static final String BUGFIX = "bugfix"; + public static final String SURVIVAL = "survival"; + public static final String CREATIVE = "creative"; + public static final String EXPERIMENTAL = "experimental"; + public static final String OPTIMIZATIONS = "optimizations"; + public static final String FEATURE = "feature"; + public static final String COMMANDS = "commands"; -public enum RuleCategory { - BUGFIX, SURVIVAL, CREATIVE, EXPERIMENTAL, OPTIMIZATIONS, FEATURE, COMMANDS ; - - public final String lowerCase; - - RuleCategory() { - this.lowerCase = this.name().toLowerCase(Locale.ROOT); - } } diff --git a/src/main/java/carpet/settings/Settings.java b/src/main/java/carpet/settings/Settings.java index 00228776..7ebe2fc7 100644 --- a/src/main/java/carpet/settings/Settings.java +++ b/src/main/java/carpet/settings/Settings.java @@ -1,5 +1,7 @@ package carpet.settings; +import net.minecraft.server.command.ServerCommandSource; + import static carpet.settings.RuleCategory.BUGFIX; import static carpet.settings.RuleCategory.COMMANDS; import static carpet.settings.RuleCategory.CREATIVE; @@ -28,11 +30,20 @@ public class Settings @Rule(desc = "fill/clone/setblock and structure blocks cause block updates", category = CREATIVE) public static boolean fillUpdates = true; + + private static class CheckFillLimitLimits extends Validator + { + @Override + Integer validate(ServerCommandSource source, ParsedRule currentRule, Integer newValue, String typedString) + { + return newValue < 20000000 ? newValue : null; + } + } @Rule( desc = "Customizable fill/clone volume limit", options = {"32768", "250000", "1000000"}, - validate = Validator.POSITIVE_NUMBER.class, - category = CREATIVE + validate = {Validator.POSITIVE_NUMBER.class, CheckFillLimitLimits.class}, + category = {CREATIVE, "skyblock"} ) public static int fillLimit = 32768; diff --git a/src/main/java/carpet/settings/SettingsManager.java b/src/main/java/carpet/settings/SettingsManager.java index 34b8941a..52d2ca9d 100644 --- a/src/main/java/carpet/settings/SettingsManager.java +++ b/src/main/java/carpet/settings/SettingsManager.java @@ -11,14 +11,7 @@ import org.apache.logging.log4j.Logger; import java.io.*; import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; +import java.util.*; import java.util.function.Predicate; import java.util.stream.Collectors; @@ -47,6 +40,13 @@ public class SettingsManager { } } + public static Iterable getCategories() + { + Set categories = new HashSet<>(); + getRules().stream().map(r -> r.categories).forEach(categories::addAll); + return categories; + } + public ParsedRule getRule(String name) { return rules.get(name); @@ -75,7 +75,7 @@ public class SettingsManager { return server.getLevelStorage().resolveFile(server.getLevelName(), "carpet.conf"); } - public void disableBooleanFromCategory(RuleCategory category) { + public void disableBooleanFromCategory(String category) { for (ParsedRule rule : rules.values()) { if (rule.type != boolean.class || !rule.categories.contains(category)) continue; ((ParsedRule) rule).set(server.getCommandSource(), false, "false"); @@ -223,7 +223,7 @@ public class SettingsManager { String lcSearch = search.toLowerCase(Locale.ROOT); return getRulesMatching(rule -> { if (rule.name.toLowerCase(Locale.ROOT).contains(lcSearch)) return true; - for (RuleCategory c : rule.categories) if (c.lowerCase.equals(search)) return true; + for (String c : rule.categories) if (c.toLowerCase(Locale.ROOT).equals(search)) return true; return false; }); } diff --git a/src/main/java/carpet/settings/Validator.java b/src/main/java/carpet/settings/Validator.java index 9ab287ab..a950c190 100644 --- a/src/main/java/carpet/settings/Validator.java +++ b/src/main/java/carpet/settings/Validator.java @@ -11,40 +11,42 @@ public abstract class Validator { * Validate the new value of a rule * @return true if valid, false if new rule invalid. */ - abstract boolean validate(ServerCommandSource source, ParsedRule currentRule, T newValue, String string); + abstract T validate(ServerCommandSource source, ParsedRule currentRule, T newValue, String string); public static class POSITIVE_NUMBER extends Validator { @Override - public boolean validate(ServerCommandSource source, ParsedRule currentRule, T newValue, String string) { - return newValue.doubleValue() > 0; + public T validate(ServerCommandSource source, ParsedRule currentRule, T newValue, String string) { + return newValue.doubleValue() > 0 ? newValue : null; } } + + public static class _COMMAND extends Validator { @Override - public boolean validate(ServerCommandSource source, ParsedRule currentRule, T newValue, String string) { + public T validate(ServerCommandSource source, ParsedRule currentRule, T newValue, String string) { if (CarpetServer.settingsManager != null) CarpetServer.settingsManager.notifyPlayersCommandsChanged(); - return true; + return newValue; } } public static class WIP extends Validator { @Override - public boolean validate(ServerCommandSource source, ParsedRule currentRule, T newValue, String string) { + public T validate(ServerCommandSource source, ParsedRule currentRule, T newValue, String string) { if (source != null) try { Messenger.m(source, "r Work in progress - limited or no functionality available for "+currentRule.name); } catch (NullPointerException ignored) { } - return true; + return newValue; } } public static class _STRICT extends Validator { @Override - public boolean validate(ServerCommandSource source, ParsedRule currentRule, T newValue, String string) { + public T validate(ServerCommandSource source, ParsedRule currentRule, T newValue, String string) { if (!currentRule.options.contains(string.toLowerCase(Locale.ROOT))) { if (source != null) @@ -55,9 +57,9 @@ public abstract class Validator { catch (NullPointerException ignored) { } - return false; + return null; } - return true; + return newValue; } } } From 8ddef0ce6ac03cf5e02309e232574b56d820061f Mon Sep 17 00:00:00 2001 From: gnembon Date: Tue, 11 Jun 2019 17:58:45 -0300 Subject: [PATCH 3/7] porting rules wip --- src/main/java/carpet/settings/Settings.java | 218 ++++++++++++++++++++ 1 file changed, 218 insertions(+) diff --git a/src/main/java/carpet/settings/Settings.java b/src/main/java/carpet/settings/Settings.java index 7ebe2fc7..be0aab85 100644 --- a/src/main/java/carpet/settings/Settings.java +++ b/src/main/java/carpet/settings/Settings.java @@ -20,6 +20,224 @@ public class Settings ) public static boolean watchdogCrashFix = false; + @Rule( + desc = "Nether portals correctly place entities going through", + extra = "Entities shouldn't suffocate in obsidian", + category = BUGFIX, + validate = Validator.WIP.class + ) + public static boolean portalSuffocationFix = false; + + @Rule( + desc = "Gbhs sgnf sadsgras fhskdpri!", + category = EXPERIMENTAL, + ) + public static boolean superSecretSetting = false; + + @Rule( + desc = "Portals won't let a creative player go through instantly", + extra = "Holding obsidian in either hand won't let you through at all", + category = CREATIVE + ) + public static boolean portalCreativeDelay = false; + + + @Rule( + desc = "Dropping entire stacks works also from on the crafting UI result slot", + category = {BUGFIX, SURVIVAL} + ) + public static boolean ctrlQCraftingFix = false; + + + @Rule( + desc = "Parrots don't get of your shoulders until you receive damage", + extra = "", + category = {SURVIVAL, FEATURE}, + validate = Validator.WIP.class + ) + public static boolean persistentParrots = false; + + + /*@Rule( + desc = "Mobs growing up won't glitch into walls or go through fences", + category = BUGFIX, + validate = Validator.WIP.class + ) + public static boolean growingUpWallJump = false; + + + @Rule( + desc = "Won't let mobs glitch into blocks when reloaded.", + extra = "Can cause slight differences in mobs behaviour", + category = {BUGFIX, EXPERIMENTAL}, + validate = Validator.WIP.class + ) + public static boolean reloadSuffocationFix = false; + */ + + + + @Rule( desc = "Players absorb XP instantly, without delay", category = CREATIVE ) + public static boolean xpNoCooldown = false; + + + @Rule( desc = "XP orbs combine with other into bigger orbs", category = FEATURE ) + public static boolean combineXPOrbs = false; + + + @Rule( + desc = "Empty shulker boxes can stack to 64 when dropped on the ground", + extra = "To move them around between inventories, use shift click to move entire stacks", + category = {SURVIVAL, FEATURE} + ) + public static boolean stackableShulkerBoxes = false; + + + @Rule( desc = "Explosions won't destroy blocks", category = CREATIVE ) + public static boolean explosionNoBlockDamage = false; + + @Rule( desc = "Removes random TNT momentum when primed", category = CREATIVE ) + public static boolean tntPrimerMomentumRemoved = false; + + @Rule( + desc = "Lag optimizations for redstone dust", + extra = "by Theosib", + category = {EXPERIMENTAL, OPTIMIZATIONS}, + validate = Validator.WIP.class + ) + public static boolean fastRedstoneDust = false; + + @Rule( + desc = "Only husks spawn in desert temples", + category = FEATURE, + validate = Validator.WIP.class + ) + public static boolean huskSpawningInTemples = false; + + @Rule( desc = "Shulkers will respawn in end cities", category = FEATURE ) + public static boolean shulkerSpawningInEndCities = false; + + @Rule( + desc = "Entities pushed or moved into unloaded chunks no longer disappear", + category = {EXPERIMENTAL, BUGFIX}, + validate = Validator.WIP.class + ) + public static boolean unloadedEntityFix = false; + + @Rule( desc = "TNT doesn't update when placed against a power source", category = CREATIVE ) + public static boolean TNTDoNotUpdate = false; + + @Rule( + desc = "Prevents players from rubberbanding when moving too fast", + extra = "Puts more trust in clients positioning", + category = {CREATIVE, SURVIVAL}, + validate = Validator.WIP.class + ) + public static boolean antiCheatSpeed = false; + + @Rule( + desc = "Pistons, droppers and dispensers react if block above them is powered", + category = CREATIVE, + validate = Validator.WIP.class + ) + public static boolean quasiConnectivity = true; + + @Rule( + desc = "Players can flip and rotate blocks when holding cactus", + extra = { + "Doesn't cause block updates when rotated/flipped", + "Applies to pistons, observers, droppers, repeaters, stairs, glazed terracotta etc..." + }, + category = {CREATIVE, SURVIVAL, FEATURE} + ) + public static boolean flippinCactus = false; + + @Rule( + desc = "hoppers pointing to wool will count items passing through them", + extra = { + "Enables /counter command, and actions while placing red and green carpets on wool blocks", + "Use /counter reset to reset the counter, and /counter to query", + "In survival, place green carpet on same color wool to query, red to reset the counters", + "Counters are global and shared between players, 16 channels available", + "Items counted are destroyed, count up to one stack per tick per hopper" + }, + category = {COMMANDS, CREATIVE, FEATURE} + ) + public static boolean hopperCounters = false; + + @Rule( desc = "Guardians turn into Elder Guardian when struck by lightning", category = FEATURE ) + public static boolean renewableSponges = false; + + @Rule( desc = "Pistons can push tile entities, like hoppers, chests etc.", category = {EXPERIMENTAL, FEATURE} ) + public static boolean movableTileEntities = false; + + @Rule( desc = "Saplings turn into dead shrubs in hot climates and no water access", category = FEATURE ) + public static boolean desertShrubs = false; + + @Rule( desc = "Silverfish drop a gravel item when breaking out of a block", category = FEATURE ) + public static boolean silverFishDropGravel = false; + + @Rule( desc = "summoning a lightning bolt has all the side effects of natural lightning", category = CREATIVE ) + public static boolean summonNaturalLightning = false; + + @Rule( + desc = "", + category = CREATIVE, + validate = Validator.WIP.class + ) + public static boolean aaa = false; + + @Rule( + desc = "", + category = CREATIVE, + validate = Validator.WIP.class + ) + public static boolean aaa = false; + + @Rule( + desc = "", + category = CREATIVE, + validate = Validator.WIP.class + ) + public static boolean aaa = false; + + @Rule( + desc = "", + category = CREATIVE, + validate = Validator.WIP.class + ) + public static boolean aaa = false; + + @Rule( + desc = "", + category = CREATIVE, + validate = Validator.WIP.class + ) + public static boolean aaa = false; + + @Rule( + desc = "", + category = CREATIVE, + validate = Validator.WIP.class + ) + public static boolean aaa = false; + + + + + + + + + + + + + + + + + @Rule( desc = "Enables /c and /s commands to quickly switch between camera and survival modes", extra = "/c and /s commands are available to all players regardless of their permission levels", From 79495eccd0d890ae83a5d99ba9774e4ff2d15372 Mon Sep 17 00:00:00 2001 From: gnembon Date: Tue, 11 Jun 2019 20:24:22 -0300 Subject: [PATCH 4/7] new settings moved --- src/main/java/carpet/settings/Settings.java | 327 +++++++++++-------- src/main/java/carpet/settings/Validator.java | 7 + 2 files changed, 199 insertions(+), 135 deletions(-) diff --git a/src/main/java/carpet/settings/Settings.java b/src/main/java/carpet/settings/Settings.java index be0aab85..528b4f68 100644 --- a/src/main/java/carpet/settings/Settings.java +++ b/src/main/java/carpet/settings/Settings.java @@ -1,6 +1,11 @@ package carpet.settings; +import carpet.CarpetServer; +import carpet.fakes.MinecraftServer_motdInterface; +import carpet.utils.Messenger; +import net.minecraft.server.MinecraftServer; import net.minecraft.server.command.ServerCommandSource; +import net.minecraft.server.dedicated.DedicatedServer; import static carpet.settings.RuleCategory.BUGFIX; import static carpet.settings.RuleCategory.COMMANDS; @@ -28,10 +33,7 @@ public class Settings ) public static boolean portalSuffocationFix = false; - @Rule( - desc = "Gbhs sgnf sadsgras fhskdpri!", - category = EXPERIMENTAL, - ) + @Rule(desc = "Gbhs sgnf sadsgras fhskdpri!", category = EXPERIMENTAL) public static boolean superSecretSetting = false; @Rule( @@ -41,23 +43,16 @@ public class Settings ) public static boolean portalCreativeDelay = false; - - @Rule( - desc = "Dropping entire stacks works also from on the crafting UI result slot", - category = {BUGFIX, SURVIVAL} - ) + @Rule(desc = "Dropping entire stacks works also from on the crafting UI result slot", category = {BUGFIX, SURVIVAL}) public static boolean ctrlQCraftingFix = false; - @Rule( desc = "Parrots don't get of your shoulders until you receive damage", - extra = "", category = {SURVIVAL, FEATURE}, validate = Validator.WIP.class ) public static boolean persistentParrots = false; - /*@Rule( desc = "Mobs growing up won't glitch into walls or go through fences", category = BUGFIX, @@ -65,7 +60,6 @@ public class Settings ) public static boolean growingUpWallJump = false; - @Rule( desc = "Won't let mobs glitch into blocks when reloaded.", extra = "Can cause slight differences in mobs behaviour", @@ -75,16 +69,12 @@ public class Settings public static boolean reloadSuffocationFix = false; */ - - @Rule( desc = "Players absorb XP instantly, without delay", category = CREATIVE ) public static boolean xpNoCooldown = false; - @Rule( desc = "XP orbs combine with other into bigger orbs", category = FEATURE ) public static boolean combineXPOrbs = false; - @Rule( desc = "Empty shulker boxes can stack to 64 when dropped on the ground", extra = "To move them around between inventories, use shift click to move entire stacks", @@ -92,7 +82,6 @@ public class Settings ) public static boolean stackableShulkerBoxes = false; - @Rule( desc = "Explosions won't destroy blocks", category = CREATIVE ) public static boolean explosionNoBlockDamage = false; @@ -107,21 +96,13 @@ public class Settings ) public static boolean fastRedstoneDust = false; - @Rule( - desc = "Only husks spawn in desert temples", - category = FEATURE, - validate = Validator.WIP.class - ) + @Rule(desc = "Only husks spawn in desert temples", category = FEATURE, validate = Validator.WIP.class) public static boolean huskSpawningInTemples = false; @Rule( desc = "Shulkers will respawn in end cities", category = FEATURE ) public static boolean shulkerSpawningInEndCities = false; - @Rule( - desc = "Entities pushed or moved into unloaded chunks no longer disappear", - category = {EXPERIMENTAL, BUGFIX}, - validate = Validator.WIP.class - ) + @Rule(desc = "Entities pushed or moved into unloaded chunks no longer disappear", category = {EXPERIMENTAL, BUGFIX}, validate = Validator.WIP.class) public static boolean unloadedEntityFix = false; @Rule( desc = "TNT doesn't update when placed against a power source", category = CREATIVE ) @@ -135,11 +116,7 @@ public class Settings ) public static boolean antiCheatSpeed = false; - @Rule( - desc = "Pistons, droppers and dispensers react if block above them is powered", - category = CREATIVE, - validate = Validator.WIP.class - ) + @Rule(desc = "Pistons, droppers and dispensers react if block above them is powered", category = CREATIVE, validate = Validator.WIP.class) public static boolean quasiConnectivity = true; @Rule( @@ -180,134 +157,214 @@ public class Settings @Rule( desc = "summoning a lightning bolt has all the side effects of natural lightning", category = CREATIVE ) public static boolean summonNaturalLightning = false; + @Rule(desc = "Enables /spawn command for spawn tracking", category = COMMANDS) + public static boolean commandSpawn = true; + + @Rule(desc = "Enables /tick command to control game clocks", category = COMMANDS) + public static boolean commandTick = true; + + @Rule(desc = "Enables /log command to monitor events in the game via chat and overlays", category = COMMANDS) + public static boolean commandLog = true; + @Rule( - desc = "", - category = CREATIVE, - validate = Validator.WIP.class + desc = "Enables /distance command to measure in game distance between points", + extra = "Also enables brown carpet placement action if 'carpets' rule is turned on as well", + category = COMMANDS ) - public static boolean aaa = false; + public static boolean commandDistance = true; @Rule( - desc = "", - category = CREATIVE, - validate = Validator.WIP.class + desc = "Enables /info command for blocks", + extra = { + "Also enables gray carpet placement action", + "if 'carpets' rule is turned on as well" + }, + category = COMMANDS ) - public static boolean aaa = false; + public static boolean commandInfo = true; @Rule( - desc = "", - category = CREATIVE, - validate = Validator.WIP.class - ) - public static boolean aaa = false; - - @Rule( - desc = "", - category = CREATIVE, - validate = Validator.WIP.class - ) - public static boolean aaa = false; - - @Rule( - desc = "", - category = CREATIVE, - validate = Validator.WIP.class - ) - public static boolean aaa = false; - - @Rule( - desc = "", - category = CREATIVE, - validate = Validator.WIP.class - ) - public static boolean aaa = false; - - - - - - - - - - - - - - - - - - @Rule( - desc = "Enables /c and /s commands to quickly switch between camera and survival modes", - extra = "/c and /s commands are available to all players regardless of their permission levels", - category = COMMANDS + desc = "Enables /c and /s commands to quickly switch between camera and survival modes", + extra = "/c and /s commands are available to all players regardless of their permission levels", + category = COMMANDS ) public static boolean commandCameramode = true; + @Rule( + desc = "Enables /perimeterinfo command", + extra = "... that scans the area around the block for potential spawnable spots", + category = COMMANDS + ) + public static boolean commandPerimeterInfo = true; + + @Rule(desc = "Enables /draw commands", extra = "... allows for drawing simple shapes", category = COMMANDS) + public static boolean commandDraw = true; + + @Rule(desc = "Enables /script command", extra = "an in-game scripting API", category = COMMANDS) + public static boolean commandScript = true; + + @Rule(desc = "Enables /player command to control/spawn players", category = COMMANDS, validate = Validator.WIP.class) + public static boolean commandPlayer = true; + + @Rule(desc = "Placing carpets may issue carpet commands for non-op players", category = SURVIVAL) + public static boolean carpets = false; + + @Rule( + desc = "Pistons, Glass and Sponge can be broken faster with their appropriate tools", + category = SURVIVAL, + validate = Validator.WIP.class + ) + public static boolean missingTools = false; + + @Rule(desc = "Alternative, persistent caching strategy for nether portals", category = {SURVIVAL, CREATIVE}) + public static boolean portalCaching = false; + + @Rule(desc = "Permanent fires don't schedule random updates", category = OPTIMIZATIONS, validate = Validator.WIP.class) + public static boolean calmNetherFires = false; + @Rule(desc = "fill/clone/setblock and structure blocks cause block updates", category = CREATIVE) public static boolean fillUpdates = true; - - private static class CheckFillLimitLimits extends Validator - { - @Override - Integer validate(ServerCommandSource source, ParsedRule currentRule, Integer newValue, String typedString) - { - return newValue < 20000000 ? newValue : null; + private class PushLimitLimits extends Validator { + @Override Integer validate(ServerCommandSource source, ParsedRule currentRule, Integer newValue, String string) { + return (newValue>0 && newValue < 1024) ? newValue : null; } } @Rule( - desc = "Customizable fill/clone volume limit", - options = {"32768", "250000", "1000000"}, - validate = {Validator.POSITIVE_NUMBER.class, CheckFillLimitLimits.class}, - category = {CREATIVE, "skyblock"} + desc = "Customizable piston push limit", + options = {"10", "12", "14", "100"}, + category = CREATIVE, + validate = PushLimitLimits.class + ) + public static int pushLimit = 12; + + @Rule( + desc = "Customizable powered rail power range", + options = {"9", "15", "30"}, + category = CREATIVE, + validate = PushLimitLimits.class + ) + public static int railPowerLimit = 9; + + private class FillLimitLimits extends Validator { + @Override Integer validate(ServerCommandSource source, ParsedRule currentRule, Integer newValue, String string) { + return (newValue>0 && newValue < 20000000) ? newValue : null; + } + } + @Rule( + desc = "Customizable fill/clone volume limit", + options = {"32768", "250000", "1000000"}, + category = CREATIVE, + validate = FillLimitLimits.class ) public static int fillLimit = 32768; @Rule( - desc = "Hoppers pointing to wool will count items passing through them", - extra = { - "Enables /counter command, and actions while placing red and green carpets on wool blocks", - "Use /counter reset to reset the counter, and /counter to query", - "In survival, place green carpet on same color wool to query, red to reset the counters", - "Counters are global and shared between players, 16 channels available", - "Items counted are destroyed, count up to one stack per tick per hopper" - }, - category = COMMANDS + desc = "Customizable maximal entity collision limits, 0 for no limits", + options = {"0", "1", "20"}, + category = OPTIMIZATIONS, + validate = Validator.NONNEGATIVE_NUMBER.class ) - public static boolean hopperCounters = false; + public static int maxEntityCollisions = 0; - @Rule(desc = "Explosions won't destroy blocks", category = CREATIVE) - public static boolean explosionNoBlockDamage = false; + @Rule(desc = "One player is required on the server to cause night to pass", category = SURVIVAL) + public static boolean onePlayerSleeping = false; + + private class SetMotd extends Validator { + @Override String validate(ServerCommandSource source, ParsedRule currentRule, String newValue, String string) { + customMOTD = newValue; // accelerate a smidge + ((MinecraftServer_motdInterface) CarpetServer.minecraft_server).checkMOTD(); + return newValue; + } + } + @Rule( + desc = "Sets a different motd message on client trying to connect to the server", + extra = "use '_' to use the startup setting from server.properties", + options = "_", + category = CREATIVE, + validate = {SetMotd.class, Validator.WIP.class} // for some reason doesn't yet work + ) + public static String customMOTD = "_"; + + @Rule(desc = "Cactus in dispensers rotates blocks.", extra = "Rotates block anti-clockwise if possible", category = FEATURE) + public static boolean rotatorBlock = false; + + private class ViewDistanceValidator extends Validator + { + @Override Integer validate(ServerCommandSource source, ParsedRule currentRule, Integer newValue, String string) + { + if (newValue < 0 || newValue > 32) + { + Messenger.m(source, "r view distance has to be between 0 and 32"); + return null; + } + MinecraftServer server = source.getMinecraftServer(); + + if (server.isDedicated()) + { + int vd = (newValue >= 2)?newValue:((DedicatedServer) server).getProperties().viewDistance; + if (vd != CarpetServer.minecraft_server.getPlayerManager().getViewDistance()) + CarpetServer.minecraft_server.getPlayerManager().setViewDistance(vd); + return newValue; + } + else + { + Messenger.m(source, "r view distance can only be changed on a server"); + return 0; + } + } + } + @Rule( + desc = "Changes the view distance of the server.", + extra = "Set to 0 to not override the value in server settings.", + options = {"0", "12", "16", "32"}, + category = CREATIVE, + validate = ViewDistanceValidator.class + ) + public static int viewDistance = 0; + + private class DisableSpawnChunksValidator extends Validator { + @Override Boolean validate(ServerCommandSource source, ParsedRule currentRule, Boolean newValue, String string) { + if (!newValue) + Messenger.m(source, "w Spawn chunks re-enabled. Visit spawn to load them?"); + return newValue; + } + } + @Rule( + desc = "Allows spawn chunks to unload", + category = CREATIVE, + validate = {Validator.WIP.class, DisableSpawnChunksValidator.class} + ) + public static boolean disableSpawnChunks = false; + + private class KelpLimit extends Validator { + @Override Integer validate(ServerCommandSource source, ParsedRule currentRule, Integer newValue, String string) { + return (newValue>=0 && newValue <=25)?newValue:null; + } + } + @Rule( + desc = "limits growth limit of newly naturally generated kelp to this amount of blocks", + options = {"0", "2", "25"}, + category = FEATURE, + validate = KelpLimit.class + ) + public static int kelpGenerationGrowthLimit = 25; + + @Rule(desc = "Coral structures will grow with bonemeal from coral plants", category = FEATURE) + public static boolean renewableCoral = false; + + @Rule(desc = "fixes block placement rotation issue when player rotates quickly while placing blocks", category = BUGFIX) + public static boolean placementRotationFix = false; @Rule( - desc = "Silverfish drop a gravel item when breaking out of a block", - category = {FEATURE, EXPERIMENTAL} + desc = "Fixes leads breaking/becoming invisible in unloaded chunks", + extra = "You may still get visibly broken leash links on the client side, but server side the link is still there.", + category = BUGFIX, + validate = Validator.WIP.class ) - public static boolean silverFishDropGravel = false; + public static boolean leadFix = false; - @Rule(desc = "Shulkers will respawn in end cities", category = {FEATURE, EXPERIMENTAL}) - public static boolean shulkerSpawningInEndCities = false; - - @Rule( - desc = "Portals won't let a creative player go through instantly", - extra = "Holding obsidian in either hand won't let you through at all", - category = CREATIVE - ) - public static boolean portalCreativeDelay = false; - - @Rule(desc = "Pistons can push block entities, like hoppers, chests etc.", category = {FEATURE, EXPERIMENTAL}) - public static boolean movableTileEntities = false; - - @Rule( - desc = "Empty shulker boxes can stack to 64 when dropped on the ground", - extra = "To move them around between inventories, use shift click to move entire stacks", - category = SURVIVAL - ) - public static boolean stackableShulkerBoxes = false; - - @Rule(desc = "Optimizes spawning", category = {OPTIMIZATIONS, EXPERIMENTAL}) + @Rule(desc = "Spawning requires much less CPU and Memory", category = OPTIMIZATIONS) public static boolean lagFreeSpawning = false; } diff --git a/src/main/java/carpet/settings/Validator.java b/src/main/java/carpet/settings/Validator.java index a950c190..dc924a3e 100644 --- a/src/main/java/carpet/settings/Validator.java +++ b/src/main/java/carpet/settings/Validator.java @@ -62,4 +62,11 @@ public abstract class Validator { return newValue; } } + + public static class NONNEGATIVE_NUMBER extends Validator { + @Override + public T validate(ServerCommandSource source, ParsedRule currentRule, T newValue, String string) { + return newValue.doubleValue() >= 0 ? newValue : null; + } + } } From 734dc95dabd2581c24cb54a63610e4ee3e2590c2 Mon Sep 17 00:00:00 2001 From: gnembon Date: Tue, 11 Jun 2019 23:01:09 -0300 Subject: [PATCH 5/7] settings ported to the annotation based system --- src/main/java/carpet/CarpetServer.java | 12 +- src/main/java/carpet/CarpetSettings.java | 731 ------------------ .../carpet/commands/CameraModeCommand.java | 6 +- .../java/carpet/commands/CarpetCommand.java | 136 ++-- .../java/carpet/commands/CounterCommand.java | 4 +- .../java/carpet/commands/DistanceCommand.java | 4 +- .../java/carpet/commands/DrawCommand.java | 14 +- .../java/carpet/commands/InfoCommand.java | 4 +- src/main/java/carpet/commands/LogCommand.java | 4 +- .../java/carpet/commands/ParcetCommand.java | 204 ----- .../carpet/commands/PerimeterInfoCommand.java | 4 +- .../java/carpet/commands/PlayerCommand.java | 4 +- .../java/carpet/commands/ScriptCommand.java | 30 +- .../java/carpet/commands/SpawnCommand.java | 4 +- .../java/carpet/commands/TestCommand.java | 2 +- .../java/carpet/commands/TickCommand.java | 4 +- .../java/carpet/helpers/BlockRotator.java | 9 +- .../helpers/EntityPlayerActionPack.java | 2 +- .../java/carpet/helpers/FeatureGenerator.java | 2 +- .../java/carpet/logging/LoggerRegistry.java | 2 +- ...BlockPlacementDispenserBehaviourMixin.java | 4 +- .../BuriedTreasureGeneratorPieceMixin.java | 2 +- .../carpet/mixins/ChunkGeneratorMixin.java | 2 +- src/main/java/carpet/mixins/ChunkMixin.java | 2 +- .../java/carpet/mixins/CloneCommandMixin.java | 6 +- .../carpet/mixins/CommandManagerMixin.java | 4 +- .../java/carpet/mixins/ContainerMixin.java | 4 +- .../java/carpet/mixins/CoralBlockMixin.java | 4 +- .../java/carpet/mixins/DebugHudMixin.java | 2 - .../java/carpet/mixins/DirectionMixin.java | 4 +- .../carpet/mixins/EndCityFeatureMixin.java | 4 +- .../mixins/ExperienceOrbEntityMixin.java | 6 +- .../java/carpet/mixins/ExplosionMixin.java | 4 +- .../java/carpet/mixins/FillCommandMixin.java | 9 +- .../FloatingIslandsChunkGeneratorMixin.java | 4 +- .../carpet/mixins/FossilFeatureMixin.java | 2 +- .../GravityStructureProcessorMixin.java | 2 +- .../carpet/mixins/GuardianEntityMixin.java | 4 +- .../carpet/mixins/HopperBlockEntityMixin.java | 4 +- .../mixins/IglooGeneratorPieceMixin.java | 2 +- .../carpet/mixins/InfestedBlockMixin.java | 4 +- .../carpet/mixins/IntegratedServerMixin.java | 8 +- .../java/carpet/mixins/ItemEntityMixin.java | 8 +- .../java/carpet/mixins/KelpFeatureMixin.java | 4 +- .../LivingEntity_maxCollisionsMixin.java | 7 +- .../carpet/mixins/MinecraftClientMixin.java | 2 +- .../mixins/MinecraftDedicatedServerMixin.java | 10 +- .../mixins/MinecraftServer_motdMixin.java | 8 +- .../mixins/OceanRuinGeneratorPieceMixin.java | 2 +- ...tonBlockEntityRenderer_movableTEMixin.java | 4 +- .../PistonBlockEntity_movableTEMixin.java | 12 +- .../mixins/PistonBlock_movableTEMixin.java | 10 +- .../mixins/PistonHandler_pushLimitMixin.java | 5 +- .../java/carpet/mixins/PlayerEntityMixin.java | 4 +- .../mixins/PlayerEntity_parrotMixin.java | 6 +- .../PortalBlock_portalCachingMixin.java | 6 +- .../PortalForcer_portalCachingMixin.java | 6 +- .../PoweredRailBlock_powerLimitMixin.java | 4 +- .../java/carpet/mixins/SaplingBlockMixin.java | 4 +- .../mixins/ServerPlayNetworkHandlerMixin.java | 6 +- ...PlayNetworkHandler_scarpetEventsMixin.java | 1 - .../ServerWorld_onePlayerSleepingMixin.java | 7 +- .../carpet/mixins/SetBlockCommandMixin.java | 4 +- .../mixins/ShipwreckGeneratorPieceMixin.java | 2 +- .../java/carpet/mixins/SpawnHelperMixin.java | 8 +- ...tureBlockBlockEntity_fillUpdatesMixin.java | 4 +- .../carpet/mixins/StructureFeatureMixin.java | 2 +- .../carpet/mixins/StructurePieceMixin.java | 2 +- .../mixins/Structure_fillUpdatesMixin.java | 2 +- .../carpet/mixins/SummonCommandMixin.java | 4 +- .../java/carpet/mixins/TntBlockMixin.java | 4 +- .../java/carpet/mixins/TntEntityMixin.java | 5 +- .../mixins/WorldChunk_fillUpdatesMixin.java | 2 +- .../mixins/WorldChunk_movableTEMixin.java | 4 +- .../carpet/mixins/World_fillUpdatesMixin.java | 2 +- .../java/carpet/script/CarpetExpression.java | 5 +- .../carpet/script/CarpetScriptServer.java | 6 +- src/main/java/carpet/script/ScriptHost.java | 2 +- .../{Settings.java => CarpetSettings.java} | 21 +- src/main/java/carpet/settings/ParsedRule.java | 48 +- .../java/carpet/settings/SettingsManager.java | 2 - .../java/carpet/utils/CarpetProfiler.java | 2 +- src/main/java/carpet/utils/SpawnReporter.java | 1 - src/main/java/carpet/utils/WoolTool.java | 20 +- 84 files changed, 299 insertions(+), 1238 deletions(-) delete mode 100644 src/main/java/carpet/CarpetSettings.java delete mode 100644 src/main/java/carpet/commands/ParcetCommand.java rename src/main/java/carpet/settings/{Settings.java => CarpetSettings.java} (95%) diff --git a/src/main/java/carpet/CarpetServer.java b/src/main/java/carpet/CarpetServer.java index 7c9d6cec..4c5e64e1 100644 --- a/src/main/java/carpet/CarpetServer.java +++ b/src/main/java/carpet/CarpetServer.java @@ -10,7 +10,6 @@ import carpet.commands.DistanceCommand; import carpet.commands.DrawCommand; import carpet.commands.InfoCommand; import carpet.commands.LogCommand; -import carpet.commands.ParcetCommand; import carpet.commands.PerimeterInfoCommand; import carpet.commands.PlayerCommand; import carpet.commands.ScriptCommand; @@ -19,7 +18,7 @@ import carpet.commands.TickCommand; import carpet.helpers.TickSpeed; import carpet.logging.LoggerRegistry; import carpet.script.CarpetScriptServer; -import carpet.settings.Settings; +import carpet.settings.CarpetSettings; import carpet.settings.SettingsManager; import carpet.utils.HUDController; import com.mojang.brigadier.CommandDispatcher; @@ -33,7 +32,7 @@ public class CarpetServer // static for now - easier to handle all around the co public static CarpetScriptServer scriptServer; public static SettingsManager settingsManager; static { - SettingsManager.parseSettingsClass(Settings.class); + SettingsManager.parseSettingsClass(CarpetSettings.class); //... } public static void init(MinecraftServer server) //aka constructor of this static singleton class @@ -42,11 +41,7 @@ public class CarpetServer // static for now - easier to handle all around the co } public static void onServerLoaded(MinecraftServer server) { - //new settingsManager = new SettingsManager(server); - - //old - CarpetSettings.apply_settings_from_conf(server); scriptServer = new CarpetScriptServer(); } // Separate from onServerLoaded, because a server can be loaded multiple times in singleplayer @@ -65,7 +60,6 @@ public class CarpetServer // static for now - easier to handle all around the co public static void registerCarpetCommands(CommandDispatcher dispatcher) { - CarpetCommand.register(dispatcher); TickCommand.register(dispatcher); CounterCommand.register(dispatcher); LogCommand.register(dispatcher); @@ -77,7 +71,7 @@ public class CarpetServer // static for now - easier to handle all around the co PerimeterInfoCommand.register(dispatcher); DrawCommand.register(dispatcher); ScriptCommand.register(dispatcher); - ParcetCommand.register(dispatcher); + CarpetCommand.register(dispatcher); //TestCommand.register(dispatcher); } diff --git a/src/main/java/carpet/CarpetSettings.java b/src/main/java/carpet/CarpetSettings.java deleted file mode 100644 index 2a619272..00000000 --- a/src/main/java/carpet/CarpetSettings.java +++ /dev/null @@ -1,731 +0,0 @@ -package carpet; - -import carpet.fakes.MinecraftServer_motdInterface; -import carpet.fakes.PortalForcerInterface; -import carpet.utils.Messenger; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.command.ServerCommandSource; -import net.minecraft.server.dedicated.DedicatedServer; -import net.minecraft.server.network.ServerPlayerEntity; -import org.apache.commons.lang3.tuple.Pair; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.function.BiConsumer; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -//import carpet.helpers.SpawnChunks; - -public class CarpetSettings -{ - public static boolean locked = false; - public static final String carpetVersion = "v19_06_04alpha"; - - public static final Logger LOG = LogManager.getLogger(); - private static final Map settings_store; - public static final CarpetSettingEntry FalseEntry = CarpetSettingEntry.create("void","all","Error").choices("None",""); - - public static final String[] default_tags = {"tnt","fix","survival","creative", "experimental","optimizations","feature","commands"}; //tab completion only - public static boolean skipGenerationChecks = false; - public static boolean impendingFillSkipUpdates = false; - - static { - settings_store = new HashMap<>(); - set_defaults(); - } - - //those don't have to mimic defaults - defaults will be ' - //static store - public static int n_pushLimit = 12; - public static int n_maxEntityCollisions = 0; - public static boolean b_hopperCounters = false; - public static boolean b_shulkerSpawningInEndCities = false; - public static boolean b_fastRedstoneDust = false; - public static int railPowerLimitAdjusted = 8; - public static boolean b_disableSpawnChunks = false; - public static boolean b_movableTileEntities = false; - public static boolean b_huskSpawningInTemples = false; - public static boolean b_stackableShulkerBoxes = false; - public static boolean b_fillUpdates = true; - public static boolean b_lagFreeSpawning = false; - - private static CarpetSettingEntry rule(String s1, String s2, String s3) { return CarpetSettingEntry.create(s1,s2,s3);} - - private static void set_defaults() - { - CarpetSettingEntry[] RuleList = new CarpetSettingEntry[] { - rule("watchdogCrashFix", "fix", "Fixes server crashing supposedly on falling behind 60s in ONE tick, yeah bs."). - extraInfo("Fixed 1.12 watchdog crash in 1.13 pre-releases, reintroduced with 1.13, GG.").wip(), - rule("portalSuffocationFix", "fix", "Nether portals correctly place entities going through") - .extraInfo("Entities shouldn't suffocate in obsidian").wip(), - rule("superSecretSetting", "experimental","Gbhs sgnf sadsgras fhskdpri!"), - rule("portalCreativeDelay", "creative", "Portals won't let a creative player go through instantly") - .extraInfo("Holding obsidian in either hand won't let you through at all"), - rule("ctrlQCraftingFix", "fix survival", "Dropping entire stacks works also from on the crafting UI result slot"), - rule("persistentParrots", "survival feature", "Parrots don't get of your shoulders until you receive damage"), - //!rule("growingUpWallJump", "fix", "Mobs growing up won't glitch into walls or go through fences"), - //!rule("reloadSuffocationFix", "fix experimental", "Won't let mobs glitch into blocks when reloaded.") - // .extraInfo("Can cause slight differences in mobs behaviour"), - rule("xpNoCooldown", "creative", "Players absorb XP instantly, without delay"), - rule("combineXPOrbs", "creative", "XP orbs combine with other into bigger orbs"), - rule("stackableShulkerBoxes", "survival", "Empty shulker boxes can stack to 64 when dropped on the ground") - .extraInfo("To move them around between inventories, use shift click to move entire stacks").boolAccelerate().defaultFalse(), - rule("explosionNoBlockDamage", "tnt", "Explosions won't destroy blocks"), - rule("tntPrimerMomentumRemoved", "tnt", "Removes random TNT momentum when primed"), - rule("fastRedstoneDust", "experimental optimizations", "Lag optimizations for redstone dust") - .extraInfo("by Theosib").boolAccelerate().defaultFalse().wip(), - rule("huskSpawningInTemples", "experimental feature", "Only husks spawn in desert temples").boolAccelerate().wip(), - rule("shulkerSpawningInEndCities", "feature experimental", "Shulkers will respawn in end cities").boolAccelerate(), - rule("unloadedEntityFix", "experimental creative", "Entities pushed or moved into unloaded chunks no longer disappear").wip(), - rule("TNTDoNotUpdate", "tnt", "TNT doesn't update when placed against a power source"), - rule("antiCheatSpeed", "creative surival", "Prevents players from rubberbanding when moving too fast").wip(), - rule("quasiConnectivity", "creative", "Pistons, droppers and dispensers react if block above them is powered") - .defaultTrue().wip(), - rule("flippinCactus", "creative survival", "Players can flip and rotate blocks when holding cactus") - .extraInfo("Doesn't cause block updates when rotated/flipped", - "Applies to pistons, observers, droppers, repeaters, stairs, glazed terracotta etc..."), - rule("hopperCounters", "commands creative survival","hoppers pointing to wool will count items passing through them") - .extraInfo("Enables /counter command, and actions while placing red and green carpets on wool blocks", - "Use /counter reset to reset the counter, and /counter to query", - "In survival, place green carpet on same color wool to query, red to reset the counters", - "Counters are global and shared between players, 16 channels available", - "Items counted are destroyed, count up to one stack per tick per hopper") - .isACommand().boolAccelerate().defaultFalse(), - rule("renewableSponges", "experimental feature", "Guardians turn into Elder Guardian when struck by lightning"), - rule("movableTileEntities", "experimental", "Pistons can push tile entities, like hoppers, chests etc.").boolAccelerate(), - rule("desertShrubs", "feature", "Saplings turn into dead shrubs in hot climates and no water access when it attempts to grow into a tree"), - rule("silverFishDropGravel", "experimental", "Silverfish drop a gravel item when breaking out of a block"), - rule("summonNaturalLightning","creative", "summoning a lightning bolt has all the side effects of natural lightning"), - rule("commandSpawn", "commands", "Enables /spawn command for spawn tracking").isACommand(), - rule("commandTick", "commands", "Enables /tick command to control game speed").isACommand(), - rule("commandLog", "commands", "Enables /log command to monitor events in the game via chat and overlays").isACommand().wip(), - rule("commandDistance", "commands", "Enables /distance command to measure in game distance between points").isACommand() - .extraInfo("Also enables brown carpet placement action if 'carpets' rule is turned on as well"), - rule("commandInfo", "commands", "Enables /info command for blocks and entities").isACommand() - .extraInfo("Also enables gray carpet placement action ") - .extraInfo("and yellow carpet placement action for entities if 'carpets' rule is turned on as well"), - rule("commandCameramode", "commands", "Enables /c and /s commands to quickly switch between camera and survival modes").isACommand() - .extraInfo("/c and /s commands are available to all players regardless of their permission levels"), - rule("commandPerimeterInfo", "commands", "Enables /perimeterinfo command").isACommand() - .extraInfo("... that scans the area around the block for potential spawnable spots"), - rule("commandDraw", "commands", "Enables /draw commands").isACommand() - .extraInfo("... allows for drawing simple shapes"), - rule("commandScript", "commands", "Enables /script command").isACommand() - .extraInfo("a powerful in-game scripting API"), - rule("commandPlayer", "commands", "Enables /player command to control/spawn players").isACommand().wip(), - rule("carpets", "survival", "Placing carpets may issue carpet commands for non-op players"), - rule("missingTools", "survival", "Pistons, Glass and Sponge can be broken faster with their appropriate tools").wip(), - rule("portalCaching", "survival experimental", "Alternative, persistent caching strategy for nether portals").validate( - (s, n) -> s.getMinecraftServer().getWorlds().forEach(w -> ((PortalForcerInterface)w.getPortalForcer()).invalidateCache()) - ), - rule("calmNetherFires", "experimental", "Permanent fires don't schedule random updates").wip(), - rule("fillUpdates", "creative", "fill/clone/setblock and structure blocks cause block updates").defaultTrue().boolAccelerate(), - rule("pushLimit", "creative","Customizable piston push limit") - .choices("12","10 12 14 100").setNotStrict().numAccelerate(), - rule("railPowerLimit", "creative", "Customizable powered rail power range") - .choices("9","9 15 30").setNotStrict().validate( (s, n) -> - railPowerLimitAdjusted = CarpetSettings.getInt("railPowerLimit") - 1), - rule("fillLimit", "creative","Customizable fill/clone volume limit") - .choices("32768","32768 250000 1000000").setNotStrict(), - rule("maxEntityCollisions", "optimizations", "Customizable maximal entity collision limits, 0 for no limits") - .choices("0","0 1 20").setNotStrict().numAccelerate(), - //???rule("pistonGhostBlocksFix", "fix", "Fix for piston ghost blocks") - // .extraInfo("true(serverOnly) option works with all clients, including vanilla", - // "clientAndServer option requires compatible carpet clients and messes up flying machines") - // .choices("false","false true clientAndServer"), - //???rule("waterFlow", "optimizations", "fixes water flowing issues") - // .choices("vanilla","vanilla optimized correct"), - rule("onePlayerSleeping", "survival", "One player is required on the server to cause night to pass"), - rule("customMOTD", "creative","Sets a different motd message on client trying to connect to the server") - .extraInfo("use '_' to use the startup setting from server.properties") - .choices("_","_").setNotStrict().validate((s, n) -> - ((MinecraftServer_motdInterface)CarpetServer.minecraft_server).checkMOTD()), - rule("rotatorBlock", "experimental", "Cactus in dispensers rotates blocks.") - .extraInfo("Cactus in a dispenser gives the dispenser the ability to rotate the blocks " + - "that are in front of it anti-clockwise if possible."), - rule("viewDistance", "creative", "Changes the view distance of the server.") - .extraInfo("Set to 0 to not override the value in server settings.") - .choices("0", "0 12 16 32 64").setNotStrict() - .validate( (s, n) -> { - int viewDistance = getInt("viewDistance"); - if (CarpetServer.minecraft_server.isDedicated()) - { - if (viewDistance < 2) - { - viewDistance = ((DedicatedServer) CarpetServer.minecraft_server).getProperties().viewDistance; - } - if (viewDistance > 64) - { - viewDistance = 64; - } - if (viewDistance != CarpetServer.minecraft_server.getPlayerManager().getViewDistance()) - CarpetServer.minecraft_server.getPlayerManager().setViewDistance(viewDistance); - } - else - { - CarpetSettings.get(n).setForce("0"); - if (s != null) - Messenger.m(s, "w view distance can only be changed on a server"); - } - }), - rule("disableSpawnChunks", "creative", "Removes the spawn chunks.") - .validate((s, n) -> { - if (!CarpetSettings.getBool("disableSpawnChunks")) - if (s != null) - Messenger.m(s, "w Spawn chunks re-enabled. Visit spawn to load it."); - }).boolAccelerate().wip(), - rule("kelpGenerationGrowLimit", "feature", "limits growth limit of newly naturally generated kelp to this amount of blocks") - .choices("25", "0 2 25").setNotStrict(), - rule("renewableCoral", "feature", "Coral structures will grow with bonemeal from coral plants"), - rule("placementRotationFix", "fix", "fixes block placement rotation issue when player rotates quickly while placing blocks"), - rule("leadFix", "fix", "Fixes leads breaking/becoming invisible in unloaded chunks") - .extraInfo("You may still get visibly broken leash links on the client side, but server side the link is still there.").wip(), - rule("lagFreeSpawning", "optimizations", "Spawning requires much less CPU and Memory").boolAccelerate() - }; - for (CarpetSettingEntry rule: RuleList) - { - settings_store.put(rule.getName(), rule); - } - } - - public static void notifyPlayersCommandsChanged() - { - if (CarpetServer.minecraft_server == null || CarpetServer.minecraft_server.getPlayerManager() == null) - { - return; - } - for (ServerPlayerEntity entityplayermp : CarpetServer.minecraft_server.getPlayerManager().getPlayerList()) - { - CarpetServer.minecraft_server.getCommandManager().sendCommandTree(entityplayermp); - } - } - - public static void apply_settings_from_conf(MinecraftServer server) - { - Pair,Boolean> conf = read_conf(server); - locked = false; - if (conf.getRight()) - { - LOG.info("[CM]: Carpet Mod is locked by the administrator"); - disable_commands_by_default(); - } - for (String key: conf.getLeft().keySet()) - { - set(server.getCommandSource(), key, conf.getLeft().get(key)); - LOG.info("[CM]: loaded setting "+key+" as "+conf.getLeft().get(key)+" from carpet.conf"); - } - locked = conf.getRight(); - } - private static void disable_commands_by_default() - { - for (CarpetSettingEntry entry: settings_store.values()) - { - if (entry.getName().startsWith("command")) - { - entry.defaultFalse(); - } - } - } - - private static Pair,Boolean> read_conf(MinecraftServer server) - { - try - { - File settings_file = server.getLevelStorage().resolveFile(server.getLevelName(), "carpet.conf"); - BufferedReader b = new BufferedReader(new FileReader(settings_file)); - String line = ""; - boolean confLocked = false; - Map result = new HashMap(); - while ((line = b.readLine()) != null) - { - line = line.replaceAll("\\r|\\n", ""); - if ("locked".equalsIgnoreCase(line)) - { - confLocked = true; - } - String[] fields = line.split("\\s+",2); - if (fields.length > 1) - { - if (get(fields[0])==FalseEntry) - { - LOG.error("[CM]: Setting " + fields[0] + " is not a valid - ignoring..."); - continue; - } - if (!(Arrays.asList(get(fields[0]).getOptions()).contains(fields[1])) && get(fields[0]).isStrict()) - { - LOG.error("[CM]: The value of " + fields[1] + " for " + fields[0] + " is not valid - ignoring..."); - continue; - } - result.put(fields[0],fields[1]); - } - } - b.close(); - return Pair.of(result, confLocked); - } - catch(FileNotFoundException e) - { - return Pair.of(new HashMap<>(), false); - } - catch (IOException e) - { - e.printStackTrace(); - return Pair.of(new HashMap<>(), false); - } - - } - private static void write_conf(MinecraftServer server, Map values) - { - if (locked) return; - try - { - File settings_file = server.getLevelStorage().resolveFile(server.getLevelName(), "carpet.conf"); - FileWriter fw = new FileWriter(settings_file); - for (String key: values.keySet()) - { - fw.write(key+" "+values.get(key)+"\n"); - } - fw.close(); - } - catch (IOException e) - { - e.printStackTrace(); - LOG.error("[CM]: failed write the carpet.conf"); - } - } - - // stores different defaults in the file - public static boolean setDefaultRule(ServerCommandSource source, String setting_name, String string_value) - { - if (locked) return false; - if (settings_store.containsKey(setting_name)) - { - Pair,Boolean> conf = read_conf(source.getMinecraftServer()); - conf.getLeft().put(setting_name, string_value); - write_conf(source.getMinecraftServer(), conf.getLeft()); // this may feels weird, but if conf - // is locked, it will never reach this point. - set(source, setting_name,string_value); - return true; - } - return false; - } - // removes overrides of the default values in the file - public static boolean removeDefaultRule(ServerCommandSource source, String setting_name) - { - if (locked) return false; - if (settings_store.containsKey(setting_name)) - { - Pair,Boolean> conf = read_conf(source.getMinecraftServer()); - conf.getLeft().remove(setting_name); - write_conf(source.getMinecraftServer(), conf.getLeft()); - set(source, setting_name,get(setting_name).getDefault()); - return true; - } - return false; - } - - //changes setting temporarily - public static boolean set(ServerCommandSource source, String setting_name, String string_value) - { - CarpetSettingEntry en = get(setting_name); - if (en != FalseEntry) - { - en.set(source, string_value); - //reload_stat(setting_name); - //CarpetClientRuleChanger.updateCarpetClientsRule(setting_name, string_value); - return true; - } - return false; - } - - // used as CarpetSettings.get("pushLimit").integer to get the int value of push limit - public static CarpetSettingEntry get(String setting_name) - { - if (!settings_store.containsKey(setting_name) ) - { - return FalseEntry; - } - return settings_store.get(setting_name); - } - - public static int getInt(String setting_name) - { - return get(setting_name).getIntegerValue(); - } - public static boolean getBool(String setting_name) - { - return get(setting_name).getBoolValue(); - } - public static String getString(String setting_name) { return get(setting_name).getStringValue(); } - public static float getFloat(String setting_name) - { - return get(setting_name).getFloatValue(); - } - public static CarpetSettingEntry[] findAll(String tag) - { - ArrayList res = new ArrayList(); - for (String rule: settings_store.keySet().stream().sorted().collect(Collectors.toList())) - { - if (tag == null || settings_store.get(rule).matches(tag)) - { - res.add(settings_store.get(rule)); - } - } - return res.toArray(new CarpetSettingEntry[0]); - } - public static CarpetSettingEntry[] find_nondefault(MinecraftServer server) - { - ArrayList res = new ArrayList(); - Map defaults = read_conf(server).getLeft(); - for (String rule: settings_store.keySet().stream().sorted().collect(Collectors.toList())) - { - if (!settings_store.get(rule).isDefault() || defaults.containsKey(rule)) - { - res.add(settings_store.get(rule)); - } - } - return res.toArray(new CarpetSettingEntry[0]); - } - public static CarpetSettingEntry[] findStartupOverrides(MinecraftServer server) - { - ArrayList res = new ArrayList(); - if (locked) return res.toArray(new CarpetSettingEntry[0]); - Map defaults = read_conf(server).getLeft(); - for (String rule: settings_store.keySet().stream().sorted().collect(Collectors.toList())) - { - if (defaults.containsKey(rule)) - { - res.add(settings_store.get(rule)); - } - } - return res.toArray(new CarpetSettingEntry[0]); - } - public static String[] toStringArray(CarpetSettingEntry[] entry_array) - { - return Stream.of(entry_array).map(CarpetSettingEntry::getName).toArray( String[]::new ); - } - public static ArrayList getAllCarpetSettings() - { - ArrayList res = new ArrayList(); - for (String rule: settings_store.keySet().stream().sorted().collect(Collectors.toList())) - { - res.add(settings_store.get(rule)); - } - - return res; - } - public static CarpetSettingEntry getCarpetSetting(String rule) - { - return settings_store.get(rule); - } - - public static void resetToVanilla(ServerCommandSource source) - { - for (String rule: settings_store.keySet()) - { - get(rule).reset(source); - //reload_stat(rule); - } - } - - public static void resetToUserDefaults(ServerCommandSource source) - { - resetToVanilla(source); - apply_settings_from_conf(source.getMinecraftServer()); - } - - public static void resetToCreative(ServerCommandSource source) - { - resetToBugFixes(source); - set(source, "fillLimit","500000"); - set(source, "fillUpdates","false"); - set(source, "portalCreativeDelay","true"); - set(source, "portalCaching","true"); - set(source, "flippinCactus","true"); - set(source, "hopperCounters","true"); - set(source, "antiCheatSpeed","true"); - - } - public static void resetToSurvival(ServerCommandSource source) - { - resetToBugFixes(source); - set(source, "ctrlQCraftingFix","true"); - set(source, "persistentParrots", "true"); - set(source, "stackableEmptyShulkerBoxes","true"); - set(source, "flippinCactus","true"); - set(source, "hopperCounters","true"); - set(source, "carpets","true"); - set(source, "missingTools","true"); - set(source, "portalCaching","true"); - set(source, "miningGhostBlocksFix","true"); - } - public static void resetToBugFixes(ServerCommandSource source) - { - resetToVanilla(source); - set(source, "portalSuffocationFix","true"); - set(source, "pistonGhostBlocksFix","serverOnly"); - set(source, "portalTeleportationFix","true"); - set(source, "entityDuplicationFix","true"); - set(source, "inconsistentRedstoneTorchesFix","true"); - set(source, "llamaOverfeedingFix","true"); - set(source, "invisibilityFix","true"); - set(source, "potionsDespawnFix","true"); - set(source, "liquidsNotRandom","true"); - set(source, "mobsDontControlMinecarts","true"); - set(source, "breedingMountingDisabled","true"); - set(source, "growingUpWallJump","true"); - set(source, "reloadSuffocationFix","true"); - set(source, "watchdogFix","true"); - set(source, "unloadedEntityFix","true"); - set(source, "hopperDuplicationFix","true"); - set(source, "calmNetherFires","true"); - } - - public static class CarpetSettingEntry - { - private String rule; - private String string; - private int integer; - private boolean bool; - private float flt; - private String[] options; - private String[] tags; - private String toast; - private String[] extra_info; - private String default_string_value; - private boolean isFloat; - private boolean strict; - private List> validators; - - //factory - public static CarpetSettingEntry create(String rule_name, String tags, String toast) - { - return new CarpetSettingEntry(rule_name, tags, toast); - } - private CarpetSettingEntry(String rule_name, String tags_string, String toast_string) - { - set(null, "false"); - rule = rule_name; - default_string_value = string; - tags = tags_string.split("\\s+"); // never empty - toast = toast_string; - options = "true false".split("\\s+"); - isFloat = false; - extra_info = null; - strict = true; - validators = null; - } - public CarpetSettingEntry defaultTrue() - { - set(null, "true"); - default_string_value = string; - options = "true false".split("\\s+"); - return this; - } - public CarpetSettingEntry validate(BiConsumer method) - { - if (validators == null) - { - validators = new ArrayList<>(); - } - validators.add(method); - return this; - } - public CarpetSettingEntry boolAccelerate() - { - BiConsumer validator = (source, name) -> { - try - { - Field f = CarpetSettings.class.getDeclaredField("b_"+name); - f.setBoolean(null, CarpetSettings.getBool(name)); - } - catch (IllegalAccessException e) - { - CarpetSettings.LOG.error("[CM Error] rule "+name+" has wrong access to boolean accelerator"); - } - catch (NoSuchFieldException e) - { - CarpetSettings.LOG.error("[CM Error] rule "+name+" doesn't have a boolean accelerator"); - } - }; - return validate(validator); - } - public CarpetSettingEntry numAccelerate() - { - BiConsumer validator = (source, name) -> { - try - { - Field f = CarpetSettings.class.getDeclaredField("n_"+name); - if (CarpetSettings.get(name).isFloat) - { - f.setDouble(null, (double) CarpetSettings.getFloat(name)); - } - else - { - f.setInt(null, CarpetSettings.getInt(name)); - } - } - catch (IllegalAccessException e) - { - CarpetSettings.LOG.error("[CM Error] rule "+name+" wrong type of numerical accelerator"); - } - catch (NoSuchFieldException e) - { - CarpetSettings.LOG.error("[CM Error] rule "+name+" doesn't have a numerical accelerator"); - } - }; - return validate(validator); - } - - - public CarpetSettingEntry isACommand() - { - return this.defaultTrue().validate( (s, n) -> notifyPlayersCommandsChanged()); - } - - public CarpetSettingEntry defaultFalse() - { - set(null, "false"); - default_string_value = string; - options = "true false".split("\\s+"); - return this; - } - - public CarpetSettingEntry choices(String defaults, String options_string) - { - set(null, defaults); - default_string_value = string; - options = options_string.split("\\s+"); - return this; - } - public CarpetSettingEntry extraInfo(String ... extra_info_string) - { - extra_info = extra_info_string; - return this; - } - - public CarpetSettingEntry setFloat() - { - isFloat = true; - strict = false; - return this; - } - - public CarpetSettingEntry setNotStrict() - { - strict = false; - return this; - } - - private void set(ServerCommandSource source, String unparsed) - { - setForce(unparsed); - if (validators != null) - { - validators.forEach((r) -> r.accept(source, this.getName())); - } - } - private void setForce(String unparsed) - { - string = unparsed; - try - { - integer = Integer.parseInt(unparsed); - } - catch(NumberFormatException e) - { - integer = 0; - } - try - { - flt = Float.parseFloat(unparsed); - } - catch(NumberFormatException e) - { - flt = 0.0F; - } - bool = (integer > 0) || Boolean.parseBoolean(unparsed); - } - - //accessors - public boolean isDefault() { return string.equals(default_string_value); } - public String getDefault() { return default_string_value; } - public String toString() { return rule + ": " + string; } - public String getToast() { return toast; } - public String[] getInfo() { return extra_info == null?new String[0]:extra_info; } - public String[] getOptions() { return options;} - public String[] getTags() { return tags; } - public String getName() { return rule; } - public String getStringValue() { return string; } - public boolean getBoolValue() { return bool; } - public int getIntegerValue() { return integer; } - public float getFloatValue() { return flt; } - public boolean getIsFloat() { return isFloat;} - - //actual stuff - public void reset(ServerCommandSource s) - { - set(s, default_string_value); - } - - public boolean matches(String tag) - { - tag = tag.toLowerCase(); - if (rule.toLowerCase().contains(tag)) - { - return true; - } - for (String t: tags) - { - if (tag.equalsIgnoreCase(t)) - { - return true; - } - } - return false; - } - public String getNextValue() - { - int i; - for(i = 0; i < options.length; i++) - { - if(options[i].equals(string)) - { - break; - } - } - i++; - return options[i % options.length]; - } - - public boolean isStrict() - { - return strict; - } - - public CarpetSettingEntry wip() - { - return validate( (s, n) -> { - if (s != null) - try - { - Messenger.m(s, "r Work in progress - limited or no functionality available for "+n); - } - catch (NullPointerException ignored) { } - }); - } - } -} - diff --git a/src/main/java/carpet/commands/CameraModeCommand.java b/src/main/java/carpet/commands/CameraModeCommand.java index fc9a358b..ab2af25f 100644 --- a/src/main/java/carpet/commands/CameraModeCommand.java +++ b/src/main/java/carpet/commands/CameraModeCommand.java @@ -1,6 +1,6 @@ package carpet.commands; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.builder.LiteralArgumentBuilder; import com.mojang.brigadier.exceptions.CommandSyntaxException; @@ -19,13 +19,13 @@ public class CameraModeCommand public static void register(CommandDispatcher dispatcher) { LiteralArgumentBuilder camera = literal("c"). - requires((player) -> CarpetSettings.getBool("commandCameramode")). + requires((player) -> CarpetSettings.commandCameramode). executes((c) -> cameraMode(c.getSource(), c.getSource().getPlayer())). then(argument("player", EntityArgumentType.player()). executes( (c) -> cameraMode(c.getSource(), EntityArgumentType.getPlayer(c, "player")))); LiteralArgumentBuilder survival = literal("s"). - requires((player) -> CarpetSettings.getBool("commandCameramode")). + requires((player) -> CarpetSettings.commandCameramode). executes((c) -> survivalMode( c.getSource(), c.getSource().getPlayer())). diff --git a/src/main/java/carpet/commands/CarpetCommand.java b/src/main/java/carpet/commands/CarpetCommand.java index a2ccae5f..4e1eb9c7 100644 --- a/src/main/java/carpet/commands/CarpetCommand.java +++ b/src/main/java/carpet/commands/CarpetCommand.java @@ -1,19 +1,20 @@ package carpet.commands; -import carpet.CarpetSettings; -import carpet.CarpetSettings.CarpetSettingEntry; +import carpet.CarpetServer; +import carpet.settings.CarpetSettings; +import carpet.settings.ParsedRule; +import carpet.settings.SettingsManager; import carpet.utils.Messenger; import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.arguments.StringArgumentType; import com.mojang.brigadier.builder.LiteralArgumentBuilder; import com.mojang.brigadier.exceptions.CommandSyntaxException; import net.minecraft.server.command.ServerCommandSource; -import net.minecraft.server.command.CommandManager; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.text.BaseText; import java.util.ArrayList; -import java.util.Arrays; +import java.util.Collection; import java.util.List; import static net.minecraft.server.command.CommandManager.argument; @@ -25,46 +26,49 @@ public class CarpetCommand public static void register(CommandDispatcher dispatcher) { LiteralArgumentBuilder literalargumentbuilder = literal("carpet").requires((player) -> - player.hasPermissionLevel(2) && !CarpetSettings.locked); + player.hasPermissionLevel(2) && !CarpetServer.settingsManager.locked); literalargumentbuilder.executes((context)->listAllSettings(context.getSource())). then(literal("list"). executes( (c) -> listSettings(c.getSource(), "All CarpetMod Settings", - CarpetSettings.findAll(null))). + SettingsManager.getRules())). then(literal("defaults"). executes( (c)-> listSettings(c.getSource(), "Current CarpetMod Startup Settings from carpet.conf", - CarpetSettings.findStartupOverrides(c.getSource().getMinecraftServer())))). + CarpetServer.settingsManager.findStartupOverrides()))). then(argument("tag",StringArgumentType.word()). - suggests( (c, b)->suggestMatching(CarpetSettings.default_tags, b)). + suggests( (c, b)->suggestMatching(SettingsManager.getCategories(), b)). executes( (c) -> listSettings(c.getSource(), String.format("CarpetMod Settings matching \"%s\"", StringArgumentType.getString(c, "tag")), - CarpetSettings.findAll(StringArgumentType.getString(c, "tag")))))); + CarpetServer.settingsManager.getRulesMatching(StringArgumentType.getString(c, "tag")))))); - for (CarpetSettingEntry rule: CarpetSettings.getAllCarpetSettings()) + for (ParsedRule rule: SettingsManager.getRules()) { - literalargumentbuilder.then(literal(rule.getName()).executes( (context) -> + literalargumentbuilder.then(literal(rule.name).executes( (context) -> displayRuleMenu(context.getSource(),rule))); literalargumentbuilder.then(literal("removeDefault"). - then(literal(rule.getName()).executes((context) -> + requires(s -> !CarpetServer.settingsManager.locked). + then(literal(rule.name).executes((context) -> removeDefault(context.getSource(), rule)))); - literalargumentbuilder.then(literal(rule.getName()). + literalargumentbuilder.then(literal(rule.name). + requires(s -> !CarpetServer.settingsManager.locked). then(argument("value", StringArgumentType.word()). - suggests((c, b)-> suggestMatching(rule.getOptions(),b)). + suggests((c, b)-> suggestMatching(rule.options,b)). executes((context) -> - setRule(context.getSource(), rule, StringArgumentType.getString(context, "value"))))); + setRule(context.getSource(), rule, StringArgumentType.getString(context, "value"))))); literalargumentbuilder.then(literal("setDefault"). - then(literal(rule.getName()). - then(argument("value", StringArgumentType.word()). - suggests((c, b)-> suggestMatching(rule.getOptions(),b)). - executes((context) -> - setDefault(context.getSource(), rule, StringArgumentType.getString(context, "value")))))); + requires(s -> !CarpetServer.settingsManager.locked). + then(literal(rule.name). + then(argument("value", StringArgumentType.word()). + suggests((c, b)-> suggestMatching(rule.options,b)). + executes((context) -> + setDefault(context.getSource(), rule, StringArgumentType.getString(context, "value")))))); } dispatcher.register(literalargumentbuilder); } - private static int displayRuleMenu(ServerCommandSource source, CarpetSettingEntry rule) + private static int displayRuleMenu(ServerCommandSource source, ParsedRule rule) { PlayerEntity player; try @@ -73,19 +77,19 @@ public class CarpetCommand } catch (CommandSyntaxException e) { - Messenger.m(source, "w "+rule.getName() +" is set to: ","wb "+rule.getStringValue()); + Messenger.m(source, "w "+rule.name +" is set to: ","wb "+rule.getAsString()); return 1; } Messenger.m(player, ""); - Messenger.m(player, "wb "+rule.getName(),"!/carpet "+rule.getName(),"^g refresh"); - Messenger.m(player, "w "+rule.getToast()); + Messenger.m(player, "wb "+rule.name,"!/carpet "+rule.name,"^g refresh"); + Messenger.m(player, "w "+rule.description); - Arrays.stream(rule.getInfo()).forEach(s -> Messenger.m(player, "g "+s)); + rule.extraInfo.forEach(s -> Messenger.m(player, "g "+s)); List tags = new ArrayList<>(); tags.add(Messenger.c("w Tags: ")); - for (String t: rule.getTags()) + for (String t: rule.categories) { tags.add(Messenger.c("c ["+t+"]", "^g list all "+t+" settings","!/carpet list "+t)); tags.add(Messenger.c("w , ")); @@ -93,15 +97,12 @@ public class CarpetCommand tags.remove(tags.size()-1); Messenger.m(player, tags.toArray(new Object[0])); - Messenger.m(player, "w Current value: ",String.format("%s %s (%s value)",rule.getBoolValue()?"lb":"nb", rule.getStringValue(),rule.isDefault()?"default":"modified")); + Messenger.m(player, "w Current value: ",String.format("%s %s (%s value)",rule.getBoolValue()?"lb":"nb", rule.getAsString(),rule.isDefault()?"default":"modified")); List options = new ArrayList<>(); options.add(Messenger.c("w Options: ", "y [ ")); - for (String o: rule.getOptions()) + for (String o: rule.options) { - options.add(Messenger.c( - String.format("%s%s %s",(o.equals(rule.getDefault()))?"u":"", (o.equals(rule.getStringValue()))?"bl":"y", o ), - "^g switch to "+o, - String.format("?/carpet %s %s",rule.getName(),o))); + options.add(makeSetRuleButton(rule, o, false)); options.add(Messenger.c("w ")); } options.remove(options.size()-1); @@ -111,80 +112,85 @@ public class CarpetCommand return 1; } - private static int setRule(ServerCommandSource source, CarpetSettingEntry rule, String newValue) + private static int setRule(ServerCommandSource source, ParsedRule rule, String newValue) { - CarpetSettings.set(source, rule.getName(), newValue); - Messenger.m(source, "w "+rule.toString()+", ", "c [change permanently?]", - "^w Click to keep the settings in carpet.conf to save across restarts", - "?/carpet setDefault "+rule.getName()+" "+rule.getStringValue()); + if (rule.set(source, newValue) != null) + Messenger.m(source, "w "+rule.toString()+", ", "c [change permanently?]", + "^w Click to keep the settings in carpet.conf to save across restarts", + "?/carpet setDefault "+rule.name+" "+rule.getAsString()); return 1; } - private static int setDefault(ServerCommandSource source, CarpetSettingEntry rule, String defaultValue) + private static int setDefault(ServerCommandSource source, ParsedRule rule, String defaultValue) { - CarpetSettings.setDefaultRule(source, rule.getName(), defaultValue); - Messenger.m(source ,"gi rule "+ rule.getName()+" will now default to "+ defaultValue); + if (CarpetServer.settingsManager.setDefaultRule(source, rule.name, defaultValue)) + Messenger.m(source ,"gi rule "+ rule.name+" will now default to "+ defaultValue); return 1; } - private static int removeDefault(ServerCommandSource source, CarpetSettingEntry rule) + private static int removeDefault(ServerCommandSource source, ParsedRule rule) { - CarpetSettings.removeDefaultRule(source, rule.getName()); - Messenger.m(source ,"gi rule "+ rule.getName()+" defaults to Vanilla"); + if (CarpetServer.settingsManager.removeDefaultRule(source, rule.name)) + Messenger.m(source ,"gi rule "+ rule.name+" defaults to Vanilla"); return 1; } - private static BaseText displayInteractiveSetting(CarpetSettingEntry e) + private static BaseText displayInteractiveSetting(ParsedRule rule) { List args = new ArrayList<>(); - args.add("w - "+e.getName()+" "); - args.add("!/carpet "+e.getName()); - args.add("^y "+e.getToast()); - for (String option: e.getOptions()) + args.add("w - "+rule.name+" "); + args.add("!/carpet "+rule.name); + args.add("^y "+rule.description); + for (String option: rule.options) { - String style = e.isDefault()?"g":(option.equalsIgnoreCase(e.getDefault())?"y":"e"); - if (option.equalsIgnoreCase(e.getDefault())) - style = style+"b"; - else if (option.equalsIgnoreCase(e.getStringValue())) - style = style+"u"; - args.add(style+" ["+option+"]"); - if (!option.equalsIgnoreCase(e.getStringValue())) - { - args.add("!/carpet " + e.getName() + " " + option); - args.add("^w switch to " + option); - } + args.add(makeSetRuleButton(rule, option, true)); args.add("w "); } args.remove(args.size()-1); return Messenger.c(args.toArray(new Object[0])); } - private static int listSettings(ServerCommandSource source, String title, CarpetSettingEntry[] settings_list) + private static BaseText makeSetRuleButton(ParsedRule rule, String option, boolean brackets) { + String style = rule.isDefault()?"g":(option.equalsIgnoreCase(rule.defaultAsString)?"y":"e"); + if (option.equalsIgnoreCase(rule.defaultAsString)) + style = style+"b"; + else if (option.equalsIgnoreCase(rule.getAsString())) + style = style+"u"; + String baseText = style + (brackets ? " [" : " ") + option + (brackets ? "]" : ""); + if (CarpetServer.settingsManager.locked) { + return Messenger.c(baseText, "^g Settings are locked"); + } + if (option.equalsIgnoreCase(rule.getAsString())) + return Messenger.c(baseText); + return Messenger.c(baseText, "^g Switch to " + option, "?/carpet " + rule.name + " " + option); + } + + private static int listSettings(ServerCommandSource source, String title, Collection> settings_list) { try { PlayerEntity player = source.getPlayer(); Messenger.m(player,String.format("wb %s:",title)); - Arrays.stream(settings_list).forEach(e -> Messenger.m(player,displayInteractiveSetting(e))); + settings_list.forEach(e -> Messenger.m(player,displayInteractiveSetting(e))); } catch (CommandSyntaxException e) { Messenger.m(source, "w s:"+title); - Arrays.stream(settings_list).forEach(r -> Messenger.m(source, "w - "+ r.toString())); + settings_list.forEach(r -> Messenger.m(source, "w - "+ r.toString())); } return 1; } private static int listAllSettings(ServerCommandSource source) { - listSettings(source, "Current CarpetMod Settings", CarpetSettings.find_nondefault(source.getMinecraftServer())); + listSettings(source, "Current CarpetMod Settings", CarpetServer.settingsManager.getNonDefault()); - Messenger.m(source, "Carpet Mod version: "+CarpetSettings.carpetVersion); + Messenger.m(source, "Carpet Mod version: "+ CarpetSettings.carpetVersion); try { PlayerEntity player = source.getPlayer(); List tags = new ArrayList<>(); tags.add("w Browse Categories:\n"); - for (String t : CarpetSettings.default_tags) + for (String t : SettingsManager.getCategories()) { tags.add("c [" + t+"]"); tags.add("^g list all " + t + " settings"); diff --git a/src/main/java/carpet/commands/CounterCommand.java b/src/main/java/carpet/commands/CounterCommand.java index d332c6ae..9fd73aaf 100644 --- a/src/main/java/carpet/commands/CounterCommand.java +++ b/src/main/java/carpet/commands/CounterCommand.java @@ -1,6 +1,6 @@ package carpet.commands; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import carpet.helpers.HopperCounter; import carpet.utils.Messenger; import com.mojang.brigadier.CommandDispatcher; @@ -17,7 +17,7 @@ public class CounterCommand { LiteralArgumentBuilder literalargumentbuilder = CommandManager.literal("counter").executes((context) -> listAllCounters(context.getSource(), false)).requires((player) -> - CarpetSettings.getBool("hopperCounters")); + CarpetSettings.hopperCounters); literalargumentbuilder. then((CommandManager.literal("reset").executes( (p_198489_1_)-> diff --git a/src/main/java/carpet/commands/DistanceCommand.java b/src/main/java/carpet/commands/DistanceCommand.java index 947fe38a..a4bd4669 100644 --- a/src/main/java/carpet/commands/DistanceCommand.java +++ b/src/main/java/carpet/commands/DistanceCommand.java @@ -1,6 +1,6 @@ package carpet.commands; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import carpet.utils.DistanceCalculator; import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.builder.LiteralArgumentBuilder; @@ -15,7 +15,7 @@ public class DistanceCommand public static void register(CommandDispatcher dispatcher) { LiteralArgumentBuilder command = literal("distance"). - requires((player) -> CarpetSettings.getBool("commandDistance")). + requires((player) -> CarpetSettings.commandDistance). then(literal("from"). executes( (c) -> DistanceCalculator.setStart(c.getSource(), c.getSource().getPosition())). then(argument("from", Vec3ArgumentType.create()). diff --git a/src/main/java/carpet/commands/DrawCommand.java b/src/main/java/carpet/commands/DrawCommand.java index 3ec9e7fe..dc1b92c2 100644 --- a/src/main/java/carpet/commands/DrawCommand.java +++ b/src/main/java/carpet/commands/DrawCommand.java @@ -1,6 +1,6 @@ package carpet.commands; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import carpet.utils.Messenger; import com.google.common.collect.Lists; import com.mojang.brigadier.CommandDispatcher; @@ -29,7 +29,7 @@ public class DrawCommand public static void register(CommandDispatcher dispatcher) { LiteralArgumentBuilder command = literal("draw"). - requires((player) -> CarpetSettings.getBool("commandDraw")). + requires((player) -> CarpetSettings.commandDraw). then(literal("sphere"). then(argument("center",BlockPosArgumentType.create()). then(argument("radius",IntegerArgumentType.integer(1)). @@ -113,6 +113,7 @@ public class DrawCommand } } + CarpetSettings.impendingFillSkipUpdates = !CarpetSettings.fillUpdates; for (int xmod = -1; xmod < 2; xmod+= 2) { for (int ymod = -1; ymod < 2; ymod += 2) @@ -129,11 +130,7 @@ public class DrawCommand ((Inventory)tileentity).clear(); } - if (block.setBlockState( - world, - mbpos, - 2 | (CarpetSettings.getBool("fillUpdates") ?0:1024) - )) + if (block.setBlockState(world, mbpos,2)) { list.add(mbpos.toImmutable()); ++affected; @@ -142,10 +139,11 @@ public class DrawCommand } } } + CarpetSettings.impendingFillSkipUpdates = false; } } } - if (CarpetSettings.getBool("fillUpdates")) + if (CarpetSettings.fillUpdates) { for (BlockPos blockpos1 : list) diff --git a/src/main/java/carpet/commands/InfoCommand.java b/src/main/java/carpet/commands/InfoCommand.java index 2ad6a673..3c7db9a7 100644 --- a/src/main/java/carpet/commands/InfoCommand.java +++ b/src/main/java/carpet/commands/InfoCommand.java @@ -1,6 +1,6 @@ package carpet.commands; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import carpet.utils.BlockInfo; import carpet.utils.EntityInfo; import carpet.utils.Messenger; @@ -29,7 +29,7 @@ public class InfoCommand public static void register(CommandDispatcher dispatcher) { LiteralArgumentBuilder command = literal("info"). - requires((player) -> CarpetSettings.getBool("commandInfo")). + requires((player) -> CarpetSettings.commandInfo). then(literal("block"). then(argument("block position", BlockPosArgumentType.create()). executes( (c) -> infoBlock( diff --git a/src/main/java/carpet/commands/LogCommand.java b/src/main/java/carpet/commands/LogCommand.java index 4e7cc4e1..1089bf21 100644 --- a/src/main/java/carpet/commands/LogCommand.java +++ b/src/main/java/carpet/commands/LogCommand.java @@ -1,6 +1,6 @@ package carpet.commands; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import carpet.logging.Logger; import carpet.logging.LoggerRegistry; import carpet.utils.Messenger; @@ -26,7 +26,7 @@ public class LogCommand public static void register(CommandDispatcher dispatcher) { LiteralArgumentBuilder literalargumentbuilder = CommandManager.literal("log"). - requires((player) -> CarpetSettings.getBool("commandLog")). + requires((player) -> CarpetSettings.commandLog). executes((context) -> listLogs(context.getSource())). then(CommandManager.literal("clear"). executes( (c) -> unsubFromAll(c.getSource(), c.getSource().getName())). diff --git a/src/main/java/carpet/commands/ParcetCommand.java b/src/main/java/carpet/commands/ParcetCommand.java deleted file mode 100644 index 083c1766..00000000 --- a/src/main/java/carpet/commands/ParcetCommand.java +++ /dev/null @@ -1,204 +0,0 @@ -package carpet.commands; - -import carpet.CarpetServer; -import carpet.CarpetSettings; -import carpet.settings.ParsedRule; -import carpet.settings.SettingsManager; -import carpet.utils.Messenger; -import com.mojang.brigadier.CommandDispatcher; -import com.mojang.brigadier.arguments.StringArgumentType; -import com.mojang.brigadier.builder.LiteralArgumentBuilder; -import com.mojang.brigadier.exceptions.CommandSyntaxException; -import net.minecraft.server.command.ServerCommandSource; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.text.BaseText; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import static net.minecraft.server.command.CommandManager.argument; -import static net.minecraft.server.command.CommandManager.literal; -import static net.minecraft.server.command.CommandSource.suggestMatching; - -public class ParcetCommand -{ - public static void register(CommandDispatcher dispatcher) - { - LiteralArgumentBuilder literalargumentbuilder = literal("parcet").requires((player) -> - player.hasPermissionLevel(2) && !CarpetServer.settingsManager.locked); - - literalargumentbuilder.executes((context)->listAllSettings(context.getSource())). - then(literal("list"). - executes( (c) -> listSettings(c.getSource(), - "All CarpetMod Settings", - SettingsManager.getRules())). - then(literal("defaults"). - executes( (c)-> listSettings(c.getSource(), - "Current CarpetMod Startup Settings from carpet.conf", - CarpetServer.settingsManager.findStartupOverrides()))). - then(argument("tag",StringArgumentType.word()). - suggests( (c, b)->suggestMatching(SettingsManager.getCategories(), b)). - executes( (c) -> listSettings(c.getSource(), - String.format("CarpetMod Settings matching \"%s\"", StringArgumentType.getString(c, "tag")), - CarpetServer.settingsManager.getRulesMatching(StringArgumentType.getString(c, "tag")))))); - - for (ParsedRule rule: SettingsManager.getRules()) - { - literalargumentbuilder.then(literal(rule.name).executes( (context) -> - displayRuleMenu(context.getSource(),rule))); - literalargumentbuilder.then(literal("removeDefault"). - requires(s -> !CarpetServer.settingsManager.locked). - then(literal(rule.name).executes((context) -> - removeDefault(context.getSource(), rule)))); - literalargumentbuilder.then(literal(rule.name). - requires(s -> !CarpetServer.settingsManager.locked). - then(argument("value", StringArgumentType.word()). - suggests((c, b)-> suggestMatching(rule.options,b)). - executes((context) -> - setRule(context.getSource(), rule, StringArgumentType.getString(context, "value"))))); - literalargumentbuilder.then(literal("setDefault"). - requires(s -> !CarpetServer.settingsManager.locked). - then(literal(rule.name). - then(argument("value", StringArgumentType.word()). - suggests((c, b)-> suggestMatching(rule.options,b)). - executes((context) -> - setDefault(context.getSource(), rule, StringArgumentType.getString(context, "value")))))); - } - dispatcher.register(literalargumentbuilder); - } - - private static int displayRuleMenu(ServerCommandSource source, ParsedRule rule) - { - PlayerEntity player; - try - { - player = source.getPlayer(); - } - catch (CommandSyntaxException e) - { - Messenger.m(source, "w "+rule.name +" is set to: ","wb "+rule.getAsString()); - return 1; - } - - Messenger.m(player, ""); - Messenger.m(player, "wb "+rule.name,"!/carpet "+rule.name,"^g refresh"); - Messenger.m(player, "w "+rule.description); - - rule.extraInfo.forEach(s -> Messenger.m(player, "g "+s)); - - List tags = new ArrayList<>(); - tags.add(Messenger.c("w Tags: ")); - for (String t: SettingsManager.getCategories()) - { - tags.add(Messenger.c("c ["+t+"]", "^g list all "+t+" settings","!/carpet list "+t)); - tags.add(Messenger.c("w , ")); - } - tags.remove(tags.size()-1); - Messenger.m(player, tags.toArray(new Object[0])); - - Messenger.m(player, "w Current value: ",String.format("%s %s (%s value)",rule.getBoolValue()?"lb":"nb", rule.getAsString(),rule.isDefault()?"default":"modified")); - List options = new ArrayList<>(); - options.add(Messenger.c("w Options: ", "y [ ")); - for (String o: rule.options) - { - options.add(makeSetRuleButton(rule, o, false)); - options.add(Messenger.c("w ")); - } - options.remove(options.size()-1); - options.add(Messenger.c("y ]")); - Messenger.m(player, options.toArray(new Object[0])); - - return 1; - } - - private static int setRule(ServerCommandSource source, ParsedRule rule, String newValue) - { - if (rule.set(source, newValue) != null) - Messenger.m(source, "w "+rule.toString()+", ", "c [change permanently?]", - "^w Click to keep the settings in carpet.conf to save across restarts", - "?/carpet setDefault "+rule.name+" "+rule.getAsString()); - return 1; - } - private static int setDefault(ServerCommandSource source, ParsedRule rule, String defaultValue) - { - CarpetServer.settingsManager.setDefaultRule(source, rule.name, defaultValue); - Messenger.m(source ,"gi rule "+ rule.name+" will now default to "+ defaultValue); - return 1; - } - private static int removeDefault(ServerCommandSource source, ParsedRule rule) - { - CarpetServer.settingsManager.removeDefaultRule(source, rule.name); - Messenger.m(source ,"gi rule "+ rule.name+" defaults to Vanilla"); - return 1; - } - - - private static BaseText displayInteractiveSetting(ParsedRule rule) - { - List args = new ArrayList<>(); - args.add("w - "+rule.name+" "); - args.add("!/carpet "+rule.name); - args.add("^y "+rule.description); - for (String option: rule.options) - { - args.add(makeSetRuleButton(rule, option, true)); - args.add("w "); - } - args.remove(args.size()-1); - return Messenger.c(args.toArray(new Object[0])); - } - - private static BaseText makeSetRuleButton(ParsedRule rule, String option, boolean brackets) { - String color = ""; - if (option.equals(rule.defaultAsString) && !brackets) color += "u"; - color += option.equals(rule.getAsString()) ? "bl" : "y"; - String baseText = color + (brackets ? " [" : " ") + option + (brackets ? "]" : ""); - if (CarpetServer.settingsManager.locked) { - return Messenger.c(baseText, "^g Settings are locked"); - } - return Messenger.c(baseText, "^g Switch to " + option, "?/carpet " + rule.name + " " + option); - } - - private static int listSettings(ServerCommandSource source, String title, Collection> settings_list) - { - try - { - PlayerEntity player = source.getPlayer(); - Messenger.m(player,String.format("wb %s:",title)); - settings_list.forEach(e -> Messenger.m(player,displayInteractiveSetting(e))); - - } - catch (CommandSyntaxException e) - { - Messenger.m(source, "w s:"+title); - settings_list.forEach(r -> Messenger.m(source, "w - "+ r.toString())); - } - return 1; - } - private static int listAllSettings(ServerCommandSource source) - { - listSettings(source, "Current CarpetMod Settings", CarpetServer.settingsManager.getNonDefault()); - - Messenger.m(source, "Carpet Mod version: "+ CarpetSettings.carpetVersion); - try - { - PlayerEntity player = source.getPlayer(); - List tags = new ArrayList<>(); - tags.add("w Browse Categories:\n"); - for (String t : SettingsManager.getCategories()) - { - tags.add("c [" + t+"]"); - tags.add("^g list all " + t + " settings"); - tags.add("!/carpet list " + t); - tags.add("w "); - } - tags.remove(tags.size() - 1); - Messenger.m(player, tags.toArray(new Object[0])); - } - catch (CommandSyntaxException e) - { - } - return 1; - } -} diff --git a/src/main/java/carpet/commands/PerimeterInfoCommand.java b/src/main/java/carpet/commands/PerimeterInfoCommand.java index e8b6fbce..acb336eb 100644 --- a/src/main/java/carpet/commands/PerimeterInfoCommand.java +++ b/src/main/java/carpet/commands/PerimeterInfoCommand.java @@ -1,6 +1,6 @@ package carpet.commands; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import carpet.utils.Messenger; import carpet.utils.PerimeterDiagnostics; import com.mojang.brigadier.CommandDispatcher; @@ -22,7 +22,7 @@ public class PerimeterInfoCommand public static void register(CommandDispatcher dispatcher) { LiteralArgumentBuilder command = literal("perimeterinfo"). - requires((player) -> CarpetSettings.getBool("commandPerimeterInfo")). + requires((player) -> CarpetSettings.commandPerimeterInfo). executes( (c) -> perimeterDiagnose( c.getSource(), new BlockPos(c.getSource().getPosition()), diff --git a/src/main/java/carpet/commands/PlayerCommand.java b/src/main/java/carpet/commands/PlayerCommand.java index 4901d1b1..7cd88ffc 100644 --- a/src/main/java/carpet/commands/PlayerCommand.java +++ b/src/main/java/carpet/commands/PlayerCommand.java @@ -1,6 +1,6 @@ package carpet.commands; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import carpet.fakes.ServerPlayerEntityInterface; import carpet.patches.EntityPlayerMPFake; import carpet.utils.Messenger; @@ -38,7 +38,7 @@ public class PlayerCommand public static void register(CommandDispatcher dispatcher) { LiteralArgumentBuilder literalargumentbuilder = literal("player"). - requires((player) -> CarpetSettings.getBool("commandPlayer")). + requires((player) -> CarpetSettings.commandPlayer). then(argument("player", word()). suggests( (c, b) -> suggestMatching(getPlayers(c.getSource()), b)). then(literal("stop"). diff --git a/src/main/java/carpet/commands/ScriptCommand.java b/src/main/java/carpet/commands/ScriptCommand.java index 394e8149..b2f0bfed 100644 --- a/src/main/java/carpet/commands/ScriptCommand.java +++ b/src/main/java/carpet/commands/ScriptCommand.java @@ -1,7 +1,7 @@ package carpet.commands; import carpet.CarpetServer; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import carpet.script.CarpetEventServer; import carpet.script.CarpetExpression; import carpet.script.Expression; @@ -26,8 +26,6 @@ import net.minecraft.util.Clearable; import net.minecraft.util.math.BlockPos; import net.minecraft.server.world.ServerWorld; import net.minecraft.util.math.MutableIntBoundingBox; -import net.minecraft.util.math.Vec3d; -import net.minecraft.util.math.Vec3i; import java.util.ArrayList; import java.util.Collection; @@ -228,10 +226,10 @@ public class ScriptCommand dispatcher.register(literal("script"). - requires((player) -> CarpetSettings.getBool("commandScript")). + requires((player) -> CarpetSettings.commandScript). then(b).then(u).then(o).then(l).then(s).then(c).then(h).then(i).then(e).then(t).then(a).then(f).then(q)); dispatcher.register(literal("script"). - requires((player) -> CarpetSettings.getBool("commandScript")). + requires((player) -> CarpetSettings.commandScript). then(literal("in"). then(argument("package", StringArgumentType.word()). suggests( (cc, bb) -> suggestMatching(CarpetServer.scriptServer.modules.keySet(), bb)). @@ -379,12 +377,13 @@ public class ScriptCommand MutableIntBoundingBox area = new MutableIntBoundingBox(a, b); CarpetExpression cexpr = new CarpetExpression(expr, source, origin); int int_1 = area.getBlockCountX() * area.getBlockCountY() * area.getBlockCountZ(); - if (int_1 > CarpetSettings.getInt("fillLimit")) + if (int_1 > CarpetSettings.fillLimit) { Messenger.m(source, "r too many blocks to evaluate: " + int_1); return 1; } int successCount = 0; + CarpetSettings.impendingFillSkipUpdates = !CarpetSettings.fillUpdates; try { for (int x = area.minX; x <= area.maxX; x++) @@ -409,6 +408,10 @@ public class ScriptCommand Messenger.m(source, "r Error while processing command: "+exc); return 0; } + finally + { + CarpetSettings.impendingFillSkipUpdates = false; + } Messenger.m(source, "w Expression successful in " + successCount + " out of " + int_1 + " blocks"); return successCount; @@ -423,7 +426,7 @@ public class ScriptCommand MutableIntBoundingBox area = new MutableIntBoundingBox(a, b); CarpetExpression cexpr = new CarpetExpression(expr, source, origin); int int_1 = area.getBlockCountX() * area.getBlockCountY() * area.getBlockCountZ(); - if (int_1 > CarpetSettings.getInt("fillLimit")) + if (int_1 > CarpetSettings.fillLimit) { Messenger.m(source, "r too many blocks to evaluate: "+ int_1); return 1; @@ -434,7 +437,6 @@ public class ScriptCommand BlockPos.Mutable mbpos = new BlockPos.Mutable(origin); ServerWorld world = source.getWorld(); - for (int x = area.minX; x <= area.maxX; x++) { for (int y = area.minY; y <= area.maxY; y++) @@ -490,6 +492,8 @@ public class ScriptCommand volume = newVolume; } int affected = 0; + + CarpetSettings.impendingFillSkipUpdates = !CarpetSettings.fillUpdates; for (int x = 0; x <= maxx; x++) { for (int y = 0; y <= maxy; y++) @@ -505,11 +509,7 @@ public class ScriptCommand BlockEntity tileentity = world.getBlockEntity(mbpos); Clearable.clear(tileentity); - if (block.setBlockState( - world, - mbpos, - 2 | (CarpetSettings.getBool("fillUpdates") ?0:1024) - )) + if (block.setBlockState(world, mbpos,2)) { ++affected; } @@ -518,7 +518,9 @@ public class ScriptCommand } } } - if (CarpetSettings.getBool("fillUpdates") && block != null) + CarpetSettings.impendingFillSkipUpdates = false; + + if (CarpetSettings.fillUpdates && block != null) { for (int x = 0; x <= maxx; x++) { diff --git a/src/main/java/carpet/commands/SpawnCommand.java b/src/main/java/carpet/commands/SpawnCommand.java index aa1d2a15..c1763fbd 100644 --- a/src/main/java/carpet/commands/SpawnCommand.java +++ b/src/main/java/carpet/commands/SpawnCommand.java @@ -1,6 +1,6 @@ package carpet.commands; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import carpet.helpers.HopperCounter; import carpet.helpers.TickSpeed; import carpet.utils.Messenger; @@ -37,7 +37,7 @@ public class SpawnCommand public static void register(CommandDispatcher dispatcher) { LiteralArgumentBuilder literalargumentbuilder = literal("spawn"). - requires((player) -> CarpetSettings.getBool("commandSpawn")); + requires((player) -> CarpetSettings.commandSpawn); literalargumentbuilder. then(literal("list"). diff --git a/src/main/java/carpet/commands/TestCommand.java b/src/main/java/carpet/commands/TestCommand.java index 39a94086..2cbcb7a5 100644 --- a/src/main/java/carpet/commands/TestCommand.java +++ b/src/main/java/carpet/commands/TestCommand.java @@ -23,7 +23,7 @@ public class TestCommand private static int test(CommandContext c, String term) { - Messenger.m(c.getSource(),"w term is: ",term.substring(0,1)+"b "+term); + Messenger.m(c.getSource(),term.substring(0,1)+" "+term+": how did you get here?"); return 1; } } diff --git a/src/main/java/carpet/commands/TickCommand.java b/src/main/java/carpet/commands/TickCommand.java index 892d88c5..83854462 100644 --- a/src/main/java/carpet/commands/TickCommand.java +++ b/src/main/java/carpet/commands/TickCommand.java @@ -1,6 +1,6 @@ package carpet.commands; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import carpet.helpers.TickSpeed; import carpet.utils.CarpetProfiler; import carpet.utils.Messenger; @@ -26,7 +26,7 @@ public class TickCommand public static void register(CommandDispatcher dispatcher) { LiteralArgumentBuilder literalargumentbuilder = literal("tick"). - requires((player) -> CarpetSettings.getBool("commandTick")). + requires((player) -> CarpetSettings.commandTick). then(literal("rate"). executes((c) -> queryTps(c.getSource())). then(argument("rate", floatArg(0.1F, 500.0F)). diff --git a/src/main/java/carpet/helpers/BlockRotator.java b/src/main/java/carpet/helpers/BlockRotator.java index 68b71b5e..5b169389 100644 --- a/src/main/java/carpet/helpers/BlockRotator.java +++ b/src/main/java/carpet/helpers/BlockRotator.java @@ -1,6 +1,6 @@ package carpet.helpers; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import net.minecraft.block.AbstractRedstoneGateBlock; import net.minecraft.block.Block; import net.minecraft.block.BlockState; @@ -44,7 +44,7 @@ public class BlockRotator { public static boolean flipBlockWithCactus(BlockState state, World world, PlayerEntity player, Hand hand, BlockHitResult hit) { - if (!player.abilities.allowModifyWorld || !CarpetSettings.getBool("flippinCactus") || !player_holds_cactus_mainhand(player)) + if (!player.abilities.allowModifyWorld || !CarpetSettings.flippinCactus || !player_holds_cactus_mainhand(player)) { return false; } @@ -283,8 +283,7 @@ public class BlockRotator } public static boolean flippinEligibility(Entity entity) { - if (CarpetSettings.getBool("flippinCactus") - && (entity instanceof PlayerEntity)) + if (CarpetSettings.flippinCactus && (entity instanceof PlayerEntity)) { PlayerEntity player = (PlayerEntity)entity; return (!player.getOffHandStack().isEmpty() @@ -299,7 +298,7 @@ public class BlockRotator @Override protected ItemStack dispenseSilently(BlockPointer source, ItemStack stack) { - if (CarpetSettings.getBool("rotatorBlock")) + if (CarpetSettings.rotatorBlock) { return BlockRotator.dispenserRotate(source, stack); } diff --git a/src/main/java/carpet/helpers/EntityPlayerActionPack.java b/src/main/java/carpet/helpers/EntityPlayerActionPack.java index d52114f7..f0e0eb55 100644 --- a/src/main/java/carpet/helpers/EntityPlayerActionPack.java +++ b/src/main/java/carpet/helpers/EntityPlayerActionPack.java @@ -1,6 +1,6 @@ package carpet.helpers; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import carpet.mixins.PlayerActionC2SPacketMixin; import net.minecraft.entity.Entity; import net.minecraft.server.network.ServerPlayerEntity; diff --git a/src/main/java/carpet/helpers/FeatureGenerator.java b/src/main/java/carpet/helpers/FeatureGenerator.java index 8f542373..2764ee3c 100644 --- a/src/main/java/carpet/helpers/FeatureGenerator.java +++ b/src/main/java/carpet/helpers/FeatureGenerator.java @@ -1,6 +1,6 @@ package carpet.helpers; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import carpet.fakes.StructureFeatureInterface; import net.minecraft.block.Blocks; import net.minecraft.util.math.BlockPos; diff --git a/src/main/java/carpet/logging/LoggerRegistry.java b/src/main/java/carpet/logging/LoggerRegistry.java index 8628e4a5..bf4b332b 100644 --- a/src/main/java/carpet/logging/LoggerRegistry.java +++ b/src/main/java/carpet/logging/LoggerRegistry.java @@ -1,6 +1,6 @@ package carpet.logging; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.util.DyeColor; diff --git a/src/main/java/carpet/mixins/BlockPlacementDispenserBehaviourMixin.java b/src/main/java/carpet/mixins/BlockPlacementDispenserBehaviourMixin.java index 37af7460..8fda5326 100644 --- a/src/main/java/carpet/mixins/BlockPlacementDispenserBehaviourMixin.java +++ b/src/main/java/carpet/mixins/BlockPlacementDispenserBehaviourMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import net.minecraft.block.dispenser.BlockPlacementDispenserBehavior; import net.minecraft.item.ItemStack; import org.spongepowered.asm.mixin.Mixin; @@ -13,7 +13,7 @@ public class BlockPlacementDispenserBehaviourMixin @Redirect(method = "dispenseSilently", at = @At(value="INVOKE", target="Lnet/minecraft/item/ItemStack;decrement(I)V")) private void cancleDoubleDecrement(ItemStack stack, int amount) { - if (!CarpetSettings.b_stackableShulkerBoxes) + if (!CarpetSettings.stackableShulkerBoxes) { stack.decrement(amount); } diff --git a/src/main/java/carpet/mixins/BuriedTreasureGeneratorPieceMixin.java b/src/main/java/carpet/mixins/BuriedTreasureGeneratorPieceMixin.java index 2f9f59a3..560ebb6f 100644 --- a/src/main/java/carpet/mixins/BuriedTreasureGeneratorPieceMixin.java +++ b/src/main/java/carpet/mixins/BuriedTreasureGeneratorPieceMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import net.minecraft.structure.BuriedTreasureGenerator; import net.minecraft.world.Heightmap; import net.minecraft.world.IWorld; diff --git a/src/main/java/carpet/mixins/ChunkGeneratorMixin.java b/src/main/java/carpet/mixins/ChunkGeneratorMixin.java index a30e002c..c256e209 100644 --- a/src/main/java/carpet/mixins/ChunkGeneratorMixin.java +++ b/src/main/java/carpet/mixins/ChunkGeneratorMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import net.minecraft.world.biome.Biome; import net.minecraft.world.gen.chunk.ChunkGenerator; import net.minecraft.world.gen.feature.FeatureConfig; diff --git a/src/main/java/carpet/mixins/ChunkMixin.java b/src/main/java/carpet/mixins/ChunkMixin.java index 75994ed6..d76f9f9e 100644 --- a/src/main/java/carpet/mixins/ChunkMixin.java +++ b/src/main/java/carpet/mixins/ChunkMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import net.minecraft.util.math.BlockPos; import net.minecraft.world.chunk.Chunk; import org.spongepowered.asm.mixin.Mixin; diff --git a/src/main/java/carpet/mixins/CloneCommandMixin.java b/src/main/java/carpet/mixins/CloneCommandMixin.java index 3ccad37e..d9426d80 100644 --- a/src/main/java/carpet/mixins/CloneCommandMixin.java +++ b/src/main/java/carpet/mixins/CloneCommandMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import net.minecraft.block.Block; import net.minecraft.server.command.CloneCommand; import net.minecraft.server.world.ServerWorld; @@ -17,7 +17,7 @@ public abstract class CloneCommandMixin { @ModifyConstant(method = "execute", constant = @Constant(intValue = 32768)) private static int fillLimit(int original) { - return CarpetSettings.getInt("fillLimit"); + return CarpetSettings.fillLimit; } @Redirect(method = "execute", at = @At( @@ -26,6 +26,6 @@ public abstract class CloneCommandMixin )) private static void conditionalUpdating(ServerWorld serverWorld, BlockPos blockPos_1, Block block_1) { - if (CarpetSettings.b_fillUpdates) serverWorld.updateNeighbors(blockPos_1, block_1); + if (CarpetSettings.fillUpdates) serverWorld.updateNeighbors(blockPos_1, block_1); } } diff --git a/src/main/java/carpet/mixins/CommandManagerMixin.java b/src/main/java/carpet/mixins/CommandManagerMixin.java index 05b6cbbc..94b05a56 100644 --- a/src/main/java/carpet/mixins/CommandManagerMixin.java +++ b/src/main/java/carpet/mixins/CommandManagerMixin.java @@ -1,7 +1,7 @@ package carpet.mixins; import carpet.CarpetServer; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import com.mojang.brigadier.CommandDispatcher; import net.minecraft.server.command.CommandManager; import net.minecraft.server.command.ServerCommandSource; @@ -30,7 +30,7 @@ public abstract class CommandManagerMixin @Inject(method = "execute", at = @At("HEAD")) private void onExecuteBegin(ServerCommandSource serverCommandSource_1, String string_1, CallbackInfoReturnable cir) { - if (!CarpetSettings.b_fillUpdates) + if (!CarpetSettings.fillUpdates) CarpetSettings.impendingFillSkipUpdates = true; } diff --git a/src/main/java/carpet/mixins/ContainerMixin.java b/src/main/java/carpet/mixins/ContainerMixin.java index 5a93c892..ea1b83fb 100644 --- a/src/main/java/carpet/mixins/ContainerMixin.java +++ b/src/main/java/carpet/mixins/ContainerMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import net.minecraft.container.Container; import net.minecraft.container.Slot; import net.minecraft.container.SlotActionType; @@ -29,7 +29,7 @@ public class ContainerMixin CallbackInfoReturnable cir ) { - if (slotActionType_1 == SlotActionType.THROW && CarpetSettings.getBool("ctrlQCraftingFix") && playerEntity_1.inventory.getCursorStack().isEmpty() && int_1 >= 0) + if (slotActionType_1 == SlotActionType.THROW && CarpetSettings.ctrlQCraftingFix && playerEntity_1.inventory.getCursorStack().isEmpty() && int_1 >= 0) { ItemStack itemStack_1 = ItemStack.EMPTY; Slot slot_4 = slotList.get(int_1); diff --git a/src/main/java/carpet/mixins/CoralBlockMixin.java b/src/main/java/carpet/mixins/CoralBlockMixin.java index af68f352..8e5f0760 100644 --- a/src/main/java/carpet/mixins/CoralBlockMixin.java +++ b/src/main/java/carpet/mixins/CoralBlockMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import carpet.fakes.CoralFeatureInterface; import net.minecraft.block.Block; import net.minecraft.block.BlockState; @@ -30,7 +30,7 @@ public abstract class CoralBlockMixin implements Fertilizable { public boolean isFertilizable(BlockView var1, BlockPos var2, BlockState var3, boolean var4) { - return CarpetSettings.getBool("renewableCoral") && var3.get(CoralParentBlock.WATERLOGGED) && var1.getFluidState(var2.up()).matches(FluidTags.WATER); + return CarpetSettings.renewableCoral && var3.get(CoralParentBlock.WATERLOGGED) && var1.getFluidState(var2.up()).matches(FluidTags.WATER); } public boolean canGrow(World var1, Random var2, BlockPos var3, BlockState var4) diff --git a/src/main/java/carpet/mixins/DebugHudMixin.java b/src/main/java/carpet/mixins/DebugHudMixin.java index 2380640f..a933319e 100644 --- a/src/main/java/carpet/mixins/DebugHudMixin.java +++ b/src/main/java/carpet/mixins/DebugHudMixin.java @@ -1,7 +1,5 @@ package carpet.mixins; -import carpet.CarpetSettings; -import com.mojang.bridge.game.GameVersion; import net.minecraft.client.MinecraftClient; import net.minecraft.client.gui.hud.DebugHud; import org.spongepowered.asm.mixin.Mixin; diff --git a/src/main/java/carpet/mixins/DirectionMixin.java b/src/main/java/carpet/mixins/DirectionMixin.java index adfeeda3..42812519 100644 --- a/src/main/java/carpet/mixins/DirectionMixin.java +++ b/src/main/java/carpet/mixins/DirectionMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import carpet.fakes.EntityInterface; import carpet.helpers.BlockRotator; import net.minecraft.entity.Entity; @@ -16,7 +16,7 @@ public abstract class DirectionMixin private static float getYaw(Entity entity, float float_1) { float yaw; - if (!CarpetSettings.getBool("placementRotationFix")) + if (!CarpetSettings.placementRotationFix) { yaw = entity.getYaw(float_1); } diff --git a/src/main/java/carpet/mixins/EndCityFeatureMixin.java b/src/main/java/carpet/mixins/EndCityFeatureMixin.java index 5437d48d..4556a1a2 100644 --- a/src/main/java/carpet/mixins/EndCityFeatureMixin.java +++ b/src/main/java/carpet/mixins/EndCityFeatureMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import com.google.common.collect.Lists; import com.mojang.datafixers.Dynamic; import net.minecraft.entity.EntityType; @@ -27,7 +27,7 @@ public abstract class EndCityFeatureMixin extends StructureFeature getMonsterSpawns() { - if (CarpetSettings.b_shulkerSpawningInEndCities) + if (CarpetSettings.shulkerSpawningInEndCities) return spawnList; return Collections.emptyList(); } diff --git a/src/main/java/carpet/mixins/ExperienceOrbEntityMixin.java b/src/main/java/carpet/mixins/ExperienceOrbEntityMixin.java index e0a201ae..5ca180b1 100644 --- a/src/main/java/carpet/mixins/ExperienceOrbEntityMixin.java +++ b/src/main/java/carpet/mixins/ExperienceOrbEntityMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import carpet.fakes.ExperienceOrbInterface; import carpet.helpers.XPcombine; import net.minecraft.entity.ExperienceOrbEntity; @@ -31,7 +31,7 @@ public abstract class ExperienceOrbEntityMixin implements ExperienceOrbInterface )) void checkCombineAtTick(CallbackInfo ci) { - if (CarpetSettings.getBool("combineXPOrbs")) + if (CarpetSettings.combineXPOrbs) { if (getCombineDelay() > 0) { @@ -48,7 +48,7 @@ public abstract class ExperienceOrbEntityMixin implements ExperienceOrbInterface @Inject(method = "onPlayerCollision", at = @At("HEAD")) void removeDelay(PlayerEntity playerEntity_1, CallbackInfo ci) { - if (CarpetSettings.getBool("xpNoCooldown")) + if (CarpetSettings.xpNoCooldown) playerEntity_1.experiencePickUpDelay = 0; } diff --git a/src/main/java/carpet/mixins/ExplosionMixin.java b/src/main/java/carpet/mixins/ExplosionMixin.java index ccca2596..e3a59349 100644 --- a/src/main/java/carpet/mixins/ExplosionMixin.java +++ b/src/main/java/carpet/mixins/ExplosionMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import net.minecraft.util.math.BlockPos; import net.minecraft.world.explosion.Explosion; import org.spongepowered.asm.mixin.Final; @@ -23,7 +23,7 @@ public abstract class ExplosionMixin target = "Ljava/util/List;addAll(Ljava/util/Collection;)Z")) private void clearList(CallbackInfo ci) { - if (CarpetSettings.getBool("explosionNoBlockDamage")) + if (CarpetSettings.explosionNoBlockDamage) { this.affectedBlocks.clear(); } diff --git a/src/main/java/carpet/mixins/FillCommandMixin.java b/src/main/java/carpet/mixins/FillCommandMixin.java index 04f66b26..7904201d 100644 --- a/src/main/java/carpet/mixins/FillCommandMixin.java +++ b/src/main/java/carpet/mixins/FillCommandMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import net.minecraft.block.Block; import net.minecraft.server.command.FillCommand; import net.minecraft.server.world.ServerWorld; @@ -15,8 +15,9 @@ import org.spongepowered.asm.mixin.injection.Redirect; public abstract class FillCommandMixin { @ModifyConstant(method = "execute", constant = @Constant(intValue = 32768)) - private static int fillLimit(int original) { - return CarpetSettings.getInt("fillLimit"); + private static int fillLimit(int original) + { + return CarpetSettings.fillLimit; } @Redirect(method = "execute", at = @At( @@ -25,6 +26,6 @@ public abstract class FillCommandMixin )) private static void conditionalUpdating(ServerWorld serverWorld, BlockPos blockPos_1, Block block_1) { - if (CarpetSettings.b_fillUpdates) serverWorld.updateNeighbors(blockPos_1, block_1); + if (CarpetSettings.fillUpdates) serverWorld.updateNeighbors(blockPos_1, block_1); } } diff --git a/src/main/java/carpet/mixins/FloatingIslandsChunkGeneratorMixin.java b/src/main/java/carpet/mixins/FloatingIslandsChunkGeneratorMixin.java index 0fba9b4b..2bc27e3b 100644 --- a/src/main/java/carpet/mixins/FloatingIslandsChunkGeneratorMixin.java +++ b/src/main/java/carpet/mixins/FloatingIslandsChunkGeneratorMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import net.minecraft.entity.EntityCategory; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IWorld; @@ -25,7 +25,7 @@ public abstract class FloatingIslandsChunkGeneratorMixin extends SurfaceChunkGen @Override public List getEntitySpawnList(EntityCategory entityCategory_1, BlockPos blockPos_1) { - if (CarpetSettings.b_shulkerSpawningInEndCities && EntityCategory.MONSTER == entityCategory_1) + if (CarpetSettings.shulkerSpawningInEndCities && EntityCategory.MONSTER == entityCategory_1) { if (Feature.END_CITY.isInsideStructure(this.world, blockPos_1)) { diff --git a/src/main/java/carpet/mixins/FossilFeatureMixin.java b/src/main/java/carpet/mixins/FossilFeatureMixin.java index 77fb3817..92e7b5d9 100644 --- a/src/main/java/carpet/mixins/FossilFeatureMixin.java +++ b/src/main/java/carpet/mixins/FossilFeatureMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import net.minecraft.world.Heightmap; import net.minecraft.world.IWorld; import net.minecraft.world.gen.feature.FossilFeature; diff --git a/src/main/java/carpet/mixins/GravityStructureProcessorMixin.java b/src/main/java/carpet/mixins/GravityStructureProcessorMixin.java index 7303a22f..137557f2 100644 --- a/src/main/java/carpet/mixins/GravityStructureProcessorMixin.java +++ b/src/main/java/carpet/mixins/GravityStructureProcessorMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import net.minecraft.structure.processor.GravityStructureProcessor; import net.minecraft.world.Heightmap; import net.minecraft.world.ViewableWorld; diff --git a/src/main/java/carpet/mixins/GuardianEntityMixin.java b/src/main/java/carpet/mixins/GuardianEntityMixin.java index 52b0d232..c72a5629 100644 --- a/src/main/java/carpet/mixins/GuardianEntityMixin.java +++ b/src/main/java/carpet/mixins/GuardianEntityMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import net.minecraft.entity.EntityData; import net.minecraft.entity.EntityType; import net.minecraft.entity.LightningEntity; @@ -24,7 +24,7 @@ public abstract class GuardianEntityMixin extends HostileEntity @Override public void onStruckByLightning(LightningEntity lightning) { - if (!this.world.isClient && !this.removed && CarpetSettings.getBool("renewableSponges")) + if (!this.world.isClient && !this.removed && CarpetSettings.renewableSponges) { ElderGuardianEntity elderGuardian = new ElderGuardianEntity(EntityType.ELDER_GUARDIAN ,this.world); elderGuardian.setPositionAndAngles(this.x, this.y, this.z, this.yaw, this.pitch); diff --git a/src/main/java/carpet/mixins/HopperBlockEntityMixin.java b/src/main/java/carpet/mixins/HopperBlockEntityMixin.java index 08e35d7a..a82b65c8 100644 --- a/src/main/java/carpet/mixins/HopperBlockEntityMixin.java +++ b/src/main/java/carpet/mixins/HopperBlockEntityMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import net.minecraft.block.HopperBlock; import net.minecraft.block.entity.BlockEntityType; import net.minecraft.block.entity.HopperBlockEntity; @@ -41,7 +41,7 @@ public abstract class HopperBlockEntityMixin extends LootableContainerBlockEntit @Inject(method = "insert", at = @At("HEAD"), cancellable = true) private void onInsert(CallbackInfoReturnable cir) { - if (CarpetSettings.b_hopperCounters) { + if (CarpetSettings.hopperCounters) { DyeColor wool_color = WoolTool.getWoolColorAtPosition( getWorld(), new BlockPos(getHopperX(), getHopperY(), getHopperZ()).offset(this.getCachedState().get(HopperBlock.FACING))); diff --git a/src/main/java/carpet/mixins/IglooGeneratorPieceMixin.java b/src/main/java/carpet/mixins/IglooGeneratorPieceMixin.java index efd24377..988f460b 100644 --- a/src/main/java/carpet/mixins/IglooGeneratorPieceMixin.java +++ b/src/main/java/carpet/mixins/IglooGeneratorPieceMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import net.minecraft.structure.IglooGenerator; import net.minecraft.world.Heightmap; import net.minecraft.world.IWorld; diff --git a/src/main/java/carpet/mixins/InfestedBlockMixin.java b/src/main/java/carpet/mixins/InfestedBlockMixin.java index a9b71f16..5b2aeebb 100644 --- a/src/main/java/carpet/mixins/InfestedBlockMixin.java +++ b/src/main/java/carpet/mixins/InfestedBlockMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.block.Blocks; @@ -26,7 +26,7 @@ public abstract class InfestedBlockMixin extends Block private void onOnStacksDropped(BlockState blockState_1, World world_1, BlockPos blockPos_1, ItemStack itemStack_1, CallbackInfo ci) { - if (CarpetSettings.getBool("silverFishDropGravel")) + if (CarpetSettings.silverFishDropGravel) { dropStack(world_1, blockPos_1, new ItemStack(Blocks.GRAVEL)); } diff --git a/src/main/java/carpet/mixins/IntegratedServerMixin.java b/src/main/java/carpet/mixins/IntegratedServerMixin.java index 1e7ba79c..a5149af5 100644 --- a/src/main/java/carpet/mixins/IntegratedServerMixin.java +++ b/src/main/java/carpet/mixins/IntegratedServerMixin.java @@ -10,13 +10,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; @Mixin(IntegratedServer.class) public class IntegratedServerMixin { - @Inject(method = "setupServer", - at = @At( - value = "INVOKE", - shift = At.Shift.AFTER, - target = "Lnet/minecraft/server/integrated/IntegratedServer;setKeyPair(Ljava/security/KeyPair;)V" - ) - ) + @Inject(method = "setupServer", at = @At("TAIL")) private void onSetupServerIntegrated(CallbackInfoReturnable cir) { CarpetServer.onServerLoaded((IntegratedServer) (Object) this); } diff --git a/src/main/java/carpet/mixins/ItemEntityMixin.java b/src/main/java/carpet/mixins/ItemEntityMixin.java index 7aeb88f0..b5b1731c 100644 --- a/src/main/java/carpet/mixins/ItemEntityMixin.java +++ b/src/main/java/carpet/mixins/ItemEntityMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import carpet.helpers.InventoryHelper; import carpet.utils.IItemEntity; import net.minecraft.block.ShulkerBoxBlock; @@ -41,7 +41,7 @@ public abstract class ItemEntityMixin extends Entity implements IItemEntity { @Inject(method="(Lnet/minecraft/world/World;DDDLnet/minecraft/item/ItemStack;)V", at = @At("RETURN")) private void removeEmptyShulkerBoxTags(World worldIn, double x, double y, double z, ItemStack stack, CallbackInfo ci) { - if (CarpetSettings.b_stackableShulkerBoxes + if (CarpetSettings.stackableShulkerBoxes && stack.getItem() instanceof BlockItem && ((BlockItem)stack.getItem()).getBlock() instanceof ShulkerBoxBlock) { @@ -59,7 +59,7 @@ public abstract class ItemEntityMixin extends Entity implements IItemEntity { ) ) private int getItemStackMaxAmount(ItemStack stack) { - if (CarpetSettings.b_stackableShulkerBoxes && stack.getItem() instanceof BlockItem && ((BlockItem)stack.getItem()).getBlock() instanceof ShulkerBoxBlock) + if (CarpetSettings.stackableShulkerBoxes && stack.getItem() instanceof BlockItem && ((BlockItem)stack.getItem()).getBlock() instanceof ShulkerBoxBlock) return SHULKERBOX_MAX_STACK_AMOUNT; return stack.getMaxCount(); @@ -74,7 +74,7 @@ public abstract class ItemEntityMixin extends Entity implements IItemEntity { { ItemEntity self = (ItemEntity)(Object)this; ItemStack selfStack = self.getStack(); - if (!CarpetSettings.b_stackableShulkerBoxes || !(selfStack.getItem() instanceof BlockItem) || !(((BlockItem)selfStack.getItem()).getBlock() instanceof ShulkerBoxBlock)) { + if (!CarpetSettings.stackableShulkerBoxes || !(selfStack.getItem() instanceof BlockItem) || !(((BlockItem)selfStack.getItem()).getBlock() instanceof ShulkerBoxBlock)) { return; } diff --git a/src/main/java/carpet/mixins/KelpFeatureMixin.java b/src/main/java/carpet/mixins/KelpFeatureMixin.java index 5e317feb..35a3a735 100644 --- a/src/main/java/carpet/mixins/KelpFeatureMixin.java +++ b/src/main/java/carpet/mixins/KelpFeatureMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import net.minecraft.world.gen.feature.KelpFeature; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; @@ -16,7 +16,7 @@ public class KelpFeatureMixin { if (bound==10) return random.nextInt(bound); - int limit = CarpetSettings.getInt("kelpGenerationGrowLimit"); + int limit = CarpetSettings.kelpGenerationGrowthLimit; if (limit == 0) return random.nextInt(bound); return 25-limit+random.nextInt(Math.min(23,limit+1)); diff --git a/src/main/java/carpet/mixins/LivingEntity_maxCollisionsMixin.java b/src/main/java/carpet/mixins/LivingEntity_maxCollisionsMixin.java index c18240d8..d88ea96a 100644 --- a/src/main/java/carpet/mixins/LivingEntity_maxCollisionsMixin.java +++ b/src/main/java/carpet/mixins/LivingEntity_maxCollisionsMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityType; import net.minecraft.entity.LivingEntity; @@ -12,7 +12,6 @@ import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import java.util.List; @@ -50,8 +49,8 @@ public abstract class LivingEntity_maxCollisionsMixin extends Entity } int limit = list_1.size(); - if (CarpetSettings.n_maxEntityCollisions > 0) - limit = Math.min(limit, CarpetSettings.n_maxEntityCollisions); + if (CarpetSettings.maxEntityCollisions > 0) + limit = Math.min(limit, CarpetSettings.maxEntityCollisions); for(int_2 = 0; int_2 < limit; ++int_2) { Entity entity_1 = (Entity)list_1.get(int_2); diff --git a/src/main/java/carpet/mixins/MinecraftClientMixin.java b/src/main/java/carpet/mixins/MinecraftClientMixin.java index 533288b5..93dddc12 100644 --- a/src/main/java/carpet/mixins/MinecraftClientMixin.java +++ b/src/main/java/carpet/mixins/MinecraftClientMixin.java @@ -1,7 +1,7 @@ package carpet.mixins; import carpet.CarpetServer; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import net.minecraft.client.MinecraftClient; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; diff --git a/src/main/java/carpet/mixins/MinecraftDedicatedServerMixin.java b/src/main/java/carpet/mixins/MinecraftDedicatedServerMixin.java index a169081b..9b23c940 100644 --- a/src/main/java/carpet/mixins/MinecraftDedicatedServerMixin.java +++ b/src/main/java/carpet/mixins/MinecraftDedicatedServerMixin.java @@ -12,15 +12,7 @@ public class MinecraftDedicatedServerMixin { //to inject right before // this.tickWorlds(booleanSupplier_1); - @Inject( - method = "setupServer", - at = @At( - value = "INVOKE", - target = "Lnet/minecraft/util/UserCache;setUseRemote(Z)V", - shift = At.Shift.AFTER, - ordinal = 0 - ) - ) + @Inject(method = "setupServer", at = @At("TAIL")) private void onSetupServer(CallbackInfoReturnable cir) { //CM init - all stuff loaded from the server, just before worlds loading CarpetServer.onServerLoaded((MinecraftDedicatedServer) (Object) this); diff --git a/src/main/java/carpet/mixins/MinecraftServer_motdMixin.java b/src/main/java/carpet/mixins/MinecraftServer_motdMixin.java index c177d465..187018ab 100644 --- a/src/main/java/carpet/mixins/MinecraftServer_motdMixin.java +++ b/src/main/java/carpet/mixins/MinecraftServer_motdMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import carpet.fakes.MinecraftServer_motdInterface; import net.minecraft.server.MinecraftServer; import org.spongepowered.asm.mixin.Mixin; @@ -27,15 +27,15 @@ public abstract class MinecraftServer_motdMixin implements MinecraftServer_motdI @Override public String checkMOTD() { - if ("_".equals(CarpetSettings.getString("customMOTD"))) + if ("_".equals(CarpetSettings.customMOTD)) { setMotd(motd); return motd; } else { - setMotd(CarpetSettings.getString("customMOTD")); - return CarpetSettings.getString("customMOTD"); + setMotd(CarpetSettings.customMOTD); + return CarpetSettings.customMOTD; } } } diff --git a/src/main/java/carpet/mixins/OceanRuinGeneratorPieceMixin.java b/src/main/java/carpet/mixins/OceanRuinGeneratorPieceMixin.java index d16defd2..4cf03752 100644 --- a/src/main/java/carpet/mixins/OceanRuinGeneratorPieceMixin.java +++ b/src/main/java/carpet/mixins/OceanRuinGeneratorPieceMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import net.minecraft.structure.OceanRuinGenerator; import net.minecraft.world.Heightmap; import net.minecraft.world.IWorld; diff --git a/src/main/java/carpet/mixins/PistonBlockEntityRenderer_movableTEMixin.java b/src/main/java/carpet/mixins/PistonBlockEntityRenderer_movableTEMixin.java index 584b879f..9be523af 100644 --- a/src/main/java/carpet/mixins/PistonBlockEntityRenderer_movableTEMixin.java +++ b/src/main/java/carpet/mixins/PistonBlockEntityRenderer_movableTEMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import carpet.fakes.BlockEntityRenderDispatcherInterface; import carpet.fakes.PistonBlockEntityInterface; import net.minecraft.block.entity.BlockEntity; @@ -22,7 +22,7 @@ public abstract class PistonBlockEntityRenderer_movableTEMixin extends BlockEnti double double_3, float float_1, int int_1, CallbackInfo ci) { if (!((PistonBlockEntityInterface) pistonBlockEntity_1).isRenderModeSet()) - ((PistonBlockEntityInterface) pistonBlockEntity_1).setRenderCarriedBlockEntity(CarpetSettings.b_movableTileEntities && ((PistonBlockEntityInterface) pistonBlockEntity_1).getCarriedBlockEntity() != null); + ((PistonBlockEntityInterface) pistonBlockEntity_1).setRenderCarriedBlockEntity(CarpetSettings.movableTileEntities && ((PistonBlockEntityInterface) pistonBlockEntity_1).getCarriedBlockEntity() != null); } @Inject(method = "method_3576", at = @At("RETURN")) diff --git a/src/main/java/carpet/mixins/PistonBlockEntity_movableTEMixin.java b/src/main/java/carpet/mixins/PistonBlockEntity_movableTEMixin.java index 90c09d33..0de7a544 100644 --- a/src/main/java/carpet/mixins/PistonBlockEntity_movableTEMixin.java +++ b/src/main/java/carpet/mixins/PistonBlockEntity_movableTEMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import carpet.fakes.PistonBlockEntityInterface; import carpet.fakes.WorldInterface; import net.minecraft.block.Block; @@ -77,7 +77,7 @@ public abstract class PistonBlockEntity_movableTEMixin extends BlockEntity imple target = "Lnet/minecraft/world/World;setBlockState(Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/BlockState;I)Z")) private boolean movableTEsetBlockState0(World world, BlockPos blockPos_1, BlockState blockAState_2, int int_1) { - if (!CarpetSettings.b_movableTileEntities) + if (!CarpetSettings.movableTileEntities) return world.setBlockState(blockPos_1, blockAState_2, int_1); else return ((WorldInterface) (world)).setBlockStateWithBlockEntity(blockPos_1, blockAState_2, this.carriedBlockEntity, int_1); @@ -87,7 +87,7 @@ public abstract class PistonBlockEntity_movableTEMixin extends BlockEntity imple target = "Lnet/minecraft/world/World;setBlockState(Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/BlockState;I)Z")) private boolean movableTEsetBlockState1(World world, BlockPos blockPos_1, BlockState blockState_2, int int_1) { - if (!CarpetSettings.b_movableTileEntities) + if (!CarpetSettings.movableTileEntities) return world.setBlockState(blockPos_1, blockState_2, int_1); else { @@ -103,7 +103,7 @@ public abstract class PistonBlockEntity_movableTEMixin extends BlockEntity imple //Handle TNT Explosions or other ways the moving Block is broken //Also /setblock will cause this to be called, and drop e.g. a moving chest's contents. // This is MC-40380 (BlockEntities that aren't Inventories drop stuff when setblock is called ) - if (CarpetSettings.b_movableTileEntities && this.carriedBlockEntity != null && !this.world.isClient && this.world.getBlockState(this.pos).getBlock() == Blocks.AIR) + if (CarpetSettings.movableTileEntities && this.carriedBlockEntity != null && !this.world.isClient && this.world.getBlockState(this.pos).getBlock() == Blocks.AIR) { BlockState blockState_2; if (this.source) @@ -118,7 +118,7 @@ public abstract class PistonBlockEntity_movableTEMixin extends BlockEntity imple @Inject(method = "fromTag", at = @At(value = "TAIL")) private void onFromTag(CompoundTag compoundTag_1, CallbackInfo ci) { - if (CarpetSettings.b_movableTileEntities && compoundTag_1.containsKey("carriedTileEntityCM", 10)) + if (CarpetSettings.movableTileEntities && compoundTag_1.containsKey("carriedTileEntityCM", 10)) { if (this.pushedBlock.getBlock() instanceof BlockEntityProvider) this.carriedBlockEntity = ((BlockEntityProvider) (this.pushedBlock.getBlock())).createBlockEntity(this.world); @@ -130,7 +130,7 @@ public abstract class PistonBlockEntity_movableTEMixin extends BlockEntity imple @Inject(method = "toTag", at = @At(value = "RETURN", shift = At.Shift.BEFORE)) private void onToTag(CompoundTag compoundTag_1, CallbackInfoReturnable cir) { - if (CarpetSettings.b_movableTileEntities && this.carriedBlockEntity != null) + if (CarpetSettings.movableTileEntities && this.carriedBlockEntity != null) { //Leave name "carriedTileEntityCM" instead of "carriedBlockEntityCM" for upgrade compatibility with 1.13.2 movable TE compoundTag_1.put("carriedTileEntityCM", this.carriedBlockEntity.toTag(new CompoundTag())); diff --git a/src/main/java/carpet/mixins/PistonBlock_movableTEMixin.java b/src/main/java/carpet/mixins/PistonBlock_movableTEMixin.java index 41e76b86..7dda8b94 100644 --- a/src/main/java/carpet/mixins/PistonBlock_movableTEMixin.java +++ b/src/main/java/carpet/mixins/PistonBlock_movableTEMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import carpet.fakes.PistonBlockEntityInterface; import com.google.common.collect.Lists; import net.minecraft.block.*; @@ -35,7 +35,7 @@ public abstract class PistonBlock_movableTEMixin extends FacingBlock { Block block_1 = blockState_1.getBlock(); //Make CommandBlocks movable, either use instanceof CommandBlock or the 3 cmd block objects, - if (CarpetSettings.b_movableTileEntities && block_1 instanceof CommandBlock) + if (CarpetSettings.movableTileEntities && block_1 instanceof CommandBlock) { cir.setReturnValue(true); } @@ -58,7 +58,7 @@ public abstract class PistonBlock_movableTEMixin extends FacingBlock } else { - return !(CarpetSettings.b_movableTileEntities && isPushableTileEntityBlock(block)); + return !(CarpetSettings.movableTileEntities && isPushableTileEntityBlock(block)); } } @Inject(method = "move", at = @At(value = "INVOKE", shift = At.Shift.BEFORE, @@ -69,7 +69,7 @@ public abstract class PistonBlock_movableTEMixin extends FacingBlock Direction direction_2, Set set_1) { //Get the blockEntities and remove them from the world before any magic starts to happen - if (CarpetSettings.b_movableTileEntities) + if (CarpetSettings.movableTileEntities) { list1_BlockEntities.set(Lists.newArrayList()); for (int i = 0; i < list_1.size(); ++i) @@ -99,7 +99,7 @@ public abstract class PistonBlock_movableTEMixin extends FacingBlock { BlockEntity blockEntityPiston = PistonExtensionBlock.createBlockEntityPiston((BlockState) list_2.get(int_3), direction_1, boolean_1, false); - if (CarpetSettings.b_movableTileEntities) + if (CarpetSettings.movableTileEntities) ((PistonBlockEntityInterface) blockEntityPiston).setCarriedBlockEntity(list1_BlockEntities.get().get(int_3)); world_1.setBlockEntity(blockPos_4, blockEntityPiston); } diff --git a/src/main/java/carpet/mixins/PistonHandler_pushLimitMixin.java b/src/main/java/carpet/mixins/PistonHandler_pushLimitMixin.java index 04a9497f..8bfbb1b1 100644 --- a/src/main/java/carpet/mixins/PistonHandler_pushLimitMixin.java +++ b/src/main/java/carpet/mixins/PistonHandler_pushLimitMixin.java @@ -1,9 +1,8 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import net.minecraft.block.piston.PistonHandler; import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Constant; import org.spongepowered.asm.mixin.injection.ModifyConstant; @@ -13,6 +12,6 @@ public class PistonHandler_pushLimitMixin @ModifyConstant(method = "tryMove", constant = @Constant(intValue = 12), expect = 3) private int pushLimit(int original) { - return CarpetSettings.n_pushLimit; + return CarpetSettings.pushLimit; } } diff --git a/src/main/java/carpet/mixins/PlayerEntityMixin.java b/src/main/java/carpet/mixins/PlayerEntityMixin.java index 812ad91d..7b22f908 100644 --- a/src/main/java/carpet/mixins/PlayerEntityMixin.java +++ b/src/main/java/carpet/mixins/PlayerEntityMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import carpet.helpers.PortalHelper; import net.minecraft.entity.player.PlayerEntity; import org.spongepowered.asm.mixin.Mixin; @@ -13,7 +13,7 @@ public abstract class PlayerEntityMixin @ModifyConstant(method = "getMaxPortalTime", constant = @Constant(intValue = 1)) private int addFillUpdatesInt(int original) { - if (CarpetSettings.getBool("portalCreativeDelay")) + if (CarpetSettings.portalCreativeDelay) if (PortalHelper.player_holds_obsidian((PlayerEntity) (Object)this)) return 72000; else diff --git a/src/main/java/carpet/mixins/PlayerEntity_parrotMixin.java b/src/main/java/carpet/mixins/PlayerEntity_parrotMixin.java index e950fdbe..6c27bc42 100644 --- a/src/main/java/carpet/mixins/PlayerEntity_parrotMixin.java +++ b/src/main/java/carpet/mixins/PlayerEntity_parrotMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import net.minecraft.entity.EntityType; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.damage.DamageSource; @@ -50,7 +50,7 @@ public abstract class PlayerEntity_parrotMixin extends LivingEntity target = "Lnet/minecraft/entity/player/PlayerEntity;updateShoulderEntity(Lnet/minecraft/nbt/CompoundTag;)V")) private void onTickMovement(CallbackInfo ci) { - boolean parrots_will_drop = !CarpetSettings.getBool("persistentParrots") || this.abilities.invulnerable; + boolean parrots_will_drop = !CarpetSettings.persistentParrots || this.abilities.invulnerable; if (!this.world.isClient && ((parrots_will_drop && this.fallDistance > 0.5F) || this.isInWater() || (parrots_will_drop && this.hasVehicle())) || this.abilities.flying) { this.dropShoulderEntities(); @@ -80,7 +80,7 @@ public abstract class PlayerEntity_parrotMixin extends LivingEntity target = "Lnet/minecraft/entity/player/PlayerEntity;dropShoulderEntities()V")) private void onDamage(DamageSource damageSource_1, float float_1, CallbackInfoReturnable cir) { - if (CarpetSettings.getBool("persistentParrots") && !this.isSneaking()) + if (CarpetSettings.persistentParrots && !this.isSneaking()) { if (this.random.nextFloat() < ((float_1)/15.0) ) { diff --git a/src/main/java/carpet/mixins/PortalBlock_portalCachingMixin.java b/src/main/java/carpet/mixins/PortalBlock_portalCachingMixin.java index a3e94ad0..d92a16ba 100644 --- a/src/main/java/carpet/mixins/PortalBlock_portalCachingMixin.java +++ b/src/main/java/carpet/mixins/PortalBlock_portalCachingMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import carpet.fakes.PortalForcerInterface; import net.minecraft.block.BlockState; import net.minecraft.block.PortalBlock; @@ -22,7 +22,7 @@ public class PortalBlock_portalCachingMixin )) private void onCreatePortal(IWorld iWorld_1, BlockPos blockPos_1, CallbackInfoReturnable cir) { - if (!iWorld_1.isClient() && CarpetSettings.getBool("portalCaching")) + if (!iWorld_1.isClient() && CarpetSettings.portalCaching) { ((PortalForcerInterface)((ServerWorld)iWorld_1).getPortalForcer()).invalidateCache(); } @@ -34,7 +34,7 @@ public class PortalBlock_portalCachingMixin )) private void getAirBlockState(BlockState blockState_1, Direction direction_1, BlockState blockState_2, IWorld iWorld_1, BlockPos blockPos_1, BlockPos blockPos_2, CallbackInfoReturnable cir) { - if (!iWorld_1.isClient() && CarpetSettings.getBool("portalCaching")) + if (!iWorld_1.isClient() && CarpetSettings.portalCaching) { ((PortalForcerInterface)((ServerWorld)iWorld_1).getPortalForcer()).invalidateCache(); } diff --git a/src/main/java/carpet/mixins/PortalForcer_portalCachingMixin.java b/src/main/java/carpet/mixins/PortalForcer_portalCachingMixin.java index bedda2ca..136d8796 100644 --- a/src/main/java/carpet/mixins/PortalForcer_portalCachingMixin.java +++ b/src/main/java/carpet/mixins/PortalForcer_portalCachingMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import carpet.fakes.PortalForcerInterface; import net.minecraft.entity.Entity; import net.minecraft.server.world.ChunkTicketType; @@ -45,7 +45,7 @@ public class PortalForcer_portalCachingMixin implements PortalForcerInterface private Object /* private TicketInfo */ getTicketInfo(Map map, Object /* ColumnPos */ key) { //Do the dance with ticketinfos. If vanilla has one, we gonna borrow, if vanilla is missing, we supply - if (!CarpetSettings.getBool("portalCaching")) + if (!CarpetSettings.portalCaching) return map.get(key); Object ticketInfo = map.get(key); if (ticketInfo != null) @@ -71,7 +71,7 @@ public class PortalForcer_portalCachingMixin implements PortalForcerInterface )) private Object /* TicketInfo */ putNewTicket(Map map, Object /*ColumnPos */ key, Object /*TicketInfo */ value) { - if (CarpetSettings.getBool("portalCaching")) + if (CarpetSettings.portalCaching) storedTicketInfos.put((ColumnPos) key, value); return map.put(key, value); } diff --git a/src/main/java/carpet/mixins/PoweredRailBlock_powerLimitMixin.java b/src/main/java/carpet/mixins/PoweredRailBlock_powerLimitMixin.java index 660ea173..685ed710 100644 --- a/src/main/java/carpet/mixins/PoweredRailBlock_powerLimitMixin.java +++ b/src/main/java/carpet/mixins/PoweredRailBlock_powerLimitMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import net.minecraft.block.PoweredRailBlock; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.Constant; @@ -13,6 +13,6 @@ public class PoweredRailBlock_powerLimitMixin constant = @Constant(intValue = 8)) private int powerLimit(int original) { - return CarpetSettings.railPowerLimitAdjusted; + return CarpetSettings.railPowerLimit-1; } } diff --git a/src/main/java/carpet/mixins/SaplingBlockMixin.java b/src/main/java/carpet/mixins/SaplingBlockMixin.java index 81760d3b..fb5dc59d 100644 --- a/src/main/java/carpet/mixins/SaplingBlockMixin.java +++ b/src/main/java/carpet/mixins/SaplingBlockMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import carpet.helpers.BlockSaplingHelper; import net.minecraft.block.BlockState; import net.minecraft.block.Blocks; @@ -23,7 +23,7 @@ public abstract class SaplingBlockMixin cancellable = true) private void onGenerate(IWorld iWorld_1, BlockPos blockPos_1, BlockState blockState_1, Random random_1, CallbackInfo ci) { - if(CarpetSettings.getBool("desertShrubs") && iWorld_1.getBiome(blockPos_1) == Biomes.DESERT && !BlockSaplingHelper.hasWater(iWorld_1, blockPos_1)) + if(CarpetSettings.desertShrubs && iWorld_1.getBiome(blockPos_1) == Biomes.DESERT && !BlockSaplingHelper.hasWater(iWorld_1, blockPos_1)) { iWorld_1.setBlockState(blockPos_1, Blocks.DEAD_BUSH.getDefaultState(), 3); ci.cancel(); diff --git a/src/main/java/carpet/mixins/ServerPlayNetworkHandlerMixin.java b/src/main/java/carpet/mixins/ServerPlayNetworkHandlerMixin.java index cb07ae50..779e7619 100644 --- a/src/main/java/carpet/mixins/ServerPlayNetworkHandlerMixin.java +++ b/src/main/java/carpet/mixins/ServerPlayNetworkHandlerMixin.java @@ -1,19 +1,17 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import carpet.helpers.TickSpeed; import net.minecraft.server.network.ServerPlayNetworkHandler; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.server.network.packet.PlayerInputC2SPacket; import net.minecraft.server.network.packet.PlayerMoveC2SPacket; -import net.minecraft.server.network.packet.VehicleMoveC2SPacket; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import org.spongepowered.asm.mixin.injection.callback.LocalCapture; @Mixin(ServerPlayNetworkHandler.class) public class ServerPlayNetworkHandlerMixin @@ -51,7 +49,7 @@ public class ServerPlayNetworkHandlerMixin target = "Lnet/minecraft/server/network/ServerPlayerEntity;isInTeleportationState()Z")) private boolean relaxMoveRestrictions(ServerPlayerEntity serverPlayerEntity) { - return serverPlayerEntity.isInTeleportationState() || CarpetSettings.getBool("antiCheatSpeed"); + return serverPlayerEntity.isInTeleportationState() || CarpetSettings.antiCheatSpeed; } } diff --git a/src/main/java/carpet/mixins/ServerPlayNetworkHandler_scarpetEventsMixin.java b/src/main/java/carpet/mixins/ServerPlayNetworkHandler_scarpetEventsMixin.java index 7fb9b64e..53cb398f 100644 --- a/src/main/java/carpet/mixins/ServerPlayNetworkHandler_scarpetEventsMixin.java +++ b/src/main/java/carpet/mixins/ServerPlayNetworkHandler_scarpetEventsMixin.java @@ -1,7 +1,6 @@ package carpet.mixins; import carpet.CarpetServer; -import carpet.CarpetSettings; import net.minecraft.server.network.ServerPlayNetworkHandler; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.server.network.packet.ClientCommandC2SPacket; diff --git a/src/main/java/carpet/mixins/ServerWorld_onePlayerSleepingMixin.java b/src/main/java/carpet/mixins/ServerWorld_onePlayerSleepingMixin.java index 6406b15f..3d76cca8 100644 --- a/src/main/java/carpet/mixins/ServerWorld_onePlayerSleepingMixin.java +++ b/src/main/java/carpet/mixins/ServerWorld_onePlayerSleepingMixin.java @@ -1,7 +1,6 @@ package carpet.mixins; -import carpet.CarpetSettings; -import net.minecraft.entity.player.PlayerEntity; +import carpet.settings.CarpetSettings; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.server.world.ServerWorld; import org.spongepowered.asm.mixin.Final; @@ -26,7 +25,7 @@ public class ServerWorld_onePlayerSleepingMixin @Inject(method = "updatePlayersSleeping", cancellable = true, at = @At("HEAD")) private void updateOnePlayerSleeping(CallbackInfo ci) { - if(CarpetSettings.getBool("onePlayerSleeping")) + if(CarpetSettings.onePlayerSleeping) { allPlayersSleeping = false; for (ServerPlayerEntity p : players) @@ -46,7 +45,7 @@ public class ServerWorld_onePlayerSleepingMixin )) private boolean noneMatchSleep(Stream stream, Predicate predicate) { - if (CarpetSettings.getBool("onePlayerSleeping")) + if (CarpetSettings.onePlayerSleeping) return stream.anyMatch((p) -> !p.isSpectator() && p.isSleepingLongEnough()); return stream.noneMatch(predicate); } diff --git a/src/main/java/carpet/mixins/SetBlockCommandMixin.java b/src/main/java/carpet/mixins/SetBlockCommandMixin.java index a66035be..c435cbe2 100644 --- a/src/main/java/carpet/mixins/SetBlockCommandMixin.java +++ b/src/main/java/carpet/mixins/SetBlockCommandMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import net.minecraft.block.Block; import net.minecraft.server.command.SetBlockCommand; import net.minecraft.server.world.ServerWorld; @@ -18,6 +18,6 @@ public class SetBlockCommandMixin )) private static void conditionalUpdating(ServerWorld serverWorld, BlockPos blockPos_1, Block block_1) { - if (CarpetSettings.b_fillUpdates) serverWorld.updateNeighbors(blockPos_1, block_1); + if (CarpetSettings.fillUpdates) serverWorld.updateNeighbors(blockPos_1, block_1); } } diff --git a/src/main/java/carpet/mixins/ShipwreckGeneratorPieceMixin.java b/src/main/java/carpet/mixins/ShipwreckGeneratorPieceMixin.java index f9e59c3b..8ed3032e 100644 --- a/src/main/java/carpet/mixins/ShipwreckGeneratorPieceMixin.java +++ b/src/main/java/carpet/mixins/ShipwreckGeneratorPieceMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import net.minecraft.structure.ShipwreckGenerator; import net.minecraft.world.Heightmap; import net.minecraft.world.IWorld; diff --git a/src/main/java/carpet/mixins/SpawnHelperMixin.java b/src/main/java/carpet/mixins/SpawnHelperMixin.java index 2ab39342..7e8854e0 100644 --- a/src/main/java/carpet/mixins/SpawnHelperMixin.java +++ b/src/main/java/carpet/mixins/SpawnHelperMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import carpet.fakes.WorldInterface; import carpet.utils.SpawnReporter; import net.minecraft.block.Block; @@ -35,7 +35,7 @@ public class SpawnHelperMixin // various configurations, but solid and 'passable' blocks, like air, water grass, etc. // checking if in the BB of the entity are only passable blocks is very cheap and covers most cases // in case something more complex happens - we default to full block collision check - if (CarpetSettings.b_lagFreeSpawning) + if (CarpetSettings.lagFreeSpawning) { BlockPos.Mutable blockpos = new BlockPos.Mutable(); for (int y = (int)bb.minY, maxy = (int)Math.ceil(bb.maxY); y < maxy; y++) @@ -61,7 +61,7 @@ public class SpawnHelperMixin )) private static Entity create(EntityType entityType, World world_1) { - if (CarpetSettings.b_lagFreeSpawning) + if (CarpetSettings.lagFreeSpawning) { Map precookedMobs = ((WorldInterface)world_1).getPrecookedMobs(); if (precookedMobs.containsKey(entityType)) @@ -80,7 +80,7 @@ public class SpawnHelperMixin )) private static boolean spawnEntity(World world, Entity entity_1) { - if (CarpetSettings.b_lagFreeSpawning) + if (CarpetSettings.lagFreeSpawning) // we used the mob - next time we will create a new one when needed ((WorldInterface) world).getPrecookedMobs().remove(entity_1.getType()); diff --git a/src/main/java/carpet/mixins/StructureBlockBlockEntity_fillUpdatesMixin.java b/src/main/java/carpet/mixins/StructureBlockBlockEntity_fillUpdatesMixin.java index c386905e..e95c2c2f 100644 --- a/src/main/java/carpet/mixins/StructureBlockBlockEntity_fillUpdatesMixin.java +++ b/src/main/java/carpet/mixins/StructureBlockBlockEntity_fillUpdatesMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import net.minecraft.block.entity.StructureBlockBlockEntity; import net.minecraft.structure.Structure; import net.minecraft.structure.StructurePlacementData; @@ -19,7 +19,7 @@ public abstract class StructureBlockBlockEntity_fillUpdatesMixin )) private void onStructurePlacen(Structure structure, IWorld iWorld_1, BlockPos blockPos_1, StructurePlacementData structurePlacementData_1) { - if(!CarpetSettings.b_fillUpdates) + if(!CarpetSettings.fillUpdates) CarpetSettings.impendingFillSkipUpdates = true; try { diff --git a/src/main/java/carpet/mixins/StructureFeatureMixin.java b/src/main/java/carpet/mixins/StructureFeatureMixin.java index cac476f4..baf2b738 100644 --- a/src/main/java/carpet/mixins/StructureFeatureMixin.java +++ b/src/main/java/carpet/mixins/StructureFeatureMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import carpet.fakes.StructureFeatureInterface; import net.minecraft.server.world.ServerWorld; import net.minecraft.structure.StructureStart; diff --git a/src/main/java/carpet/mixins/StructurePieceMixin.java b/src/main/java/carpet/mixins/StructurePieceMixin.java index f4859078..abecaed9 100644 --- a/src/main/java/carpet/mixins/StructurePieceMixin.java +++ b/src/main/java/carpet/mixins/StructurePieceMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import net.minecraft.structure.StructurePiece; import net.minecraft.world.Heightmap; import net.minecraft.world.ViewableWorld; diff --git a/src/main/java/carpet/mixins/Structure_fillUpdatesMixin.java b/src/main/java/carpet/mixins/Structure_fillUpdatesMixin.java index ef081a18..61e12b77 100644 --- a/src/main/java/carpet/mixins/Structure_fillUpdatesMixin.java +++ b/src/main/java/carpet/mixins/Structure_fillUpdatesMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import net.minecraft.block.Block; import net.minecraft.structure.Structure; import net.minecraft.util.math.BlockPos; diff --git a/src/main/java/carpet/mixins/SummonCommandMixin.java b/src/main/java/carpet/mixins/SummonCommandMixin.java index 8f4561e1..18495e73 100644 --- a/src/main/java/carpet/mixins/SummonCommandMixin.java +++ b/src/main/java/carpet/mixins/SummonCommandMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import net.minecraft.entity.EntityType; import net.minecraft.entity.LightningEntity; import net.minecraft.entity.mob.SkeletonHorseEntity; @@ -31,7 +31,7 @@ public class SummonCommandMixin private static void addRiders(ServerCommandSource source, Identifier identifier_1, Vec3d vec3d_1, CompoundTag compoundTag_1, boolean arg4, CallbackInfoReturnable cir, CompoundTag compoundTag_2, LightningEntity lightningEntity_1) { // [CM] SummonNaturalLightning - if statement around - if (CarpetSettings.getBool("summonNaturalLightning") && !source.getWorld().isClient) + if (CarpetSettings.summonNaturalLightning && !source.getWorld().isClient) { ServerWorld world = source.getWorld(); BlockPos at = new BlockPos(vec3d_1); diff --git a/src/main/java/carpet/mixins/TntBlockMixin.java b/src/main/java/carpet/mixins/TntBlockMixin.java index 3c4cc0ce..608f3c2f 100644 --- a/src/main/java/carpet/mixins/TntBlockMixin.java +++ b/src/main/java/carpet/mixins/TntBlockMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import net.minecraft.block.TntBlock; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; @@ -16,6 +16,6 @@ public abstract class TntBlockMixin target = "Lnet/minecraft/world/World;isReceivingRedstonePower(Lnet/minecraft/util/math/BlockPos;)Z")) private boolean isTNTDoNotUpdate(World world, BlockPos blockPos) { - return !CarpetSettings.getBool("TNTDoNotUpdate") && world.isReceivingRedstonePower(blockPos); + return !CarpetSettings.TNTDoNotUpdate && world.isReceivingRedstonePower(blockPos); } } diff --git a/src/main/java/carpet/mixins/TntEntityMixin.java b/src/main/java/carpet/mixins/TntEntityMixin.java index 94ae0178..8818cc8d 100644 --- a/src/main/java/carpet/mixins/TntEntityMixin.java +++ b/src/main/java/carpet/mixins/TntEntityMixin.java @@ -1,11 +1,10 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityType; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.TntEntity; -import net.minecraft.nbt.CompoundTag; import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; import org.spongepowered.asm.mixin.Mixin; @@ -49,7 +48,7 @@ public abstract class TntEntityMixin extends Entity private void initTNTLogger(World world_1, double double_1, double double_2, double double_3, LivingEntity livingEntity_1, CallbackInfo ci) { - if(CarpetSettings.getBool("tntPrimerMomentumRemoved")) + if(CarpetSettings.tntPrimerMomentumRemoved) this.setVelocity(new Vec3d(0.0, 0.20000000298023224D, 0.0)); } diff --git a/src/main/java/carpet/mixins/WorldChunk_fillUpdatesMixin.java b/src/main/java/carpet/mixins/WorldChunk_fillUpdatesMixin.java index b780dd36..bdd5e9b0 100644 --- a/src/main/java/carpet/mixins/WorldChunk_fillUpdatesMixin.java +++ b/src/main/java/carpet/mixins/WorldChunk_fillUpdatesMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import net.minecraft.block.BlockState; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; diff --git a/src/main/java/carpet/mixins/WorldChunk_movableTEMixin.java b/src/main/java/carpet/mixins/WorldChunk_movableTEMixin.java index e7b993a3..161f72e8 100644 --- a/src/main/java/carpet/mixins/WorldChunk_movableTEMixin.java +++ b/src/main/java/carpet/mixins/WorldChunk_movableTEMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import carpet.fakes.WorldChunkInterface; import net.minecraft.block.Block; import net.minecraft.block.BlockEntityProvider; @@ -48,7 +48,7 @@ public abstract class WorldChunk_movableTEMixin implements WorldChunkInterface private BlockEntity ifGetBlockEntity(WorldChunk worldChunk, BlockPos blockPos_1, WorldChunk.CreationType worldChunk$CreationType_1) { - if (!CarpetSettings.b_movableTileEntities) + if (!CarpetSettings.movableTileEntities) { return this.getBlockEntity(blockPos_1, WorldChunk.CreationType.CHECK); } diff --git a/src/main/java/carpet/mixins/World_fillUpdatesMixin.java b/src/main/java/carpet/mixins/World_fillUpdatesMixin.java index 8c80014a..b71c623d 100644 --- a/src/main/java/carpet/mixins/World_fillUpdatesMixin.java +++ b/src/main/java/carpet/mixins/World_fillUpdatesMixin.java @@ -1,6 +1,6 @@ package carpet.mixins; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import net.minecraft.world.World; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.Constant; diff --git a/src/main/java/carpet/script/CarpetExpression.java b/src/main/java/carpet/script/CarpetExpression.java index 7f9f6b7d..a8d797cf 100644 --- a/src/main/java/carpet/script/CarpetExpression.java +++ b/src/main/java/carpet/script/CarpetExpression.java @@ -1,7 +1,7 @@ package carpet.script; import carpet.CarpetServer; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import carpet.helpers.FeatureGenerator; import carpet.fakes.MinecraftServerInterface; import carpet.script.exception.CarpetExpressionException; @@ -21,7 +21,6 @@ import com.mojang.brigadier.StringReader; import com.mojang.brigadier.exceptions.CommandSyntaxException; import net.minecraft.block.Block; import net.minecraft.block.BlockState; -import net.minecraft.block.Blocks; import net.minecraft.block.entity.BlockEntity; import net.minecraft.enchantment.Enchantments; import net.minecraft.entity.EntityType; @@ -707,7 +706,7 @@ public class CarpetExpression } if (sourceBlockState == targetBlockState) return (c_, t_) -> Value.FALSE; - if (!CarpetSettings.b_fillUpdates) CarpetSettings.impendingFillSkipUpdates = true; + CarpetSettings.impendingFillSkipUpdates = !CarpetSettings.fillUpdates; cc.s.getWorld().setBlockState(targetLocator.block.getPos(), sourceBlockState, 2); CarpetSettings.impendingFillSkipUpdates = false; Value retval = new BlockValue(sourceBlockState, world, targetLocator.block.getPos()); diff --git a/src/main/java/carpet/script/CarpetScriptServer.java b/src/main/java/carpet/script/CarpetScriptServer.java index c312f013..d3bd038f 100644 --- a/src/main/java/carpet/script/CarpetScriptServer.java +++ b/src/main/java/carpet/script/CarpetScriptServer.java @@ -1,7 +1,7 @@ package carpet.script; import carpet.CarpetServer; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import carpet.script.bundled.CameraPathModule; import carpet.script.bundled.FileModule; import carpet.script.bundled.ModuleInterface; @@ -242,7 +242,7 @@ public class CarpetScriptServer } Messenger.m(source, "gi Package "+hostName+" loaded with /"+hostName+" command"); CarpetServer.minecraft_server.getCommandManager().getDispatcher().register(command); - CarpetSettings.notifyPlayersCommandsChanged(); + CarpetServer.settingsManager.notifyPlayersCommandsChanged(); } public void setChatErrorSnooper(ServerCommandSource source) @@ -304,7 +304,7 @@ public class CarpetScriptServer } // stop all events associated with name modules.remove(name); - CarpetSettings.notifyPlayersCommandsChanged(); + CarpetServer.settingsManager.notifyPlayersCommandsChanged(); Messenger.m(source, "w Removed host "+name); return true; } diff --git a/src/main/java/carpet/script/ScriptHost.java b/src/main/java/carpet/script/ScriptHost.java index c72327b7..4cede524 100644 --- a/src/main/java/carpet/script/ScriptHost.java +++ b/src/main/java/carpet/script/ScriptHost.java @@ -1,7 +1,7 @@ package carpet.script; import carpet.CarpetServer; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import carpet.script.exception.ExpressionException; import carpet.script.exception.InvalidCallbackException; import carpet.script.value.NumericValue; diff --git a/src/main/java/carpet/settings/Settings.java b/src/main/java/carpet/settings/CarpetSettings.java similarity index 95% rename from src/main/java/carpet/settings/Settings.java rename to src/main/java/carpet/settings/CarpetSettings.java index 528b4f68..552d01f8 100644 --- a/src/main/java/carpet/settings/Settings.java +++ b/src/main/java/carpet/settings/CarpetSettings.java @@ -6,6 +6,8 @@ import carpet.utils.Messenger; import net.minecraft.server.MinecraftServer; import net.minecraft.server.command.ServerCommandSource; import net.minecraft.server.dedicated.DedicatedServer; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import static carpet.settings.RuleCategory.BUGFIX; import static carpet.settings.RuleCategory.COMMANDS; @@ -15,8 +17,13 @@ import static carpet.settings.RuleCategory.FEATURE; import static carpet.settings.RuleCategory.OPTIMIZATIONS; import static carpet.settings.RuleCategory.SURVIVAL; -public class Settings +public class CarpetSettings { + public static final String carpetVersion = "v19_06_04alpha"; + public static final Logger LOG = LogManager.getLogger(); + public static boolean skipGenerationChecks = false; + public static boolean impendingFillSkipUpdates = false; + @Rule( desc = "Fixes server crashing supposedly on falling behind 60s in ONE tick, yeah bs.", extra = "Fixed 1.12 watchdog crash in 1.13 pre-releases, reintroduced with 1.13, GG.", @@ -225,7 +232,7 @@ public class Settings @Rule(desc = "fill/clone/setblock and structure blocks cause block updates", category = CREATIVE) public static boolean fillUpdates = true; - private class PushLimitLimits extends Validator { + private static class PushLimitLimits extends Validator { @Override Integer validate(ServerCommandSource source, ParsedRule currentRule, Integer newValue, String string) { return (newValue>0 && newValue < 1024) ? newValue : null; } @@ -246,7 +253,7 @@ public class Settings ) public static int railPowerLimit = 9; - private class FillLimitLimits extends Validator { + private static class FillLimitLimits extends Validator { @Override Integer validate(ServerCommandSource source, ParsedRule currentRule, Integer newValue, String string) { return (newValue>0 && newValue < 20000000) ? newValue : null; } @@ -270,7 +277,7 @@ public class Settings @Rule(desc = "One player is required on the server to cause night to pass", category = SURVIVAL) public static boolean onePlayerSleeping = false; - private class SetMotd extends Validator { + private static class SetMotd extends Validator { @Override String validate(ServerCommandSource source, ParsedRule currentRule, String newValue, String string) { customMOTD = newValue; // accelerate a smidge ((MinecraftServer_motdInterface) CarpetServer.minecraft_server).checkMOTD(); @@ -289,7 +296,7 @@ public class Settings @Rule(desc = "Cactus in dispensers rotates blocks.", extra = "Rotates block anti-clockwise if possible", category = FEATURE) public static boolean rotatorBlock = false; - private class ViewDistanceValidator extends Validator + private static class ViewDistanceValidator extends Validator { @Override Integer validate(ServerCommandSource source, ParsedRule currentRule, Integer newValue, String string) { @@ -323,7 +330,7 @@ public class Settings ) public static int viewDistance = 0; - private class DisableSpawnChunksValidator extends Validator { + private static class DisableSpawnChunksValidator extends Validator { @Override Boolean validate(ServerCommandSource source, ParsedRule currentRule, Boolean newValue, String string) { if (!newValue) Messenger.m(source, "w Spawn chunks re-enabled. Visit spawn to load them?"); @@ -337,7 +344,7 @@ public class Settings ) public static boolean disableSpawnChunks = false; - private class KelpLimit extends Validator { + private static class KelpLimit extends Validator { @Override Integer validate(ServerCommandSource source, ParsedRule currentRule, Integer newValue, String string) { return (newValue>=0 && newValue <=25)?newValue:null; } diff --git a/src/main/java/carpet/settings/ParsedRule.java b/src/main/java/carpet/settings/ParsedRule.java index 674dd137..859d9270 100644 --- a/src/main/java/carpet/settings/ParsedRule.java +++ b/src/main/java/carpet/settings/ParsedRule.java @@ -71,8 +71,9 @@ public final class ParsedRule implements Comparable { } - public ParsedRule set(ServerCommandSource source, String value) { - if (CarpetServer.settingsManager.locked) + public ParsedRule set(ServerCommandSource source, String value) + { + if (CarpetServer.settingsManager != null && CarpetServer.settingsManager.locked) return null; if (type == String.class) { @@ -98,8 +99,10 @@ public final class ParsedRule implements Comparable { } } - ParsedRule set(ServerCommandSource source, T value, String stringValue) { - try { + ParsedRule set(ServerCommandSource source, T value, String stringValue) + { + try + { for (Validator validator : this.validators) { value = validator.validate(source, this, value, stringValue); @@ -120,55 +123,68 @@ public final class ParsedRule implements Comparable { return this; } - public T get() { - try { + public T get() + { + try + { return (T) this.field.get(null); - } catch (IllegalAccessException e) { + } + catch (IllegalAccessException e) + { throw new IllegalStateException(e); } } - public String getAsString() { + public String getAsString() + { return convertToString(get()); } - public boolean getBoolValue() { + public boolean getBoolValue() + { if (type == boolean.class) return (Boolean) get(); if (type.isAssignableFrom(Number.class)) return ((Number) get()).doubleValue() > 0; return false; } - public boolean isDefault() { + public boolean isDefault() + { return defaultValue.equals(get()); } - public void resetToDefault(ServerCommandSource source) { + public void resetToDefault(ServerCommandSource source) + { set(source, defaultValue, defaultAsString); } - private static String convertToString(Object value) { + private static String convertToString(Object value) + { if (value instanceof Enum) return ((Enum) value).name().toLowerCase(Locale.ROOT); return value.toString(); } @Override - public boolean equals(Object obj) { + public boolean equals(Object obj) + { return obj.getClass() == ParsedRule.class && ((ParsedRule) obj).name.equals(this.name); } @Override - public int hashCode() { + public int hashCode() + { return this.name.hashCode(); } @Override - public int compareTo(ParsedRule o) { + public int compareTo(ParsedRule o) + { return this.name.compareTo(o.name); } @Override - public String toString() { + public String toString() + { return this.name + ": " + getAsString(); } } diff --git a/src/main/java/carpet/settings/SettingsManager.java b/src/main/java/carpet/settings/SettingsManager.java index 52d2ca9d..435f7b47 100644 --- a/src/main/java/carpet/settings/SettingsManager.java +++ b/src/main/java/carpet/settings/SettingsManager.java @@ -1,6 +1,5 @@ package carpet.settings; -import carpet.CarpetSettings; import com.google.common.collect.ImmutableList; import net.minecraft.server.MinecraftServer; import net.minecraft.server.command.ServerCommandSource; @@ -35,7 +34,6 @@ public class SettingsManager { Rule rule = f.getAnnotation(Rule.class); if (rule == null) continue; ParsedRule parsed = new ParsedRule(f, rule); - CarpetSettings.LOG.error("REGISTERED RULE: "+parsed.name); rules.put(parsed.name, parsed); } } diff --git a/src/main/java/carpet/utils/CarpetProfiler.java b/src/main/java/carpet/utils/CarpetProfiler.java index fd1e3ac9..d0bfe218 100644 --- a/src/main/java/carpet/utils/CarpetProfiler.java +++ b/src/main/java/carpet/utils/CarpetProfiler.java @@ -1,6 +1,6 @@ package carpet.utils; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import net.minecraft.entity.Entity; import net.minecraft.server.MinecraftServer; import net.minecraft.block.entity.BlockEntity; diff --git a/src/main/java/carpet/utils/SpawnReporter.java b/src/main/java/carpet/utils/SpawnReporter.java index 6874840b..43fa2a57 100644 --- a/src/main/java/carpet/utils/SpawnReporter.java +++ b/src/main/java/carpet/utils/SpawnReporter.java @@ -1,7 +1,6 @@ package carpet.utils; -import carpet.CarpetSettings; import carpet.mixins.WeightedPickerEntryMixin; import it.unimi.dsi.fastutil.objects.Object2IntMap; import it.unimi.dsi.fastutil.objects.Object2LongMap; diff --git a/src/main/java/carpet/utils/WoolTool.java b/src/main/java/carpet/utils/WoolTool.java index 4d3f864d..9634ae6c 100644 --- a/src/main/java/carpet/utils/WoolTool.java +++ b/src/main/java/carpet/utils/WoolTool.java @@ -1,6 +1,6 @@ package carpet.utils; -import carpet.CarpetSettings; +import carpet.settings.CarpetSettings; import carpet.helpers.HopperCounter; import net.minecraft.block.Material; import net.minecraft.block.MaterialColor; @@ -30,23 +30,23 @@ public class WoolTool public static void carpetPlacedAction(DyeColor color, PlayerEntity placer, BlockPos pos, World worldIn) { - if (!CarpetSettings.getBool("carpets")) + if (!CarpetSettings.carpets) { return; } switch (color) { case PINK: - if (CarpetSettings.getBool("commandSpawn")) + if (CarpetSettings.commandSpawn) Messenger.send(placer, SpawnReporter.report(pos, worldIn)); break; case BLACK: - if (CarpetSettings.getBool("commandSpawn")) + if (CarpetSettings.commandSpawn) Messenger.send(placer, SpawnReporter.show_mobcaps(pos, worldIn)); break; case BROWN: - if (CarpetSettings.getBool("commandDistance")) + if (CarpetSettings.commandDistance) { ServerCommandSource source = placer.getCommandSource(); if (!DistanceCalculator.hasStartingPoint(source) || placer.isSneaking()) { @@ -58,16 +58,16 @@ public class WoolTool } break; case GRAY: - if (CarpetSettings.getBool("commandInfo")) + if (CarpetSettings.commandInfo) Messenger.send(placer, BlockInfo.blockInfo(pos.down(), worldIn)); break; case YELLOW: - if (CarpetSettings.getBool("commandInfo")) - Messenger.m(placer, "r use data get entity command"); + if (CarpetSettings.commandInfo) + Messenger.m(placer, "r This used to show entity info around the player. Use data get entity command, sorry"); //EntityInfo.issue_entity_info(placer); break; case GREEN: - if (CarpetSettings.getBool("hopperCounters")) + if (CarpetSettings.hopperCounters) { DyeColor under = getWoolColorAtPosition(worldIn, pos.down()); if (under == null) return; @@ -77,7 +77,7 @@ public class WoolTool } break; case RED: - if (CarpetSettings.getBool("hopperCounters")) + if (CarpetSettings.hopperCounters) { DyeColor under = getWoolColorAtPosition(worldIn, pos.down()); if (under == null) return; From 9bbaaccb3e62649dbdc03c9d92382e7859336692 Mon Sep 17 00:00:00 2001 From: gnembon Date: Wed, 12 Jun 2019 01:03:34 -0300 Subject: [PATCH 6/7] freekin egyptian braces --- README.md | 466 ++++++++++++++++++ src/main/java/carpet/CarpetServer.java | 8 +- .../java/carpet/commands/CarpetCommand.java | 10 +- .../java/carpet/commands/TestCommand.java | 2 + .../carpet/mixins/HopperBlockEntityMixin.java | 9 +- .../java/carpet/mixins/TntBlockMixin.java | 4 +- .../java/carpet/settings/CarpetSettings.java | 62 ++- src/main/java/carpet/settings/ParsedRule.java | 17 +- src/main/java/carpet/settings/Rule.java | 3 +- .../java/carpet/settings/RuleCategory.java | 7 +- .../java/carpet/settings/SettingsManager.java | 76 ++- src/main/java/carpet/settings/Validator.java | 49 +- 12 files changed, 626 insertions(+), 87 deletions(-) diff --git a/README.md b/README.md index 85614794..13e8a191 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,469 @@ # Fabric Carpet Cause all carpets are made of fabric? + +# Carpet Settings + +## antiCheatSpeed +Prevents players from rubberbanding when moving too fast +Puts more trust in clients positioning +* Type: `boolean` +* Default value: `false` +* Required options: `true`, `false` +* Categories: `CREATIVE`, `SURVIVAL` +* Additional notes: + * Its not yet fully implemented - we are working on it + +## calmNetherFires +Permanent fires don't schedule random updates +* Type: `boolean` +* Default value: `false` +* Required options: `true`, `false` +* Categories: `OPTIMIZATION` +* Additional notes: + * Its not yet fully implemented - we are working on it + +## carpets +Placing carpets may issue carpet commands for non-op players +* Type: `boolean` +* Default value: `false` +* Required options: `true`, `false` +* Categories: `SURVIVAL` + +## combineXPOrbs +XP orbs combine with other into bigger orbs +* Type: `boolean` +* Default value: `false` +* Required options: `true`, `false` +* Categories: `FEATURE` + +## commandCameramode +Enables /c and /s commands to quickly switch between camera and survival modes +/c and /s commands are available to all players regardless of their permission levels +* Type: `boolean` +* Default value: `true` +* Required options: `true`, `false` +* Categories: `COMMAND` +* Additional notes: + * It has an accompanying command + +## commandDistance +Enables /distance command to measure in game distance between points +Also enables brown carpet placement action if 'carpets' rule is turned on as well +* Type: `boolean` +* Default value: `true` +* Required options: `true`, `false` +* Categories: `COMMAND` +* Additional notes: + * It has an accompanying command + +## commandDraw +Enables /draw commands +... allows for drawing simple shapes +* Type: `boolean` +* Default value: `true` +* Required options: `true`, `false` +* Categories: `COMMAND` +* Additional notes: + * It has an accompanying command + +## commandInfo +Enables /info command for blocks +Also enables gray carpet placement action +if 'carpets' rule is turned on as well +* Type: `boolean` +* Default value: `true` +* Required options: `true`, `false` +* Categories: `COMMAND` +* Additional notes: + * It has an accompanying command + +## commandLog +Enables /log command to monitor events in the game via chat and overlays +* Type: `boolean` +* Default value: `true` +* Required options: `true`, `false` +* Categories: `COMMAND` +* Additional notes: + * It has an accompanying command + +## commandPerimeterInfo +Enables /perimeterinfo command +... that scans the area around the block for potential spawnable spots +* Type: `boolean` +* Default value: `true` +* Required options: `true`, `false` +* Categories: `COMMAND` +* Additional notes: + * It has an accompanying command + +## commandPlayer +Enables /player command to control/spawn players +* Type: `boolean` +* Default value: `true` +* Required options: `true`, `false` +* Categories: `COMMAND` +* Additional notes: + * Its not yet fully implemented - we are working on it + * It has an accompanying command + +## commandScript +Enables /script command +An in-game scripting API for Scarpet programming language +* Type: `boolean` +* Default value: `true` +* Required options: `true`, `false` +* Categories: `COMMAND` +* Additional notes: + * It has an accompanying command + +## commandSpawn +Enables /spawn command for spawn tracking +* Type: `boolean` +* Default value: `true` +* Required options: `true`, `false` +* Categories: `COMMAND` +* Additional notes: + * It has an accompanying command + +## commandTick +Enables /tick command to control game clocks +* Type: `boolean` +* Default value: `true` +* Required options: `true`, `false` +* Categories: `COMMAND` +* Additional notes: + * It has an accompanying command + +## ctrlQCraftingFix +Dropping entire stacks works also from on the crafting UI result slot +* Type: `boolean` +* Default value: `false` +* Required options: `true`, `false` +* Categories: `BUGFIX`, `SURVIVAL` + +## customMOTD +Sets a different motd message on client trying to connect to the server +use '_' to use the startup setting from server.properties +* Type: `String` +* Default value: `_` +* Suggested options: `_` +* Categories: `CREATIVE` +* Additional notes: + * Its not yet fully implemented - we are working on it + +## desertShrubs +Saplings turn into dead shrubs in hot climates and no water access +* Type: `boolean` +* Default value: `false` +* Required options: `true`, `false` +* Categories: `FEATURE` + +## disableSpawnChunks +Allows spawn chunks to unload +* Type: `boolean` +* Default value: `false` +* Required options: `true`, `false` +* Categories: `CREATIVE` +* Additional notes: + * Its not yet fully implemented - we are working on it + +## explosionNoBlockDamage +Explosions won't destroy blocks +* Type: `boolean` +* Default value: `false` +* Required options: `true`, `false` +* Categories: `CREATIVE` + +## fastRedstoneDust +Lag optimizations for redstone dust +by Theosib +* Type: `boolean` +* Default value: `false` +* Required options: `true`, `false` +* Categories: `EXPERIMENTAL`, `OPTIMIZATION` +* Additional notes: + * Its not yet fully implemented - we are working on it + +## fillLimit +Customizable fill/clone volume limit +* Type: `int` +* Default value: `32768` +* Suggested options: `32768`, `250000`, `1000000` +* Categories: `CREATIVE` +* Additional notes: + * You must choose a value from 1 to 20M + +## fillUpdates +fill/clone/setblock and structure blocks cause block updates +* Type: `boolean` +* Default value: `true` +* Required options: `true`, `false` +* Categories: `CREATIVE` + +## flippinCactus +Players can flip and rotate blocks when holding cactus +Doesn't cause block updates when rotated/flipped +Applies to pistons, observers, droppers, repeaters, stairs, glazed terracotta etc... +* Type: `boolean` +* Default value: `false` +* Required options: `true`, `false` +* Categories: `CREATIVE`, `SURVIVAL`, `FEATURE` + +## hopperCounters +hoppers pointing to wool will count items passing through them +Enables /counter command, and actions while placing red and green carpets on wool blocks +Use /counter reset to reset the counter, and /counter to query +In survival, place green carpet on same color wool to query, red to reset the counters +Counters are global and shared between players, 16 channels available +Items counted are destroyed, count up to one stack per tick per hopper +* Type: `boolean` +* Default value: `false` +* Required options: `true`, `false` +* Categories: `COMMAND`, `CREATIVE`, `FEATURE` +* Additional notes: + * It has an accompanying command + +## huskSpawningInTemples +Only husks spawn in desert temples +* Type: `boolean` +* Default value: `false` +* Required options: `true`, `false` +* Categories: `FEATURE` +* Additional notes: + * Its not yet fully implemented - we are working on it + +## kelpGenerationGrowthLimit +limits growth limit of newly naturally generated kelp to this amount of blocks +* Type: `int` +* Default value: `25` +* Suggested options: `0`, `2`, `25` +* Categories: `FEATURE` +* Additional notes: + * You must choose a value from 0 to 25. 25 and all natural kelp can grow 25 blocks, choose 0 to make all generated kelp not to grow + +## lagFreeSpawning +Spawning requires much less CPU and Memory +* Type: `boolean` +* Default value: `false` +* Required options: `true`, `false` +* Categories: `OPTIMIZATION` + +## leadFix +Fixes leads breaking/becoming invisible in unloaded chunks +You may still get visibly broken leash links on the client side, but server side the link is still there. +* Type: `boolean` +* Default value: `false` +* Required options: `true`, `false` +* Categories: `BUGFIX` +* Additional notes: + * Its not yet fully implemented - we are working on it + +## maxEntityCollisions +Customizable maximal entity collision limits, 0 for no limits +* Type: `int` +* Default value: `0` +* Suggested options: `0`, `1`, `20` +* Categories: `OPTIMIZATION` +* Additional notes: + * Must be a positive number + +## missingTools +Pistons, Glass and Sponge can be broken faster with their appropriate tools +* Type: `boolean` +* Default value: `false` +* Required options: `true`, `false` +* Categories: `SURVIVAL` +* Additional notes: + * Its not yet fully implemented - we are working on it + +## movableTileEntities +Pistons can push tile entities, like hoppers, chests etc. +* Type: `boolean` +* Default value: `false` +* Required options: `true`, `false` +* Categories: `EXPERIMENTAL`, `FEATURE` + +## onePlayerSleeping +One player is required on the server to cause night to pass +* Type: `boolean` +* Default value: `false` +* Required options: `true`, `false` +* Categories: `SURVIVAL` + +## persistentParrots +Parrots don't get of your shoulders until you receive damage +* Type: `boolean` +* Default value: `false` +* Required options: `true`, `false` +* Categories: `SURVIVAL`, `FEATURE` +* Additional notes: + * Its not yet fully implemented - we are working on it + +## placementRotationFix +fixes block placement rotation issue when player rotates quickly while placing blocks +* Type: `boolean` +* Default value: `false` +* Required options: `true`, `false` +* Categories: `BUGFIX` + +## portalCaching +Alternative, persistent caching strategy for nether portals +* Type: `boolean` +* Default value: `false` +* Required options: `true`, `false` +* Categories: `SURVIVAL`, `CREATIVE` + +## portalCreativeDelay +Portals won't let a creative player go through instantly +Holding obsidian in either hand won't let you through at all +* Type: `boolean` +* Default value: `false` +* Required options: `true`, `false` +* Categories: `CREATIVE` + +## portalSuffocationFix +Nether portals correctly place entities going through +Entities shouldn't suffocate in obsidian +* Type: `boolean` +* Default value: `false` +* Required options: `true`, `false` +* Categories: `BUGFIX` +* Additional notes: + * Its not yet fully implemented - we are working on it + +## pushLimit +Customizable piston push limit +* Type: `int` +* Default value: `12` +* Suggested options: `10`, `12`, `14`, `100` +* Categories: `CREATIVE` +* Additional notes: + * You must choose a value from 1 to 1024 + +## quasiConnectivity +Pistons, droppers and dispensers react if block above them is powered +* Type: `boolean` +* Default value: `true` +* Required options: `true`, `false` +* Categories: `CREATIVE` +* Additional notes: + * Its not yet fully implemented - we are working on it + +## railPowerLimit +Customizable powered rail power range +* Type: `int` +* Default value: `9` +* Suggested options: `9`, `15`, `30` +* Categories: `CREATIVE` +* Additional notes: + * You must choose a value from 1 to 1024 + +## renewableCoral +Coral structures will grow with bonemeal from coral plants +* Type: `boolean` +* Default value: `false` +* Required options: `true`, `false` +* Categories: `FEATURE` + +## renewableSponges +Guardians turn into Elder Guardian when struck by lightning +* Type: `boolean` +* Default value: `false` +* Required options: `true`, `false` +* Categories: `FEATURE` + +## rotatorBlock +Cactus in dispensers rotates blocks. +Rotates block anti-clockwise if possible +* Type: `boolean` +* Default value: `false` +* Required options: `true`, `false` +* Categories: `FEATURE` + +## shulkerSpawningInEndCities +Shulkers will respawn in end cities +* Type: `boolean` +* Default value: `false` +* Required options: `true`, `false` +* Categories: `FEATURE` + +## silverFishDropGravel +Silverfish drop a gravel item when breaking out of a block +* Type: `boolean` +* Default value: `false` +* Required options: `true`, `false` +* Categories: `FEATURE` + +## stackableShulkerBoxes +Empty shulker boxes can stack to 64 when dropped on the ground +To move them around between inventories, use shift click to move entire stacks +* Type: `boolean` +* Default value: `false` +* Required options: `true`, `false` +* Categories: `SURVIVAL`, `FEATURE` + +## summonNaturalLightning +summoning a lightning bolt has all the side effects of natural lightning +* Type: `boolean` +* Default value: `false` +* Required options: `true`, `false` +* Categories: `CREATIVE` + +## superSecretSetting +Gbhs sgnf sadsgras fhskdpri! +* Type: `boolean` +* Default value: `false` +* Required options: `true`, `false` +* Categories: `EXPERIMENTAL` + +## tntDoNotUpdate +TNT doesn't update when placed against a power source +* Type: `boolean` +* Default value: `false` +* Required options: `true`, `false` +* Categories: `CREATIVE` + +## tntPrimerMomentumRemoved +Removes random TNT momentum when primed +* Type: `boolean` +* Default value: `false` +* Required options: `true`, `false` +* Categories: `CREATIVE` + +## unloadedEntityFix +Entities pushed or moved into unloaded chunks no longer disappear +* Type: `boolean` +* Default value: `false` +* Required options: `true`, `false` +* Categories: `EXPERIMENTAL`, `BUGFIX` +* Additional notes: + * Its not yet fully implemented - we are working on it + +## viewDistance +Changes the view distance of the server. +Set to 0 to not override the value in server settings. +* Type: `int` +* Default value: `0` +* Suggested options: `0`, `12`, `16`, `32` +* Categories: `CREATIVE` +* Additional notes: + * You must choose a value from 0 (use server settings) to 32 + +## watchdogCrashFix +Fixes server crashing supposedly on falling behind 60s in ONE tick, yeah bs. +Fixed 1.12 watchdog crash in 1.13 pre-releases, reintroduced with 1.13, GG. +* Type: `boolean` +* Default value: `false` +* Required options: `true`, `false` +* Categories: `BUGFIX` +* Additional notes: + * Its not yet fully implemented - we are working on it + +## xpNoCooldown +Players absorb XP instantly, without delay +* Type: `boolean` +* Default value: `false` +* Required options: `true`, `false` +* Categories: `CREATIVE` + diff --git a/src/main/java/carpet/CarpetServer.java b/src/main/java/carpet/CarpetServer.java index 4c5e64e1..6a378d10 100644 --- a/src/main/java/carpet/CarpetServer.java +++ b/src/main/java/carpet/CarpetServer.java @@ -14,6 +14,7 @@ import carpet.commands.PerimeterInfoCommand; import carpet.commands.PlayerCommand; import carpet.commands.ScriptCommand; import carpet.commands.SpawnCommand; +import carpet.commands.TestCommand; import carpet.commands.TickCommand; import carpet.helpers.TickSpeed; import carpet.logging.LoggerRegistry; @@ -31,7 +32,8 @@ public class CarpetServer // static for now - easier to handle all around the co public static MinecraftServer minecraft_server; public static CarpetScriptServer scriptServer; public static SettingsManager settingsManager; - static { + static + { SettingsManager.parseSettingsClass(CarpetSettings.class); //... } @@ -45,7 +47,8 @@ public class CarpetServer // static for now - easier to handle all around the co scriptServer = new CarpetScriptServer(); } // Separate from onServerLoaded, because a server can be loaded multiple times in singleplayer - public static void onGameStarted() { + public static void onGameStarted() + { LoggerRegistry.initLoggers(); } @@ -72,7 +75,6 @@ public class CarpetServer // static for now - easier to handle all around the co DrawCommand.register(dispatcher); ScriptCommand.register(dispatcher); CarpetCommand.register(dispatcher); - //TestCommand.register(dispatcher); } } diff --git a/src/main/java/carpet/commands/CarpetCommand.java b/src/main/java/carpet/commands/CarpetCommand.java index 4e1eb9c7..ab64394a 100644 --- a/src/main/java/carpet/commands/CarpetCommand.java +++ b/src/main/java/carpet/commands/CarpetCommand.java @@ -149,16 +149,16 @@ public class CarpetCommand return Messenger.c(args.toArray(new Object[0])); } - private static BaseText makeSetRuleButton(ParsedRule rule, String option, boolean brackets) { + private static BaseText makeSetRuleButton(ParsedRule rule, String option, boolean brackets) + { String style = rule.isDefault()?"g":(option.equalsIgnoreCase(rule.defaultAsString)?"y":"e"); if (option.equalsIgnoreCase(rule.defaultAsString)) style = style+"b"; else if (option.equalsIgnoreCase(rule.getAsString())) style = style+"u"; String baseText = style + (brackets ? " [" : " ") + option + (brackets ? "]" : ""); - if (CarpetServer.settingsManager.locked) { + if (CarpetServer.settingsManager.locked) return Messenger.c(baseText, "^g Settings are locked"); - } if (option.equalsIgnoreCase(rule.getAsString())) return Messenger.c(baseText); return Messenger.c(baseText, "^g Switch to " + option, "?/carpet " + rule.name + " " + option); @@ -200,9 +200,7 @@ public class CarpetCommand tags.remove(tags.size() - 1); Messenger.m(player, tags.toArray(new Object[0])); } - catch (CommandSyntaxException e) - { - } + catch (CommandSyntaxException ignored) { } return 1; } } diff --git a/src/main/java/carpet/commands/TestCommand.java b/src/main/java/carpet/commands/TestCommand.java index 2cbcb7a5..469c8e5a 100644 --- a/src/main/java/carpet/commands/TestCommand.java +++ b/src/main/java/carpet/commands/TestCommand.java @@ -1,5 +1,6 @@ package carpet.commands; +import carpet.CarpetServer; import carpet.utils.Messenger; import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.context.CommandContext; @@ -15,6 +16,7 @@ public class TestCommand public static void register(CommandDispatcher dispatcher) { dispatcher.register(literal("test"). + then(literal("dump").executes((c) -> CarpetServer.settingsManager.printAllRulesToLog())). then(argument("first",word()). executes( (c)-> test(c, getString(c, "first")+" 1"))). then(argument("second", word()). diff --git a/src/main/java/carpet/mixins/HopperBlockEntityMixin.java b/src/main/java/carpet/mixins/HopperBlockEntityMixin.java index a82b65c8..e2bfb957 100644 --- a/src/main/java/carpet/mixins/HopperBlockEntityMixin.java +++ b/src/main/java/carpet/mixins/HopperBlockEntityMixin.java @@ -45,9 +45,12 @@ public abstract class HopperBlockEntityMixin extends LootableContainerBlockEntit DyeColor wool_color = WoolTool.getWoolColorAtPosition( getWorld(), new BlockPos(getHopperX(), getHopperY(), getHopperZ()).offset(this.getCachedState().get(HopperBlock.FACING))); - if (wool_color != null) { - for (int i = 0; i < this.getInvSize(); ++i) { - if (!this.getInvStack(i).isEmpty()) { + if (wool_color != null) + { + for (int i = 0; i < this.getInvSize(); ++i) + { + if (!this.getInvStack(i).isEmpty()) + { ItemStack itemstack = this.getInvStack(i);//.copy(); HopperCounter.COUNTERS.get(wool_color).add(this.getWorld().getServer(), itemstack); this.setInvStack(i, ItemStack.EMPTY); diff --git a/src/main/java/carpet/mixins/TntBlockMixin.java b/src/main/java/carpet/mixins/TntBlockMixin.java index 608f3c2f..a220f9a9 100644 --- a/src/main/java/carpet/mixins/TntBlockMixin.java +++ b/src/main/java/carpet/mixins/TntBlockMixin.java @@ -11,11 +11,11 @@ import org.spongepowered.asm.mixin.injection.Redirect; @Mixin(TntBlock.class) public abstract class TntBlockMixin { - // Add carpet rule check for TNTDoNotUpdate to an if statement. + // Add carpet rule check for tntDoNotUpdate to an if statement. @Redirect(method = "onBlockAdded", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/World;isReceivingRedstonePower(Lnet/minecraft/util/math/BlockPos;)Z")) private boolean isTNTDoNotUpdate(World world, BlockPos blockPos) { - return !CarpetSettings.TNTDoNotUpdate && world.isReceivingRedstonePower(blockPos); + return !CarpetSettings.tntDoNotUpdate && world.isReceivingRedstonePower(blockPos); } } diff --git a/src/main/java/carpet/settings/CarpetSettings.java b/src/main/java/carpet/settings/CarpetSettings.java index 552d01f8..2a36bbd2 100644 --- a/src/main/java/carpet/settings/CarpetSettings.java +++ b/src/main/java/carpet/settings/CarpetSettings.java @@ -10,11 +10,11 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import static carpet.settings.RuleCategory.BUGFIX; -import static carpet.settings.RuleCategory.COMMANDS; +import static carpet.settings.RuleCategory.COMMAND; import static carpet.settings.RuleCategory.CREATIVE; import static carpet.settings.RuleCategory.EXPERIMENTAL; import static carpet.settings.RuleCategory.FEATURE; -import static carpet.settings.RuleCategory.OPTIMIZATIONS; +import static carpet.settings.RuleCategory.OPTIMIZATION; import static carpet.settings.RuleCategory.SURVIVAL; public class CarpetSettings @@ -98,7 +98,7 @@ public class CarpetSettings @Rule( desc = "Lag optimizations for redstone dust", extra = "by Theosib", - category = {EXPERIMENTAL, OPTIMIZATIONS}, + category = {EXPERIMENTAL, OPTIMIZATION}, validate = Validator.WIP.class ) public static boolean fastRedstoneDust = false; @@ -113,7 +113,7 @@ public class CarpetSettings public static boolean unloadedEntityFix = false; @Rule( desc = "TNT doesn't update when placed against a power source", category = CREATIVE ) - public static boolean TNTDoNotUpdate = false; + public static boolean tntDoNotUpdate = false; @Rule( desc = "Prevents players from rubberbanding when moving too fast", @@ -145,7 +145,7 @@ public class CarpetSettings "Counters are global and shared between players, 16 channels available", "Items counted are destroyed, count up to one stack per tick per hopper" }, - category = {COMMANDS, CREATIVE, FEATURE} + category = {COMMAND, CREATIVE, FEATURE} ) public static boolean hopperCounters = false; @@ -164,19 +164,19 @@ public class CarpetSettings @Rule( desc = "summoning a lightning bolt has all the side effects of natural lightning", category = CREATIVE ) public static boolean summonNaturalLightning = false; - @Rule(desc = "Enables /spawn command for spawn tracking", category = COMMANDS) + @Rule(desc = "Enables /spawn command for spawn tracking", category = COMMAND) public static boolean commandSpawn = true; - @Rule(desc = "Enables /tick command to control game clocks", category = COMMANDS) + @Rule(desc = "Enables /tick command to control game clocks", category = COMMAND) public static boolean commandTick = true; - @Rule(desc = "Enables /log command to monitor events in the game via chat and overlays", category = COMMANDS) + @Rule(desc = "Enables /log command to monitor events in the game via chat and overlays", category = COMMAND) public static boolean commandLog = true; @Rule( desc = "Enables /distance command to measure in game distance between points", extra = "Also enables brown carpet placement action if 'carpets' rule is turned on as well", - category = COMMANDS + category = COMMAND ) public static boolean commandDistance = true; @@ -186,31 +186,31 @@ public class CarpetSettings "Also enables gray carpet placement action", "if 'carpets' rule is turned on as well" }, - category = COMMANDS + category = COMMAND ) public static boolean commandInfo = true; @Rule( desc = "Enables /c and /s commands to quickly switch between camera and survival modes", extra = "/c and /s commands are available to all players regardless of their permission levels", - category = COMMANDS + category = COMMAND ) public static boolean commandCameramode = true; @Rule( desc = "Enables /perimeterinfo command", extra = "... that scans the area around the block for potential spawnable spots", - category = COMMANDS + category = COMMAND ) public static boolean commandPerimeterInfo = true; - @Rule(desc = "Enables /draw commands", extra = "... allows for drawing simple shapes", category = COMMANDS) + @Rule(desc = "Enables /draw commands", extra = "... allows for drawing simple shapes", category = COMMAND) public static boolean commandDraw = true; - @Rule(desc = "Enables /script command", extra = "an in-game scripting API", category = COMMANDS) + @Rule(desc = "Enables /script command", extra = "An in-game scripting API for Scarpet programming language", category = COMMAND) public static boolean commandScript = true; - @Rule(desc = "Enables /player command to control/spawn players", category = COMMANDS, validate = Validator.WIP.class) + @Rule(desc = "Enables /player command to control/spawn players", category = COMMAND, validate = Validator.WIP.class) public static boolean commandPlayer = true; @Rule(desc = "Placing carpets may issue carpet commands for non-op players", category = SURVIVAL) @@ -226,16 +226,18 @@ public class CarpetSettings @Rule(desc = "Alternative, persistent caching strategy for nether portals", category = {SURVIVAL, CREATIVE}) public static boolean portalCaching = false; - @Rule(desc = "Permanent fires don't schedule random updates", category = OPTIMIZATIONS, validate = Validator.WIP.class) + @Rule(desc = "Permanent fires don't schedule random updates", category = OPTIMIZATION, validate = Validator.WIP.class) public static boolean calmNetherFires = false; @Rule(desc = "fill/clone/setblock and structure blocks cause block updates", category = CREATIVE) public static boolean fillUpdates = true; private static class PushLimitLimits extends Validator { - @Override Integer validate(ServerCommandSource source, ParsedRule currentRule, Integer newValue, String string) { - return (newValue>0 && newValue < 1024) ? newValue : null; + @Override public Integer validate(ServerCommandSource source, ParsedRule currentRule, Integer newValue, String string) { + return (newValue>0 && newValue <= 1024) ? newValue : null; } + @Override + public String description() { return "You must choose a value from 1 to 1024";} } @Rule( desc = "Customizable piston push limit", @@ -254,9 +256,11 @@ public class CarpetSettings public static int railPowerLimit = 9; private static class FillLimitLimits extends Validator { - @Override Integer validate(ServerCommandSource source, ParsedRule currentRule, Integer newValue, String string) { + @Override public Integer validate(ServerCommandSource source, ParsedRule currentRule, Integer newValue, String string) { return (newValue>0 && newValue < 20000000) ? newValue : null; } + @Override + public String description() { return "You must choose a value from 1 to 20M";} } @Rule( desc = "Customizable fill/clone volume limit", @@ -269,7 +273,7 @@ public class CarpetSettings @Rule( desc = "Customizable maximal entity collision limits, 0 for no limits", options = {"0", "1", "20"}, - category = OPTIMIZATIONS, + category = OPTIMIZATION, validate = Validator.NONNEGATIVE_NUMBER.class ) public static int maxEntityCollisions = 0; @@ -278,7 +282,7 @@ public class CarpetSettings public static boolean onePlayerSleeping = false; private static class SetMotd extends Validator { - @Override String validate(ServerCommandSource source, ParsedRule currentRule, String newValue, String string) { + @Override public String validate(ServerCommandSource source, ParsedRule currentRule, String newValue, String string) { customMOTD = newValue; // accelerate a smidge ((MinecraftServer_motdInterface) CarpetServer.minecraft_server).checkMOTD(); return newValue; @@ -298,7 +302,7 @@ public class CarpetSettings private static class ViewDistanceValidator extends Validator { - @Override Integer validate(ServerCommandSource source, ParsedRule currentRule, Integer newValue, String string) + @Override public Integer validate(ServerCommandSource source, ParsedRule currentRule, Integer newValue, String string) { if (newValue < 0 || newValue > 32) { @@ -320,6 +324,8 @@ public class CarpetSettings return 0; } } + @Override + public String description() { return "You must choose a value from 0 (use server settings) to 32";} } @Rule( desc = "Changes the view distance of the server.", @@ -331,7 +337,7 @@ public class CarpetSettings public static int viewDistance = 0; private static class DisableSpawnChunksValidator extends Validator { - @Override Boolean validate(ServerCommandSource source, ParsedRule currentRule, Boolean newValue, String string) { + @Override public Boolean validate(ServerCommandSource source, ParsedRule currentRule, Boolean newValue, String string) { if (!newValue) Messenger.m(source, "w Spawn chunks re-enabled. Visit spawn to load them?"); return newValue; @@ -344,10 +350,13 @@ public class CarpetSettings ) public static boolean disableSpawnChunks = false; - private static class KelpLimit extends Validator { - @Override Integer validate(ServerCommandSource source, ParsedRule currentRule, Integer newValue, String string) { + private static class KelpLimit extends Validator + { + @Override public Integer validate(ServerCommandSource source, ParsedRule currentRule, Integer newValue, String string) { return (newValue>=0 && newValue <=25)?newValue:null; } + @Override + public String description() { return "You must choose a value from 0 to 25. 25 and all natural kelp can grow 25 blocks, choose 0 to make all generated kelp not to grow";} } @Rule( desc = "limits growth limit of newly naturally generated kelp to this amount of blocks", @@ -371,7 +380,6 @@ public class CarpetSettings ) public static boolean leadFix = false; - @Rule(desc = "Spawning requires much less CPU and Memory", category = OPTIMIZATIONS) + @Rule(desc = "Spawning requires much less CPU and Memory", category = OPTIMIZATION) public static boolean lagFreeSpawning = false; - } diff --git a/src/main/java/carpet/settings/ParsedRule.java b/src/main/java/carpet/settings/ParsedRule.java index 859d9270..3cc1b974 100644 --- a/src/main/java/carpet/settings/ParsedRule.java +++ b/src/main/java/carpet/settings/ParsedRule.java @@ -25,17 +25,22 @@ public final class ParsedRule implements Comparable { public final T defaultValue; public final String defaultAsString; - public static T callConstructor(Class cls) { - try { + public static T callConstructor(Class cls) + { + try + { Constructor constr = cls.getDeclaredConstructor(); constr.setAccessible(true); return constr.newInstance(); - } catch (ReflectiveOperationException e) { + } + catch (ReflectiveOperationException e) + { throw new RuntimeException(e); } } - ParsedRule(Field field, Rule rule) { + ParsedRule(Field field, Rule rule) + { this.field = field; this.name = rule.name().isEmpty() ? field.getName() : rule.name(); this.type = (Class) field.getType(); @@ -45,10 +50,8 @@ public final class ParsedRule implements Comparable { this.categories = ImmutableList.copyOf(rule.category()); this.validators = new ArrayList<>(); for (Class v : rule.validate()) - { this.validators.add((Validator) callConstructor(v)); - } - if (categories.contains(RuleCategory.COMMANDS)) + if (categories.contains(RuleCategory.COMMAND)) this.validators.add(callConstructor(Validator._COMMAND.class)); this.defaultValue = get(); this.defaultAsString = convertToString(this.defaultValue); diff --git a/src/main/java/carpet/settings/Rule.java b/src/main/java/carpet/settings/Rule.java index 62a54bab..b4c5b316 100644 --- a/src/main/java/carpet/settings/Rule.java +++ b/src/main/java/carpet/settings/Rule.java @@ -17,7 +17,8 @@ import java.lang.annotation.Target; */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) -@interface Rule { +@interface Rule +{ /** * The rule name, by default the same as the field name */ diff --git a/src/main/java/carpet/settings/RuleCategory.java b/src/main/java/carpet/settings/RuleCategory.java index fbb952bc..c5da5add 100644 --- a/src/main/java/carpet/settings/RuleCategory.java +++ b/src/main/java/carpet/settings/RuleCategory.java @@ -1,12 +1,13 @@ package carpet.settings; -public class RuleCategory { +public class RuleCategory +{ public static final String BUGFIX = "bugfix"; public static final String SURVIVAL = "survival"; public static final String CREATIVE = "creative"; public static final String EXPERIMENTAL = "experimental"; - public static final String OPTIMIZATIONS = "optimizations"; + public static final String OPTIMIZATION = "optimization"; public static final String FEATURE = "feature"; - public static final String COMMANDS = "commands"; + public static final String COMMAND = "command"; } diff --git a/src/main/java/carpet/settings/SettingsManager.java b/src/main/java/carpet/settings/SettingsManager.java index 435f7b47..80225f2d 100644 --- a/src/main/java/carpet/settings/SettingsManager.java +++ b/src/main/java/carpet/settings/SettingsManager.java @@ -11,10 +11,10 @@ import org.apache.logging.log4j.Logger; import java.io.*; import java.lang.reflect.Field; import java.util.*; -import java.util.function.Predicate; import java.util.stream.Collectors; -public class SettingsManager { +public class SettingsManager +{ private static final Logger LOG = LogManager.getLogger(); private static Map> rules = new HashMap<>(); public boolean locked; @@ -46,11 +46,13 @@ public class SettingsManager { } - public ParsedRule getRule(String name) { + public ParsedRule getRule(String name) + { return rules.get(name); } - public static Collection> getRules() { + public static Collection> getRules() + { CarpetSettings.LOG.error("grabbing rules"); List> r = rules.values().stream().sorted().collect(Collectors.toList()); CarpetSettings.LOG.error("Got: "+r.size()+" rules"); @@ -65,17 +67,22 @@ public class SettingsManager { } - public Collection> getNonDefault() { + public Collection> getNonDefault() + { return rules.values().stream().filter(r -> !r.isDefault()).sorted().collect(Collectors.toList()); } - private File getFile() { + private File getFile() + { return server.getLevelStorage().resolveFile(server.getLevelName(), "carpet.conf"); } - public void disableBooleanFromCategory(String category) { - for (ParsedRule rule : rules.values()) { - if (rule.type != boolean.class || !rule.categories.contains(category)) continue; + public void disableBooleanFromCategory(String category) + { + for (ParsedRule rule : rules.values()) + { + if (rule.type != boolean.class || !rule.categories.contains(category)) + continue; ((ParsedRule) rule).set(server.getCommandSource(), false, "false"); } } @@ -84,7 +91,8 @@ public class SettingsManager { private void writeSettingsToConf(Map values) { - if (locked) return; + if (locked) + return; try { FileWriter fw = new FileWriter(getFile()); @@ -122,7 +130,7 @@ public class SettingsManager { if (conf.getRight()) { LOG.info("[CM]: Carpet Mod is locked by the administrator"); - disableBooleanFromCategory(RuleCategory.COMMANDS); + disableBooleanFromCategory(RuleCategory.COMMAND); } for (String key: conf.getLeft().keySet()) { @@ -158,8 +166,6 @@ public class SettingsManager { } ParsedRule rule = rules.get(fields[0]); - - if (!(rule.options.contains(fields[1])) && rule.isStrict) { LOG.error("[CM]: The value of " + fields[1] + " for " + fields[0] + " is not valid - ignoring..."); @@ -213,16 +219,48 @@ public class SettingsManager { return false; } - public Collection> getRulesMatching(Predicate> predicate) { - return rules.values().stream().filter(predicate).collect(ImmutableList.toImmutableList()); - } - public Collection> getRulesMatching(String search) { String lcSearch = search.toLowerCase(Locale.ROOT); - return getRulesMatching(rule -> { + return rules.values().stream().filter(rule -> + { if (rule.name.toLowerCase(Locale.ROOT).contains(lcSearch)) return true; for (String c : rule.categories) if (c.toLowerCase(Locale.ROOT).equals(search)) return true; return false; - }); + }).collect(ImmutableList.toImmutableList()); } + + public int printAllRulesToLog() + { + PrintStream ps = System.out; + ps.println("# Carpet Settings"); + for (Map.Entry> e : new TreeMap<>(rules).entrySet()) + { + ParsedRule rule = e.getValue(); + ps.println("## " + rule.name); + ps.println(rule.description+" "); + for (String extra : rule.extraInfo) + ps.println(extra + " "); + ps.println("* Type: `" + rule.type.getSimpleName() + "` "); + ps.println("* Default value: `" + rule.defaultAsString + "` "); + String optionString = rule.options.stream().map(s -> "`" + s + "`").collect(Collectors.joining(", ")); + ps.println((rule.isStrict?"* Required":"* Suggested")+" options: " + optionString + " "); + ps.println("* Categories: " + rule.categories.stream().map(s -> "`" + s.toUpperCase(Locale.ROOT) + "`").collect(Collectors.joining(", ")) + " "); + boolean preamble = false; + for (Validator validator : rule.validators) + { + if(validator.description() != null) + { + if (!preamble) + { + ps.println("* Additional notes: "); + preamble = true; + } + ps.println(" * "+validator.description()+" "); + } + } + ps.println(" "); + } + return 1; + } + } diff --git a/src/main/java/carpet/settings/Validator.java b/src/main/java/carpet/settings/Validator.java index dc924a3e..98d6f084 100644 --- a/src/main/java/carpet/settings/Validator.java +++ b/src/main/java/carpet/settings/Validator.java @@ -6,35 +6,44 @@ import net.minecraft.server.command.ServerCommandSource; import java.util.Locale; -public abstract class Validator { +public abstract class Validator +{ /** * Validate the new value of a rule * @return true if valid, false if new rule invalid. */ - abstract T validate(ServerCommandSource source, ParsedRule currentRule, T newValue, String string); + public abstract T validate(ServerCommandSource source, ParsedRule currentRule, T newValue, String string); + public String description() {return null;} - - public static class POSITIVE_NUMBER extends Validator { + public static class POSITIVE_NUMBER extends Validator + { @Override - public T validate(ServerCommandSource source, ParsedRule currentRule, T newValue, String string) { + public T validate(ServerCommandSource source, ParsedRule currentRule, T newValue, String string) + { return newValue.doubleValue() > 0 ? newValue : null; } + @Override + public String description() { return "Must be a positive number"; } } - - - public static class _COMMAND extends Validator { + public static class _COMMAND extends Validator + { @Override - public T validate(ServerCommandSource source, ParsedRule currentRule, T newValue, String string) { + public T validate(ServerCommandSource source, ParsedRule currentRule, T newValue, String string) + { if (CarpetServer.settingsManager != null) CarpetServer.settingsManager.notifyPlayersCommandsChanged(); return newValue; } + @Override + public String description() { return "It has an accompanying command";} } - public static class WIP extends Validator { + public static class WIP extends Validator + { @Override - public T validate(ServerCommandSource source, ParsedRule currentRule, T newValue, String string) { + public T validate(ServerCommandSource source, ParsedRule currentRule, T newValue, String string) + { if (source != null) try { @@ -43,10 +52,14 @@ public abstract class Validator { catch (NullPointerException ignored) { } return newValue; } - } - public static class _STRICT extends Validator { @Override - public T validate(ServerCommandSource source, ParsedRule currentRule, T newValue, String string) { + public String description() { return "Its not yet fully implemented - we are working on it";} + } + public static class _STRICT extends Validator + { + @Override + public T validate(ServerCommandSource source, ParsedRule currentRule, T newValue, String string) + { if (!currentRule.options.contains(string.toLowerCase(Locale.ROOT))) { if (source != null) @@ -63,10 +76,14 @@ public abstract class Validator { } } - public static class NONNEGATIVE_NUMBER extends Validator { + public static class NONNEGATIVE_NUMBER extends Validator + { @Override - public T validate(ServerCommandSource source, ParsedRule currentRule, T newValue, String string) { + public T validate(ServerCommandSource source, ParsedRule currentRule, T newValue, String string) + { return newValue.doubleValue() >= 0 ? newValue : null; } + @Override + public String description() { return "Must be a positive number";} } } From e8fbf3aadc9f77509d25c224d14681a7b4b07bb2 Mon Sep 17 00:00:00 2001 From: gnembon Date: Wed, 12 Jun 2019 01:29:24 -0300 Subject: [PATCH 7/7] add observers --- src/main/java/carpet/settings/ParsedRule.java | 34 +++++++++--------- .../java/carpet/settings/SettingsManager.java | 36 +++++++++++++++---- 2 files changed, 48 insertions(+), 22 deletions(-) diff --git a/src/main/java/carpet/settings/ParsedRule.java b/src/main/java/carpet/settings/ParsedRule.java index 3cc1b974..b0f0073e 100644 --- a/src/main/java/carpet/settings/ParsedRule.java +++ b/src/main/java/carpet/settings/ParsedRule.java @@ -25,20 +25,6 @@ public final class ParsedRule implements Comparable { public final T defaultValue; public final String defaultAsString; - public static T callConstructor(Class cls) - { - try - { - Constructor constr = cls.getDeclaredConstructor(); - constr.setAccessible(true); - return constr.newInstance(); - } - catch (ReflectiveOperationException e) - { - throw new RuntimeException(e); - } - } - ParsedRule(Field field, Rule rule) { this.field = field; @@ -73,6 +59,19 @@ public final class ParsedRule implements Comparable { this.validators.add(callConstructor(Validator._STRICT.class)); } + private T callConstructor(Class cls) + { + try + { + Constructor constr = cls.getDeclaredConstructor(); + constr.setAccessible(true); + return constr.newInstance(); + } + catch (ReflectiveOperationException e) + { + throw new RuntimeException(e); + } + } public ParsedRule set(ServerCommandSource source, String value) { @@ -115,8 +114,11 @@ public final class ParsedRule implements Comparable { return null; } } - this.field.set(null, value); - + if (!value.equals(get())) + { + this.field.set(null, value); + SettingsManager.notifyRuleChanged(this, stringValue); + } } catch (IllegalAccessException e) { diff --git a/src/main/java/carpet/settings/SettingsManager.java b/src/main/java/carpet/settings/SettingsManager.java index 80225f2d..091ad7c1 100644 --- a/src/main/java/carpet/settings/SettingsManager.java +++ b/src/main/java/carpet/settings/SettingsManager.java @@ -8,9 +8,24 @@ import org.apache.commons.lang3.tuple.Pair; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import java.io.*; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.PrintStream; import java.lang.reflect.Field; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.function.BiConsumer; import java.util.stream.Collectors; public class SettingsManager @@ -18,7 +33,8 @@ public class SettingsManager private static final Logger LOG = LogManager.getLogger(); private static Map> rules = new HashMap<>(); public boolean locked; - MinecraftServer server; + private MinecraftServer server; + private static List, String>> observers = new ArrayList<>(); public SettingsManager(MinecraftServer server) { @@ -26,7 +42,6 @@ public class SettingsManager loadConfigurationFromConf(); } - public static void parseSettingsClass(Class settingsClass) { for (Field f : settingsClass.getDeclaredFields()) @@ -38,6 +53,16 @@ public class SettingsManager } } + public static void addRuleObserver(BiConsumer, String> observer) + { + observers.add(observer); + } + + static void notifyRuleChanged(ParsedRule rule, String userTypedValue) + { + observers.forEach(observer -> observer.accept(rule, userTypedValue)); + } + public static Iterable getCategories() { Set categories = new HashSet<>(); @@ -88,7 +113,6 @@ public class SettingsManager } - private void writeSettingsToConf(Map values) { if (locked) @@ -141,7 +165,7 @@ public class SettingsManager } - public Pair,Boolean> readSettingsFromConf() + private Pair,Boolean> readSettingsFromConf() { try {