Skip to content

Commit

Permalink
Prevent conflicting tasks from being added and report this to the user
Browse files Browse the repository at this point in the history
  • Loading branch information
Earthcomputer committed May 28, 2024
1 parent ff1f858 commit 3f28e73
Show file tree
Hide file tree
Showing 11 changed files with 52 additions and 23 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.mojang.brigadier.Command;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.earthcomputer.clientcommands.Configs;
import net.earthcomputer.clientcommands.features.EnchantmentCracker;
import net.earthcomputer.clientcommands.features.PlayerRandCracker;
Expand Down Expand Up @@ -34,7 +35,7 @@ private static boolean enchantmentPredicate(Item item, Enchantment ench) {
return !ench.isTreasureOnly() && ench.isDiscoverable() && (item == Items.BOOK || ench.canEnchant(new ItemStack(item)));
}

private static int cenchant(FabricClientCommandSource source, ItemAndEnchantmentsPredicate itemAndEnchantmentsPredicate) {
private static int cenchant(FabricClientCommandSource source, ItemAndEnchantmentsPredicate itemAndEnchantmentsPredicate) throws CommandSyntaxException {
if (!Configs.getEnchantingPrediction()) {
Component component = Component.translatable("commands.cenchant.needEnchantingPrediction")
.withStyle(ChatFormatting.RED)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.mojang.brigadier.Command;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.earthcomputer.clientcommands.Configs;
import net.earthcomputer.clientcommands.features.ServerBrandManager;
import net.earthcomputer.clientcommands.features.CCrackRng;
Expand All @@ -18,7 +19,7 @@ public static void register(CommandDispatcher<FabricClientCommandSource> dispatc
.executes(ctx -> crackPlayerRNG(ctx.getSource())));
}

private static int crackPlayerRNG(FabricClientCommandSource source) {
private static int crackPlayerRNG(FabricClientCommandSource source) throws CommandSyntaxException {
ServerBrandManager.rngWarning();
CCrackRng.crack(seed -> {
source.sendFeedback(Component.translatable("commands.ccrackrng.success", Long.toHexString(seed)));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public static void register(CommandDispatcher<FabricClientCommandSource> dispatc
})));
}

public static int findBlock(Component startingMessage, ClientBlockPredicate block) {
public static int findBlock(Component startingMessage, ClientBlockPredicate block) throws CommandSyntaxException {
sendFeedback(startingMessage);
TaskManager.addTask("cfindblock", new FindBlockTask(block));
return Command.SINGLE_SUCCESS;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.mojang.brigadier.Command;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.earthcomputer.clientcommands.features.ClientcommandsDataQueryHandler;
import net.earthcomputer.clientcommands.util.GuiBlocker;
import net.earthcomputer.clientcommands.util.MathUtil;
Expand Down Expand Up @@ -79,7 +80,7 @@ public static void register(CommandDispatcher<FabricClientCommandSource> dispatc
FLAG_KEEP_SEARCHING.addToCommand(dispatcher, cfinditem, ctx -> true);
}

private static int findItem(CommandContext<FabricClientCommandSource> ctx, boolean noSearchShulkerBox, boolean keepSearching, WithStringArgument.Result<Predicate<ItemStack>> item) {
private static int findItem(CommandContext<FabricClientCommandSource> ctx, boolean noSearchShulkerBox, boolean keepSearching, WithStringArgument.Result<Predicate<ItemStack>> item) throws CommandSyntaxException {
String taskName = TaskManager.addTask("cfinditem", makeFindItemsTask(item.string(), item.value(), !noSearchShulkerBox, keepSearching));
if (keepSearching) {
ctx.getSource().sendFeedback(Component.translatable("commands.cfinditem.starting.keepSearching", item.string())
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package net.earthcomputer.clientcommands.features;

import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.earthcomputer.clientcommands.Configs;
import net.earthcomputer.clientcommands.command.ClientCommandHelper;
import net.earthcomputer.clientcommands.task.ItemThrowTask;
Expand All @@ -8,6 +9,7 @@
import net.minecraft.client.Minecraft;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.ComponentUtils;
import net.minecraft.network.protocol.game.ClientboundAddEntityPacket;
import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket;

Expand All @@ -29,15 +31,19 @@ public interface OnCrack {
private static final int MAX_ATTEMPTS = 5;
private static String currentTaskName = null;

private static String throwItems() {
private static String throwItems() throws CommandSyntaxException {
LocalPlayer player = Minecraft.getInstance().player;
assert player != null;
player.moveTo(player.getX(), player.getY(), player.getZ(), player.getYRot(), 90);
player.connection.send(new ServerboundMovePlayerPacket.Rot(player.getYRot(), 90, true)); // point to correct location
ItemThrowTask task = new ItemThrowTask(NUM_THROWS) {
@Override
protected void onSuccess() {
CCrackRng.attemptCrack();
try {
CCrackRng.attemptCrack();
} catch (CommandSyntaxException e) {
ClientCommandHelper.sendError(ComponentUtils.fromMessage(e.getRawMessage()));
}
}

@Override
Expand All @@ -61,7 +67,7 @@ protected void onItemSpawn(ClientboundAddEntityPacket packet) {
}
}

public static void attemptCrack() {
public static void attemptCrack() throws CommandSyntaxException {
long[] seeds = CCrackRngGen.getSeeds(
Math.max(0, nextFloats[0] - MAX_ERROR), Math.min(1, nextFloats[0] + MAX_ERROR),
Math.max(0, nextFloats[1] - MAX_ERROR), Math.min(1, nextFloats[1] + MAX_ERROR),
Expand Down Expand Up @@ -92,12 +98,12 @@ public static void attemptCrack() {
callback.callback(seeds[0]);
}

public static void crack(OnCrack callback) {
public static void crack(OnCrack callback) throws CommandSyntaxException {
attemptCount = 1;
doCrack(callback);
}

private static void doCrack(OnCrack Callback){
private static void doCrack(OnCrack Callback) throws CommandSyntaxException {
callback=Callback;
ClientCommandHelper.addOverlayMessage(Component.translatable("commands.ccrackrng.retries", attemptCount, MAX_ATTEMPTS), 100);
currentTaskName = throwItems();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public class ChorusManipulation {
private static final Object GOAL_POS_KEY = new Object();

public static void onChorusManipEnabled() {
TaskManager.addTask("chorusManipRenderer", new SimpleTask() {
TaskManager.addNonConflictingTask("chorusManipRenderer", new SimpleTask() {
@Override
public boolean condition() {
return Configs.getChorusManipulation() && Minecraft.getInstance().player != null;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package net.earthcomputer.clientcommands.features;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.logging.LogUtils;
import com.seedfinding.mcseed.lcg.LCG;
import com.seedfinding.mcseed.rand.Rand;
Expand Down Expand Up @@ -320,7 +321,7 @@ public static void onEnchantedItem() {
* seed
*/

public static String manipulateEnchantments(Item item, Predicate<List<EnchantmentInstance>> enchantmentsPredicate, boolean simulate, Consumer<@Nullable ManipulateResult> callback) {
public static String manipulateEnchantments(Item item, Predicate<List<EnchantmentInstance>> enchantmentsPredicate, boolean simulate, Consumer<@Nullable ManipulateResult> callback) throws CommandSyntaxException {
LocalPlayer player = Minecraft.getInstance().player;
assert player != null;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ public static void reset() {

if (canManipulateFishing() && Configs.getFishingManipulation() == Configs.FishingManipulation.AFK) {
state = State.WAITING_FOR_RETRHOW;
TaskManager.addTask("cfishRethrow", new LongTask() {
TaskManager.addNonConflictingTask("cfishRethrow", new LongTask() {
private int counter;
@Override
public void initialize() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,4 +48,8 @@ public boolean stopOnLevelUnload(boolean isDisconnect) {
public Set<Object> getMutexKeys() {
return Set.of();
}

public final boolean conflictsWith(LongTask other) {
return getMutexKeys().stream().anyMatch(other.getMutexKeys()::contains);
}
}
Original file line number Diff line number Diff line change
@@ -1,22 +1,27 @@
package net.earthcomputer.clientcommands.task;

import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.Dynamic2CommandExceptionType;
import com.mojang.logging.LogUtils;
import net.earthcomputer.clientcommands.command.ClientCommandHelper;
import net.earthcomputer.clientcommands.event.ClientLevelEvents;
import net.earthcomputer.clientcommands.features.Relogger;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.client.Minecraft;
import net.minecraft.network.chat.Component;
import org.slf4j.Logger;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

public class TaskManager {
private static final Logger LOGGER = LogUtils.getLogger();

private static final Dynamic2CommandExceptionType CONFLICTING_TASK_EXCEPTION =
new Dynamic2CommandExceptionType((conflictingTask, cancel) -> Component.translatable("commands.ctask.conflicting", conflictingTask, cancel));

static {
ClientTickEvents.START_CLIENT_TICK.register(TaskManager::tick);
ClientLevelEvents.UNLOAD_LEVEL.register(TaskManager::onLevelUnload);
Expand All @@ -31,8 +36,6 @@ private static void tick(Minecraft mc) {
return;
}

Set<Object> mutexKeys = new HashSet<>();

int iterationCount = 0;
var iteratingTasks = new ArrayList<>(tasks.entrySet());
while (!iteratingTasks.isEmpty()) {
Expand All @@ -41,12 +44,7 @@ private static void tick(Minecraft mc) {
while (itr.hasNext()) {
var taskEntry = itr.next();
LongTask task = taskEntry.getValue();
Set<Object> taskMutexKeys = task.getMutexKeys();
if (mutexKeys.stream().anyMatch(taskMutexKeys::contains)) {
continue;
}
tickedAnyTask = true;
mutexKeys.addAll(taskMutexKeys);
if (!task.isInitialized) {
task.initialize();
task.isInitialized = true;
Expand All @@ -58,7 +56,6 @@ private static void tick(Minecraft mc) {
tasks.remove(taskEntry.getKey());
}
itr.remove();
mutexKeys.removeAll(taskMutexKeys);
} else {
task.body();
if (!task.isCompleted()) {
Expand Down Expand Up @@ -108,12 +105,29 @@ private static void onLevelUnload(boolean isDisconnect) {
}
}

public static String addTask(String name, LongTask task) {
public static String addTask(String name, LongTask task) throws CommandSyntaxException {
for (var otherTask : tasks.entrySet()) {
if (task.conflictsWith(otherTask.getValue())) {
throw CONFLICTING_TASK_EXCEPTION.create(
otherTask.getKey(),
ClientCommandHelper.getCommandTextComponent("commands.client.cancel", "/ctask stop " + otherTask.getKey())
);
}
}

String actualName = (nextTaskId++) + "." + name;
tasks.put(actualName, task);
return actualName;
}

public static String addNonConflictingTask(String name, LongTask task) {
try {
return addTask(name, task);
} catch (CommandSyntaxException e) {
throw new AssertionError("Task " + task + " was conflicting but it was asserted that the task can't conflict");
}
}

public static void forceAddTask(String fullName, LongTask task) {
tasks.put(fullName, task);
forceAddedTaskName = fullName;
Expand Down
1 change: 1 addition & 0 deletions src/main/resources/assets/clientcommands/lang/en_us.json
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@
"commands.cstopsound.success.source.any": "Stopped all '%s' sounds for self",
"commands.cstopsound.success.source.sound": "Stopped sound '%s' on source '%s' for self",

"commands.ctask.conflicting": "A conflicting task '%s' is already running. %s",
"commands.ctask.list.noTasks": "No currently executing tasks",
"commands.ctask.list.success": "%d currently executing tasks",
"commands.ctask.stop.noMatch": "No matching tasks",
Expand Down

0 comments on commit 3f28e73

Please sign in to comment.