From 5f05e7bf6c08880af5c3c00ae15c494ec5b87d9c Mon Sep 17 00:00:00 2001 From: Kevinthegreat <92656833+kevinthegreat1@users.noreply.github.com> Date: Wed, 17 May 2023 23:11:15 -0400 Subject: Added docs to SkyblockerMod and Scheduler and refactored Scheduler --- .../me/xmrvizzy/skyblocker/utils/Scheduler.java | 45 ++++++++++++++++------ 1 file changed, 33 insertions(+), 12 deletions(-) (limited to 'src/main/java/me/xmrvizzy/skyblocker/utils/Scheduler.java') diff --git a/src/main/java/me/xmrvizzy/skyblocker/utils/Scheduler.java b/src/main/java/me/xmrvizzy/skyblocker/utils/Scheduler.java index 16e5b023..efba4995 100644 --- a/src/main/java/me/xmrvizzy/skyblocker/utils/Scheduler.java +++ b/src/main/java/me/xmrvizzy/skyblocker/utils/Scheduler.java @@ -1,27 +1,46 @@ package me.xmrvizzy.skyblocker.utils; +import me.xmrvizzy.skyblocker.SkyblockerMod; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.PriorityQueue; +/** + * A scheduler for running tasks at a later time. Tasks will be run synchronously on the main client thread. Use the instance stored in {@link SkyblockerMod#scheduler}. Do not instantiate this class. + */ public class Scheduler { private static final Logger LOGGER = LoggerFactory.getLogger(Scheduler.class); private int currentTick; private final PriorityQueue tasks; + /** + * Do not instantiate this class. Use {@link SkyblockerMod#scheduler} instead. + */ + @SuppressWarnings("DeprecatedIsStillUsed") + @Deprecated public Scheduler() { currentTick = 0; tasks = new PriorityQueue<>(); } + /** + * Schedules a task to run after a delay. + * @param task the task to run + * @param delay the delay in ticks + */ public void schedule(Runnable task, int delay) { if (delay < 0) LOGGER.warn("Scheduled a task with negative delay"); - ScheduledTask tmp = new ScheduledTask(currentTick + delay, task); + ScheduledTask tmp = new ScheduledTask(task, currentTick + delay); tasks.add(tmp); } + /** + * Schedules a task to run every period ticks. + * @param task the task to run + * @param period the period in ticks + */ public void scheduleCyclic(Runnable task, int period) { if (period <= 0) LOGGER.error("Attempted to schedule a cyclic task with period lower than 1"); @@ -38,23 +57,25 @@ public class Scheduler { } } - private class CyclicTask implements Runnable { - private final Runnable inner; - private final int period; - - public CyclicTask(Runnable task, int period) { - this.inner = task; - this.period = period; - } - + /** + * A task that runs every period ticks. More specifically, this task reschedules itself to run again after period ticks every time it runs. + * @param inner the task to run + * @param period the period in ticks + */ + private record CyclicTask(Runnable inner, int period) implements Runnable { @Override public void run() { - schedule(this, period); + SkyblockerMod.getInstance().scheduler.schedule(this, period); inner.run(); } } - private record ScheduledTask(int schedule, Runnable inner) implements Comparable, Runnable { + /** + * A task that runs at a specific tick, relative to {@link #currentTick}. + * @param inner the task to run + * @param schedule the tick to run at + */ + private record ScheduledTask(Runnable inner, int schedule) implements Comparable, Runnable { @Override public int compareTo(ScheduledTask o) { return schedule - o.schedule; -- cgit From 049f988c904e7bee85e4d0a03e2dbbcf0047d27e Mon Sep 17 00:00:00 2001 From: Kevinthegreat <92656833+kevinthegreat1@users.noreply.github.com> Date: Mon, 22 May 2023 20:30:12 -0400 Subject: Add Livid Color --- .../java/me/xmrvizzy/skyblocker/SkyblockerMod.java | 7 ++++ .../skyblocker/config/SkyblockerConfig.java | 2 + .../skyblocker/skyblock/dungeon/LividColor.java | 43 ++++++++++++++++++++++ .../skyblocker/skyblock/dungeon/Reparty.java | 11 +++--- .../skyblock/quicknav/QuickNavButton.java | 3 +- .../skyblocker/utils/MessageScheduler.java | 43 ++++++++++++++++++++++ .../me/xmrvizzy/skyblocker/utils/Scheduler.java | 13 ++++--- 7 files changed, 110 insertions(+), 12 deletions(-) create mode 100644 src/main/java/me/xmrvizzy/skyblocker/skyblock/dungeon/LividColor.java create mode 100644 src/main/java/me/xmrvizzy/skyblocker/utils/MessageScheduler.java (limited to 'src/main/java/me/xmrvizzy/skyblocker/utils/Scheduler.java') diff --git a/src/main/java/me/xmrvizzy/skyblocker/SkyblockerMod.java b/src/main/java/me/xmrvizzy/skyblocker/SkyblockerMod.java index 64c09a2f..2ab1b45e 100644 --- a/src/main/java/me/xmrvizzy/skyblocker/SkyblockerMod.java +++ b/src/main/java/me/xmrvizzy/skyblocker/SkyblockerMod.java @@ -11,11 +11,13 @@ import me.xmrvizzy.skyblocker.skyblock.StatusBarTracker; import me.xmrvizzy.skyblocker.skyblock.api.RepositoryUpdate; import me.xmrvizzy.skyblocker.skyblock.api.StatsCommand; import me.xmrvizzy.skyblocker.skyblock.dungeon.DungeonBlaze; +import me.xmrvizzy.skyblocker.skyblock.dungeon.LividColor; import me.xmrvizzy.skyblocker.skyblock.dwarven.DwarvenHud; import me.xmrvizzy.skyblocker.skyblock.item.PriceInfoTooltip; import me.xmrvizzy.skyblocker.skyblock.item.WikiLookup; import me.xmrvizzy.skyblocker.skyblock.itemlist.ItemRegistry; import me.xmrvizzy.skyblocker.skyblock.quicknav.QuickNav; +import me.xmrvizzy.skyblocker.utils.MessageScheduler; import me.xmrvizzy.skyblocker.utils.Scheduler; import me.xmrvizzy.skyblocker.utils.UpdateChecker; import me.xmrvizzy.skyblocker.utils.Utils; @@ -32,6 +34,7 @@ public class SkyblockerMod implements ClientModInitializer { @SuppressWarnings("deprecation") public final Scheduler scheduler = new Scheduler(); + public final MessageScheduler messageScheduler = new MessageScheduler(); public final ContainerSolverManager containerSolverManager = new ContainerSolverManager(); public final StatusBarTracker statusBarTracker = new StatusBarTracker(); @@ -66,20 +69,24 @@ public class SkyblockerMod implements ClientModInitializer { ChatMessageListener.init(); UpdateChecker.init(); DiscordRPCManager.init(); + LividColor.init(); FishingHelper.init(); containerSolverManager.init(); scheduler.scheduleCyclic(Utils::sbChecker, 20); scheduler.scheduleCyclic(DiscordRPCManager::update, 100); scheduler.scheduleCyclic(DungeonBlaze::update, 4); + scheduler.scheduleCyclic(LividColor::update, 10); scheduler.scheduleCyclic(BackpackPreview::tick, 50); scheduler.scheduleCyclic(DwarvenHud::update, 40); } /** * Ticks the scheduler. Called once at the end of every client tick through {@link ClientTickEvents#END_CLIENT_TICK}. + * * @param client the Minecraft client. */ public void tick(MinecraftClient client) { scheduler.tick(); + messageScheduler.tick(); } } diff --git a/src/main/java/me/xmrvizzy/skyblocker/config/SkyblockerConfig.java b/src/main/java/me/xmrvizzy/skyblocker/config/SkyblockerConfig.java index 13f70137..65e5c392 100644 --- a/src/main/java/me/xmrvizzy/skyblocker/config/SkyblockerConfig.java +++ b/src/main/java/me/xmrvizzy/skyblocker/config/SkyblockerConfig.java @@ -269,6 +269,8 @@ public class SkyblockerConfig implements ConfigData { public boolean solveThreeWeirdos = true; public boolean blazesolver = true; public boolean solveTrivia = true; + public boolean lividColor = true; + public String lividColorText = "[color]"; @ConfigEntry.Gui.CollapsibleObject() public Terminals terminals = new Terminals(); } diff --git a/src/main/java/me/xmrvizzy/skyblocker/skyblock/dungeon/LividColor.java b/src/main/java/me/xmrvizzy/skyblocker/skyblock/dungeon/LividColor.java new file mode 100644 index 00000000..d05c8cb9 --- /dev/null +++ b/src/main/java/me/xmrvizzy/skyblocker/skyblock/dungeon/LividColor.java @@ -0,0 +1,43 @@ +package me.xmrvizzy.skyblocker.skyblock.dungeon; + +import me.xmrvizzy.skyblocker.SkyblockerMod; +import me.xmrvizzy.skyblocker.config.SkyblockerConfig; +import me.xmrvizzy.skyblocker.utils.Utils; +import net.fabricmc.fabric.api.client.message.v1.ClientReceiveMessageEvents; +import net.minecraft.client.MinecraftClient; +import net.minecraft.util.math.BlockPos; + +public class LividColor { + private static int tenTicks = 0; + + public static void init() { + ClientReceiveMessageEvents.ALLOW_GAME.register((message, overlay) -> { + if (SkyblockerConfig.get().locations.dungeons.lividColor && message.getString().equals("[BOSS] Livid: I respect you for making it to here, but I'll be your undoing.")) { + tenTicks = 8; + } + return true; + }); + } + + public static void update() { + MinecraftClient client = MinecraftClient.getInstance(); + if (tenTicks != 0) { + if (SkyblockerConfig.get().locations.dungeons.lividColor && Utils.isInDungeons() && client.world != null) { + if (tenTicks == 1) { + SkyblockerMod.getInstance().messageScheduler.sendMessageAfterCooldown(SkyblockerConfig.get().locations.dungeons.lividColorText.replace("[color]", "red")); + tenTicks = 0; + return; + } + String key = client.world.getBlockState(new BlockPos(5, 110, 42)).getBlock().getTranslationKey(); + if (key.startsWith("block.minecraft.") && key.endsWith("wool") && !key.endsWith("red_wool")) { + SkyblockerMod.getInstance().messageScheduler.sendMessageAfterCooldown(SkyblockerConfig.get().locations.dungeons.lividColorText.replace("[color]", key.substring(16, key.length() - 5))); + tenTicks = 0; + return; + } + tenTicks--; + } else { + tenTicks = 0; + } + } + } +} diff --git a/src/main/java/me/xmrvizzy/skyblocker/skyblock/dungeon/Reparty.java b/src/main/java/me/xmrvizzy/skyblocker/skyblock/dungeon/Reparty.java index fdc39c42..d6e799ab 100644 --- a/src/main/java/me/xmrvizzy/skyblocker/skyblock/dungeon/Reparty.java +++ b/src/main/java/me/xmrvizzy/skyblocker/skyblock/dungeon/Reparty.java @@ -29,7 +29,7 @@ public class Reparty extends ChatPatternListener { ClientCommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) -> dispatcher.register(ClientCommandManager.literal("rp").executes(context -> { if (!Utils.isOnSkyblock() || this.repartying || client.player == null) return 0; this.repartying = true; - client.player.networkHandler.sendCommand("p list"); + SkyblockerMod.getInstance().messageScheduler.sendMessageAfterCooldown("/p list"); return 0; }))); } @@ -63,16 +63,15 @@ public class Reparty extends ChatPatternListener { this.repartying = false; return; } - sendCommand(playerEntity, "p disband", 1); + sendCommand("p disband", 1); for (int i = 0; i < this.players.length; ++i) { String command = "p invite " + this.players[i]; - sendCommand(playerEntity, command, i + 2); + sendCommand(command, i + 2); } skyblocker.scheduler.schedule(() -> this.repartying = false, this.players.length + 2); } - private void sendCommand(ClientPlayerEntity player, String command, int delay) { - // skyblocker.scheduler.schedule(() -> player.sendChatMessage(command, Text.of(command)), delay * BASE_DELAY); - skyblocker.scheduler.schedule(() -> player.networkHandler.sendCommand(command), delay * BASE_DELAY); + private void sendCommand(String command, int delay) { + skyblocker.messageScheduler.queueMessage(command, delay * BASE_DELAY); } } diff --git a/src/main/java/me/xmrvizzy/skyblocker/skyblock/quicknav/QuickNavButton.java b/src/main/java/me/xmrvizzy/skyblocker/skyblock/quicknav/QuickNavButton.java index e31827ab..7269840a 100644 --- a/src/main/java/me/xmrvizzy/skyblocker/skyblock/quicknav/QuickNavButton.java +++ b/src/main/java/me/xmrvizzy/skyblocker/skyblock/quicknav/QuickNavButton.java @@ -2,6 +2,7 @@ package me.xmrvizzy.skyblocker.skyblock.quicknav; import com.mojang.blaze3d.systems.RenderSystem; +import me.xmrvizzy.skyblocker.SkyblockerMod; import me.xmrvizzy.skyblocker.mixin.HandledScreenAccessor; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; @@ -57,7 +58,7 @@ public class QuickNavButton extends ClickableWidget { public void onClick(double mouseX, double mouseY) { if (!this.toggled) { this.toggled = true; - CLIENT.player.networkHandler.sendCommand(command.replace("/", "")); + SkyblockerMod.getInstance().messageScheduler.sendMessageAfterCooldown(command); // TODO : add null check with log error } } diff --git a/src/main/java/me/xmrvizzy/skyblocker/utils/MessageScheduler.java b/src/main/java/me/xmrvizzy/skyblocker/utils/MessageScheduler.java new file mode 100644 index 00000000..85cc963d --- /dev/null +++ b/src/main/java/me/xmrvizzy/skyblocker/utils/MessageScheduler.java @@ -0,0 +1,43 @@ +package me.xmrvizzy.skyblocker.utils; + +import net.minecraft.client.MinecraftClient; + +/** + * A scheduler for sending chat messages or commands. Use the instance in {@link me.xmrvizzy.skyblocker.SkyblockerMod#messageScheduler SkyblockerMod.messageScheduler}. Do not instantiate this class. + */ +@SuppressWarnings("deprecation") +public class MessageScheduler extends Scheduler { + private long lastMessage = 0; + + public void sendMessageAfterCooldown(String message) { + if (lastMessage + 200 < System.currentTimeMillis()) { + sendMessage(message); + lastMessage = System.currentTimeMillis(); + } else { + tasks.add(new ScheduledTask(() -> sendMessage(message), 0)); + } + } + + private void sendMessage(String message) { + if (MinecraftClient.getInstance().player != null) { + MinecraftClient.getInstance().inGameHud.getChatHud().addToMessageHistory(message); + if (message.startsWith("/")) { + MinecraftClient.getInstance().player.networkHandler.sendCommand(message.substring(1)); + } else { + MinecraftClient.getInstance().player.networkHandler.sendChatMessage(message); + } + } + } + + public void queueMessage(String message, int delay) { + tasks.add(new ScheduledTask(() -> sendMessage(message), delay)); + } + + @Override + protected void runTask(Runnable task) { + if (lastMessage + 200 < System.currentTimeMillis()) { + task.run(); + lastMessage = System.currentTimeMillis(); + } + } +} diff --git a/src/main/java/me/xmrvizzy/skyblocker/utils/Scheduler.java b/src/main/java/me/xmrvizzy/skyblocker/utils/Scheduler.java index efba4995..09db3f93 100644 --- a/src/main/java/me/xmrvizzy/skyblocker/utils/Scheduler.java +++ b/src/main/java/me/xmrvizzy/skyblocker/utils/Scheduler.java @@ -12,7 +12,7 @@ import java.util.PriorityQueue; public class Scheduler { private static final Logger LOGGER = LoggerFactory.getLogger(Scheduler.class); private int currentTick; - private final PriorityQueue tasks; + protected final PriorityQueue tasks; /** * Do not instantiate this class. Use {@link SkyblockerMod#scheduler} instead. @@ -52,17 +52,20 @@ public class Scheduler { currentTick += 1; ScheduledTask task; while ((task = tasks.peek()) != null && task.schedule <= currentTick) { - tasks.poll(); - task.run(); + runTask(tasks.poll()); } } + protected void runTask(Runnable task){ + task.run(); + } + /** * A task that runs every period ticks. More specifically, this task reschedules itself to run again after period ticks every time it runs. * @param inner the task to run * @param period the period in ticks */ - private record CyclicTask(Runnable inner, int period) implements Runnable { + protected record CyclicTask(Runnable inner, int period) implements Runnable { @Override public void run() { SkyblockerMod.getInstance().scheduler.schedule(this, period); @@ -75,7 +78,7 @@ public class Scheduler { * @param inner the task to run * @param schedule the tick to run at */ - private record ScheduledTask(Runnable inner, int schedule) implements Comparable, Runnable { + protected record ScheduledTask(Runnable inner, int schedule) implements Comparable, Runnable { @Override public int compareTo(ScheduledTask o) { return schedule - o.schedule; -- cgit From 300fe03100274d0e4f75e1294d71542cd0cc8e0e Mon Sep 17 00:00:00 2001 From: Kevinthegreat <92656833+kevinthegreat1@users.noreply.github.com> Date: Tue, 30 May 2023 11:23:46 -0400 Subject: Fix MessageScheduler removing and not sending message tasks during cooldown --- src/main/java/me/xmrvizzy/skyblocker/utils/MessageScheduler.java | 6 ++++-- src/main/java/me/xmrvizzy/skyblocker/utils/Scheduler.java | 7 ++++--- 2 files changed, 8 insertions(+), 5 deletions(-) (limited to 'src/main/java/me/xmrvizzy/skyblocker/utils/Scheduler.java') diff --git a/src/main/java/me/xmrvizzy/skyblocker/utils/MessageScheduler.java b/src/main/java/me/xmrvizzy/skyblocker/utils/MessageScheduler.java index 85cc963d..8aff5517 100644 --- a/src/main/java/me/xmrvizzy/skyblocker/utils/MessageScheduler.java +++ b/src/main/java/me/xmrvizzy/skyblocker/utils/MessageScheduler.java @@ -14,7 +14,7 @@ public class MessageScheduler extends Scheduler { sendMessage(message); lastMessage = System.currentTimeMillis(); } else { - tasks.add(new ScheduledTask(() -> sendMessage(message), 0)); + queueMessage(message, 0); } } @@ -34,10 +34,12 @@ public class MessageScheduler extends Scheduler { } @Override - protected void runTask(Runnable task) { + protected boolean runTask(Runnable task) { if (lastMessage + 200 < System.currentTimeMillis()) { task.run(); lastMessage = System.currentTimeMillis(); + return true; } + return false; } } diff --git a/src/main/java/me/xmrvizzy/skyblocker/utils/Scheduler.java b/src/main/java/me/xmrvizzy/skyblocker/utils/Scheduler.java index 09db3f93..73c15efc 100644 --- a/src/main/java/me/xmrvizzy/skyblocker/utils/Scheduler.java +++ b/src/main/java/me/xmrvizzy/skyblocker/utils/Scheduler.java @@ -51,13 +51,14 @@ public class Scheduler { public void tick() { currentTick += 1; ScheduledTask task; - while ((task = tasks.peek()) != null && task.schedule <= currentTick) { - runTask(tasks.poll()); + while ((task = tasks.peek()) != null && task.schedule <= currentTick && runTask(task)) { + tasks.poll(); } } - protected void runTask(Runnable task){ + protected boolean runTask(Runnable task) { task.run(); + return true; } /** -- cgit From d5bdb1ef2bf50084fb59029184224b84f0b99806 Mon Sep 17 00:00:00 2001 From: Kevinthegreat <92656833+kevinthegreat1@users.noreply.github.com> Date: Tue, 30 May 2023 11:35:48 -0400 Subject: Fix MessageScheduler not scheduling relative to current tick --- src/main/java/me/xmrvizzy/skyblocker/utils/MessageScheduler.java | 2 +- src/main/java/me/xmrvizzy/skyblocker/utils/Scheduler.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'src/main/java/me/xmrvizzy/skyblocker/utils/Scheduler.java') diff --git a/src/main/java/me/xmrvizzy/skyblocker/utils/MessageScheduler.java b/src/main/java/me/xmrvizzy/skyblocker/utils/MessageScheduler.java index 8aff5517..a46bb9f3 100644 --- a/src/main/java/me/xmrvizzy/skyblocker/utils/MessageScheduler.java +++ b/src/main/java/me/xmrvizzy/skyblocker/utils/MessageScheduler.java @@ -30,7 +30,7 @@ public class MessageScheduler extends Scheduler { } public void queueMessage(String message, int delay) { - tasks.add(new ScheduledTask(() -> sendMessage(message), delay)); + schedule(() -> sendMessage(message), delay); } @Override diff --git a/src/main/java/me/xmrvizzy/skyblocker/utils/Scheduler.java b/src/main/java/me/xmrvizzy/skyblocker/utils/Scheduler.java index 73c15efc..7313ec10 100644 --- a/src/main/java/me/xmrvizzy/skyblocker/utils/Scheduler.java +++ b/src/main/java/me/xmrvizzy/skyblocker/utils/Scheduler.java @@ -12,7 +12,7 @@ import java.util.PriorityQueue; public class Scheduler { private static final Logger LOGGER = LoggerFactory.getLogger(Scheduler.class); private int currentTick; - protected final PriorityQueue tasks; + private final PriorityQueue tasks; /** * Do not instantiate this class. Use {@link SkyblockerMod#scheduler} instead. -- cgit From 69e794ffcd06fe14f76f368b33d5af0e4bc60b3a Mon Sep 17 00:00:00 2001 From: Kevinthegreat <92656833+kevinthegreat1@users.noreply.github.com> Date: Tue, 30 May 2023 11:43:13 -0400 Subject: Refactored schedulers and added docs --- .../skyblocker/utils/MessageScheduler.java | 22 +++++++++++++-- .../me/xmrvizzy/skyblocker/utils/Scheduler.java | 32 ++++++++++++++-------- 2 files changed, 41 insertions(+), 13 deletions(-) (limited to 'src/main/java/me/xmrvizzy/skyblocker/utils/Scheduler.java') diff --git a/src/main/java/me/xmrvizzy/skyblocker/utils/MessageScheduler.java b/src/main/java/me/xmrvizzy/skyblocker/utils/MessageScheduler.java index a46bb9f3..ac6aa293 100644 --- a/src/main/java/me/xmrvizzy/skyblocker/utils/MessageScheduler.java +++ b/src/main/java/me/xmrvizzy/skyblocker/utils/MessageScheduler.java @@ -7,10 +7,22 @@ import net.minecraft.client.MinecraftClient; */ @SuppressWarnings("deprecation") public class MessageScheduler extends Scheduler { + /** + * The minimum delay that the server will accept between chat messages. + */ + private static final int MIN_DELAY = 200; + /** + * The timestamp of the last message send, + */ private long lastMessage = 0; + /** + * Sends a chat message or command after the minimum cooldown. Prefer this method to send messages or commands to the server. + * + * @param message the message to send + */ public void sendMessageAfterCooldown(String message) { - if (lastMessage + 200 < System.currentTimeMillis()) { + if (lastMessage + MIN_DELAY < System.currentTimeMillis()) { sendMessage(message); lastMessage = System.currentTimeMillis(); } else { @@ -29,13 +41,19 @@ public class MessageScheduler extends Scheduler { } } + /** + * Queues a chat message or command to send in {@code delay} ticks. Use this method to send messages or commands a set time in the future. The minimum cooldown is still respected. + * + * @param message the message to send + * @param delay the delay before sending the message in ticks + */ public void queueMessage(String message, int delay) { schedule(() -> sendMessage(message), delay); } @Override protected boolean runTask(Runnable task) { - if (lastMessage + 200 < System.currentTimeMillis()) { + if (lastMessage + MIN_DELAY < System.currentTimeMillis()) { task.run(); lastMessage = System.currentTimeMillis(); return true; diff --git a/src/main/java/me/xmrvizzy/skyblocker/utils/Scheduler.java b/src/main/java/me/xmrvizzy/skyblocker/utils/Scheduler.java index 7313ec10..02162140 100644 --- a/src/main/java/me/xmrvizzy/skyblocker/utils/Scheduler.java +++ b/src/main/java/me/xmrvizzy/skyblocker/utils/Scheduler.java @@ -11,8 +11,8 @@ import java.util.PriorityQueue; */ public class Scheduler { private static final Logger LOGGER = LoggerFactory.getLogger(Scheduler.class); - private int currentTick; - private final PriorityQueue tasks; + private int currentTick = 0; + private final PriorityQueue tasks = new PriorityQueue<>(); /** * Do not instantiate this class. Use {@link SkyblockerMod#scheduler} instead. @@ -20,32 +20,34 @@ public class Scheduler { @SuppressWarnings("DeprecatedIsStillUsed") @Deprecated public Scheduler() { - currentTick = 0; - tasks = new PriorityQueue<>(); } /** * Schedules a task to run after a delay. - * @param task the task to run + * + * @param task the task to run * @param delay the delay in ticks */ public void schedule(Runnable task, int delay) { - if (delay < 0) + if (delay < 0) { LOGGER.warn("Scheduled a task with negative delay"); + } ScheduledTask tmp = new ScheduledTask(task, currentTick + delay); tasks.add(tmp); } /** * Schedules a task to run every period ticks. - * @param task the task to run + * + * @param task the task to run * @param period the period in ticks */ public void scheduleCyclic(Runnable task, int period) { - if (period <= 0) + if (period <= 0) { LOGGER.error("Attempted to schedule a cyclic task with period lower than 1"); - else + } else { new CyclicTask(task, period).run(); + } } public void tick() { @@ -56,6 +58,12 @@ public class Scheduler { } } + /** + * Runs the task if able. + * + * @param task the task to run + * @return {@code true} if the task is run, and {@link false} if task is not run. + */ protected boolean runTask(Runnable task) { task.run(); return true; @@ -63,7 +71,8 @@ public class Scheduler { /** * A task that runs every period ticks. More specifically, this task reschedules itself to run again after period ticks every time it runs. - * @param inner the task to run + * + * @param inner the task to run * @param period the period in ticks */ protected record CyclicTask(Runnable inner, int period) implements Runnable { @@ -76,7 +85,8 @@ public class Scheduler { /** * A task that runs at a specific tick, relative to {@link #currentTick}. - * @param inner the task to run + * + * @param inner the task to run * @param schedule the tick to run at */ protected record ScheduledTask(Runnable inner, int schedule) implements Comparable, Runnable { -- cgit From 796177d64aac6c64949973a5604aedc0d1f2651f Mon Sep 17 00:00:00 2001 From: Kevinthegreat <92656833+kevinthegreat1@users.noreply.github.com> Date: Sat, 8 Jul 2023 17:20:55 +0800 Subject: Refactor Title Container --- .../skyblocker/config/SkyblockerConfig.java | 10 +- .../skyblocker/skyblock/FishingHelper.java | 4 +- .../skyblocker/skyblock/rift/EffigyWaypoints.java | 4 +- .../skyblock/rift/HealingMelonIndicator.java | 19 +-- .../skyblocker/skyblock/rift/ManiaIndicator.java | 27 ++--- .../skyblock/rift/MirrorverseWaypoints.java | 4 +- .../skyblocker/skyblock/rift/StakeIndicator.java | 19 ++- .../skyblock/rift/TwinClawsIndicator.java | 25 ++-- .../me/xmrvizzy/skyblocker/utils/RenderHelper.java | 25 +++- .../me/xmrvizzy/skyblocker/utils/Scheduler.java | 21 ++++ .../me/xmrvizzy/skyblocker/utils/title/Title.java | 31 +++-- .../skyblocker/utils/title/TitleContainer.java | 128 +++++++++++++-------- .../utils/title/TitleContainerConfigScreen.java | 110 +++++++----------- 13 files changed, 237 insertions(+), 190 deletions(-) (limited to 'src/main/java/me/xmrvizzy/skyblocker/utils/Scheduler.java') diff --git a/src/main/java/me/xmrvizzy/skyblocker/config/SkyblockerConfig.java b/src/main/java/me/xmrvizzy/skyblocker/config/SkyblockerConfig.java index 1aeee35e..7da9979a 100644 --- a/src/main/java/me/xmrvizzy/skyblocker/config/SkyblockerConfig.java +++ b/src/main/java/me/xmrvizzy/skyblocker/config/SkyblockerConfig.java @@ -1,5 +1,6 @@ package me.xmrvizzy.skyblocker.config; +import com.mojang.brigadier.Command; import com.mojang.brigadier.builder.LiteralArgumentBuilder; import me.shedaniel.autoconfig.AutoConfig; import me.shedaniel.autoconfig.ConfigData; @@ -10,8 +11,6 @@ import me.xmrvizzy.skyblocker.SkyblockerMod; import me.xmrvizzy.skyblocker.chat.ChatFilterResult; import net.fabricmc.fabric.api.client.command.v2.ClientCommandRegistrationCallback; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; -import net.minecraft.client.MinecraftClient; -import net.minecraft.client.gui.screen.Screen; import net.minecraft.client.resource.language.I18n; import java.util.ArrayList; @@ -500,11 +499,8 @@ public class SkyblockerConfig implements ConfigData { private static LiteralArgumentBuilder optionsLiteral(String name) { return literal(name).executes(context -> { // Don't immediately open the next screen as it will be closed by ChatScreen right after this command is executed - SkyblockerMod.getInstance().scheduler.schedule(() -> { - Screen a = AutoConfig.getConfigScreen(SkyblockerConfig.class, null).get(); - MinecraftClient.getInstance().setScreen(a); - }, 0); - return 1; + SkyblockerMod.getInstance().scheduler.queueOpenScreen(AutoConfig.getConfigScreen(SkyblockerConfig.class, null)); + return Command.SINGLE_SUCCESS; }); } diff --git a/src/main/java/me/xmrvizzy/skyblocker/skyblock/FishingHelper.java b/src/main/java/me/xmrvizzy/skyblocker/skyblock/FishingHelper.java index 822b89d9..8dee3fcb 100644 --- a/src/main/java/me/xmrvizzy/skyblocker/skyblock/FishingHelper.java +++ b/src/main/java/me/xmrvizzy/skyblocker/skyblock/FishingHelper.java @@ -2,6 +2,7 @@ package me.xmrvizzy.skyblocker.skyblock; import me.xmrvizzy.skyblocker.config.SkyblockerConfig; import me.xmrvizzy.skyblocker.utils.RenderHelper; +import me.xmrvizzy.skyblocker.utils.title.Title; import net.fabricmc.fabric.api.event.player.UseItemCallback; import net.minecraft.client.MinecraftClient; import net.minecraft.client.network.ClientPlayerEntity; @@ -15,6 +16,7 @@ import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.Vec3d; public class FishingHelper { + private static final Title title = new Title("skyblocker.fishing.reelNow", Formatting.GREEN); private static long startTime; private static Vec3d normalYawVector; @@ -49,7 +51,7 @@ public class FishingHelper { if (player != null && player.fishHook != null) { Vec3d soundToFishHook = player.fishHook.getPos().subtract(packet.getX(), 0, packet.getZ()); if (Math.abs(normalYawVector.x * soundToFishHook.z - normalYawVector.z * soundToFishHook.x) < 0.2D && Math.abs(normalYawVector.dotProduct(soundToFishHook)) < 4D && player.getPos().squaredDistanceTo(packet.getX(), packet.getY(), packet.getZ()) > 1D) { - RenderHelper.displayTitleAndPlaySound(10, 5, "skyblocker.fishing.reelNow", Formatting.GREEN); + RenderHelper.displayInTitleContainerAndPlaySound(title, 10); reset(); } } else { diff --git a/src/main/java/me/xmrvizzy/skyblocker/skyblock/rift/EffigyWaypoints.java b/src/main/java/me/xmrvizzy/skyblocker/skyblock/rift/EffigyWaypoints.java index 0d44900a..7376c896 100644 --- a/src/main/java/me/xmrvizzy/skyblocker/skyblock/rift/EffigyWaypoints.java +++ b/src/main/java/me/xmrvizzy/skyblocker/skyblock/rift/EffigyWaypoints.java @@ -32,7 +32,7 @@ public class EffigyWaypoints { ); private static final List unBrokenEffigies = new ArrayList<>(); - public static void updateEffigies() { + protected static void updateEffigies() { if (!SkyblockerConfig.get().slayer.vampireSlayer.enableEffigyWaypoints || !Utils.isOnSkyblock() || !Utils.isInTheRift() || !Utils.getLocation().contains("Stillgore Château")) return; unBrokenEffigies.clear(); @@ -61,7 +61,7 @@ public class EffigyWaypoints { } } - public static void render(WorldRenderContext context) { + protected static void render(WorldRenderContext context) { if (SkyblockerConfig.get().slayer.vampireSlayer.enableEffigyWaypoints && Utils.getLocation().contains("Stillgore Château")) { for (BlockPos effigy : unBrokenEffigies) { float[] colorComponents = DyeColor.RED.getColorComponents(); diff --git a/src/main/java/me/xmrvizzy/skyblocker/skyblock/rift/HealingMelonIndicator.java b/src/main/java/me/xmrvizzy/skyblocker/skyblock/rift/HealingMelonIndicator.java index d1657d67..fed34796 100644 --- a/src/main/java/me/xmrvizzy/skyblocker/skyblock/rift/HealingMelonIndicator.java +++ b/src/main/java/me/xmrvizzy/skyblocker/skyblock/rift/HealingMelonIndicator.java @@ -7,28 +7,21 @@ import me.xmrvizzy.skyblocker.utils.title.Title; import me.xmrvizzy.skyblocker.utils.title.TitleContainer; import net.minecraft.client.MinecraftClient; import net.minecraft.client.network.ClientPlayerEntity; -import net.minecraft.client.resource.language.I18n; import net.minecraft.util.Formatting; public class HealingMelonIndicator { - private static Title title = null; - public static void updateHealth(MinecraftClient client) { - if(title == null) - title = new Title(I18n.translate("skyblocker.rift.healNow"), Formatting.DARK_RED.getColorValue()); + private static final Title title = new Title("skyblocker.rift.healNow", Formatting.DARK_RED); + public static void updateHealth(MinecraftClient client) { if (!SkyblockerConfig.get().slayer.vampireSlayer.enableHealingMelonIndicator || !Utils.isOnSkyblock() || !Utils.isInTheRift() || !Utils.getLocation().contains("Stillgore Château")) { - title.active = false; + TitleContainer.removeTitle(title); return; } - title.active = true; ClientPlayerEntity player = client.player; if (player != null && player.getHealth() <= SkyblockerConfig.get().slayer.vampireSlayer.healingMelonHealthThreshold * 2F) { - title.active = true; - if(!TitleContainer.titles.contains(title)) - RenderHelper.displayInTitleContainerAndPlaySound(title); - } - else { - title.active = false; + RenderHelper.displayInTitleContainerAndPlaySound(title); + } else { + TitleContainer.removeTitle(title); } } } \ No newline at end of file diff --git a/src/main/java/me/xmrvizzy/skyblocker/skyblock/rift/ManiaIndicator.java b/src/main/java/me/xmrvizzy/skyblocker/skyblock/rift/ManiaIndicator.java index 7d5a1cb4..4e873eed 100644 --- a/src/main/java/me/xmrvizzy/skyblocker/skyblock/rift/ManiaIndicator.java +++ b/src/main/java/me/xmrvizzy/skyblocker/skyblock/rift/ManiaIndicator.java @@ -8,18 +8,16 @@ import me.xmrvizzy.skyblocker.utils.title.Title; import me.xmrvizzy.skyblocker.utils.title.TitleContainer; import net.minecraft.block.Blocks; import net.minecraft.client.MinecraftClient; -import net.minecraft.client.resource.language.I18n; import net.minecraft.entity.Entity; import net.minecraft.util.Formatting; +import net.minecraft.util.math.BlockPos; public class ManiaIndicator { - private static Title title = null; - public static void updateMania() { - if(title == null) - title = new Title("b", Formatting.RED.getColorValue()); + private static final Title title = new Title("skyblocker.rift.mania", Formatting.RED); + protected static void updateMania() { if (!SkyblockerConfig.get().slayer.vampireSlayer.enableManiaIndicator || !Utils.isOnSkyblock() || !Utils.isInTheRift() || !(Utils.getLocation().contains("Stillgore Château")) || !SlayerUtils.isInSlayer()) { - title.active = false; + TitleContainer.removeTitle(title); return; } @@ -30,17 +28,14 @@ public class ManiaIndicator { for (Entity entity : SlayerUtils.getEntityArmorStands(slayerEntity)) { if (entity.getDisplayName().toString().contains("MANIA")) { anyMania = true; - title.active = true; - var pos = MinecraftClient.getInstance().player.getBlockPos().down(); - var isGreen = MinecraftClient.getInstance().world.getBlockState(pos).getBlock() == Blocks.GREEN_TERRACOTTA; - title.color = isGreen ? Formatting.GREEN.getColorValue() : Formatting.RED.getColorValue(); - if(!TitleContainer.titles.contains(title)) { - title.text = I18n.translate("skyblocker.rift.mania"); - RenderHelper.displayInTitleContainerAndPlaySound(title); - } + BlockPos pos = MinecraftClient.getInstance().player.getBlockPos().down(); + boolean isGreen = MinecraftClient.getInstance().world.getBlockState(pos).getBlock() == Blocks.GREEN_TERRACOTTA; + title.setFormatting(isGreen ? Formatting.GREEN : Formatting.RED); + RenderHelper.displayInTitleContainerAndPlaySound(title); } } - if(!anyMania) - title.active = false; + if (!anyMania) { + TitleContainer.removeTitle(title); + } } } \ No newline at end of file diff --git a/src/main/java/me/xmrvizzy/skyblocker/skyblock/rift/MirrorverseWaypoints.java b/src/main/java/me/xmrvizzy/skyblocker/skyblock/rift/MirrorverseWaypoints.java index 276ec551..32551179 100644 --- a/src/main/java/me/xmrvizzy/skyblocker/skyblock/rift/MirrorverseWaypoints.java +++ b/src/main/java/me/xmrvizzy/skyblocker/skyblock/rift/MirrorverseWaypoints.java @@ -34,7 +34,7 @@ public class MirrorverseWaypoints { /** * Loads the waypoint locations into memory */ - public static void loadWaypoints() { + private static void loadWaypoints() { try (BufferedReader reader = CLIENT.getResourceManager().openAsReader(WAYPOINTS_JSON)) { JsonObject file = JsonParser.parseReader(reader).getAsJsonObject(); JsonArray sections = file.get("sections").getAsJsonArray(); @@ -69,7 +69,7 @@ public class MirrorverseWaypoints { } } - public static void render(WorldRenderContext wrc) { + protected static void render(WorldRenderContext wrc) { //I would also check for the mirrorverse location but the scoreboard stuff is not performant at all... if (Utils.isInTheRift() && SkyblockerConfig.get().locations.rift.mirrorverseWaypoints) { for (BlockPos pos : LAVA_PATH_WAYPOINTS) { diff --git a/src/main/java/me/xmrvizzy/skyblocker/skyblock/rift/StakeIndicator.java b/src/main/java/me/xmrvizzy/skyblocker/skyblock/rift/StakeIndicator.java index d946df6d..90fc436d 100644 --- a/src/main/java/me/xmrvizzy/skyblocker/skyblock/rift/StakeIndicator.java +++ b/src/main/java/me/xmrvizzy/skyblocker/skyblock/rift/StakeIndicator.java @@ -6,28 +6,23 @@ import me.xmrvizzy.skyblocker.utils.SlayerUtils; import me.xmrvizzy.skyblocker.utils.Utils; import me.xmrvizzy.skyblocker.utils.title.Title; import me.xmrvizzy.skyblocker.utils.title.TitleContainer; -import net.minecraft.client.resource.language.I18n; import net.minecraft.entity.Entity; +import net.minecraft.text.Text; import net.minecraft.util.Formatting; public class StakeIndicator { - private static Title title = null; - public static void updateStake() { - if (title == null) - title = new Title("b", Formatting.RED.getColorValue()); + private static final Title title = new Title("skyblocker.rift.stakeNow",Formatting.RED); + protected static void updateStake() { if (!SkyblockerConfig.get().slayer.vampireSlayer.enableSteakStakeIndicator || !Utils.isOnSkyblock() || !Utils.isInTheRift() || !Utils.getLocation().contains("Stillgore Château") || !SlayerUtils.isInSlayer()) { - title.active = false; + TitleContainer.removeTitle(title); return; } Entity slayerEntity = SlayerUtils.getSlayerEntity(); if (slayerEntity != null && slayerEntity.getDisplayName().toString().contains("҉")) { - title.active = true; - title.text = I18n.translate("skyblocker.rift.stakeNow"); - if(!TitleContainer.titles.contains(title)) - RenderHelper.displayInTitleContainerAndPlaySound(title); + RenderHelper.displayInTitleContainerAndPlaySound(title); + } else { + TitleContainer.removeTitle(title); } - else - title.active = false; } } \ No newline at end of file diff --git a/src/main/java/me/xmrvizzy/skyblocker/skyblock/rift/TwinClawsIndicator.java b/src/main/java/me/xmrvizzy/skyblocker/skyblock/rift/TwinClawsIndicator.java index 706aa95e..f36b97df 100644 --- a/src/main/java/me/xmrvizzy/skyblocker/skyblock/rift/TwinClawsIndicator.java +++ b/src/main/java/me/xmrvizzy/skyblocker/skyblock/rift/TwinClawsIndicator.java @@ -7,19 +7,17 @@ import me.xmrvizzy.skyblocker.utils.SlayerUtils; import me.xmrvizzy.skyblocker.utils.Utils; import me.xmrvizzy.skyblocker.utils.title.Title; import me.xmrvizzy.skyblocker.utils.title.TitleContainer; -import net.minecraft.client.resource.language.I18n; import net.minecraft.entity.Entity; +import net.minecraft.text.Text; import net.minecraft.util.Formatting; public class TwinClawsIndicator { - private static Title title = null; - public static boolean scheduling = false; - public static void updateIce() { - if(title == null) - title = new Title("b", Formatting.AQUA.getColorValue()); + private static final Title title = new Title("skyblocker.rift.iceNow",Formatting.AQUA); + private static boolean scheduled = false; + protected static void updateIce() { if (!SkyblockerConfig.get().slayer.vampireSlayer.enableHolyIceIndicator || !Utils.isOnSkyblock() || !Utils.isInTheRift() || !(Utils.getLocation().contains("Stillgore Château")) || !SlayerUtils.isInSlayer()) { - title.active = false; + TitleContainer.removeTitle(title); return; } @@ -30,18 +28,17 @@ public class TwinClawsIndicator { for (Entity entity : SlayerUtils.getEntityArmorStands(slayerEntity)) { if (entity.getDisplayName().toString().contains("TWINCLAWS")) { anyClaws = true; - title.active = true; - if(!TitleContainer.titles.contains(title) && !scheduling) { - scheduling = true; + if (!TitleContainer.containsTitle(title) && !scheduled) { + scheduled = true; SkyblockerMod.getInstance().scheduler.schedule(() -> { - title.text = I18n.translate("skyblocker.rift.iceNow"); RenderHelper.displayInTitleContainerAndPlaySound(title); - scheduling = false; + scheduled = false; }, SkyblockerConfig.get().slayer.vampireSlayer.holyIceIndicatorTickDelay); } } } - if(!anyClaws) - title.active = false; + if (!anyClaws) { + TitleContainer.removeTitle(title); + } } } \ No newline at end of file diff --git a/src/main/java/me/xmrvizzy/skyblocker/utils/RenderHelper.java b/src/main/java/me/xmrvizzy/skyblocker/utils/RenderHelper.java index 4a151129..6fa93735 100644 --- a/src/main/java/me/xmrvizzy/skyblocker/utils/RenderHelper.java +++ b/src/main/java/me/xmrvizzy/skyblocker/utils/RenderHelper.java @@ -53,14 +53,29 @@ public class RenderHelper { playNotificationSound(); } + /** + * Adds the title to {@link TitleContainer} and {@link #playNotificationSound() plays the notification sound} if the title is not in the {@link TitleContainer} already. + * No checking needs to be done on whether the title is in the {@link TitleContainer} already by the caller. + * + * @param title the title + */ public static void displayInTitleContainerAndPlaySound(Title title) { - TitleContainer.addTitle(title); - playNotificationSound(); + if (TitleContainer.addTitle(title)) { + playNotificationSound(); + } } - public static void displayInTitleContainerWDismissAndPlaySound(Title title, int ticks) { - TitleContainer.addTitleWithDismiss(title, ticks); - playNotificationSound(); + /** + * Adds the title to {@link TitleContainer} for a set number of ticks and {@link #playNotificationSound() plays the notification sound} if the title is not in the {@link TitleContainer} already. + * No checking needs to be done on whether the title is in the {@link TitleContainer} already by the caller. + * + * @param title the title + * @param ticks the number of ticks the title will remain + */ + public static void displayInTitleContainerAndPlaySound(Title title, int ticks) { + if (TitleContainer.addTitle(title, ticks)) { + playNotificationSound(); + } } private static void playNotificationSound() { diff --git a/src/main/java/me/xmrvizzy/skyblocker/utils/Scheduler.java b/src/main/java/me/xmrvizzy/skyblocker/utils/Scheduler.java index 02162140..7b19e284 100644 --- a/src/main/java/me/xmrvizzy/skyblocker/utils/Scheduler.java +++ b/src/main/java/me/xmrvizzy/skyblocker/utils/Scheduler.java @@ -1,10 +1,13 @@ package me.xmrvizzy.skyblocker.utils; import me.xmrvizzy.skyblocker.SkyblockerMod; +import net.minecraft.client.MinecraftClient; +import net.minecraft.client.gui.screen.Screen; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.PriorityQueue; +import java.util.function.Supplier; /** * A scheduler for running tasks at a later time. Tasks will be run synchronously on the main client thread. Use the instance stored in {@link SkyblockerMod#scheduler}. Do not instantiate this class. @@ -50,6 +53,24 @@ public class Scheduler { } } + /** + * Schedules a screen to open in the next tick. Used in commands to avoid screen immediately closing after the command is executed. + * + * @param screenSupplier the supplier of the screen to open + */ + public void queueOpenScreen(Supplier screenSupplier) { + queueOpenScreen(screenSupplier.get()); + } + + /** + * Schedules a screen to open in the next tick. Used in commands to avoid screen immediately closing after the command is executed. + * + * @param screen the supplier of the screen to open + */ + public void queueOpenScreen(Screen screen) { + MinecraftClient.getInstance().send(() -> MinecraftClient.getInstance().setScreen(screen)); + } + public void tick() { currentTick += 1; ScheduledTask task; diff --git a/src/main/java/me/xmrvizzy/skyblocker/utils/title/Title.java b/src/main/java/me/xmrvizzy/skyblocker/utils/title/Title.java index d1977470..ac06eb36 100644 --- a/src/main/java/me/xmrvizzy/skyblocker/utils/title/Title.java +++ b/src/main/java/me/xmrvizzy/skyblocker/utils/title/Title.java @@ -1,14 +1,31 @@ package me.xmrvizzy.skyblocker.utils.title; +import net.minecraft.text.MutableText; +import net.minecraft.text.Text; +import net.minecraft.util.Formatting; + public class Title { - public String text = ""; - public boolean active = true; - public int color; - public float lastX = 0; - public float lastY = 0; + private MutableText text; + protected float lastX = 0; + protected float lastY = 0; + + public MutableText getText() { + return text; + } + + public void setText(MutableText text) { + this.text = text; + } + + public void setFormatting(Formatting formatting) { + this.text.formatted(formatting); + } + + public Title(String textKey, Formatting formatting) { + this(Text.translatable(textKey).formatted(formatting)); + } - public Title(String text, int color) { + public Title(MutableText text) { this.text = text; - this.color = color; } } diff --git a/src/main/java/me/xmrvizzy/skyblocker/utils/title/TitleContainer.java b/src/main/java/me/xmrvizzy/skyblocker/utils/title/TitleContainer.java index 14db8d6e..c4908a73 100644 --- a/src/main/java/me/xmrvizzy/skyblocker/utils/title/TitleContainer.java +++ b/src/main/java/me/xmrvizzy/skyblocker/utils/title/TitleContainer.java @@ -1,8 +1,8 @@ package me.xmrvizzy.skyblocker.utils.title; +import com.mojang.brigadier.Command; import me.xmrvizzy.skyblocker.SkyblockerMod; import me.xmrvizzy.skyblocker.config.SkyblockerConfig; -import me.xmrvizzy.skyblocker.skyblock.dwarven.DwarvenHudConfigScreen; import net.fabricmc.fabric.api.client.command.v2.ClientCommandManager; import net.fabricmc.fabric.api.client.command.v2.ClientCommandRegistrationCallback; import net.fabricmc.fabric.api.client.rendering.v1.HudRenderCallback; @@ -12,55 +12,99 @@ import net.minecraft.client.gui.DrawContext; import net.minecraft.text.Text; import net.minecraft.util.math.MathHelper; -import java.util.ArrayList; -import java.util.List; +import java.util.LinkedHashSet; +import java.util.Set; public class TitleContainer { - public static final MinecraftClient client = MinecraftClient.getInstance(); - public static List titles = new ArrayList<>(); + /** + * The set of titles which will be rendered. + * + * @see #containsTitle(Title) + * @see #addTitle(Title) + * @see #addTitle(Title, int) + * @see #removeTitle(Title) + */ + private static final Set<Title> titles = new LinkedHashSet<>(); public static void init() { - HudRenderCallback.EVENT.register(TitleContainer::draw); + HudRenderCallback.EVENT.register(TitleContainer::render); ClientCommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) -> dispatcher.register(ClientCommandManager.literal("skyblocker") .then(ClientCommandManager.literal("hud") .then(ClientCommandManager.literal("titleContainer") .executes(context -> { - client.send(() -> client.setScreen(new TitleContainerConfigScreen(Text.of("Title Container HUD Config")))); - return 1; + SkyblockerMod.getInstance().scheduler.queueOpenScreen(new TitleContainerConfigScreen(Text.of("Title Container HUD Config"))); + return Command.SINGLE_SUCCESS; }))))); } - public static void addTitle(Title title) { - title.active = true; - title.lastX = 0; - title.lastY = SkyblockerConfig.get().general.titleContainer.y; - titles.add(title); + + /** + * Returns {@code true} if the title is currently shown. + * + * @param title the title to check + * @return whether the title in currently shown + */ + public static boolean containsTitle(Title title) { + return titles.contains(title); } - public static void addTitleWithDismiss(Title title, int ticks) { - addTitle(title); - SkyblockerMod.getInstance().scheduler.schedule(() -> { - title.active = false; - }, ticks); + + /** + * Adds a title to be shown + * + * @param title the title to be shown + * @return whether the title is already currently being shown + */ + public static boolean addTitle(Title title) { + if (titles.add(title)) { + title.lastX = 0; + title.lastY = SkyblockerConfig.get().general.titleContainer.y; + return true; + } + return false; } - public static void draw(DrawContext context, float tickDelta) { - draw(titles, SkyblockerConfig.get().general.titleContainer.x, SkyblockerConfig.get().general.titleContainer.y, context, tickDelta, false); + + /** + * Adds a title to be shown for a set number of ticks + * + * @param title the title to be shown + * @param ticks the number of ticks to show the title + * @return whether the title is already currently being shown + */ + public static boolean addTitle(Title title, int ticks) { + if (addTitle(title)) { + SkyblockerMod.getInstance().scheduler.schedule(() -> TitleContainer.removeTitle(title), ticks); + return true; + } + return false; + } + + /** + * Stops showing a title + * + * @param title the title to stop showing + */ + public static void removeTitle(Title title) { + titles.remove(title); } - public static void draw(List<Title> titlesToDraw, int xPos, int yPos, DrawContext context, float tickDelta, boolean example) { + + private static void render(DrawContext context, float tickDelta) { + render(context, titles, SkyblockerConfig.get().general.titleContainer.x, SkyblockerConfig.get().general.titleContainer.y, tickDelta); + } + + protected static void render(DrawContext context, Set<Title> titles, int xPos, int yPos, float tickDelta) { var client = MinecraftClient.getInstance(); TextRenderer textRenderer = client.textRenderer; - List<Title> toRemove = new ArrayList<>(); - float scale = 3F * (SkyblockerConfig.get().general.titleContainer.titleContainerScale / 100F); - var direction = SkyblockerConfig.get().general.titleContainer.direction; - var alignment = SkyblockerConfig.get().general.titleContainer.alignment; + SkyblockerConfig.Direction direction = SkyblockerConfig.get().general.titleContainer.direction; + SkyblockerConfig.Alignment alignment = SkyblockerConfig.get().general.titleContainer.alignment; float x = 0; float y; float width = 0; - for (Title title : titlesToDraw) { - width += textRenderer.getWidth(title.text) * scale + 10; + for (Title title : titles) { + width += textRenderer.getWidth(title.getText()) * scale + 10; } - if(direction == SkyblockerConfig.Direction.HORIZONTAL) { + if (direction == SkyblockerConfig.Direction.HORIZONTAL) { if (alignment == SkyblockerConfig.Alignment.MIDDLE) { x = xPos - (width / 2); } @@ -69,51 +113,45 @@ public class TitleContainer { x = xPos; } } - if(alignment == SkyblockerConfig.Alignment.LEFT || alignment == SkyblockerConfig.Alignment.RIGHT) { + if (alignment == SkyblockerConfig.Alignment.LEFT || alignment == SkyblockerConfig.Alignment.RIGHT) { x = xPos; } y = yPos; - for (Title title : titlesToDraw) { + for (Title title : titles) { context.getMatrices().push(); context.getMatrices().translate(title.lastX, title.lastY, 200); context.getMatrices().scale(scale, scale, scale); - float xToUse = 0; - if(direction == SkyblockerConfig.Direction.HORIZONTAL) { + float xToUse; + if (direction == SkyblockerConfig.Direction.HORIZONTAL) { xToUse = alignment == SkyblockerConfig.Alignment.RIGHT ? - x - (textRenderer.getWidth(title.text) * scale) : + x - (textRenderer.getWidth(title.getText()) * scale) : x; } else { xToUse = alignment == SkyblockerConfig.Alignment.MIDDLE ? - x - (textRenderer.getWidth(title.text) * scale) / 2 : + x - (textRenderer.getWidth(title.getText()) * scale) / 2 : alignment == SkyblockerConfig.Alignment.RIGHT ? - x - (textRenderer.getWidth(title.text) * scale) : + x - (textRenderer.getWidth(title.getText()) * scale) : x; } title.lastX = MathHelper.lerp(tickDelta * 0.5F, title.lastX, xToUse); title.lastY = MathHelper.lerp(tickDelta * 0.5F, title.lastY, y); - if(direction == SkyblockerConfig.Direction.HORIZONTAL) { + if (direction == SkyblockerConfig.Direction.HORIZONTAL) { if (alignment == SkyblockerConfig.Alignment.MIDDLE || alignment == SkyblockerConfig.Alignment.LEFT) { - x += textRenderer.getWidth(title.text) * scale + 10; + x += textRenderer.getWidth(title.getText()) * scale + 10; } if (alignment == SkyblockerConfig.Alignment.RIGHT) { - x -= textRenderer.getWidth(title.text) * scale + 10; + x -= textRenderer.getWidth(title.getText()) * scale + 10; } } else { y += textRenderer.fontHeight * scale + 10; } - context.drawText(textRenderer, title.text, 0, 0, title.color, true); + context.drawTextWithShadow(textRenderer, title.getText(), 0, 0, 0xFFFFFF); context.getMatrices().pop(); - if (!title.active && !example) { - toRemove.add(title); - } - } - if (!example) { - titlesToDraw.removeAll(toRemove); } } } \ No newline at end of file diff --git a/src/main/java/me/xmrvizzy/skyblocker/utils/title/TitleContainerConfigScreen.java b/src/main/java/me/xmrvizzy/skyblocker/utils/title/TitleContainerConfigScreen.java index a035f862..b4f3093f 100644 --- a/src/main/java/me/xmrvizzy/skyblocker/utils/title/TitleContainerConfigScreen.java +++ b/src/main/java/me/xmrvizzy/skyblocker/utils/title/TitleContainerConfigScreen.java @@ -2,29 +2,26 @@ package me.xmrvizzy.skyblocker.utils.title; import me.shedaniel.autoconfig.AutoConfig; import me.xmrvizzy.skyblocker.config.SkyblockerConfig; -import me.xmrvizzy.skyblocker.skyblock.dwarven.DwarvenHud; import me.xmrvizzy.skyblocker.utils.RenderUtils; import net.minecraft.client.MinecraftClient; import net.minecraft.client.gui.DrawContext; import net.minecraft.client.gui.screen.Screen; -import net.minecraft.client.input.KeyCodes; import net.minecraft.text.Text; import net.minecraft.util.Formatting; -import net.minecraft.util.math.Box; -import org.joml.Vector4i; +import net.minecraft.util.Pair; +import org.joml.Vector2i; import org.lwjgl.glfw.GLFW; import java.awt.*; -import java.awt.event.KeyEvent; -import java.util.List; +import java.util.Set; public class TitleContainerConfigScreen extends Screen { - - private final Title example1 = new Title("Test1", Formatting.RED.getColorValue()); - private final Title example2 = new Title("Test23", Formatting.AQUA.getColorValue()); - private final Title example3 = new Title("Testing1234", Formatting.DARK_GREEN.getColorValue()); + private final Title example1 = new Title(Text.literal("Test1").formatted(Formatting.RED)); + private final Title example2 = new Title(Text.literal("Test23").formatted(Formatting.AQUA)); + private final Title example3 = new Title(Text.literal("Testing1234").formatted(Formatting.DARK_GREEN)); private int hudX = SkyblockerConfig.get().general.titleContainer.x; private int hudY = SkyblockerConfig.get().general.titleContainer.y; + protected TitleContainerConfigScreen(Text title) { super(title); } @@ -33,25 +30,18 @@ public class TitleContainerConfigScreen extends Screen { public void render(DrawContext context, int mouseX, int mouseY, float delta) { super.render(context, mouseX, mouseY, delta); renderBackground(context); - TitleContainer.draw(List.of(example1, example2, example3), hudX, hudY, context, delta, true); - context.drawCenteredTextWithShadow(textRenderer, "Right Click To Reset Position", width / 2, height / 2, Color.GRAY.getRGB()); - var direction = SkyblockerConfig.get().general.titleContainer.direction; - var alignment = SkyblockerConfig.get().general.titleContainer.alignment; - int width1 = client.textRenderer.getWidth("Press Q/E to change Alignment: " + alignment.toString()); - int width2 = client.textRenderer.getWidth("Press R to change Direction: " + direction.toString()); - context.drawText(client.textRenderer, "Press Q/E to change Alignment: " + alignment.toString(), (width / 2) - width1 / 2, client.textRenderer.fontHeight * 2, Color.WHITE.getRGB(), true); - context.drawText(client.textRenderer, "Press R to change Direction: " + direction.toString(), (width / 2) - width2 / 2, client.textRenderer.fontHeight * 3 + 5, Color.WHITE.getRGB(), true); - - int x1; - int x2; - int y1; - int y2; - - var vec = getSelectionBounding(); - x1 = vec.x; - x2 = vec.y; - y1 = vec.z; - y2 = vec.w; + TitleContainer.render(context, Set.of(example1, example2, example3), hudX, hudY, delta); + SkyblockerConfig.Direction direction = SkyblockerConfig.get().general.titleContainer.direction; + SkyblockerConfig.Alignment alignment = SkyblockerConfig.get().general.titleContainer.alignment; + context.drawCenteredTextWithShadow(client.textRenderer, "Press Q/E to change Alignment: " + alignment, width / 2, client.textRenderer.fontHeight * 2, Color.WHITE.getRGB()); + context.drawCenteredTextWithShadow(client.textRenderer, "Press R to change Direction: " + direction, width / 2, client.textRenderer.fontHeight * 3 + 5, Color.WHITE.getRGB()); + context.drawCenteredTextWithShadow(textRenderer, "Right Click To Reset Position", width / 2, client.textRenderer.fontHeight * 4 + 10, Color.GRAY.getRGB()); + + Pair<Vector2i, Vector2i> boundingBox = getSelectionBoundingBox(); + int x1 = boundingBox.getLeft().x; + int y1 = boundingBox.getLeft().y; + int x2 = boundingBox.getRight().x; + int y2 = boundingBox.getRight().y; context.drawHorizontalLine(x1, x2, y1, Color.RED.getRGB()); context.drawHorizontalLine(x1, x2, y2, Color.RED.getRGB()); @@ -59,46 +49,39 @@ public class TitleContainerConfigScreen extends Screen { context.drawVerticalLine(x2, y1, y2, Color.RED.getRGB()); } - public Vector4i getSelectionBounding() - { - var direction = SkyblockerConfig.get().general.titleContainer.direction; - var alignment = SkyblockerConfig.get().general.titleContainer.alignment; + public Pair<Vector2i, Vector2i> getSelectionBoundingBox() { + SkyblockerConfig.Alignment alignment = SkyblockerConfig.get().general.titleContainer.alignment; int midWidth = getSelectionWidth() / 2; - int midHeight = getSelectionHeight() / 2; int x1 = 0; int x2 = 0; - int y1 = 0; - int y2 = 0; - y1 = hudY; - y2 = hudY + midHeight * 2; + int y1 = hudY; + int y2 = hudY + getSelectionHeight(); switch (alignment) { - case RIGHT: + case RIGHT -> { x1 = hudX - midWidth * 2; x2 = hudX; - break; - case MIDDLE: + } + case MIDDLE -> { x1 = hudX - midWidth; x2 = hudX + midWidth; - break; - case LEFT: + } + case LEFT -> { x1 = hudX; x2 = hudX + midWidth * 2; - break; + } } - return new Vector4i(x1, x2, y1, y2); + return new Pair<>(new Vector2i(x1, y1), new Vector2i(x2, y2)); } - public int getSelectionHeight() - { + public int getSelectionHeight() { int scale = (int) (3F * (SkyblockerConfig.get().general.titleContainer.titleContainerScale / 100F)); return SkyblockerConfig.get().general.titleContainer.direction == SkyblockerConfig.Direction.HORIZONTAL ? textRenderer.fontHeight * scale : (textRenderer.fontHeight + 10) * 3 * scale; } - public int getSelectionWidth() - { + public int getSelectionWidth() { int scale = (int) (3F * (SkyblockerConfig.get().general.titleContainer.titleContainerScale / 100F)); return SkyblockerConfig.get().general.titleContainer.direction == SkyblockerConfig.Direction.HORIZONTAL ? (textRenderer.getWidth("Test1") + 10 + textRenderer.getWidth("Test23") + 10 + textRenderer.getWidth("Testing1234")) * scale : @@ -111,16 +94,11 @@ public class TitleContainerConfigScreen extends Screen { int midHeight = getSelectionHeight() / 2; var alignment = SkyblockerConfig.get().general.titleContainer.alignment; - int x1; - int x2; - int y1; - int y2; - - var vec = getSelectionBounding(); - x1 = vec.x; - x2 = vec.y; - y1 = vec.z; - y2 = vec.w; + Pair<Vector2i, Vector2i> boundingBox = getSelectionBoundingBox(); + int x1 = boundingBox.getLeft().x; + int y1 = boundingBox.getLeft().y; + int x2 = boundingBox.getRight().x; + int y2 = boundingBox.getRight().y; if (RenderUtils.pointExistsInArea((int) mouseX, (int) mouseY, x1, y1, x2, y2) && button == 0) { hudX = alignment == SkyblockerConfig.Alignment.RIGHT ? @@ -135,31 +113,31 @@ public class TitleContainerConfigScreen extends Screen { public boolean mouseClicked(double mouseX, double mouseY, int button) { if (button == 1) { hudX = this.width / 2; - hudY = (int) (this.height * 0.6F); + hudY = this.height / 2; } return super.mouseClicked(mouseX, mouseY, button); } @Override public boolean keyPressed(int keyCode, int scanCode, int modifiers) { - if(keyCode == GLFW.GLFW_KEY_Q) { - var current = SkyblockerConfig.get().general.titleContainer.alignment; + if (keyCode == GLFW.GLFW_KEY_Q) { + SkyblockerConfig.Alignment current = SkyblockerConfig.get().general.titleContainer.alignment; SkyblockerConfig.get().general.titleContainer.alignment = switch (current) { case LEFT -> SkyblockerConfig.Alignment.MIDDLE; case MIDDLE -> SkyblockerConfig.Alignment.RIGHT; case RIGHT -> SkyblockerConfig.Alignment.LEFT; }; } - if(keyCode == GLFW.GLFW_KEY_E) { - var current = SkyblockerConfig.get().general.titleContainer.alignment; + if (keyCode == GLFW.GLFW_KEY_E) { + SkyblockerConfig.Alignment current = SkyblockerConfig.get().general.titleContainer.alignment; SkyblockerConfig.get().general.titleContainer.alignment = switch (current) { case LEFT -> SkyblockerConfig.Alignment.RIGHT; case MIDDLE -> SkyblockerConfig.Alignment.LEFT; case RIGHT -> SkyblockerConfig.Alignment.MIDDLE; }; } - if(keyCode == GLFW.GLFW_KEY_R) { - var current = SkyblockerConfig.get().general.titleContainer.direction; + if (keyCode == GLFW.GLFW_KEY_R) { + SkyblockerConfig.Direction current = SkyblockerConfig.get().general.titleContainer.direction; SkyblockerConfig.get().general.titleContainer.direction = switch (current) { case HORIZONTAL -> SkyblockerConfig.Direction.VERTICAL; case VERTICAL -> SkyblockerConfig.Direction.HORIZONTAL; -- cgit