Skip to content

Commit

Permalink
Merge branch 'rewrite' into rewrite
Browse files Browse the repository at this point in the history
  • Loading branch information
maghedo243 authored Dec 31, 2023
2 parents 5abac36 + 9d01295 commit a373cd6
Show file tree
Hide file tree
Showing 16 changed files with 108 additions and 97 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,24 @@

import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.command.CommandRegistryAccess;
import net.minecraft.command.argument.BlockStateArgument;
import net.minecraft.command.argument.BlockStateArgumentType;
import net.minecraft.registry.Registry;
import net.minecraft.state.property.Property;
import net.minecraft.registry.Registries;

public class BlockStateArgumentSerializer extends BrigadierSerializer<BlockStateArgument, String> {

private static final BlockStateArgumentSerializer INSTANCE = new BlockStateArgumentSerializer();
private static BlockStateArgumentSerializer INSTANCE;

private BlockStateArgumentSerializer() {
super(BlockStateArgument.class, BlockStateArgumentType.blockState());
private BlockStateArgumentSerializer(CommandRegistryAccess registryAccess) {
super(BlockStateArgument.class, BlockStateArgumentType.blockState(registryAccess));
}

public static BlockStateArgumentSerializer blockState() {
public static BlockStateArgumentSerializer blockState(CommandRegistryAccess registryAccess) {
if (INSTANCE == null) {
INSTANCE = new BlockStateArgumentSerializer(registryAccess);
}

return INSTANCE;
}

Expand All @@ -36,7 +38,7 @@ public String serialize(BlockStateArgument value) {
var block = state.getBlock();

var builder = new StringBuilder()
.append(Registry.BLOCK.getId(block));
.append(Registries.BLOCK.getId(block));

if (state.getProperties().size() == 0) {
return builder.toString();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,23 +58,24 @@ private T deserializeUnchecked(String serialized) {
return tryParse(serialized);
}

if(serialized.charAt(0) == '-' && serialized.chars().filter(ch -> ch == '-').count() == 1){
if (serialized.charAt(0) == '-' && serialized.chars().filter(ch -> ch == '-').count() == 1) {
isNegative = true;
serialized = serialized.replace("-","");
serialized = serialized.replace("-", "");
}

if (serialized.charAt(0) == '0') {
if(serialized.length() > 1) {
if (serialized.length() > 1) {
var prefixedBase = serialized.substring(0, 2);
var number = serialized.substring(2);

var numberBase = NumberBase.fromPrefix(prefixedBase).orElse(null);

if (numberBase != null) {
return isNegative ? tryParse("-" + number, numberBase.toInt()) : tryParse(number, numberBase.toInt());
return isNegative ? tryParse("-" + number, numberBase.toInt())
: tryParse(number, numberBase.toInt());
}
} else {
return tryParse(serialized,10);
return tryParse(serialized, 10);
}
}

Expand All @@ -93,10 +94,10 @@ private T deserializeUnchecked(String serialized) {
throw new IllegalArgumentException("Invalid base '" + parts[1] + "'.");
}

return isNegative ? tryParse("-"+number, base) : tryParse(number, base);
return isNegative ? tryParse("-" + number, base) : tryParse(number, base);
}

return isNegative ? tryParse("-"+serialized) : tryParse(serialized);
return isNegative ? tryParse("-" + serialized) : tryParse(serialized);
}

private T tryParse(String string) {
Expand All @@ -106,8 +107,8 @@ private T tryParse(String string) {
private T tryParse(String string, int radix) {
return tryParseOptional(string, radix)
.orElseThrow(() -> new IllegalArgumentException(radix == 10
? "Invalid number '" + string + "'."
: "Invalid base " + radix + " number '" + string + "'."));
? "Invalid number '" + string + "'."
: "Invalid base " + radix + " number '" + string + "'."));
}

protected abstract Optional<T> tryParseOptional(String string, int radix);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,21 +27,19 @@
import static tools.redstone.redstonetools.features.arguments.serializers.NumberBaseSerializer.numberBase;



@AutoService(AbstractFeature.class)
@Feature(name = "Binary Block Read", description = "Interprets your WorldEdit selection as a binary number.", command = "/read", worldedit = true)
public class BinaryBlockReadFeature extends CommandFeature {
private static final BlockStateArgument LIT_LAMP_ARG = new BlockStateArgument(
Blocks.REDSTONE_LAMP.getDefaultState().with(RedstoneLampBlock.LIT, true),
Collections.singleton(RedstoneLampBlock.LIT),
null
);
null);

public static final Argument<Integer> offset = Argument
.ofType(integer(1))
.withDefault(2);
public static final Argument<BlockStateArgument> onBlock = Argument
.ofType(blockState())
.ofType(blockState(REGISTRY_ACCESS))
.withDefault(LIT_LAMP_ARG);
public static final Argument<Integer> toBase = Argument
.ofType(numberBase())
Expand Down Expand Up @@ -105,4 +103,4 @@ protected Feedback execute(ServerCommandSource source) throws CommandSyntaxExcep
return Feedback.success("{}.", output);
}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import net.minecraft.client.option.KeyBinding;
import net.minecraft.client.util.InputUtil;
import net.minecraft.command.CommandRegistryAccess;
import net.minecraft.registry.BuiltinRegistries;
import net.minecraft.server.command.CommandManager;
import tools.redstone.redstonetools.features.AbstractFeature;
import tools.redstone.redstonetools.features.Feature;
Expand All @@ -16,15 +17,17 @@
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.text.Text;

import java.util.ArrayList;
import java.util.List;

import static tools.redstone.redstonetools.RedstoneToolsClient.INJECTOR;


public abstract class CommandFeature extends AbstractFeature {
private static final List<KeyBinding> keyBindings = new ArrayList<>();
protected static final CommandRegistryAccess REGISTRY_ACCESS = CommandManager
.createRegistryAccess(BuiltinRegistries.createWrapperLookup());

@Override
public void register() {
Expand All @@ -41,21 +44,21 @@ public void register() {
info.name(),
InputUtil.Type.KEYSYM,
-1,
"Redstone Tools"
));
"Redstone Tools"));

keyBindings.add(keyBinding);

ClientTickEvents.END_CLIENT_TICK.register(client -> {
while (keyBinding.wasPressed()) {
assert client.player != null;
client.player.sendChatMessage("/" + info.command());
client.player.sendMessage(Text.literal("/" + info.command()));
}
});
}

@Override
protected void registerCommands(CommandDispatcher<ServerCommandSource> dispatcher, CommandRegistryAccess registryAccess, CommandManager.RegistrationEnvironment environment) {
protected void registerCommands(CommandDispatcher<ServerCommandSource> dispatcher,
CommandRegistryAccess registryAccess, CommandManager.RegistrationEnvironment environment) {
var info = ReflectionUtils.getFeatureInfo(getClass());
var arguments = ReflectionUtils.getArguments(getClass());

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@ protected Feedback execute(ServerCommandSource source) throws CommandSyntaxExcep
if (isEmpty) {
return Feedback.invalidUsage("Cannot minimize empty selections.");
}


minimiseSelection(selectionWorld, selection);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
import static tools.redstone.redstonetools.features.arguments.serializers.FloatSerializer.floatArg;



@AutoService(AbstractFeature.class)
@Feature(name = "Quick TP", description = "Teleports you in the direction you are looking.", command = "quicktp")
public class QuickTpFeature extends CommandFeature {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,15 +76,13 @@ public Mask2D toMask2D() {

var stackVector = directionToBlock(stackDirection);


try (var editSession = localSession.createEditSession(actor)) {
for (var i = 1; i <= count.getValue(); i++) {
var copy = new ForwardExtentCopy(
editSession,
selection,
editSession,
selection.getMinimumPoint().add(stackVector.multiply(i * offset.getValue()))
);
selection.getMinimumPoint().add(stackVector.multiply(i * offset.getValue())));
copy.setSourceMask(airFilter);
Operations.complete(copy);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,14 +51,14 @@ public abstract class ToggleableFeature extends AbstractFeature {
@Override
public void register() {
super.register();

// load user settings
// and register save hook
loadConfig();
ClientLifecycleEvents.CLIENT_STOPPING.register(client -> {
saveConfig();
});

var containsRequiredArguments = ReflectionUtils.getArguments(getClass()).stream()
.anyMatch(a -> !a.isOptional());
if (containsRequiredArguments) {
Expand All @@ -70,8 +70,7 @@ public void register() {
info.name(),
InputUtil.Type.KEYSYM,
-1,
"Redstone Tools"
));
"Redstone Tools"));

keyBindings.add(keyBinding);

Expand Down Expand Up @@ -99,7 +98,8 @@ public void register() {
@SuppressWarnings({ "rawtypes", "unchecked" })

@Override
protected void registerCommands(CommandDispatcher<ServerCommandSource> dispatcher, CommandRegistryAccess registryAccess, RegistrationEnvironment environment) {
protected void registerCommands(CommandDispatcher<ServerCommandSource> dispatcher,
CommandRegistryAccess registryAccess, RegistrationEnvironment environment) {
var baseCommand = literal(getCommand())
.executes(this::toggle);

Expand All @@ -109,7 +109,8 @@ protected void registerCommands(CommandDispatcher<ServerCommandSource> dispatche
baseCommand.then(literal(name)
.executes(context -> {
Object value = argument.getValue();
return Feedback.success("Option {} of feature {} is set to: {}", name, getName(), argument.getType().serialize(value)).send(context);
return Feedback.success("Option {} of feature {} is set to: {}", name, getName(),
argument.getType().serialize(value)).send(context);
})
.then(argument("value", argument.getType()).executes(context -> {
Object value = context.getArgument("value", argument.getType().getTypeClass());
Expand All @@ -123,8 +124,7 @@ protected void registerCommands(CommandDispatcher<ServerCommandSource> dispatche
IO_EXECUTOR.execute(this::saveConfig);

return Feedback.success("Set {} to {} for feature {}", name, value, getName()).send(context);
}))
);
})));
}

dispatcher.register(baseCommand);
Expand Down Expand Up @@ -183,13 +183,16 @@ public int disable(CommandContext<ServerCommandSource> context) throws CommandSy
return disable(context.getSource());
}

protected void onEnable() { }
protected void onDisable() { }
protected void onEnable() {
}

protected void onDisable() {
}

// todo: right now the configuration methods are assuming every
// type is serialized to a string, this should be fixed in the future
// but for now it works because every type right now serializes to a string
// + it will probably be refactored soon
// type is serialized to a string, this should be fixed in the future
// but for now it works because every type right now serializes to a string
// + it will probably be refactored soon

/** Reloads the configuration from the disk. */
@SuppressWarnings({ "rawtypes", "unchecked" })
Expand Down Expand Up @@ -217,9 +220,11 @@ public void loadConfig() {

setEnabled(enabled);

RedstoneToolsClient.LOGGER.info("Loaded configuration for feature " + getID() + " file(" + configFile + ")");
RedstoneToolsClient.LOGGER
.info("Loaded configuration for feature " + getID() + " file(" + configFile + ")");
} catch (Exception e) {
RedstoneToolsClient.LOGGER.error("Failed to load configuration for feature " + getID() + " file(" + configFile + ")");
RedstoneToolsClient.LOGGER
.error("Failed to load configuration for feature " + getID() + " file(" + configFile + ")");
e.printStackTrace();
}
}
Expand Down Expand Up @@ -252,7 +257,8 @@ public void saveConfig() {

RedstoneToolsClient.LOGGER.info("Saved configuration for feature " + getID() + " file(" + configFile + ")");
} catch (Exception e) {
RedstoneToolsClient.LOGGER.error("Failed to save configuration for feature " + getID() + " file(" + configFile + ")");
RedstoneToolsClient.LOGGER
.error("Failed to save configuration for feature " + getID() + " file(" + configFile + ")");
e.printStackTrace();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.json.JsonWriter;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
Expand All @@ -32,7 +31,6 @@ public MacroManager() {
.resolve("redstonetools")
.resolve("macros.json");


JsonArray macrosJson = null;
try {
Files.createDirectories(macrosFilePath.getParent());
Expand Down Expand Up @@ -135,8 +133,7 @@ private List<Macro> getDefaultMacros() {
"/gamerule doContainerDrops false",
"/time set noon",
"/weather clear"
})
);
}));
}

private Macro createCommandMacro(String name, String[] commands) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import net.minecraft.nbt.NbtCompound;
import net.minecraft.nbt.NbtElement;
import net.minecraft.nbt.NbtList;
import net.minecraft.registry.Registry;
import net.minecraft.registry.Registries;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.state.property.Property;
import net.minecraft.util.Identifier;
Expand All @@ -34,7 +34,7 @@ public static NbtCompound toNBT(BlockState state) {
}

NbtCompound root = new NbtCompound();
root.putString("Id", Registry.BLOCK.getId(state.getBlock()).toString());
root.putString("Id", Registries.BLOCK.getId(state.getBlock()).toString());

// serialize properties
if (!state.getProperties().isEmpty()) {
Expand Down Expand Up @@ -69,7 +69,7 @@ public static BlockState fromNBT(NbtCompound compound) {
// we use new Identifier(...) here to allow it to throw exceptions
// instead of getting a cryptic NPE
Identifier identifier = new Identifier(compound.getString("Id"));
Block block = Registry.BLOCK.get(identifier);
Block block = Registries.BLOCK.get(identifier);

// deserialize properties
BlockState state = block.getDefaultState();
Expand All @@ -96,7 +96,7 @@ public static BlockState fromNBT(NbtCompound compound) {
* or returns the given default if the tag is null/empty.
*
* @param compound The NBT tag.
* @param def The default.
* @param def The default.
* @return The block state or {@code def} if the tag is null/empty.
*/
public static BlockState fromNBT(NbtCompound compound, BlockState def) {
Expand Down Expand Up @@ -171,9 +171,7 @@ public static BlockState getPlacementState(ItemStack stack) {
return null;
}

BlockState def = stack.getItem() instanceof BlockItem blockItem ?
blockItem.getBlock().getDefaultState() :
null;
BlockState def = stack.getItem() instanceof BlockItem blockItem ? blockItem.getBlock().getDefaultState() : null;
return fromNBT(nbt.getCompound(EXACT_STATE_KEY), def);
}

Expand Down
Loading

0 comments on commit a373cd6

Please sign in to comment.