From 273d1435e358ae215ea676ead9461a6623575e75 Mon Sep 17 00:00:00 2001 From: Frederik van der Els Date: Fri, 20 May 2022 22:43:54 +0200 Subject: [PATCH 1/3] Use the `FabricClientCommandSource` to replace calls to other methods --- .../clientcommands/command/AliasCommand.java | 42 +++++++-------- .../command/AreaStatsCommand.java | 10 ++-- .../clientcommands/command/BookCommand.java | 9 ++-- .../command/CEnchantCommand.java | 26 ++++----- .../clientcommands/command/CGiveCommand.java | 5 +- .../command/CParticleCommand.java | 16 +++--- .../command/CPlaySoundCommand.java | 24 ++++----- .../command/CStopSoundCommand.java | 19 +++---- .../command/CTeleportCommand.java | 10 ++-- .../command/CTellRawCommand.java | 15 ++---- .../clientcommands/command/CTimeCommand.java | 51 ++++++++---------- .../clientcommands/command/CalcCommand.java | 4 +- .../command/CalcStackCommand.java | 17 +++--- .../command/ClientCommandHelper.java | 12 ----- .../command/CrackRNGCommand.java | 3 +- .../command/FakeCommandSource.java | 3 +- .../command/FindBlockCommand.java | 20 +++---- .../clientcommands/command/FindCommand.java | 8 +-- .../command/FindItemCommand.java | 53 ++++++++++-------- .../clientcommands/command/FishCommand.java | 43 +++++++-------- .../clientcommands/command/FovCommand.java | 6 +-- .../clientcommands/command/GammaCommand.java | 6 +-- .../command/GetDataCommand.java | 11 ++-- .../command/GhostBlockCommand.java | 22 ++++---- .../clientcommands/command/GlowCommand.java | 7 ++- .../clientcommands/command/HotbarCommand.java | 19 ++++--- .../command/ItemGroupCommand.java | 17 +++--- .../clientcommands/command/KitCommand.java | 33 ++++++------ .../clientcommands/command/LookCommand.java | 29 +++++----- .../clientcommands/command/NoteCommand.java | 3 +- .../command/PermissionLevelCommand.java | 11 +--- .../clientcommands/command/PingCommand.java | 13 ++--- .../command/PlayerInfoCommand.java | 54 +++++++++---------- .../clientcommands/command/RenderCommand.java | 4 +- .../clientcommands/command/ShrugCommand.java | 7 ++- .../clientcommands/command/TaskCommand.java | 23 ++++---- .../command/TempRuleCommand.java | 11 ++-- .../command/UsageTreeCommand.java | 21 ++++---- .../clientcommands/command/UuidCommand.java | 23 +++----- .../clientcommands/command/WikiCommand.java | 5 +- 40 files changed, 317 insertions(+), 398 deletions(-) diff --git a/src/main/java/net/earthcomputer/clientcommands/command/AliasCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/AliasCommand.java index e6c61f3f9..835441b5c 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/AliasCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/AliasCommand.java @@ -12,7 +12,7 @@ import net.earthcomputer.clientcommands.features.BrigadierRemover; import net.fabricmc.fabric.api.client.command.v1.FabricClientCommandSource; import net.fabricmc.loader.api.FabricLoader; -import net.minecraft.client.MinecraftClient; +import net.minecraft.text.Text; import net.minecraft.text.TranslatableText; import net.minecraft.util.Formatting; import org.slf4j.Logger; @@ -25,7 +25,6 @@ import java.util.regex.Pattern; import static com.mojang.brigadier.arguments.StringArgumentType.*; -import static net.earthcomputer.clientcommands.command.ClientCommandHelper.*; import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.*; public class AliasCommand { @@ -47,26 +46,26 @@ public static void register(CommandDispatcher dispatc .then(literal("add") .then(argument("key", string()) .then(argument("command", greedyString()) - .executes(ctx -> addAlias(getString(ctx, "key"), getString(ctx, "command")))))) + .executes(ctx -> addAlias(ctx.getSource(), getString(ctx, "key"), getString(ctx, "command")))))) .then(literal("list") - .executes(ctx -> listAliases())) + .executes(ctx -> listAliases(ctx.getSource()))) .then(literal("remove") .then(argument("key", string()) - .executes(ctx -> removeAlias(getString(ctx, "key")))))); + .executes(ctx -> removeAlias(ctx.getSource(), getString(ctx, "key")))))); - for (String key: aliasMap.keySet()) { + for (String key : aliasMap.keySet()) { if (dispatcher.getRoot().getChildren().stream().map(CommandNode::getName).noneMatch(literal -> literal.equals(key))) { dispatcher.register(literal(key) - .executes(ctx -> executeAliasCommand(key, null)) + .executes(ctx -> executeAliasCommand(ctx.getSource(), key, null)) .then(argument("arguments", greedyString()) - .executes(ctx -> executeAliasCommand(key, getString(ctx, "arguments"))))); + .executes(ctx -> executeAliasCommand(ctx.getSource(), key, getString(ctx, "arguments"))))); } else { LOGGER.error("Attempted to register alias /{}, but that command already exists", key); } } } - private static int executeAliasCommand(String aliasKey, String arguments) throws CommandSyntaxException { + private static int executeAliasCommand(FabricClientCommandSource source, String aliasKey, String arguments) throws CommandSyntaxException { String cmd = aliasMap.get(aliasKey); if (cmd == null) { throw NOT_FOUND_EXCEPTION.create(aliasKey); @@ -87,13 +86,12 @@ private static int executeAliasCommand(String aliasKey, String arguments) throws } else if (arguments != null){ cmd += " " + arguments; } - assert MinecraftClient.getInstance().player != null; - MinecraftClient.getInstance().player.sendChatMessage(cmd); + source.getPlayer().sendChatMessage(cmd); return 0; } - private static int addAlias(String key, String command) throws CommandSyntaxException { + private static int addAlias(FabricClientCommandSource source, String key, String command) throws CommandSyntaxException { if (aliasMap.containsKey(key)) { throw ALIAS_EXISTS_EXCEPTION.create(key); } @@ -105,29 +103,29 @@ private static int addAlias(String key, String command) throws CommandSyntaxExce } DISPATCHER.register(literal(key) - .executes(ctx -> executeAliasCommand(key, null)) + .executes(ctx -> executeAliasCommand(source, key, null)) .then(argument("arguments", greedyString()) - .executes(ctx -> executeAliasCommand(key, getString(ctx, "arguments"))))); + .executes(ctx -> executeAliasCommand(source, key, getString(ctx, "arguments"))))); aliasMap.put(key, command); saveAliases(); - sendFeedback(new TranslatableText("commands.calias.addAlias.success", key)); + source.sendFeedback(new TranslatableText("commands.calias.addAlias.success", key)); return 0; } - private static int listAliases() { + private static int listAliases(FabricClientCommandSource source) { if (aliasMap.isEmpty()) { - sendFeedback(new TranslatableText("commands.calias.listAliases.noAliasesRegistered")); + source.sendFeedback(new TranslatableText("commands.calias.listAliases.noAliasesRegistered")); } else { - sendFeedback("commands.calias.listAliases.success", aliasMap.size()); - for (String key: aliasMap.keySet()) { - sendFeedback(Formatting.BOLD + key + Formatting.RESET+ ": "+ aliasMap.get(key).replace("%","%%")); + source.sendFeedback(new TranslatableText("commands.calias.listAliases.success", aliasMap.size())); + for (String key : aliasMap.keySet()) { + source.sendFeedback(Text.of(Formatting.BOLD + key + Formatting.RESET + ": " + aliasMap.get(key).replace("%","%%"))); } } return 0; } - private static int removeAlias(String key) throws CommandSyntaxException { + private static int removeAlias(FabricClientCommandSource source, String key) throws CommandSyntaxException { if (aliasMap.containsKey(key)) { BrigadierRemover.of(DISPATCHER).get(key).remove(); aliasMap.remove(key); @@ -136,7 +134,7 @@ private static int removeAlias(String key) throws CommandSyntaxException { } saveAliases(); - sendFeedback(new TranslatableText("commands.calias.removeAlias.success", key)); + source.sendFeedback(new TranslatableText("commands.calias.removeAlias.success", key)); return 0; } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/AreaStatsCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/AreaStatsCommand.java index f4dca4064..4aabb8f3d 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/AreaStatsCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/AreaStatsCommand.java @@ -7,7 +7,6 @@ import com.mojang.brigadier.tree.LiteralCommandNode; import net.earthcomputer.clientcommands.render.RenderQueue; import net.fabricmc.fabric.api.client.command.v1.FabricClientCommandSource; -import net.minecraft.client.MinecraftClient; import net.minecraft.client.world.ClientWorld; import net.minecraft.text.TranslatableText; import net.minecraft.util.math.BlockPos; @@ -16,7 +15,6 @@ import net.minecraft.world.chunk.WorldChunk; import static dev.xpple.clientarguments.arguments.CBlockPosArgumentType.*; -import static net.earthcomputer.clientcommands.command.ClientCommandHelper.*; import static net.earthcomputer.clientcommands.command.arguments.ListArgumentType.*; import static net.earthcomputer.clientcommands.command.arguments.ClientBlockPredicateArgumentType.*; import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.*; @@ -38,7 +36,7 @@ public static void register(CommandDispatcher dispatc } private static int areaStats(FabricClientCommandSource source, BlockPos pos1, BlockPos pos2, ClientBlockPredicate blockPredicate) throws CommandSyntaxException { - final ClientWorld world = MinecraftClient.getInstance().world; + final ClientWorld world = source.getWorld(); chunkManager = world.getChunkManager(); assertChunkIsLoaded(pos1.getX() >> 4, pos1.getZ() >> 4); assertChunkIsLoaded(pos2.getX() >> 4, pos2.getZ() >> 4); @@ -164,9 +162,9 @@ private static int areaStats(FabricClientCommandSource source, BlockPos pos1, Bl long endTime = System.nanoTime(); - sendFeedback("commands.careastats.output.chunksScanned", chunks, endTime - startTime, (endTime - startTime) / 1000000); - sendFeedback("commands.careastats.output.blocksMatched", blocks, (maxX - minX + 1) * (maxY - minY + 1) * (maxZ - minZ + 1)); - sendFeedback("commands.careastats.output.entitiesFound", entities); + source.sendFeedback(new TranslatableText("commands.careastats.output.chunksScanned", chunks, endTime - startTime, (endTime - startTime) / 1000000)); + source.sendFeedback(new TranslatableText("commands.careastats.output.blocksMatched", blocks, (maxX - minX + 1) * (maxY - minY + 1) * (maxZ - minZ + 1))); + source.sendFeedback(new TranslatableText("commands.careastats.output.entitiesFound", entities)); return blocks; } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/BookCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/BookCommand.java index 5d3700442..f409c3838 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/BookCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/BookCommand.java @@ -6,9 +6,7 @@ import net.earthcomputer.multiconnect.api.MultiConnectAPI; import net.earthcomputer.multiconnect.api.Protocols; import net.fabricmc.fabric.api.client.command.v1.FabricClientCommandSource; -import net.minecraft.client.MinecraftClient; import net.minecraft.client.network.ClientPlayerEntity; -import net.minecraft.command.CommandSource; import net.minecraft.entity.player.PlayerInventory; import net.minecraft.item.ItemStack; import net.minecraft.item.Items; @@ -28,7 +26,6 @@ import static com.mojang.brigadier.arguments.IntegerArgumentType.*; import static com.mojang.brigadier.arguments.LongArgumentType.*; -import static net.earthcomputer.clientcommands.command.ClientCommandHelper.*; import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.*; public class BookCommand { @@ -73,8 +70,8 @@ private static IntStream ascii(Random rand) { return rand.ints(0x20, 0x7f); } - private static int fillBook(CommandSource source, IntStream characterGenerator, int limit) throws CommandSyntaxException { - ClientPlayerEntity player = MinecraftClient.getInstance().player; + private static int fillBook(FabricClientCommandSource source, IntStream characterGenerator, int limit) throws CommandSyntaxException { + ClientPlayerEntity player = source.getPlayer(); assert player != null; ItemStack heldItem = player.getMainHandStack(); @@ -102,7 +99,7 @@ private static int fillBook(CommandSource source, IntStream characterGenerator, heldItem.setSubNbt("pages", pagesNbt); player.networkHandler.sendPacket(new BookUpdateC2SPacket(slot, pages, Optional.empty())); - sendFeedback("commands.cbook.success"); + source.sendFeedback(new TranslatableText("commands.cbook.success")); return 0; } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/CEnchantCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/CEnchantCommand.java index abc575cc6..969f15113 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/CEnchantCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/CEnchantCommand.java @@ -33,7 +33,7 @@ private static int cenchant(FabricClientCommandSource source, ItemAndEnchantment .formatted(Formatting.RED) .append(" ") .append(getCommandTextComponent("commands.client.enable", "/ctemprule set enchantingPrediction true")); - sendFeedback(text); + source.sendFeedback(text); return 0; } if (!TempRules.playerCrackState.knowsSeed() && TempRules.enchCrackState != EnchantmentCracker.CrackState.CRACKED) { @@ -41,7 +41,7 @@ private static int cenchant(FabricClientCommandSource source, ItemAndEnchantment .formatted(Formatting.RED) .append(" ") .append(getCommandTextComponent("commands.client.crack", "/ccrackrng")); - sendFeedback(text); + source.sendFeedback(text); return 0; } @@ -53,29 +53,25 @@ private static int cenchant(FabricClientCommandSource source, ItemAndEnchantment simulate ); if (result == null) { - sendFeedback("commands.cenchant.failed"); - return 0; + source.sendFeedback(new TranslatableText("commands.cenchant.failed")); } else { - if (simulate) { if (result.itemThrows() < 0) { - sendFeedback("enchCrack.insn.itemThrows.noDummy"); + source.sendFeedback(new TranslatableText("enchCrack.insn.itemThrows.noDummy")); } else { - sendFeedback(new TranslatableText("enchCrack.insn.itemThrows", result.itemThrows(), (float)result.itemThrows() / 20f)); + source.sendFeedback(new TranslatableText("enchCrack.insn.itemThrows", result.itemThrows(), (float)result.itemThrows() / 20f)); } - sendFeedback(new TranslatableText("enchCrack.insn.bookshelves", result.bookshelves())); - sendFeedback(new TranslatableText("enchCrack.insn.slot", result.slot() + 1)); - sendFeedback("enchCrack.insn.enchantments"); + source.sendFeedback(new TranslatableText("enchCrack.insn.bookshelves", result.bookshelves())); + source.sendFeedback(new TranslatableText("enchCrack.insn.slot", result.slot() + 1)); + source.sendFeedback(new TranslatableText("enchCrack.insn.enchantments")); for (EnchantmentLevelEntry ench : result.enchantments()) { - sendFeedback(new LiteralText("- ").append(ench.enchantment.getName(ench.level))); + source.sendFeedback(new LiteralText("- ").append(ench.enchantment.getName(ench.level))); } - return 0; - } else { - sendFeedback("commands.cenchant.success"); - return 0; + source.sendFeedback(new TranslatableText("commands.cenchant.success")); } } + return 0; } } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/CGiveCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/CGiveCommand.java index e527f2dfc..4b9b872b6 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/CGiveCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/CGiveCommand.java @@ -11,7 +11,6 @@ import static com.mojang.brigadier.arguments.IntegerArgumentType.*; import static dev.xpple.clientarguments.arguments.CItemStackArgumentType.*; -import static net.earthcomputer.clientcommands.command.ClientCommandHelper.*; import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.*; public class CGiveCommand { @@ -27,7 +26,7 @@ public static void register(CommandDispatcher dispatc } private static int give(FabricClientCommandSource source, ItemStackArgument itemArgument, int count) throws CommandSyntaxException { - final MinecraftClient client = MinecraftClient.getInstance(); + final MinecraftClient client = source.getClient(); if (!client.player.getAbilities().creativeMode) { throw NOT_CREATIVE_EXCEPTION.create(); } @@ -36,7 +35,7 @@ private static int give(FabricClientCommandSource source, ItemStackArgument item client.interactionManager.clickCreativeStack(stack, 36 + client.player.getInventory().selectedSlot); client.player.playerScreenHandler.sendContentUpdates(); - sendFeedback(new TranslatableText("commands.cgive.success", count, stack.toHoverableText())); + source.sendFeedback(new TranslatableText("commands.cgive.success", count, stack.toHoverableText())); return 0; } } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/CParticleCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/CParticleCommand.java index 78c77e458..33938a9c3 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/CParticleCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/CParticleCommand.java @@ -4,7 +4,6 @@ import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; import net.fabricmc.fabric.api.client.command.v1.FabricClientCommandSource; -import net.minecraft.client.MinecraftClient; import net.minecraft.particle.ParticleEffect; import net.minecraft.particle.ParticleTypes; import net.minecraft.text.TranslatableText; @@ -17,19 +16,16 @@ import static com.mojang.brigadier.arguments.IntegerArgumentType.*; import static dev.xpple.clientarguments.arguments.CParticleEffectArgumentType.*; import static dev.xpple.clientarguments.arguments.CVec3ArgumentType.*; -import static net.earthcomputer.clientcommands.command.ClientCommandHelper.*; import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.*; public class CParticleCommand { private static final SimpleCommandExceptionType UNSUITABLE_PARTICLE_OPTION_EXCEPTION = new SimpleCommandExceptionType(new TranslatableText("commands.cparticle.unsuitableParticleOption")); - private static final MinecraftClient client = MinecraftClient.getInstance(); - public static void register(CommandDispatcher dispatcher) { dispatcher.register(literal("cparticle") .then(argument("name", particleEffect()) - .executes(ctx -> spawnParticle(ctx.getSource(), getCParticle(ctx, "name"), client.player.getPos(), Vec3d.ZERO, 1, 1, false)) + .executes(ctx -> spawnParticle(ctx.getSource(), getCParticle(ctx, "name"), ctx.getSource().getPlayer().getPos(), Vec3d.ZERO, 1, 1, false)) .then(argument("pos", vec3()) .executes(ctx -> spawnParticle(ctx.getSource(), getCParticle(ctx, "name"), getCVec3(ctx, "pos"), Vec3d.ZERO, 1, 1, false)) .then(argument("delta", vec3(false)) @@ -45,7 +41,7 @@ public static void register(CommandDispatcher dispatc } private static int spawnParticle(FabricClientCommandSource source, ParticleEffect parameters, Vec3d pos, Vec3d delta, float speed, int count, boolean force) throws CommandSyntaxException { - switch (client.options.particles) { + switch (source.getClient().options.particles) { case MINIMAL: if (!force) { throw UNSUITABLE_PARTICLE_OPTION_EXCEPTION.create(); @@ -56,14 +52,14 @@ private static int spawnParticle(FabricClientCommandSource source, ParticleEffec } default: if (count == 0) { - client.world.addParticle(parameters, force, pos.x, pos.y, pos.z, delta.x * speed, delta.y * speed, delta.z * speed); + source.getWorld().addParticle(parameters, force, pos.x, pos.y, pos.z, delta.x * speed, delta.y * speed, delta.z * speed); } else { - final Random random = client.getNetworkHandler().getWorld().random; + final Random random = source.getClient().getNetworkHandler().getWorld().random; for (int i = 0; i < count; i++) { - client.world.addParticle(parameters, force, pos.x + delta.x * random.nextGaussian(), pos.y + delta.y * random.nextGaussian(), pos.z + delta.z * random.nextGaussian(), speed * random.nextGaussian(), speed * random.nextGaussian(), speed * random.nextGaussian()); + source.getWorld().addParticle(parameters, force, pos.x + delta.x * random.nextGaussian(), pos.y + delta.y * random.nextGaussian(), pos.z + delta.z * random.nextGaussian(), speed * random.nextGaussian(), speed * random.nextGaussian(), speed * random.nextGaussian()); } } - sendFeedback(new TranslatableText("commands.cparticle.success", Registry.PARTICLE_TYPE.getId(parameters.getType()).toString())); + source.sendFeedback(new TranslatableText("commands.cparticle.success", Registry.PARTICLE_TYPE.getId(parameters.getType()).toString())); return 0; } } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/CPlaySoundCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/CPlaySoundCommand.java index f0bf4955f..0073f4e2b 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/CPlaySoundCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/CPlaySoundCommand.java @@ -1,23 +1,21 @@ package net.earthcomputer.clientcommands.command; -import static com.mojang.brigadier.arguments.FloatArgumentType.*; -import static dev.xpple.clientarguments.arguments.CIdentifierArgumentType.*; -import static dev.xpple.clientarguments.arguments.CVec3ArgumentType.*; -import static net.earthcomputer.clientcommands.command.ClientCommandHelper.*; -import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.*; - import com.mojang.brigadier.CommandDispatcher; -import com.mojang.brigadier.builder.*; - +import com.mojang.brigadier.builder.LiteralArgumentBuilder; import dev.xpple.clientarguments.arguments.CSuggestionProviders; import net.fabricmc.fabric.api.client.command.v1.FabricClientCommandSource; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.sound.*; +import net.minecraft.client.sound.PositionedSoundInstance; +import net.minecraft.client.sound.SoundInstance; import net.minecraft.sound.SoundCategory; import net.minecraft.text.TranslatableText; import net.minecraft.util.Identifier; import net.minecraft.util.math.Vec3d; +import static com.mojang.brigadier.arguments.FloatArgumentType.*; +import static dev.xpple.clientarguments.arguments.CIdentifierArgumentType.*; +import static dev.xpple.clientarguments.arguments.CVec3ArgumentType.*; +import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.*; + public class CPlaySoundCommand { public static void register(CommandDispatcher dispatcher) { @@ -33,7 +31,7 @@ public static void register(CommandDispatcher dispatc private static LiteralArgumentBuilder buildArguments(SoundCategory category) { return literal(category.getName()) - .executes(ctx -> playSound(ctx.getSource(), getCIdentifier(ctx, "sound"), category, MinecraftClient.getInstance().player.getPos(), 1, 1)) + .executes(ctx -> playSound(ctx.getSource(), getCIdentifier(ctx, "sound"), category, ctx.getSource().getPlayer().getPos(), 1, 1)) .then(argument("pos", vec3()) .executes(ctx -> playSound(ctx.getSource(), getCIdentifier(ctx, "sound"), category, getCVec3(ctx, "pos"), 1, 1)) .then(argument("volume", floatArg(0)) @@ -44,9 +42,9 @@ private static LiteralArgumentBuilder buildArguments( private static int playSound(FabricClientCommandSource source, Identifier sound, SoundCategory category, Vec3d pos, float volume, float pitch) { SoundInstance soundInstance = new PositionedSoundInstance(sound, category, volume, pitch, false, 0, SoundInstance.AttenuationType.LINEAR, pos.getX(), pos.getY(), pos.getZ(), false); - MinecraftClient.getInstance().getSoundManager().play(soundInstance); + source.getClient().getSoundManager().play(soundInstance); - sendFeedback(new TranslatableText("commands.cplaysound.success", sound)); + source.sendFeedback(new TranslatableText("commands.cplaysound.success", sound)); return 0; } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/CStopSoundCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/CStopSoundCommand.java index 4fca7c035..e0d28d8c4 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/CStopSoundCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/CStopSoundCommand.java @@ -1,19 +1,16 @@ package net.earthcomputer.clientcommands.command; -import static dev.xpple.clientarguments.arguments.CIdentifierArgumentType.*; -import static net.earthcomputer.clientcommands.command.ClientCommandHelper.*; -import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.*; - import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.builder.LiteralArgumentBuilder; - import dev.xpple.clientarguments.arguments.CSuggestionProviders; import net.fabricmc.fabric.api.client.command.v1.FabricClientCommandSource; -import net.minecraft.client.MinecraftClient; import net.minecraft.sound.SoundCategory; import net.minecraft.text.TranslatableText; import net.minecraft.util.Identifier; +import static dev.xpple.clientarguments.arguments.CIdentifierArgumentType.*; +import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.*; + public class CStopSoundCommand { public static void register(CommandDispatcher dispatcher) { @@ -36,16 +33,16 @@ private static LiteralArgumentBuilder buildArguments( } private static int stopSound(FabricClientCommandSource source, SoundCategory category, Identifier sound) { - MinecraftClient.getInstance().getSoundManager().stopSounds(sound, category); + source.getClient().getSoundManager().stopSounds(sound, category); if (category == null && sound == null) { - sendFeedback(new TranslatableText("commands.cstopsound.success.sourceless.any")); + source.sendFeedback(new TranslatableText("commands.cstopsound.success.sourceless.any")); } else if (category == null) { - sendFeedback(new TranslatableText("commands.cstopsound.success.sourceless.sound", sound)); + source.sendFeedback(new TranslatableText("commands.cstopsound.success.sourceless.sound", sound)); } else if (sound == null) { - sendFeedback(new TranslatableText("commands.cstopsound.success.source.any", category.getName())); + source.sendFeedback(new TranslatableText("commands.cstopsound.success.source.any", category.getName())); } else { - sendFeedback(new TranslatableText("commands.cstopsound.success.source.sound", sound, category.getName())); + source.sendFeedback(new TranslatableText("commands.cstopsound.success.source.sound", sound, category.getName())); } return 0; } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/CTeleportCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/CTeleportCommand.java index 3c674bb46..b3c166359 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/CTeleportCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/CTeleportCommand.java @@ -4,22 +4,18 @@ import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; import net.fabricmc.fabric.api.client.command.v1.FabricClientCommandSource; -import net.minecraft.client.MinecraftClient; import net.minecraft.network.packet.c2s.play.SpectatorTeleportC2SPacket; import net.minecraft.text.TranslatableText; import java.util.UUID; import static dev.xpple.clientarguments.arguments.CEntityArgumentType.*; -import static net.earthcomputer.clientcommands.command.ClientCommandHelper.*; import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.*; public class CTeleportCommand { private static final SimpleCommandExceptionType NOT_SPECTATOR_EXCEPTION = new SimpleCommandExceptionType(new TranslatableText("commands.ctp.notSpectator")); - private static final MinecraftClient client = MinecraftClient.getInstance(); - public static void register(CommandDispatcher dispatcher) { dispatcher.register(literal("ctp") .then(argument("entity", entity()) @@ -27,11 +23,11 @@ public static void register(CommandDispatcher dispatc } private static int teleport(FabricClientCommandSource source, UUID uuid) throws CommandSyntaxException { - if (!client.player.isSpectator()) { + if (!source.getPlayer().isSpectator()) { throw NOT_SPECTATOR_EXCEPTION.create(); } - client.getNetworkHandler().sendPacket(new SpectatorTeleportC2SPacket(uuid)); - sendFeedback(new TranslatableText("commands.ctp.success", uuid.toString())); + source.getClient().getNetworkHandler().sendPacket(new SpectatorTeleportC2SPacket(uuid)); + source.sendFeedback(new TranslatableText("commands.ctp.success", uuid.toString())); return 0; } } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/CTellRawCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/CTellRawCommand.java index 6b2496f6d..eae78505c 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/CTellRawCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/CTellRawCommand.java @@ -2,28 +2,23 @@ import com.mojang.brigadier.CommandDispatcher; import net.fabricmc.fabric.api.client.command.v1.FabricClientCommandSource; -import net.minecraft.client.MinecraftClient; import net.minecraft.text.MutableText; import net.minecraft.text.Texts; -import static dev.xpple.clientarguments.arguments.CTextArgumentType.getCTextArgument; -import static dev.xpple.clientarguments.arguments.CTextArgumentType.text; -import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.argument; -import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.literal; +import static dev.xpple.clientarguments.arguments.CTextArgumentType.*; +import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.*; public class CTellRawCommand { - private static final MinecraftClient client = MinecraftClient.getInstance(); public static void register(CommandDispatcher dispatcher) { dispatcher.register(literal("ctellraw") .then(argument("message", text()) .executes(ctx -> { - MutableText text = Texts.parse(new FakeCommandSource(client.player), getCTextArgument(ctx, "message"), client.player, 0); - client.inGameHud.getChatHud().addMessage(text); - return 1; + MutableText text = Texts.parse(new FakeCommandSource(ctx.getSource().getPlayer()), getCTextArgument(ctx, "message"), ctx.getSource().getPlayer(), 0); + ctx.getSource().getClient().inGameHud.getChatHud().addMessage(text); + return 0; }) ) ); } - } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/CTimeCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/CTimeCommand.java index afec4c468..e2d44bdfc 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/CTimeCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/CTimeCommand.java @@ -4,68 +4,63 @@ import net.earthcomputer.clientcommands.features.ClientTimeModifier; import net.fabricmc.fabric.api.client.command.v1.FabricClientCommandSource; import net.minecraft.SharedConstants; -import net.minecraft.client.MinecraftClient; import net.minecraft.text.TranslatableText; -import static com.mojang.brigadier.arguments.IntegerArgumentType.getInteger; +import static dev.xpple.clientarguments.arguments.CTimeArgumentType.getCTime; import static dev.xpple.clientarguments.arguments.CTimeArgumentType.time; -import static net.earthcomputer.clientcommands.command.ClientCommandHelper.sendFeedback; -import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.argument; -import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.literal; +import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.*; public class CTimeCommand { - private static final MinecraftClient CLIENT = MinecraftClient.getInstance(); - public static void register(CommandDispatcher dispatcher) { dispatcher.register(literal("ctime") .then(literal("query") .then(literal("day") - .executes(ctx -> executeQueryDay())) + .executes(ctx -> executeQueryDay(ctx.getSource()))) .then(literal("daytime") - .executes(ctx -> executeQueryDayTime())) + .executes(ctx -> executeQueryDayTime(ctx.getSource()))) .then(literal("gametime") - .executes(ctx -> executeQueryGameTime()))) + .executes(ctx -> executeQueryGameTime(ctx.getSource())))) .then(literal("set") .then(literal("day") - .executes(ctx -> executeSetTime(1000))) + .executes(ctx -> executeSetTime(ctx.getSource(), 1000))) .then(literal("noon") - .executes(ctx -> executeSetTime(6000))) + .executes(ctx -> executeSetTime(ctx.getSource(), 6000))) .then(literal("night") - .executes(ctx -> executeSetTime(13000))) + .executes(ctx -> executeSetTime(ctx.getSource(), 13000))) .then(literal("midnight") - .executes(ctx -> executeSetTime(18000))) + .executes(ctx -> executeSetTime(ctx.getSource(), 18000))) .then(argument("time", time()) - .executes(ctx -> executeSetTime(getInteger(ctx, "time"))))) + .executes(ctx -> executeSetTime(ctx.getSource(), getCTime(ctx, "time"))))) .then(literal("reset") - .executes(ctx -> executeResetTime())) + .executes(ctx -> executeResetTime(ctx.getSource()))) ); } - private static int executeQueryDay() { - return executeQuery((int) (CLIENT.world.getTimeOfDay() / SharedConstants.TICKS_PER_IN_GAME_DAY % 2147483647L)); + private static int executeQueryDay(FabricClientCommandSource source) { + return executeQuery(source, (int) (source.getWorld().getTimeOfDay() / SharedConstants.TICKS_PER_IN_GAME_DAY % 2147483647L)); } - private static int executeQueryDayTime() { - return executeQuery((int) (CLIENT.world.getTimeOfDay() % SharedConstants.TICKS_PER_IN_GAME_DAY)); + private static int executeQueryDayTime(FabricClientCommandSource source) { + return executeQuery(source, (int) (source.getWorld().getTimeOfDay() % SharedConstants.TICKS_PER_IN_GAME_DAY)); } - private static int executeQueryGameTime() { - return executeQuery((int) (CLIENT.world.getTime() % 2147483647L)); + private static int executeQueryGameTime(FabricClientCommandSource source) { + return executeQuery(source, (int) (source.getWorld().getTime() % 2147483647L)); } - private static int executeQuery(int time) { - sendFeedback(new TranslatableText("commands.time.query", time)); + private static int executeQuery(FabricClientCommandSource source, int time) { + source.sendFeedback(new TranslatableText("commands.time.query", time)); return time; } - private static int executeSetTime(int time) { + private static int executeSetTime(FabricClientCommandSource source, int time) { ClientTimeModifier.lock(time); - return executeQueryDayTime(); + return executeQueryDayTime(source); } - private static int executeResetTime() { + private static int executeResetTime(FabricClientCommandSource source) { ClientTimeModifier.none(); - return executeQueryDayTime(); + return executeQueryDayTime(source); } } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/CalcCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/CalcCommand.java index 5cf969953..f912e3ca5 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/CalcCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/CalcCommand.java @@ -37,7 +37,7 @@ private static int evaluateExpression(FabricClientCommandSource source, Expressi } catch (StackOverflowError e) { throw TOO_DEEPLY_NESTED_EXCEPTION.create(); } - sendFeedback(new TranslatableText("commands.ccalc.parse", parsedTree)); + source.sendFeedback(new TranslatableText("commands.ccalc.parse", parsedTree)); } double result; @@ -64,7 +64,7 @@ private static int evaluateExpression(FabricClientCommandSource source, Expressi feedback.append(new LiteralText(String.valueOf(result)).formatted(Formatting.BOLD)); } - sendFeedback(feedback); + source.sendFeedback(feedback); return iresult; } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/CalcStackCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/CalcStackCommand.java index 95d1aebaf..b6d91288e 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/CalcStackCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/CalcStackCommand.java @@ -3,7 +3,6 @@ import com.mojang.brigadier.CommandDispatcher; import net.fabricmc.fabric.api.client.command.v1.FabricClientCommandSource; -import net.minecraft.client.MinecraftClient; import net.minecraft.item.ItemStack; import net.minecraft.text.Text; import net.minecraft.text.TranslatableText; @@ -11,7 +10,6 @@ import static dev.xpple.clientarguments.arguments.CItemStackArgumentType.*; import static com.mojang.brigadier.arguments.IntegerArgumentType.*; -import static net.earthcomputer.clientcommands.command.ClientCommandHelper.*; import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.*; public class CalcStackCommand { @@ -24,9 +22,7 @@ public static void register(CommandDispatcher dispatc ItemStack stack = getCItemStackArgument(ctx, "item").createStack(1, false); return getStackSize(ctx.getSource(), stack, getInteger(ctx, "count")); })) - .executes(ctx -> { - return getStackSize(ctx.getSource(), getInteger(ctx, "count")); - }))); + .executes(ctx -> getStackSize(ctx.getSource(), getInteger(ctx, "count"))))); } private static int getStackSize(FabricClientCommandSource source, ItemStack stack, int count) { @@ -35,16 +31,16 @@ private static int getStackSize(FabricClientCommandSource source, ItemStack stac if (stack.isEmpty()) { if (remainder == 0) { - sendFeedback(new TranslatableText("commands.ccalcstack.success.empty.exact", count, stacks)); + source.sendFeedback(new TranslatableText("commands.ccalcstack.success.empty.exact", count, stacks)); } else { - sendFeedback(new TranslatableText("commands.ccalcstack.success.empty", count, stacks, remainder)); + source.sendFeedback(new TranslatableText("commands.ccalcstack.success.empty", count, stacks, remainder)); } } else { Text itemText = stack.toHoverableText(); if (remainder == 0) { - sendFeedback(new TranslatableText("commands.ccalcstack.success.exact", count, itemText, stacks)); + source.sendFeedback(new TranslatableText("commands.ccalcstack.success.exact", count, itemText, stacks)); } else { - sendFeedback(new TranslatableText("commands.ccalcstack.success", count, itemText, stacks, remainder)); + source.sendFeedback(new TranslatableText("commands.ccalcstack.success", count, itemText, stacks, remainder)); } } @@ -52,8 +48,7 @@ private static int getStackSize(FabricClientCommandSource source, ItemStack stac } private static int getStackSize(FabricClientCommandSource source, int count) { - assert MinecraftClient.getInstance().player != null; - ItemStack heldStack = MinecraftClient.getInstance().player.getStackInHand(Hand.MAIN_HAND).copy(); + ItemStack heldStack = source.getPlayer().getStackInHand(Hand.MAIN_HAND).copy(); return getStackSize(source, heldStack, count); } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/ClientCommandHelper.java b/src/main/java/net/earthcomputer/clientcommands/command/ClientCommandHelper.java index 7122e1f47..f5a93806c 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/ClientCommandHelper.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/ClientCommandHelper.java @@ -30,18 +30,6 @@ public static FabricClientCommandSource withFlags(FabricClientCommandSource sour } } - public static void sendError(Text error) { - sendFeedback(new LiteralText("").append(error).formatted(Formatting.RED)); - } - - public static void sendFeedback(String message, Object... args) { - sendFeedback(new TranslatableText(message, args)); - } - - public static void sendFeedback(Text message) { - MinecraftClient.getInstance().inGameHud.getChatHud().addMessage(message); - } - public static void addOverlayMessage(Text message, int time) { InGameHud inGameHud = MinecraftClient.getInstance().inGameHud; inGameHud.setOverlayMessage(message, false); diff --git a/src/main/java/net/earthcomputer/clientcommands/command/CrackRNGCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/CrackRNGCommand.java index 2329f9abe..014b84b53 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/CrackRNGCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/CrackRNGCommand.java @@ -8,7 +8,6 @@ import net.fabricmc.fabric.api.client.command.v1.FabricClientCommandSource; import net.minecraft.text.TranslatableText; -import static net.earthcomputer.clientcommands.command.ClientCommandHelper.*; import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.*; public class CrackRNGCommand { @@ -21,7 +20,7 @@ public static void register(CommandDispatcher dispatc private static int crackPlayerRNG(FabricClientCommandSource source) { ServerBrandManager.rngWarning(); SeedCracker.crack(seed -> { - sendFeedback(new TranslatableText("commands.ccrackrng.success", Long.toHexString(seed))); + source.sendFeedback(new TranslatableText("commands.ccrackrng.success", Long.toHexString(seed))); PlayerRandCracker.setSeed(seed); TempRules.playerCrackState = PlayerRandCracker.CrackState.CRACKED; }); diff --git a/src/main/java/net/earthcomputer/clientcommands/command/FakeCommandSource.java b/src/main/java/net/earthcomputer/clientcommands/command/FakeCommandSource.java index 8d75f233e..5b5841903 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/FakeCommandSource.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/FakeCommandSource.java @@ -3,7 +3,6 @@ import net.minecraft.client.MinecraftClient; import net.minecraft.client.network.ClientPlayerEntity; import net.minecraft.server.command.ServerCommandSource; -import net.minecraft.server.world.ServerWorld; import net.minecraft.util.registry.DynamicRegistryManager; import java.util.Collection; @@ -11,7 +10,7 @@ public class FakeCommandSource extends ServerCommandSource { public FakeCommandSource(ClientPlayerEntity player) { - super(player, player.getPos(), player.getRotationClient(), null, 0, player.getEntityName(), player.getName(), null, player); + super(player, player.getPos(), player.getRotationClient(), null, 314159265, player.getEntityName(), player.getName(), null, player); } @Override diff --git a/src/main/java/net/earthcomputer/clientcommands/command/FindBlockCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/FindBlockCommand.java index 2ecaf11ec..dc7fc07e6 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/FindBlockCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/FindBlockCommand.java @@ -2,7 +2,6 @@ import com.mojang.brigadier.CommandDispatcher; import net.fabricmc.fabric.api.client.command.v1.FabricClientCommandSource; -import net.minecraft.client.MinecraftClient; import net.minecraft.client.world.ClientWorld; import net.minecraft.text.TranslatableText; import net.minecraft.util.math.BlockPos; @@ -54,11 +53,11 @@ public static int findBlock(FabricClientCommandSource source, ClientBlockPredica .orElse(null); if (closestBlock == null) { - sendError(new TranslatableText("commands.cfindblock.notFound")); + source.sendError(new TranslatableText("commands.cfindblock.notFound")); return 0; } else { double foundRadius = radiusType.distanceFunc.applyAsDouble(closestBlock.subtract(origin)); - sendFeedback(new TranslatableText("commands.cfindblock.success.left", foundRadius) + source.sendFeedback(new TranslatableText("commands.cfindblock.success.left", foundRadius) .append(getLookCoordsTextComponent(closestBlock)) .append(" ") .append(getGlowCoordsTextComponent(new TranslatableText("commands.cfindblock.success.glow"), closestBlock)) @@ -68,8 +67,7 @@ public static int findBlock(FabricClientCommandSource source, ClientBlockPredica } private static List findBlockCandidatesInSquareArea(FabricClientCommandSource source, ClientBlockPredicate blockMatcher, int radius, RadiusType radiusType) { - World world = MinecraftClient.getInstance().world; - assert world != null; + World world = source.getWorld(); BlockPos senderPos = new BlockPos(source.getPosition()); ChunkPos chunkPos = new ChunkPos(senderPos); @@ -83,7 +81,7 @@ private static List findBlockCandidatesInSquareArea(FabricClientComman for (int chunkZ = chunkPos.z - r; chunkZ <= chunkPos.z + r; chunkZ += chunkX == chunkPos.x - r || chunkX == chunkPos.x + r ? 1 : r + r) { Chunk chunk = world.getChunk(chunkX, chunkZ); - if (searchChunkForBlockCandidates(chunk, senderPos.getY(), blockMatcher, blockCandidates)) { + if (searchChunkForBlockCandidates(source, chunk, senderPos.getY(), blockMatcher, blockCandidates)) { // update new, potentially shortened, radius int dx = chunkPos.x - chunkX; int dz = chunkPos.z - chunkZ; @@ -105,8 +103,7 @@ private static List findBlockCandidatesInSquareArea(FabricClientComman } private static List findBlockCandidatesInTaxicabArea(FabricClientCommandSource source, ClientBlockPredicate blockMatcher, int radius) { - World world = MinecraftClient.getInstance().world; - assert world != null; + World world = source.getWorld(); BlockPos senderPos = new BlockPos(source.getPosition()); ChunkPos chunkPos = new ChunkPos(senderPos); @@ -120,7 +117,7 @@ private static List findBlockCandidatesInTaxicabArea(FabricClientComma int chunkZ = chunkPos.z - (r - Math.abs(chunkPos.x - chunkX)); for (int i = 0; i < 2; i++) { Chunk chunk = world.getChunk(chunkX, chunkZ); - if (searchChunkForBlockCandidates(chunk, senderPos.getY(), blockMatcher, blockCandidates)) { + if (searchChunkForBlockCandidates(source, chunk, senderPos.getY(), blockMatcher, blockCandidates)) { // update new, potentially shortened, radius int newChunkRadius = Math.abs(chunkPos.x - chunkX) + Math.abs(chunkPos.z - chunkZ) + 1; if (newChunkRadius < chunkRadius) { @@ -136,9 +133,8 @@ private static List findBlockCandidatesInTaxicabArea(FabricClientComma return blockCandidates; } - private static boolean searchChunkForBlockCandidates(Chunk chunk, int senderY, ClientBlockPredicate blockMatcher, List blockCandidates) { - ClientWorld world = MinecraftClient.getInstance().world; - assert world != null; + private static boolean searchChunkForBlockCandidates(FabricClientCommandSource source, Chunk chunk, int senderY, ClientBlockPredicate blockMatcher, List blockCandidates) { + ClientWorld world = source.getWorld(); int bottomY = world.getBottomY(); int topY = world.getTopY(); diff --git a/src/main/java/net/earthcomputer/clientcommands/command/FindCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/FindCommand.java index b54b4c1b7..a58fe1ff1 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/FindCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/FindCommand.java @@ -39,7 +39,7 @@ private static int listEntities(FabricClientCommandSource source, CEntitySelecto if (keepSearching) { String taskName = TaskManager.addTask("cfind", new FindTask(source, selector)); - sendFeedback(new TranslatableText("commands.cfind.keepSearching.success") + source.sendFeedback(new TranslatableText("commands.cfind.keepSearching.success") .append(" ") .append(getCommandTextComponent("commands.client.cancel", "/ctask stop " + taskName))); @@ -48,11 +48,11 @@ private static int listEntities(FabricClientCommandSource source, CEntitySelecto List entities = selector.getEntities(source); if (entities.isEmpty()) { - sendError(new TranslatableText("commands.cfind.noMatch")); + source.sendError(new TranslatableText("commands.cfind.noMatch")); return 0; } - sendFeedback(new TranslatableText("commands.cfind.success", entities.size()).formatted(Formatting.BOLD)); + source.sendFeedback(new TranslatableText("commands.cfind.success", entities.size()).formatted(Formatting.BOLD)); for (Entity entity : entities) { sendEntityFoundMessage(source, entity); } @@ -63,7 +63,7 @@ private static int listEntities(FabricClientCommandSource source, CEntitySelecto private static void sendEntityFoundMessage(FabricClientCommandSource source, Entity entity) { double distance = Math.sqrt(entity.squaredDistanceTo(source.getPosition())); - sendFeedback(new TranslatableText("commands.cfind.found.left", entity.getName(), distance) + source.sendFeedback(new TranslatableText("commands.cfind.found.left", entity.getName(), distance) .append(getLookCoordsTextComponent(entity.getBlockPos())) .append(new TranslatableText("commands.cfind.found.right", entity.getName(), distance))); } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/FindItemCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/FindItemCommand.java index 24d9a3258..a3b33c955 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/FindItemCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/FindItemCommand.java @@ -30,12 +30,15 @@ import net.minecraft.nbt.NbtCompound; import net.minecraft.screen.ScreenHandler; import net.minecraft.screen.slot.Slot; -import net.minecraft.text.*; +import net.minecraft.text.TranslatableText; import net.minecraft.util.Formatting; import net.minecraft.util.Hand; import net.minecraft.util.collection.DefaultedList; import net.minecraft.util.hit.BlockHitResult; -import net.minecraft.util.math.*; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.Direction; +import net.minecraft.util.math.MathHelper; +import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; import org.apache.commons.lang3.tuple.Pair; @@ -68,14 +71,14 @@ public static void register(CommandDispatcher dispatc getWithString(ctx, "item", ItemPredicateArgument.class))))); } - private static int findItem(CommandContext source, boolean noSearchShulkerBox, boolean keepSearching, Pair item) throws CommandSyntaxException { - String taskName = TaskManager.addTask("cfinditem", new FindItemsTask(item.getLeft(), item.getRight().create(source), !noSearchShulkerBox, keepSearching)); + private static int findItem(CommandContext ctx, boolean noSearchShulkerBox, boolean keepSearching, Pair item) throws CommandSyntaxException { + String taskName = TaskManager.addTask("cfinditem", new FindItemsTask(item.getLeft(), item.getRight().create(ctx), !noSearchShulkerBox, keepSearching)); if (keepSearching) { - sendFeedback(new TranslatableText("commands.cfinditem.starting.keepSearching", item.getLeft()) + ctx.getSource().sendFeedback(new TranslatableText("commands.cfinditem.starting.keepSearching", item.getLeft()) .append(" ") .append(getCommandTextComponent("commands.client.cancel", "/ctask stop " + taskName))); } else { - sendFeedback(new TranslatableText("commands.cfinditem.starting", item.getLeft())); + ctx.getSource().sendFeedback(new TranslatableText("commands.cfinditem.starting", item.getLeft())); } return 0; @@ -137,14 +140,17 @@ protected void onTick() { for (int y = minY; y <= maxY; y++) { for (int z = minZ; z <= maxZ; z++) { BlockPos pos = new BlockPos(x, y, z); - if (!canSearch(world, pos)) + if (!canSearch(world, pos)) { continue; - if (searchedBlocks.contains(pos)) + } + if (searchedBlocks.contains(pos)) { continue; + } BlockState state = world.getBlockState(pos); Vec3d closestPos = MathUtil.getClosestPoint(pos, state.getOutlineShape(world, pos), origin); - if (closestPos.squaredDistanceTo(origin) > reachDistance * reachDistance) + if (closestPos.squaredDistanceTo(origin) > reachDistance * reachDistance) { continue; + } searchedBlocks.add(pos); if (state.getBlock() == Blocks.ENDER_CHEST) { if (hasSearchedEnderChest) { @@ -153,10 +159,11 @@ protected void onTick() { hasSearchedEnderChest = true; } else if (state.getBlock() instanceof ChestBlock && state.get(ChestBlock.CHEST_TYPE) != ChestType.SINGLE) { BlockPos offsetPos = pos.offset(ChestBlock.getFacing(state)); - if (world.getBlockState(offsetPos).getBlock() == state.getBlock()) + if (world.getBlockState(offsetPos).getBlock() == state.getBlock()) { searchedBlocks.add(offsetPos); + } } - startSearch(world, pos, origin, closestPos); + startSearch(pos, origin, closestPos); scheduleDelay(); return; } @@ -177,28 +184,30 @@ private boolean canSearch(World world, BlockPos pos) { return false; if (state.getBlock() instanceof ChestBlock && state.get(ChestBlock.CHEST_TYPE) != ChestType.SINGLE) { BlockPos offsetPos = pos.offset(ChestBlock.getFacing(state)); - if (world.getBlockState(offsetPos).getBlock() == state.getBlock() && ChestBlock.isChestBlocked(world, offsetPos)) - return false; + return world.getBlockState(offsetPos).getBlock() != state.getBlock() || !ChestBlock.isChestBlocked(world, offsetPos); } } return true; } - private void startSearch(World world, BlockPos pos, Vec3d cameraPos, Vec3d clickPos) { + private void startSearch(BlockPos pos, Vec3d cameraPos, Vec3d clickPos) { MinecraftClient mc = MinecraftClient.getInstance(); currentlySearching = pos; currentlySearchingTimeout = 100; GuiBlocker.addBlocker(new GuiBlocker() { @Override public boolean accept(Screen screen) { - if (!(screen instanceof ScreenHandlerProvider)) + if (!(screen instanceof ScreenHandlerProvider)) { return true; + } assert mc.player != null; ScreenHandler container = ((ScreenHandlerProvider) screen).getScreenHandler(); Set playerInvSlots = new HashSet<>(); - for (Slot slot : container.slots) - if (slot.inventory instanceof PlayerInventory) + for (Slot slot : container.slots) { + if (slot.inventory instanceof PlayerInventory) { playerInvSlots.add(slot.id); + } + } mc.player.currentScreenHandler = new ScreenHandler(((ScreenHandlerAccessor) container).getNullableType(), container.syncId) { @Override public boolean canUse(PlayerEntity var1) { @@ -209,11 +218,13 @@ public boolean canUse(PlayerEntity var1) { public void updateSlotStacks(int revision, List stacks, ItemStack cursorStack) { int matchingItems = 0; for (int slot = 0; slot < stacks.size(); slot++) { - if (playerInvSlots.contains(slot)) + if (playerInvSlots.contains(slot)) { continue; + } ItemStack stack = stacks.get(slot); - if (searchingFor.test(stack)) + if (searchingFor.test(stack)) { matchingItems += stack.getCount(); + } if (searchShulkerBoxes && stack.getItem() instanceof BlockItem && ((BlockItem) stack.getItem()).getBlock() instanceof ShulkerBoxBlock) { NbtCompound blockEntityTag = stack.getSubNbt("BlockEntityTag"); if (blockEntityTag != null && blockEntityTag.contains("Items")) { @@ -228,7 +239,7 @@ public void updateSlotStacks(int revision, List stacks, ItemStack cur } } if (matchingItems > 0) { - sendFeedback(new TranslatableText("commands.cfinditem.match.left", matchingItems, searchingForName) + MinecraftClient.getInstance().inGameHud.getChatHud().addMessage(new TranslatableText("commands.cfinditem.match.left", matchingItems, searchingForName) .append(getLookCoordsTextComponent(currentlySearching)) .append(new TranslatableText("commands.cfinditem.match.right", matchingItems, searchingForName))); totalFound += matchingItems; @@ -250,7 +261,7 @@ public void updateSlotStacks(int revision, List stacks, ItemStack cur @Override public void onCompleted() { - sendFeedback(new TranslatableText("commands.cfinditem.total", totalFound, searchingForName).formatted(Formatting.BOLD)); + MinecraftClient.getInstance().inGameHud.getChatHud().addMessage(new TranslatableText("commands.cfinditem.total", totalFound, searchingForName).formatted(Formatting.BOLD)); } } } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/FishCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/FishCommand.java index 800fb74e6..d962ad22e 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/FishCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/FishCommand.java @@ -9,6 +9,7 @@ import net.fabricmc.fabric.api.client.command.v1.FabricClientCommandSource; import net.minecraft.item.Item; import net.minecraft.item.Items; +import net.minecraft.text.Text; import net.minecraft.text.TranslatableText; import net.minecraft.util.Formatting; import org.apache.commons.lang3.tuple.Pair; @@ -16,10 +17,10 @@ import java.util.Set; import static com.mojang.brigadier.arguments.IntegerArgumentType.*; +import static net.earthcomputer.clientcommands.command.ClientCommandHelper.*; import static net.earthcomputer.clientcommands.command.arguments.ClientItemPredicateArgumentType.*; import static net.earthcomputer.clientcommands.command.arguments.ItemAndEnchantmentsPredicateArgumentType.*; import static net.earthcomputer.clientcommands.command.arguments.WithStringArgumentType.*; -import static net.earthcomputer.clientcommands.command.ClientCommandHelper.*; import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.*; public class FishCommand { @@ -28,49 +29,49 @@ public class FishCommand { public static void register(CommandDispatcher dispatcher) { dispatcher.register(literal("cfish") .then(literal("list-goals") - .executes(ctx -> listGoals())) + .executes(ctx -> listGoals(ctx.getSource()))) .then(literal("add-goal") .then(argument("goal", clientItemPredicate()) - .executes(ctx -> addGoal(getClientItemPredicate(ctx, "goal"))))) + .executes(ctx -> addGoal(ctx.getSource(), getClientItemPredicate(ctx, "goal"))))) .then(literal("add-enchanted-goal") .then(argument("goal", withString(itemAndEnchantmentsPredicate().withItemPredicate(ENCHANTABLE_ITEMS::contains))) - .executes(ctx -> addEnchantedGoal(getWithString(ctx, "goal", ItemAndEnchantmentsPredicate.class))))) + .executes(ctx -> addEnchantedGoal(ctx.getSource(), getWithString(ctx, "goal", ItemAndEnchantmentsPredicate.class))))) .then(literal("remove-goal") .then(argument("index", integer(1)) - .executes(ctx -> removeGoal(getInteger(ctx, "index")))))); + .executes(ctx -> removeGoal(ctx.getSource(), getInteger(ctx, "index")))))); } - private static int listGoals() { - if (!checkFishingManipulationEnabled()) { + private static int listGoals(FabricClientCommandSource source) { + if (!checkFishingManipulationEnabled(source)) { return 0; } if (FishingCracker.goals.isEmpty()) { - sendFeedback(new TranslatableText("commands.cfish.listGoals.noGoals").styled(style -> style.withColor(Formatting.RED))); + source.sendFeedback(new TranslatableText("commands.cfish.listGoals.noGoals").styled(style -> style.withColor(Formatting.RED))); } else { - sendFeedback("commands.cfish.listGoals.success", FishingCracker.goals.size()); + source.sendFeedback(new TranslatableText("commands.cfish.listGoals.success", FishingCracker.goals.size())); for (int i = 0; i < FishingCracker.goals.size(); i++) { - sendFeedback((i + 1) + ": " + FishingCracker.goals.get(i).getPrettyString()); + source.sendFeedback(Text.of((i + 1) + ": " + FishingCracker.goals.get(i).getPrettyString())); } } return FishingCracker.goals.size(); } - private static int addGoal(ClientItemPredicateArgumentType.ClientItemPredicate goal) { - if (!checkFishingManipulationEnabled()) { + private static int addGoal(FabricClientCommandSource source, ClientItemPredicateArgumentType.ClientItemPredicate goal) { + if (!checkFishingManipulationEnabled(source)) { return 0; } FishingCracker.goals.add(goal); - sendFeedback("commands.cfish.addGoal.success", goal.getPrettyString()); + source.sendFeedback(new TranslatableText("commands.cfish.addGoal.success", goal.getPrettyString())); return FishingCracker.goals.size(); } - private static int addEnchantedGoal(Pair stringAndItemAndEnchantments) { - if (!checkFishingManipulationEnabled()) { + private static int addEnchantedGoal(FabricClientCommandSource source, Pair stringAndItemAndEnchantments) { + if (!checkFishingManipulationEnabled(source)) { return 0; } @@ -81,13 +82,13 @@ private static int addEnchantedGoal(Pair s FishingCracker.goals.add(goal); - sendFeedback("commands.cfish.addGoal.success", string); + source.sendFeedback(new TranslatableText("commands.cfish.addGoal.success", string)); return FishingCracker.goals.size(); } - private static int removeGoal(int index) throws CommandSyntaxException { - if (!checkFishingManipulationEnabled()) { + private static int removeGoal(FabricClientCommandSource source, int index) throws CommandSyntaxException { + if (!checkFishingManipulationEnabled(source)) { return 0; } @@ -96,14 +97,14 @@ private static int removeGoal(int index) throws CommandSyntaxException { } ClientItemPredicate goal = FishingCracker.goals.remove(index - 1); - sendFeedback("commands.cfish.removeGoal.success", goal.getPrettyString()); + source.sendFeedback(new TranslatableText("commands.cfish.removeGoal.success", goal.getPrettyString())); return FishingCracker.goals.size(); } - private static boolean checkFishingManipulationEnabled() { + private static boolean checkFishingManipulationEnabled(FabricClientCommandSource source) { if (!TempRules.getFishingManipulation().isEnabled()) { - sendFeedback(new TranslatableText("commands.cfish.needFishingManipulation") + source.sendFeedback(new TranslatableText("commands.cfish.needFishingManipulation") .styled(style -> style.withColor(Formatting.RED)) .append(" ") .append(getCommandTextComponent("commands.client.enable", "/ctemprule set fishingManipulation manual"))); diff --git a/src/main/java/net/earthcomputer/clientcommands/command/FovCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/FovCommand.java index 166d089f1..124d76714 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/FovCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/FovCommand.java @@ -3,12 +3,10 @@ import com.mojang.brigadier.CommandDispatcher; import net.fabricmc.fabric.api.client.command.v1.FabricClientCommandSource; -import net.minecraft.client.MinecraftClient; import net.minecraft.text.Text; import net.minecraft.text.TranslatableText; import static com.mojang.brigadier.arguments.DoubleArgumentType.*; -import static net.earthcomputer.clientcommands.command.ClientCommandHelper.*; import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.*; public class FovCommand { @@ -24,10 +22,10 @@ public static void register(CommandDispatcher dispatc } private static int setFov(FabricClientCommandSource source, double fov) { - MinecraftClient.getInstance().options.fov = fov; + source.getClient().options.fov = fov; Text feedback = new TranslatableText("commands.cfov.success", fov); - sendFeedback(feedback); + source.sendFeedback(feedback); return 0; } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/GammaCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/GammaCommand.java index 49118f2d1..aad65b1ef 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/GammaCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/GammaCommand.java @@ -3,12 +3,10 @@ import com.mojang.brigadier.CommandDispatcher; import net.fabricmc.fabric.api.client.command.v1.FabricClientCommandSource; -import net.minecraft.client.MinecraftClient; import net.minecraft.text.Text; import net.minecraft.text.TranslatableText; import static com.mojang.brigadier.arguments.DoubleArgumentType.*; -import static net.earthcomputer.clientcommands.command.ClientCommandHelper.*; import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.*; public class GammaCommand { @@ -20,10 +18,10 @@ public static void register(CommandDispatcher dispatc } private static int setGamma(FabricClientCommandSource source, double gamma) { - MinecraftClient.getInstance().options.gamma = gamma; + source.getClient().options.gamma = gamma; Text feedback = new TranslatableText("commands.cgamma.success", gamma); - sendFeedback(feedback); + source.sendFeedback(feedback); return 0; } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/GetDataCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/GetDataCommand.java index 64c2a91b5..709defa66 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/GetDataCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/GetDataCommand.java @@ -27,7 +27,6 @@ import static dev.xpple.clientarguments.arguments.CBlockPosArgumentType.*; import static dev.xpple.clientarguments.arguments.CEntityArgumentType.*; import static dev.xpple.clientarguments.arguments.CNbtPathArgumentType.*; -import static net.earthcomputer.clientcommands.command.ClientCommandHelper.*; import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.*; public class GetDataCommand { @@ -79,7 +78,7 @@ public static void register(CommandDispatcher dispatc } private static int getData(FabricClientCommandSource source, DataCommandObject dataObj) throws CommandSyntaxException { - sendFeedback(dataObj.feedbackQuery(dataObj.getNbt())); + source.sendFeedback(dataObj.feedbackQuery(dataObj.getNbt())); return 1; } @@ -98,7 +97,7 @@ private static int getData(FabricClientCommandSource source, DataCommandObject d throw GET_UNKNOWN_EXCEPTION.create(path.toString()); } - sendFeedback(dataObj.feedbackQuery(tag)); + source.sendFeedback(dataObj.feedbackQuery(tag)); return ret; } @@ -113,9 +112,9 @@ private static NbtElement getNbt(NbtPath path, DataCommandObject dataObj) throws } } - private static interface ObjectType { - public DataCommandObject getObject(CommandContext ctx) throws CommandSyntaxException; - public ArgumentBuilder addArgumentsToBuilder(ArgumentBuilder builder, Function, ArgumentBuilder> subcommandAdder); + private interface ObjectType { + DataCommandObject getObject(CommandContext ctx) throws CommandSyntaxException; + ArgumentBuilder addArgumentsToBuilder(ArgumentBuilder builder, Function, ArgumentBuilder> subcommandAdder); } } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/GhostBlockCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/GhostBlockCommand.java index f846b13bd..4b6988bed 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/GhostBlockCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/GhostBlockCommand.java @@ -3,19 +3,15 @@ import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; - import net.fabricmc.fabric.api.client.command.v1.FabricClientCommandSource; import net.minecraft.block.BlockState; -import net.minecraft.client.MinecraftClient; import net.minecraft.client.world.ClientWorld; import net.minecraft.text.TranslatableText; import net.minecraft.util.math.BlockBox; import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; import static dev.xpple.clientarguments.arguments.CBlockPosArgumentType.*; import static dev.xpple.clientarguments.arguments.CBlockStateArgumentType.*; -import static net.earthcomputer.clientcommands.command.ClientCommandHelper.*; import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.*; public class GhostBlockCommand { @@ -28,31 +24,31 @@ public static void register(CommandDispatcher dispatc .then(literal("set") .then(argument("pos", blockPos()) .then(argument("block", blockState()) - .executes(ctx -> setGhostBlock(getCBlockPos(ctx, "pos"), getCBlockState(ctx, "block").getBlockState()))))) + .executes(ctx -> setGhostBlock(ctx.getSource(), getCBlockPos(ctx, "pos"), getCBlockState(ctx, "block").getBlockState()))))) .then(literal("fill") .then(argument("from", blockPos()) .then(argument("to", blockPos()) .then(argument("block", blockState()) - .executes(ctx -> fillGhostBlocks(getCBlockPos(ctx, "from"), getCBlockPos(ctx, "to"), getCBlockState(ctx, "block").getBlockState()))))))); + .executes(ctx -> fillGhostBlocks(ctx.getSource(), getCBlockPos(ctx, "from"), getCBlockPos(ctx, "to"), getCBlockState(ctx, "block").getBlockState()))))))); } - private static int setGhostBlock(BlockPos pos, BlockState state) throws CommandSyntaxException { - ClientWorld world = MinecraftClient.getInstance().world; + private static int setGhostBlock(FabricClientCommandSource source, BlockPos pos, BlockState state) throws CommandSyntaxException { + ClientWorld world = source.getWorld(); assert world != null; checkLoaded(world, pos); boolean result = world.setBlockState(pos, state, 18); if (result) { - sendFeedback("commands.cghostblock.set.success"); + source.sendFeedback(new TranslatableText("commands.cghostblock.set.success")); return 1; } else { throw SET_FAILED_EXCEPTION.create(); } } - private static int fillGhostBlocks(BlockPos from, BlockPos to, BlockState state) throws CommandSyntaxException { - ClientWorld world = MinecraftClient.getInstance().world; + private static int fillGhostBlocks(FabricClientCommandSource source, BlockPos from, BlockPos to, BlockState state) throws CommandSyntaxException { + ClientWorld world = source.getWorld(); assert world != null; checkLoaded(world, from); @@ -70,7 +66,7 @@ private static int fillGhostBlocks(BlockPos from, BlockPos to, BlockState state) throw FILL_FAILED_EXCEPTION.create(); } - sendFeedback("commands.cghostblock.fill.success", successCount); + source.sendFeedback(new TranslatableText("commands.cghostblock.fill.success", successCount)); return successCount; } @@ -78,7 +74,7 @@ private static int fillGhostBlocks(BlockPos from, BlockPos to, BlockState state) private static void checkLoaded(ClientWorld world, BlockPos pos) throws CommandSyntaxException { if (!world.isChunkLoaded(pos)) { throw UNLOADED_EXCEPTION.create(); - } else if (!MinecraftClient.getInstance().world.isInBuildLimit(pos)) { + } else if (!world.isInBuildLimit(pos)) { throw OUT_OF_WORLD_EXCEPTION.create(); } } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/GlowCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/GlowCommand.java index cb0434f19..62e59785f 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/GlowCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/GlowCommand.java @@ -3,7 +3,6 @@ import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; - import dev.xpple.clientarguments.arguments.CEntitySelector; import net.earthcomputer.clientcommands.interfaces.IEntity; import net.earthcomputer.clientcommands.render.RenderQueue; @@ -99,7 +98,7 @@ protected void onTick() { } }); - sendFeedback(new TranslatableText("commands.cglow.entity.keepSearching.success") + source.sendFeedback(new TranslatableText("commands.cglow.entity.keepSearching.success") .append(" ") .append(getCommandTextComponent("commands.client.cancel", "/ctask stop " + taskName))); @@ -114,7 +113,7 @@ protected void onTick() { ((IEntity) entity).addGlowingTicket(seconds * 20, color); } - sendFeedback("commands.cglow.entity.success", entities.size()); + source.sendFeedback(new TranslatableText("commands.cglow.entity.success", entities.size())); return entities.size(); } @@ -145,7 +144,7 @@ private static int glowBlock(FabricClientCommandSource source, BlockPos pos1, Bl RenderQueue.addCuboid(RenderQueue.Layer.ON_TOP, box, box, color, seconds * 20); } - sendFeedback("commands.cglow.area.success", boundingBoxes.size()); + source.sendFeedback(new TranslatableText("commands.cglow.area.success", boundingBoxes.size())); return boundingBoxes.size(); } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/HotbarCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/HotbarCommand.java index 06fbcff81..5d0e01ff8 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/HotbarCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/HotbarCommand.java @@ -1,12 +1,8 @@ package net.earthcomputer.clientcommands.command; -import static com.mojang.brigadier.arguments.IntegerArgumentType.*; -import static net.earthcomputer.clientcommands.command.ClientCommandHelper.*; -import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.*; - import com.mojang.brigadier.CommandDispatcher; -import com.mojang.brigadier.exceptions.*; - +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; import net.fabricmc.fabric.api.client.command.v1.FabricClientCommandSource; import net.minecraft.client.MinecraftClient; import net.minecraft.client.network.ClientPlayerEntity; @@ -17,6 +13,9 @@ import net.minecraft.text.Text; import net.minecraft.text.TranslatableText; +import static com.mojang.brigadier.arguments.IntegerArgumentType.*; +import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.*; + public class HotbarCommand { private static final SimpleCommandExceptionType NOT_CREATIVE_EXCEPTION = new SimpleCommandExceptionType(new TranslatableText("commands.chotbar.notCreative")); @@ -33,7 +32,7 @@ public static void register(CommandDispatcher dispatc } private static int save(FabricClientCommandSource source, int index) throws CommandSyntaxException { - MinecraftClient client = MinecraftClient.getInstance(); + MinecraftClient client = source.getClient(); HotbarStorage storage = client.getCreativeHotbarStorage(); HotbarStorageEntry entry = storage.getSavedHotbar(index - 1); @@ -46,12 +45,12 @@ private static int save(FabricClientCommandSource source, int index) throws Comm Text loadKey = client.options.loadToolbarActivatorKey.getBoundKeyLocalizedText(); Text hotbarKey = client.options.hotbarKeys[index - 1].getBoundKeyLocalizedText(); - sendFeedback(new TranslatableText("inventory.hotbarSaved", loadKey, hotbarKey)); + source.sendFeedback(new TranslatableText("inventory.hotbarSaved", loadKey, hotbarKey)); return 0; } private static int restore(FabricClientCommandSource source, int index) throws CommandSyntaxException { - MinecraftClient client = MinecraftClient.getInstance(); + MinecraftClient client = source.getClient(); ClientPlayerEntity player = client.player; if (!player.getAbilities().creativeMode) { @@ -70,7 +69,7 @@ private static int restore(FabricClientCommandSource source, int index) throws C player.playerScreenHandler.sendContentUpdates(); - sendFeedback(new TranslatableText("commands.chotbar.restoredHotbar", index)); + source.sendFeedback(new TranslatableText("commands.chotbar.restoredHotbar", index)); return 0; } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/ItemGroupCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/ItemGroupCommand.java index 8543575b4..a7a346c4e 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/ItemGroupCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/ItemGroupCommand.java @@ -34,9 +34,8 @@ import static com.mojang.brigadier.arguments.IntegerArgumentType.*; import static com.mojang.brigadier.arguments.StringArgumentType.*; import static dev.xpple.clientarguments.arguments.CItemStackArgumentType.*; -import static net.earthcomputer.clientcommands.command.ClientCommandHelper.*; -import static net.minecraft.command.CommandSource.*; import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.*; +import static net.minecraft.command.CommandSource.*; public class ItemGroupCommand { @@ -113,7 +112,7 @@ private static int addGroup(FabricClientCommandSource source, String name, ItemS groups.put(name, new Group(itemGroup, icon, new NbtList())); saveFile(); - sendFeedback("commands.citemgroup.addGroup.success", name); + source.sendFeedback(new TranslatableText("commands.citemgroup.addGroup.success", name)); return 0; } @@ -143,7 +142,7 @@ private static int removeGroup(FabricClientCommandSource source, String name) th throw new RuntimeException(e); } saveFile(); - sendFeedback("commands.citemgroup.removeGroup.success", name); + source.sendFeedback(new TranslatableText("commands.citemgroup.removeGroup.success", name)); return 0; } @@ -158,7 +157,7 @@ private static int addStack(FabricClientCommandSource source, String name, ItemS reloadGroups(); saveFile(); - sendFeedback("commands.citemgroup.addStack.success", itemStack.getItem().getName(), name); + source.sendFeedback(new TranslatableText("commands.citemgroup.addStack.success", itemStack.getItem().getName(), name)); return 0; } @@ -176,7 +175,7 @@ private static int removeStack(FabricClientCommandSource source, String name, in reloadGroups(); saveFile(); - sendFeedback("commands.citemgroup.removeStack.success", name, index); + source.sendFeedback(new TranslatableText("commands.citemgroup.removeStack.success", name, index)); return 0; } @@ -194,7 +193,7 @@ private static int setStack(FabricClientCommandSource source, String name, int i reloadGroups(); saveFile(); - sendFeedback("commands.citemgroup.setStack.success", name, index, itemStack.getItem().getName()); + source.sendFeedback(new TranslatableText("commands.citemgroup.setStack.success", name, index, itemStack.getItem().getName())); return 0; } @@ -216,7 +215,7 @@ private static int changeIcon(FabricClientCommandSource source, String name, Ite reloadGroups(); saveFile(); - sendFeedback("commands.citemgroup.changeIcon.success", name, old.getItem().getName(), icon.getItem().getName()); + source.sendFeedback(new TranslatableText("commands.citemgroup.changeIcon.success", name, old.getItem().getName(), icon.getItem().getName())); return 0; } @@ -242,7 +241,7 @@ private static int renameGroup(FabricClientCommandSource source, String name, St reloadGroups(); saveFile(); - sendFeedback("commands.citemgroup.renameGroup.success", name, _new); + source.sendFeedback(new TranslatableText("commands.citemgroup.renameGroup.success", name, _new)); return 0; } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/KitCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/KitCommand.java index ee9e75062..7db086777 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/KitCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/KitCommand.java @@ -34,7 +34,6 @@ import java.util.List; import java.util.Map; -import static net.earthcomputer.clientcommands.command.ClientCommandHelper.*; import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.*; public class KitCommand { @@ -93,9 +92,9 @@ private static int create(FabricClientCommandSource source, String name) throws if (kits.containsKey(name)) { throw ALREADY_EXISTS_EXCEPTION.create(name); } - kits.put(name, client.player.getInventory().writeNbt(new NbtList())); + kits.put(name, source.getPlayer().getInventory().writeNbt(new NbtList())); saveFile(); - sendFeedback("commands.ckit.create.success", name); + source.sendFeedback(new TranslatableText("commands.ckit.create.success", name)); return 0; } @@ -104,7 +103,7 @@ private static int delete(FabricClientCommandSource source, String name) throws throw NOT_FOUND_EXCEPTION.create(name); } saveFile(); - sendFeedback("commands.ckit.delete.success", name); + source.sendFeedback(new TranslatableText("commands.ckit.delete.success", name)); return 0; } @@ -112,14 +111,14 @@ private static int edit(FabricClientCommandSource source, String name) throws Co if (!kits.containsKey(name)) { throw NOT_FOUND_EXCEPTION.create(name); } - kits.put(name, client.player.getInventory().writeNbt(new NbtList())); + kits.put(name, source.getPlayer().getInventory().writeNbt(new NbtList())); saveFile(); - sendFeedback("commands.ckit.edit.success", name); + source.sendFeedback(new TranslatableText("commands.ckit.edit.success", name)); return 0; } private static int load(FabricClientCommandSource source, String name, boolean override) throws CommandSyntaxException { - if (!client.player.getAbilities().creativeMode) { + if (!source.getPlayer().getAbilities().creativeMode) { throw NOT_CREATIVE_EXCEPTION.create(); } @@ -128,29 +127,29 @@ private static int load(FabricClientCommandSource source, String name, boolean o throw NOT_FOUND_EXCEPTION.create(name); } - PlayerInventory tempInv = new PlayerInventory(client.player); + PlayerInventory tempInv = new PlayerInventory(source.getPlayer()); tempInv.readNbt(kit); - List slots = client.player.playerScreenHandler.slots; + List slots = source.getPlayer().playerScreenHandler.slots; for (int i = 0; i < slots.size(); i++) { - if (slots.get(i).inventory == client.player.getInventory()) { + if (slots.get(i).inventory == source.getPlayer().getInventory()) { ItemStack itemStack = tempInv.getStack(slots.get(i).getIndex()); if (!itemStack.isEmpty() || override) { - client.interactionManager.clickCreativeStack(itemStack, i); + source.getClient().interactionManager.clickCreativeStack(itemStack, i); } } } - client.player.playerScreenHandler.sendContentUpdates(); - sendFeedback("commands.ckit.load.success", name); + source.getPlayer().playerScreenHandler.sendContentUpdates(); + source.sendFeedback(new TranslatableText("commands.ckit.load.success", name)); return 0; } private static int list(FabricClientCommandSource source) { if (kits.isEmpty()) { - sendFeedback("commands.ckit.list.empty"); + source.sendFeedback(new TranslatableText("commands.ckit.list.empty")); } else { String list = String.join(", ", kits.keySet()); - sendFeedback("commands.ckit.list", list); + source.sendFeedback(new TranslatableText("commands.ckit.list", list)); } return kits.size(); } @@ -161,7 +160,7 @@ private static int preview(FabricClientCommandSource source, String name) throws throw NOT_FOUND_EXCEPTION.create(name); } - PlayerInventory tempInv = new PlayerInventory(client.player); + PlayerInventory tempInv = new PlayerInventory(source.getPlayer()); tempInv.readNbt(kit); /* After executing a command, the current screen will be closed (the chat hud). @@ -169,7 +168,7 @@ After executing a command, the current screen will be closed (the chat hud). instantly along with the chat hud. Slightly delaying the opening of the screen fixes this issue. */ - client.send(() -> client.setScreen(new PreviewScreen(new PlayerScreenHandler(tempInv, true, client.player), tempInv, name))); + source.getClient().send(() -> source.getClient().setScreen(new PreviewScreen(new PlayerScreenHandler(tempInv, true, source.getPlayer()), tempInv, name))); return 0; } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/LookCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/LookCommand.java index d5459c162..948c3e14a 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/LookCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/LookCommand.java @@ -3,7 +3,6 @@ import com.mojang.brigadier.CommandDispatcher; import dev.xpple.clientarguments.arguments.CPosArgument; import net.fabricmc.fabric.api.client.command.v1.FabricClientCommandSource; -import net.minecraft.client.MinecraftClient; import net.minecraft.client.network.ClientPlayerEntity; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec2f; @@ -18,27 +17,27 @@ public static void register(CommandDispatcher dispatc dispatcher.register(literal("clook") .then(literal("block") .then(argument("pos", blockPos()) - .executes(ctx -> lookBlock(getCBlockPos(ctx, "pos"))))) + .executes(ctx -> lookBlock(ctx.getSource(), getCBlockPos(ctx, "pos"))))) .then(literal("angles") .then(argument("rotation", rotation()) .executes(ctx -> lookAngles(ctx.getSource(), getCRotation(ctx, "rotation"))))) .then(literal("cardinal") .then(literal("down") - .executes(ctx -> lookCardinal(ctx.getSource().getRotation().y, 90))) + .executes(ctx -> lookCardinal(ctx.getSource(), 90))) .then(literal("up") - .executes(ctx -> lookCardinal(ctx.getSource().getRotation().y, -90))) + .executes(ctx -> lookCardinal(ctx.getSource(), -90))) .then(literal("west") - .executes(ctx -> lookCardinal(90, 0))) + .executes(ctx -> lookCardinal(ctx.getSource(), 90, 0))) .then(literal("east") - .executes(ctx -> lookCardinal(-90, 0))) + .executes(ctx -> lookCardinal(ctx.getSource(),-90, 0))) .then(literal("north") - .executes(ctx -> lookCardinal(-180, 0))) + .executes(ctx -> lookCardinal(ctx.getSource(), -180, 0))) .then(literal("south") - .executes(ctx -> lookCardinal(0, 0))))); + .executes(ctx -> lookCardinal(ctx.getSource(), 0, 0))))); } - private static int lookBlock(BlockPos pos) { - ClientPlayerEntity player = MinecraftClient.getInstance().player; + private static int lookBlock(FabricClientCommandSource source, BlockPos pos) { + ClientPlayerEntity player = source.getPlayer(); double dx = (pos.getX() + 0.5) - player.getX(); double dy = (pos.getY() + 0.5) - (player.getY() + player.getStandingEyeHeight()); double dz = (pos.getZ() + 0.5) - player.getZ(); @@ -50,11 +49,15 @@ private static int lookBlock(BlockPos pos) { private static int lookAngles(FabricClientCommandSource source, CPosArgument rotation) { Vec2f rot = rotation.toAbsoluteRotation(source); - return doLook(MinecraftClient.getInstance().player, rot.y, rot.x); + return doLook(source.getPlayer(), rot.y, rot.x); } - private static int lookCardinal(float yaw, float pitch) { - return doLook(MinecraftClient.getInstance().player, yaw, pitch); + private static int lookCardinal(FabricClientCommandSource source, float yaw, float pitch) { + return doLook(source.getPlayer(), yaw, pitch); + } + + private static int lookCardinal(FabricClientCommandSource source, float pitch) { + return lookCardinal(source, source.getRotation().y, pitch); } private static int doLook(ClientPlayerEntity player, float yaw, float pitch) { diff --git a/src/main/java/net/earthcomputer/clientcommands/command/NoteCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/NoteCommand.java index 20c973441..185687050 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/NoteCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/NoteCommand.java @@ -2,7 +2,6 @@ import com.mojang.brigadier.CommandDispatcher; import net.fabricmc.fabric.api.client.command.v1.FabricClientCommandSource; -import net.minecraft.client.MinecraftClient; import net.minecraft.text.LiteralText; import static net.earthcomputer.clientcommands.command.arguments.FormattedTextArgumentType.*; @@ -17,7 +16,7 @@ public static void register(CommandDispatcher dispatc } private static int note(FabricClientCommandSource source, LiteralText message) { - MinecraftClient.getInstance().inGameHud.getChatHud().addMessage(message); + source.getClient().inGameHud.getChatHud().addMessage(message); return 0; } } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/PermissionLevelCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/PermissionLevelCommand.java index 615fea88b..5eedc7ff1 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/PermissionLevelCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/PermissionLevelCommand.java @@ -1,15 +1,10 @@ package net.earthcomputer.clientcommands.command; -import com.mojang.brigadier.Command; import com.mojang.brigadier.CommandDispatcher; - import net.earthcomputer.clientcommands.interfaces.IEntity; import net.fabricmc.fabric.api.client.command.v1.FabricClientCommandSource; -import net.minecraft.client.MinecraftClient; -import net.minecraft.text.LiteralText; import net.minecraft.text.TranslatableText; -import static net.earthcomputer.clientcommands.command.ClientCommandHelper.*; import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.*; public class PermissionLevelCommand { @@ -20,10 +15,8 @@ public static void register(CommandDispatcher dispatc } private static int getPermissionLevel(FabricClientCommandSource source) { - assert MinecraftClient.getInstance().player != null; - - int permissionLevel = ((IEntity) MinecraftClient.getInstance().player).callGetPermissionLevel(); - sendFeedback(new TranslatableText("commands.cpermissionlevel.success", permissionLevel)); + int permissionLevel = ((IEntity) source.getPlayer()).callGetPermissionLevel(); + source.sendFeedback(new TranslatableText("commands.cpermissionlevel.success", permissionLevel)); return permissionLevel; } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/PingCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/PingCommand.java index 351be2beb..601daca14 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/PingCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/PingCommand.java @@ -1,30 +1,27 @@ package net.earthcomputer.clientcommands.command; import com.mojang.brigadier.CommandDispatcher; -import net.earthcomputer.clientcommands.features.FishingCracker; import net.fabricmc.fabric.api.client.command.v1.FabricClientCommandSource; import net.minecraft.client.MinecraftClient; import net.minecraft.client.network.ClientPlayNetworkHandler; import net.minecraft.client.network.PlayerListEntry; import net.minecraft.text.TranslatableText; -import static net.earthcomputer.clientcommands.command.ClientCommandHelper.*; import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.*; public class PingCommand { public static void register(CommandDispatcher dispatcher) { dispatcher.register(literal("cping") - .executes(ctx -> printPing())); + .executes(ctx -> printPing(ctx.getSource()))); } - private static int printPing() { - MinecraftClient instance = MinecraftClient.getInstance(); + private static int printPing(FabricClientCommandSource source) { int ping = getLocalPing(); - if (ping == -1 || instance.isInSingleplayer()) { - sendFeedback(new TranslatableText("commands.cping.local")); + if (ping == -1 || source.getClient().isInSingleplayer()) { + source.sendFeedback(new TranslatableText("commands.cping.local")); } else { - sendFeedback(new TranslatableText("commands.cping.multiplayer", ping)); + source.sendFeedback(new TranslatableText("commands.cping.multiplayer", ping)); } return 0; diff --git a/src/main/java/net/earthcomputer/clientcommands/command/PlayerInfoCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/PlayerInfoCommand.java index dc61b8bea..3073b9f06 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/PlayerInfoCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/PlayerInfoCommand.java @@ -7,9 +7,7 @@ import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.tree.LiteralCommandNode; import net.fabricmc.fabric.api.client.command.v1.FabricClientCommandSource; -import net.minecraft.client.MinecraftClient; import net.minecraft.client.network.PlayerListEntry; -import net.minecraft.command.CommandSource; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.text.TranslatableText; @@ -18,20 +16,20 @@ import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Duration; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import static com.mojang.brigadier.arguments.StringArgumentType.*; -import static net.earthcomputer.clientcommands.command.ClientCommandHelper.*; -import static net.minecraft.command.CommandSource.*; import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.*; +import static net.minecraft.command.CommandSource.*; public class PlayerInfoCommand { private static final Map> cacheByName = new HashMap<>(); private static final Map> cacheByUuid = new HashMap<>(); - private static final MinecraftClient client = MinecraftClient.getInstance(); - private static final JsonParser parser = new JsonParser(); private static final HttpClient httpClient = HttpClient.newHttpClient(); private static final int DURATION = 5; // seconds @@ -41,34 +39,34 @@ public static void register(CommandDispatcher dispatc dispatcher.register(literal("cplayerinfo") .then(literal("namehistory") .then(argument("player", string()) - .suggests((context, builder) -> suggestMatching(((CommandSource) context.getSource()).getPlayerNames(), builder)) + .suggests((context, builder) -> suggestMatching(context.getSource().getPlayerNames(), builder)) .executes(ctx -> getNameHistory(ctx.getSource(), getString(ctx, "player")))))); } private static int getNameHistory(FabricClientCommandSource source, String player) { if (player.length() >= 32) { if (cacheByUuid.containsKey(player)) { - sendFeedback(new TranslatableText("commands.cplayerinfo.getNameHistory.success", player, String.join(", ", cacheByUuid.get(player)))); + source.sendFeedback(new TranslatableText("commands.cplayerinfo.getNameHistory.success", player, String.join(", ", cacheByUuid.get(player)))); } else { - fetchNameHistory(player); + fetchNameHistory(source, player); } } else { if (cacheByName.containsKey(player)) { - sendFeedback(new TranslatableText("commands.cplayerinfo.getNameHistory.success", player, String.join(", ", cacheByName.get(player)))); + source.sendFeedback(new TranslatableText("commands.cplayerinfo.getNameHistory.success", player, String.join(", ", cacheByName.get(player)))); } else { - if (client.isInSingleplayer()) { - ServerPlayerEntity playerEntity = client.getServer().getPlayerManager().getPlayer(player); + if (source.getClient().isInSingleplayer()) { + ServerPlayerEntity playerEntity = source.getClient().getServer().getPlayerManager().getPlayer(player); if (playerEntity == null) { - getNameHistory(player); + getNameHistoryByName(source, player); } else { - fetchNameHistory(playerEntity.getUuidAsString()); + fetchNameHistory(source, playerEntity.getUuidAsString()); } } else { - PlayerListEntry playerListEntry = client.getNetworkHandler().getPlayerListEntry(player); + PlayerListEntry playerListEntry = source.getClient().getNetworkHandler().getPlayerListEntry(player); if (playerListEntry == null) { - getNameHistory(player); + getNameHistoryByName(source, player); } else { - fetchNameHistory(playerListEntry.getProfile().getId().toString()); + fetchNameHistory(source, playerListEntry.getProfile().getId().toString()); } } } @@ -76,32 +74,32 @@ private static int getNameHistory(FabricClientCommandSource source, String playe return 0; } - private static void getNameHistory(String player) { + private static void getNameHistoryByName(FabricClientCommandSource source, String player) { HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.mojang.com/users/profiles/minecraft/" + player)) .timeout(Duration.ofSeconds(DURATION)) .GET() .build(); httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString()) .thenApply(HttpResponse::body) - .thenAccept(response -> client.send(() -> { - JsonElement result = parser.parse(response); + .thenAccept(response -> source.getClient().send(() -> { + JsonElement result = JsonParser.parseString(response); if (result instanceof JsonNull) { - sendError(new TranslatableText("commands.cplayerinfo.ioException")); + source.sendError(new TranslatableText("commands.cplayerinfo.ioException")); } else { - fetchNameHistory(result.getAsJsonObject().get("id").getAsString()); + fetchNameHistory(source, result.getAsJsonObject().get("id").getAsString()); } })); } - private static void fetchNameHistory(String uuid) { + private static void fetchNameHistory(FabricClientCommandSource source, String uuid) { HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.mojang.com/user/profiles/" + uuid + "/names")) .timeout(Duration.ofSeconds(DURATION)) .GET() .build(); httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString()) .thenApply(HttpResponse::body) - .thenAccept(response -> client.send(() -> { - JsonElement result = parser.parse(response); + .thenAccept(response -> source.getClient().send(() -> { + JsonElement result = JsonParser.parseString(response); if (result.isJsonArray()) { JsonArray array = result.getAsJsonArray(); List names = new ArrayList<>(); @@ -109,9 +107,9 @@ private static void fetchNameHistory(String uuid) { String player = names.get(names.size() - 1); cacheByName.put(player, names); cacheByUuid.put(uuid, names); - sendFeedback(new TranslatableText("commands.cplayerinfo.getNameHistory.success", player, String.join(", ", names))); + source.sendFeedback(new TranslatableText("commands.cplayerinfo.getNameHistory.success", player, String.join(", ", names))); } else { - sendError(new TranslatableText("commands.cplayerinfo.ioException")); + source.sendError(new TranslatableText("commands.cplayerinfo.ioException")); } })); } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/RenderCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/RenderCommand.java index 733c4c9d5..7ffd09fb6 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/RenderCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/RenderCommand.java @@ -4,9 +4,9 @@ import dev.xpple.clientarguments.arguments.CEntitySelector; import net.earthcomputer.clientcommands.features.RenderSettings; import net.fabricmc.fabric.api.client.command.v1.FabricClientCommandSource; +import net.minecraft.text.TranslatableText; import static dev.xpple.clientarguments.arguments.CEntityArgumentType.*; -import static net.earthcomputer.clientcommands.command.ClientCommandHelper.*; import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.*; public class RenderCommand { @@ -25,7 +25,7 @@ public static void register(CommandDispatcher dispatc private static int enableEntityRendering(FabricClientCommandSource source, CEntitySelector selector, boolean enable) { RenderSettings.addEntityRenderSelector(selector, enable); - sendFeedback("commands.crender.entities.success"); + source.sendFeedback(new TranslatableText("commands.crender.entities.success")); return 0; } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/ShrugCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/ShrugCommand.java index 78258ac14..bd71a978c 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/ShrugCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/ShrugCommand.java @@ -2,7 +2,6 @@ import com.mojang.brigadier.CommandDispatcher; import net.fabricmc.fabric.api.client.command.v1.FabricClientCommandSource; -import net.minecraft.client.MinecraftClient; import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.*; @@ -10,11 +9,11 @@ public class ShrugCommand { public static void register(CommandDispatcher dispatcher) { dispatcher.register(literal("cshrug") - .executes(ctx -> shrug())); + .executes(ctx -> shrug(ctx.getSource()))); } - private static int shrug() { - MinecraftClient.getInstance().player.sendChatMessage("¯\\_(ツ)_/¯"); + private static int shrug(FabricClientCommandSource source) { + source.getPlayer().sendChatMessage("¯\\_(ツ)_/¯"); return 0; } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/TaskCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/TaskCommand.java index 3d64675b5..1ac19db94 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/TaskCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/TaskCommand.java @@ -11,7 +11,6 @@ import java.util.List; import static com.mojang.brigadier.arguments.StringArgumentType.*; -import static net.earthcomputer.clientcommands.command.ClientCommandHelper.*; import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.*; public class TaskCommand { @@ -32,11 +31,11 @@ private static int listTasks(FabricClientCommandSource source) { int taskCount = TaskManager.getTaskCount(); if (taskCount == 0) { - sendError(new TranslatableText("commands.ctask.list.noTasks")); + source.sendError(new TranslatableText("commands.ctask.list.noTasks")); } else { - sendFeedback(new TranslatableText("commands.ctask.list.success", taskCount).formatted(Formatting.BOLD)); + source.sendFeedback(new TranslatableText("commands.ctask.list.success", taskCount).formatted(Formatting.BOLD)); for (String task : tasks) { - sendFeedback(new LiteralText("- " + task)); + source.sendFeedback(new LiteralText("- " + task)); } } @@ -52,13 +51,15 @@ private static int stopTasks(FabricClientCommandSource source, String pattern) { for (String task : tasksToStop) TaskManager.removeTask(task); - if (tasksToStop.isEmpty()) - if (pattern.isEmpty()) - sendError(new TranslatableText("commands.ctask.list.noTasks")); - else - sendError(new TranslatableText("commands.ctask.stop.noMatch")); - else - sendFeedback(new TranslatableText("commands.ctask.stop.success", tasksToStop.size())); + if (tasksToStop.isEmpty()) { + if (pattern.isEmpty()) { + source.sendError(new TranslatableText("commands.ctask.list.noTasks")); + } else { + source.sendError(new TranslatableText("commands.ctask.stop.noMatch")); + } + } else { + source.sendFeedback(new TranslatableText("commands.ctask.stop.success", tasksToStop.size())); + } return tasksToStop.size(); } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/TempRuleCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/TempRuleCommand.java index f1bc7d3f7..496c80e9b 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/TempRuleCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/TempRuleCommand.java @@ -14,7 +14,6 @@ import static com.mojang.brigadier.arguments.BoolArgumentType.*; import static com.mojang.brigadier.arguments.DoubleArgumentType.*; import static com.mojang.brigadier.arguments.IntegerArgumentType.*; -import static net.earthcomputer.clientcommands.command.ClientCommandHelper.*; import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.*; public class TempRuleCommand { @@ -80,9 +79,9 @@ private static int listRules(FabricClientCommandSource source) { List rules = TempRules.getRules(); rules.sort(Comparator.naturalOrder()); - sendFeedback(new TranslatableText("commands.ctemprule.list.header", rules.size())); + source.sendFeedback(new TranslatableText("commands.ctemprule.list.header", rules.size())); for (String rule : rules) { - sendFeedback(new LiteralText("- " + rule)); + source.sendFeedback(new LiteralText("- " + rule)); } return rules.size(); @@ -91,21 +90,21 @@ private static int listRules(FabricClientCommandSource source) { private static int getRule(FabricClientCommandSource source, String rule) { Object val = TempRules.get(rule); String str = TempRules.asString(val); - sendFeedback(new LiteralText(rule + " = " + str)); + source.sendFeedback(new LiteralText(rule + " = " + str)); return 0; } private static int setRule(FabricClientCommandSource source, String rule, Object value) { TempRules.set(rule, value); String str = TempRules.asString(value); - sendFeedback(new TranslatableText("commands.ctemprule.set.success", rule, str)); + source.sendFeedback(new TranslatableText("commands.ctemprule.set.success", rule, str)); return 0; } private static int resetRule(FabricClientCommandSource source, String rule) { TempRules.reset(rule); String str = TempRules.asString(TempRules.get(rule)); - sendFeedback(new TranslatableText("commands.ctemprule.reset.success", rule, str)); + source.sendFeedback(new TranslatableText("commands.ctemprule.reset.success", rule, str)); return 0; } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/UsageTreeCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/UsageTreeCommand.java index 2d63c06e5..31dc441eb 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/UsageTreeCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/UsageTreeCommand.java @@ -2,7 +2,6 @@ import com.google.common.collect.Iterables; import com.mojang.brigadier.CommandDispatcher; -import com.mojang.brigadier.context.CommandContext; import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; import com.mojang.brigadier.tree.CommandNode; @@ -17,7 +16,6 @@ import java.util.List; import static com.mojang.brigadier.arguments.StringArgumentType.*; -import static net.earthcomputer.clientcommands.command.ClientCommandHelper.*; import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.*; public class UsageTreeCommand { @@ -26,7 +24,7 @@ public class UsageTreeCommand { public static void register(CommandDispatcher dispatcher) { dispatcher.register( literal("cusagetree") - .executes(ctx -> usage(ctx, dispatcher)) + .executes(ctx -> usage(ctx.getSource(), dispatcher)) .then( argument("command", greedyString()) .suggests((ctx, builder) -> @@ -36,31 +34,30 @@ public static void register(CommandDispatcher dispatc .map(CommandNode::getUsageText) .toList(), builder) ) - .executes(ctx -> usageCommand(ctx, dispatcher)) + .executes(ctx -> usageCommand(ctx.getSource(), getString(ctx, "command"), dispatcher)) ) ); } - private static int usage(CommandContext ctx, CommandDispatcher dispatcher) { + private static int usage(FabricClientCommandSource source, CommandDispatcher dispatcher) { var content = tree(dispatcher.getRoot()); - sendFeedback(new LiteralText("/")); + source.sendFeedback(new LiteralText("/")); for (var line : content) { - sendFeedback(line); + source.sendFeedback(line); } return content.size() + 1; } - private static int usageCommand(CommandContext ctx, CommandDispatcher dispatcher) throws CommandSyntaxException { - String cmdName = getString(ctx, "command"); - var parseResults = dispatcher.parse(cmdName, ctx.getSource()); + private static int usageCommand(FabricClientCommandSource source, String cmdName, CommandDispatcher dispatcher) throws CommandSyntaxException { + var parseResults = dispatcher.parse(cmdName, source); if (parseResults.getContext().getNodes().isEmpty()) { throw FAILED_EXCEPTION.create(); } var node = Iterables.getLast(parseResults.getContext().getNodes()).getNode(); var content = tree(node); - sendFeedback(new LiteralText("/" + cmdName).styled(s -> s.withColor(node.getCommand() != null ? Formatting.GREEN : Formatting.WHITE))); + source.sendFeedback(new LiteralText("/" + cmdName).styled(s -> s.withColor(node.getCommand() != null ? Formatting.GREEN : Formatting.WHITE))); for (var line : content) { - sendFeedback(line); + source.sendFeedback(line); } return content.size() + 1; } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/UuidCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/UuidCommand.java index 6877c48ca..54ff5026c 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/UuidCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/UuidCommand.java @@ -1,17 +1,11 @@ package net.earthcomputer.clientcommands.command; import com.mojang.brigadier.CommandDispatcher; - import net.fabricmc.fabric.api.client.command.v1.FabricClientCommandSource; import net.minecraft.entity.Entity; -import net.minecraft.text.ClickEvent; -import net.minecraft.text.HoverEvent; -import net.minecraft.text.LiteralText; -import net.minecraft.text.Text; -import net.minecraft.text.TranslatableText; +import net.minecraft.text.*; import static dev.xpple.clientarguments.arguments.CEntityArgumentType.*; -import static net.earthcomputer.clientcommands.command.ClientCommandHelper.*; import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.*; public class UuidCommand { @@ -24,14 +18,13 @@ public static void register(CommandDispatcher dispatc private static int getUuid(FabricClientCommandSource source, Entity entity) { String uuid = entity.getUuidAsString(); - Text uuidText = new LiteralText(uuid).styled(style -> { - return style - .withUnderline(true) - .withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TranslatableText("chat.copy.click"))) - .withClickEvent(new ClickEvent(ClickEvent.Action.COPY_TO_CLIPBOARD, uuid)); - }); - - sendFeedback(new TranslatableText("commands.cuuid.success", entity.getDisplayName(), uuidText)); + Text uuidText = new LiteralText(uuid).styled(style -> style + .withUnderline(true) + .withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TranslatableText("chat.copy.click"))) + .withClickEvent(new ClickEvent(ClickEvent.Action.COPY_TO_CLIPBOARD, uuid)) + ); + + source.sendFeedback(new TranslatableText("commands.cuuid.success", entity.getDisplayName(), uuidText)); return 0; } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/WikiCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/WikiCommand.java index 569c5598a..17d81bd49 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/WikiCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/WikiCommand.java @@ -7,7 +7,6 @@ import net.minecraft.text.TranslatableText; import static com.mojang.brigadier.arguments.StringArgumentType.*; -import static net.earthcomputer.clientcommands.command.ClientCommandHelper.*; import static net.fabricmc.fabric.api.client.command.v1.ClientCommandManager.*; public class WikiCommand { @@ -22,13 +21,13 @@ private static int displayWikiPage(FabricClientCommandSource source, String page String content = WikiRetriever.getWikiSummary(page); if (content == null) { - sendError(new TranslatableText("commands.cwiki.failed")); + source.sendError(new TranslatableText("commands.cwiki.failed")); return 0; } content = content.trim(); for (String line : content.split("\n")) { - sendFeedback(new LiteralText(line)); + source.sendFeedback(new LiteralText(line)); } return content.length(); From 155a6b04814f949a4901f5a61d600ca5ca6160a2 Mon Sep 17 00:00:00 2001 From: Frederik van der Els Date: Fri, 20 May 2022 23:08:57 +0200 Subject: [PATCH 2/3] Add back the helper methods for use outside of commands --- .../clientcommands/command/ClientCommandHelper.java | 12 ++++++++++++ .../clientcommands/command/FindItemCommand.java | 4 ++-- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/src/main/java/net/earthcomputer/clientcommands/command/ClientCommandHelper.java b/src/main/java/net/earthcomputer/clientcommands/command/ClientCommandHelper.java index f5a93806c..7122e1f47 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/ClientCommandHelper.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/ClientCommandHelper.java @@ -30,6 +30,18 @@ public static FabricClientCommandSource withFlags(FabricClientCommandSource sour } } + public static void sendError(Text error) { + sendFeedback(new LiteralText("").append(error).formatted(Formatting.RED)); + } + + public static void sendFeedback(String message, Object... args) { + sendFeedback(new TranslatableText(message, args)); + } + + public static void sendFeedback(Text message) { + MinecraftClient.getInstance().inGameHud.getChatHud().addMessage(message); + } + public static void addOverlayMessage(Text message, int time) { InGameHud inGameHud = MinecraftClient.getInstance().inGameHud; inGameHud.setOverlayMessage(message, false); diff --git a/src/main/java/net/earthcomputer/clientcommands/command/FindItemCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/FindItemCommand.java index a3b33c955..353015be9 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/FindItemCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/FindItemCommand.java @@ -239,7 +239,7 @@ public void updateSlotStacks(int revision, List stacks, ItemStack cur } } if (matchingItems > 0) { - MinecraftClient.getInstance().inGameHud.getChatHud().addMessage(new TranslatableText("commands.cfinditem.match.left", matchingItems, searchingForName) + sendFeedback(new TranslatableText("commands.cfinditem.match.left", matchingItems, searchingForName) .append(getLookCoordsTextComponent(currentlySearching)) .append(new TranslatableText("commands.cfinditem.match.right", matchingItems, searchingForName))); totalFound += matchingItems; @@ -261,7 +261,7 @@ public void updateSlotStacks(int revision, List stacks, ItemStack cur @Override public void onCompleted() { - MinecraftClient.getInstance().inGameHud.getChatHud().addMessage(new TranslatableText("commands.cfinditem.total", totalFound, searchingForName).formatted(Formatting.BOLD)); + sendFeedback(new TranslatableText("commands.cfinditem.total", totalFound, searchingForName).formatted(Formatting.BOLD)); } } } From 15550d16b8a85fddd7a2de5e4729cd34e3fd2414 Mon Sep 17 00:00:00 2001 From: Frederik van der Els Date: Sat, 28 May 2022 20:03:03 +0200 Subject: [PATCH 3/3] Remove some static fields + replace occurrences of `client.player` --- .../clientcommands/command/CGiveCommand.java | 8 +++----- .../clientcommands/command/HotbarCommand.java | 7 +++---- .../clientcommands/command/ItemGroupCommand.java | 8 ++++---- .../earthcomputer/clientcommands/command/KitCommand.java | 6 +++--- 4 files changed, 13 insertions(+), 16 deletions(-) diff --git a/src/main/java/net/earthcomputer/clientcommands/command/CGiveCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/CGiveCommand.java index 4b9b872b6..7656cdce8 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/CGiveCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/CGiveCommand.java @@ -4,7 +4,6 @@ import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; import net.fabricmc.fabric.api.client.command.v1.FabricClientCommandSource; -import net.minecraft.client.MinecraftClient; import net.minecraft.command.argument.ItemStackArgument; import net.minecraft.item.ItemStack; import net.minecraft.text.TranslatableText; @@ -26,14 +25,13 @@ public static void register(CommandDispatcher dispatc } private static int give(FabricClientCommandSource source, ItemStackArgument itemArgument, int count) throws CommandSyntaxException { - final MinecraftClient client = source.getClient(); - if (!client.player.getAbilities().creativeMode) { + if (!source.getPlayer().getAbilities().creativeMode) { throw NOT_CREATIVE_EXCEPTION.create(); } ItemStack stack = itemArgument.createStack(Math.min(count, itemArgument.getItem().getMaxCount()), false); - client.interactionManager.clickCreativeStack(stack, 36 + client.player.getInventory().selectedSlot); - client.player.playerScreenHandler.sendContentUpdates(); + source.getClient().interactionManager.clickCreativeStack(stack, 36 + source.getPlayer().getInventory().selectedSlot); + source.getPlayer().playerScreenHandler.sendContentUpdates(); source.sendFeedback(new TranslatableText("commands.cgive.success", count, stack.toHoverableText())); return 0; diff --git a/src/main/java/net/earthcomputer/clientcommands/command/HotbarCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/HotbarCommand.java index 5d0e01ff8..89b03194b 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/HotbarCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/HotbarCommand.java @@ -31,14 +31,14 @@ public static void register(CommandDispatcher dispatc .executes(ctx -> restore(ctx.getSource(), getInteger(ctx, "index")))))); } - private static int save(FabricClientCommandSource source, int index) throws CommandSyntaxException { + private static int save(FabricClientCommandSource source, int index) { MinecraftClient client = source.getClient(); HotbarStorage storage = client.getCreativeHotbarStorage(); HotbarStorageEntry entry = storage.getSavedHotbar(index - 1); for (int slot = 0; slot < PlayerInventory.getHotbarSize(); slot++) { - entry.set(slot, client.player.getInventory().getStack(slot).copy()); + entry.set(slot, source.getPlayer().getInventory().getStack(slot).copy()); } storage.save(); @@ -52,7 +52,7 @@ private static int save(FabricClientCommandSource source, int index) throws Comm private static int restore(FabricClientCommandSource source, int index) throws CommandSyntaxException { MinecraftClient client = source.getClient(); - ClientPlayerEntity player = client.player; + ClientPlayerEntity player = source.getPlayer(); if (!player.getAbilities().creativeMode) { throw NOT_CREATIVE_EXCEPTION.create(); } @@ -72,5 +72,4 @@ private static int restore(FabricClientCommandSource source, int index) throws C source.sendFeedback(new TranslatableText("commands.chotbar.restoredHotbar", index)); return 0; } - } diff --git a/src/main/java/net/earthcomputer/clientcommands/command/ItemGroupCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/ItemGroupCommand.java index a7a346c4e..d6ac7dd5c 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/ItemGroupCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/ItemGroupCommand.java @@ -4,6 +4,7 @@ import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.exceptions.DynamicCommandExceptionType; import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; +import com.mojang.datafixers.DataFixer; import com.mojang.logging.LogUtils; import com.mojang.serialization.Dynamic; import net.earthcomputer.clientcommands.interfaces.IItemGroup; @@ -50,8 +51,6 @@ public class ItemGroupCommand { private static final Path configPath = FabricLoader.getInstance().getConfigDir().resolve("clientcommands"); - private static final MinecraftClient client = MinecraftClient.getInstance(); - private static final Map groups = new HashMap<>(); static { @@ -277,6 +276,7 @@ private static void loadFile() throws IOException { final int currentVersion = SharedConstants.getGameVersion().getWorldVersion(); final int fileVersion = rootTag.getInt("DataVersion"); NbtCompound compoundTag = rootTag.getCompound("Groups"); + DataFixer dataFixer = MinecraftClient.getInstance().getDataFixer(); if (fileVersion >= currentVersion) { compoundTag.getKeys().forEach(key -> { NbtCompound group = compoundTag.getCompound(key); @@ -297,13 +297,13 @@ private static void loadFile() throws IOException { compoundTag.getKeys().forEach(key -> { NbtCompound group = compoundTag.getCompound(key); Dynamic oldStackDynamic = new Dynamic<>(NbtOps.INSTANCE, group.getCompound("icon")); - Dynamic newStackDynamic = client.getDataFixer().update(TypeReferences.ITEM_STACK, oldStackDynamic, fileVersion, currentVersion); + Dynamic newStackDynamic = dataFixer.update(TypeReferences.ITEM_STACK, oldStackDynamic, fileVersion, currentVersion); ItemStack icon = ItemStack.fromNbt((NbtCompound) newStackDynamic.getValue()); NbtList updatedListTag = new NbtList(); group.getList("items", NbtElement.COMPOUND_TYPE).forEach(tag -> { Dynamic oldTagDynamic = new Dynamic<>(NbtOps.INSTANCE, tag); - Dynamic newTagDynamic = client.getDataFixer().update(TypeReferences.ITEM_STACK, oldTagDynamic, fileVersion, currentVersion); + Dynamic newTagDynamic = dataFixer.update(TypeReferences.ITEM_STACK, oldTagDynamic, fileVersion, currentVersion); updatedListTag.add(newTagDynamic.getValue()); }); ItemGroup itemGroup = FabricItemGroupBuilder.create( diff --git a/src/main/java/net/earthcomputer/clientcommands/command/KitCommand.java b/src/main/java/net/earthcomputer/clientcommands/command/KitCommand.java index 3db64cc8c..5a9e6d81b 100644 --- a/src/main/java/net/earthcomputer/clientcommands/command/KitCommand.java +++ b/src/main/java/net/earthcomputer/clientcommands/command/KitCommand.java @@ -6,6 +6,7 @@ import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.exceptions.DynamicCommandExceptionType; import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; +import com.mojang.datafixers.DataFixer; import com.mojang.logging.LogUtils; import com.mojang.serialization.Dynamic; import net.fabricmc.fabric.api.client.command.v1.FabricClientCommandSource; @@ -49,8 +50,6 @@ public class KitCommand { private static final Path configPath = FabricLoader.getInstance().getConfigDir().resolve("clientcommands"); - private static final MinecraftClient client = MinecraftClient.getInstance(); - private static final Map kits = new HashMap<>(); static { @@ -198,6 +197,7 @@ private static void loadFile() throws IOException { final int currentVersion = SharedConstants.getGameVersion().getWorldVersion(); final int fileVersion = rootTag.getInt("DataVersion"); NbtCompound compoundTag = rootTag.getCompound("Kits"); + DataFixer dataFixer = MinecraftClient.getInstance().getDataFixer(); if (fileVersion >= currentVersion) { compoundTag.getKeys().forEach(key -> kits.put(key, compoundTag.getList(key, NbtElement.COMPOUND_TYPE))); } else { @@ -205,7 +205,7 @@ private static void loadFile() throws IOException { NbtList updatedListTag = new NbtList(); compoundTag.getList(key, NbtElement.COMPOUND_TYPE).forEach(tag -> { Dynamic oldTagDynamic = new Dynamic<>(NbtOps.INSTANCE, tag); - Dynamic newTagDynamic = client.getDataFixer().update(TypeReferences.ITEM_STACK, oldTagDynamic, fileVersion, currentVersion); + Dynamic newTagDynamic = dataFixer.update(TypeReferences.ITEM_STACK, oldTagDynamic, fileVersion, currentVersion); updatedListTag.add(newTagDynamic.getValue()); }); kits.put(key, updatedListTag);