diff options
Diffstat (limited to 'src/main/java/de/hysky/skyblocker/skyblock')
43 files changed, 655 insertions, 487 deletions
diff --git a/src/main/java/de/hysky/skyblocker/skyblock/FancyStatusBars.java b/src/main/java/de/hysky/skyblocker/skyblock/FancyStatusBars.java index 4cd356a8..3456d1ad 100644 --- a/src/main/java/de/hysky/skyblocker/skyblock/FancyStatusBars.java +++ b/src/main/java/de/hysky/skyblocker/skyblock/FancyStatusBars.java @@ -85,12 +85,11 @@ public class FancyStatusBars { bars[bar].anchorNum = location; // Count how many bars are in each location - int layer1Count = 0, layer2Count = 0, rightCount = 0; + int layer1Count = 0, layer2Count = 0; for (int i = 0; i < 4; i++) { switch (bars[i].anchorNum) { case 0 -> layer1Count++; case 1 -> layer2Count++; - case 2 -> rightCount++; } } diff --git a/src/main/java/de/hysky/skyblocker/skyblock/TeleportOverlay.java b/src/main/java/de/hysky/skyblocker/skyblock/TeleportOverlay.java index c290e5b8..e572d9dc 100644 --- a/src/main/java/de/hysky/skyblocker/skyblock/TeleportOverlay.java +++ b/src/main/java/de/hysky/skyblocker/skyblock/TeleportOverlay.java @@ -102,7 +102,7 @@ public class TeleportOverlay { @SuppressWarnings("DataFlowIssue") BlockState state = client.world.getBlockState(pos); if (!state.isAir() && client.world.getBlockState(pos.up()).isAir() && client.world.getBlockState(pos.up(2)).isAir()) { - RenderHelper.renderFilledIfVisible(wrc, pos, COLOR_COMPONENTS, 0.5f); + RenderHelper.renderFilled(wrc, pos, COLOR_COMPONENTS, 0.5f, false); } } } diff --git a/src/main/java/de/hysky/skyblocker/skyblock/dungeon/CreeperBeams.java b/src/main/java/de/hysky/skyblocker/skyblock/dungeon/CreeperBeams.java index 08c22b27..5c7a01f9 100644 --- a/src/main/java/de/hysky/skyblocker/skyblock/dungeon/CreeperBeams.java +++ b/src/main/java/de/hysky/skyblocker/skyblock/dungeon/CreeperBeams.java @@ -31,14 +31,13 @@ public class CreeperBeams { private static final Logger LOGGER = LoggerFactory.getLogger(CreeperBeams.class.getName()); - // "missing, this palette looks like you stole it from a 2018 bootstrap webapp!" private static final float[][] COLORS = { DyeColor.LIGHT_BLUE.getColorComponents(), - DyeColor.PINK.getColorComponents(), - DyeColor.ORANGE.getColorComponents(), + DyeColor.LIME.getColorComponents(), + DyeColor.YELLOW.getColorComponents(), DyeColor.MAGENTA.getColorComponents(), }; - private static final float[] LIME_COLOR_COMPONENTS = DyeColor.LIME.getColorComponents(); + private static final float[] GREEN_COLOR_COMPONENTS = DyeColor.GREEN.getColorComponents(); private static final int FLOOR_Y = 68; private static final int BASE_Y = 74; @@ -81,7 +80,7 @@ public class CreeperBeams { if (base == null) { return; } - Vec3d creeperPos = new Vec3d(base.getX() + 0.5, BASE_Y + 3.5, base.getZ() + 0.5); + Vec3d creeperPos = new Vec3d(base.getX() + 0.5, BASE_Y + 1.75, base.getZ() + 0.5); ArrayList<BlockPos> targets = findTargets(world, base); beams = findLines(creeperPos, targets); } @@ -242,9 +241,9 @@ public class CreeperBeams { RenderHelper.renderOutline(wrc, outlineTwo, color, 3, false); RenderHelper.renderLinesFromPoints(wrc, line, color, 1, 2); } else { - RenderHelper.renderOutline(wrc, outlineOne, LIME_COLOR_COMPONENTS, 1, false); - RenderHelper.renderOutline(wrc, outlineTwo, LIME_COLOR_COMPONENTS, 1, false); - RenderHelper.renderLinesFromPoints(wrc, line, LIME_COLOR_COMPONENTS, 0.75f, 1); + RenderHelper.renderOutline(wrc, outlineOne, GREEN_COLOR_COMPONENTS, 1, false); + RenderHelper.renderOutline(wrc, outlineTwo, GREEN_COLOR_COMPONENTS, 1, false); + RenderHelper.renderLinesFromPoints(wrc, line, GREEN_COLOR_COMPONENTS, 0.75f, 1); } } } diff --git a/src/main/java/de/hysky/skyblocker/skyblock/dungeon/DungeonMapConfigScreen.java b/src/main/java/de/hysky/skyblocker/skyblock/dungeon/DungeonMapConfigScreen.java index df5f36ce..02b08254 100644 --- a/src/main/java/de/hysky/skyblocker/skyblock/dungeon/DungeonMapConfigScreen.java +++ b/src/main/java/de/hysky/skyblocker/skyblock/dungeon/DungeonMapConfigScreen.java @@ -13,7 +13,7 @@ public class DungeonMapConfigScreen extends Screen { private int hudX = SkyblockerConfigManager.get().locations.dungeons.mapX; private int hudY = SkyblockerConfigManager.get().locations.dungeons.mapY; private final Screen parent; - + protected DungeonMapConfigScreen() { this(null); } @@ -57,7 +57,7 @@ public class DungeonMapConfigScreen extends Screen { SkyblockerConfigManager.get().locations.dungeons.mapX = hudX; SkyblockerConfigManager.get().locations.dungeons.mapY = hudY; SkyblockerConfigManager.save(); - + this.client.setScreen(parent); } } diff --git a/src/main/java/de/hysky/skyblocker/skyblock/dungeon/LividColor.java b/src/main/java/de/hysky/skyblocker/skyblock/dungeon/LividColor.java index 762a6e17..f40b7859 100644 --- a/src/main/java/de/hysky/skyblocker/skyblock/dungeon/LividColor.java +++ b/src/main/java/de/hysky/skyblocker/skyblock/dungeon/LividColor.java @@ -1,18 +1,49 @@ package de.hysky.skyblocker.skyblock.dungeon; +import de.hysky.skyblocker.config.SkyblockerConfig; import de.hysky.skyblocker.config.SkyblockerConfigManager; import de.hysky.skyblocker.utils.Utils; import de.hysky.skyblocker.utils.scheduler.MessageScheduler; import net.fabricmc.fabric.api.client.message.v1.ClientReceiveMessageEvents; +import net.minecraft.block.Block; +import net.minecraft.block.Blocks; import net.minecraft.client.MinecraftClient; +import net.minecraft.registry.Registries; +import net.minecraft.util.Formatting; import net.minecraft.util.math.BlockPos; +import java.util.Map; + public class LividColor { + private static final Map<Block, Formatting> WOOL_TO_FORMATTING = Map.of( + Blocks.RED_WOOL, Formatting.RED, + Blocks.YELLOW_WOOL, Formatting.YELLOW, + Blocks.LIME_WOOL, Formatting.GREEN, + Blocks.GREEN_WOOL, Formatting.DARK_GREEN, + Blocks.BLUE_WOOL, Formatting.BLUE, + Blocks.MAGENTA_WOOL, Formatting.LIGHT_PURPLE, + Blocks.PURPLE_WOOL, Formatting.DARK_PURPLE, + Blocks.GRAY_WOOL, Formatting.GRAY, + Blocks.WHITE_WOOL, Formatting.WHITE + ); + private static final Map<String, Formatting> LIVID_TO_FORMATTING = Map.of( + "Hockey Livid", Formatting.RED, + "Arcade Livid", Formatting.YELLOW, + "Smile Livid", Formatting.GREEN, + "Frog Livid", Formatting.DARK_GREEN, + "Scream Livid", Formatting.BLUE, + "Crossed Livid", Formatting.LIGHT_PURPLE, + "Purple Livid", Formatting.DARK_PURPLE, + "Doctor Livid", Formatting.GRAY, + "Vendetta Livid", Formatting.WHITE + ); private static int tenTicks = 0; + private static Formatting color; public static void init() { ClientReceiveMessageEvents.GAME.register((message, overlay) -> { - if (SkyblockerConfigManager.get().locations.dungeons.lividColor.enableLividColor && message.getString().equals("[BOSS] Livid: I respect you for making it to here, but I'll be your undoing.")) { + SkyblockerConfig.LividColor config = SkyblockerConfigManager.get().locations.dungeons.lividColor; + if ((config.enableLividColorText || config.enableLividColorGlow) && message.getString().equals("[BOSS] Livid: I respect you for making it to here, but I'll be your undoing.")) { tenTicks = 8; } }); @@ -21,16 +52,15 @@ public class LividColor { public static void update() { MinecraftClient client = MinecraftClient.getInstance(); if (tenTicks != 0) { - if (SkyblockerConfigManager.get().locations.dungeons.lividColor.enableLividColor && Utils.isInDungeons() && client.world != null) { + SkyblockerConfig.LividColor config = SkyblockerConfigManager.get().locations.dungeons.lividColor; + if ((config.enableLividColorText || config.enableLividColorGlow) && Utils.isInDungeons() && client.world != null) { if (tenTicks == 1) { - MessageScheduler.INSTANCE.sendMessageAfterCooldown(SkyblockerConfigManager.get().locations.dungeons.lividColor.lividColorText.replace("[color]", "red")); - tenTicks = 0; + onLividColorFound(Blocks.RED_WOOL); 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")) { - MessageScheduler.INSTANCE.sendMessageAfterCooldown(SkyblockerConfigManager.get().locations.dungeons.lividColor.lividColorText.replace("[color]", key.substring(16, key.length() - 5))); - tenTicks = 0; + Block color = client.world.getBlockState(new BlockPos(5, 110, 42)).getBlock(); + if (WOOL_TO_FORMATTING.containsKey(color) && !color.equals(Blocks.RED_WOOL)) { + onLividColorFound(color); return; } tenTicks--; @@ -39,4 +69,22 @@ public class LividColor { } } } + + private static void onLividColorFound(Block color) { + LividColor.color = WOOL_TO_FORMATTING.get(color); + if (SkyblockerConfigManager.get().locations.dungeons.lividColor.enableLividColorText) { + String colorString = Registries.BLOCK.getId(color).getPath(); + MessageScheduler.INSTANCE.sendMessageAfterCooldown(SkyblockerConfigManager.get().locations.dungeons.lividColor.lividColorText.replaceAll("\\[color]", colorString.substring(0, colorString.length() - 5))); + } + tenTicks = 0; + } + + public static boolean shouldGlow(String name) { + return SkyblockerConfigManager.get().locations.dungeons.lividColor.enableLividColorGlow && color == LIVID_TO_FORMATTING.get(name); + } + + @SuppressWarnings("DataFlowIssue") + public static int getGlowColor(String name) { + return LIVID_TO_FORMATTING.containsKey(name) ? LIVID_TO_FORMATTING.get(name).getColorValue() : Formatting.WHITE.getColorValue(); + } } diff --git a/src/main/java/de/hysky/skyblocker/skyblock/dungeon/StarredMobGlow.java b/src/main/java/de/hysky/skyblocker/skyblock/dungeon/StarredMobGlow.java deleted file mode 100644 index 2072017d..00000000 --- a/src/main/java/de/hysky/skyblocker/skyblock/dungeon/StarredMobGlow.java +++ /dev/null @@ -1,56 +0,0 @@ -package de.hysky.skyblocker.skyblock.dungeon; - -import de.hysky.skyblocker.utils.Utils; -import de.hysky.skyblocker.utils.render.culling.OcclusionCulling; -import net.minecraft.entity.Entity; -import net.minecraft.entity.decoration.ArmorStandEntity; -import net.minecraft.entity.passive.BatEntity; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.predicate.entity.EntityPredicates; -import net.minecraft.util.math.Box; - -import java.util.List; - -public class StarredMobGlow { - - public static boolean shouldMobGlow(Entity entity) { - Box box = entity.getBoundingBox(); - - if (Utils.isInDungeons() && !entity.isInvisible() && OcclusionCulling.isVisible(box.minX, box.minY, box.minZ, box.maxX, box.maxY, box.maxZ)) { - // Minibosses - if (entity instanceof PlayerEntity) { - switch (entity.getName().getString()) { - case "Lost Adventurer", "Shadow Assassin", "Diamond Guy" -> { - return true; - } - } - } - - // Regular Mobs - if (!(entity instanceof ArmorStandEntity)) { - Box searchBox = box.expand(0, 2, 0); - List<ArmorStandEntity> armorStands = entity.getWorld().getEntitiesByClass(ArmorStandEntity.class, searchBox, EntityPredicates.NOT_MOUNTED); - - if (!armorStands.isEmpty() && armorStands.get(0).getName().getString().contains("✯")) return true; - } - - // Bats - return entity instanceof BatEntity; - } - - return false; - } - - public static int getGlowColor(Entity entity) { - if (entity instanceof PlayerEntity) { - return switch (entity.getName().getString()) { - case "Lost Adventurer" -> 0xfee15c; - case "Shadow Assassin" -> 0x5b2cb2; - case "Diamond Guy" -> 0x57c2f7; - default -> 0xf57738; - }; - } - - return 0xf57738; - } -} diff --git a/src/main/java/de/hysky/skyblocker/skyblock/dungeon/Trivia.java b/src/main/java/de/hysky/skyblocker/skyblock/dungeon/Trivia.java index 262d4a4e..53368c14 100644 --- a/src/main/java/de/hysky/skyblocker/skyblock/dungeon/Trivia.java +++ b/src/main/java/de/hysky/skyblocker/skyblock/dungeon/Trivia.java @@ -1,7 +1,7 @@ package de.hysky.skyblocker.skyblock.dungeon; import de.hysky.skyblocker.config.SkyblockerConfigManager; -import de.hysky.skyblocker.skyblock.FairySouls; +import de.hysky.skyblocker.skyblock.waypoint.FairySouls; import de.hysky.skyblocker.utils.chat.ChatFilterResult; import de.hysky.skyblocker.utils.chat.ChatPatternListener; import net.minecraft.client.MinecraftClient; diff --git a/src/main/java/de/hysky/skyblocker/skyblock/dungeon/secrets/DungeonSecrets.java b/src/main/java/de/hysky/skyblocker/skyblock/dungeon/secrets/DungeonSecrets.java index eda08cf6..ee517eb8 100644 --- a/src/main/java/de/hysky/skyblocker/skyblock/dungeon/secrets/DungeonSecrets.java +++ b/src/main/java/de/hysky/skyblocker/skyblock/dungeon/secrets/DungeonSecrets.java @@ -255,7 +255,7 @@ public class DungeonSecrets { dungeonFutures.add(CompletableFuture.runAsync(() -> { try (BufferedReader customWaypointsReader = Files.newBufferedReader(CUSTOM_WAYPOINTS_DIR)) { SkyblockerMod.GSON.fromJson(customWaypointsReader, JsonObject.class).asMap().forEach((room, waypointsJson) -> - addCustomWaypoints(room, SecretWaypoint.LIST_CODEC.parse(JsonOps.INSTANCE, waypointsJson).resultOrPartial(LOGGER::error).orElseThrow()) + addCustomWaypoints(room, SecretWaypoint.LIST_CODEC.parse(JsonOps.INSTANCE, waypointsJson).resultOrPartial(LOGGER::error).orElseGet(ArrayList::new)) ); LOGGER.debug("[Skyblocker Dungeon Secrets] Loaded custom dungeon secret waypoints"); } catch (Exception e) { @@ -273,7 +273,7 @@ public class DungeonSecrets { try (BufferedWriter writer = Files.newBufferedWriter(CUSTOM_WAYPOINTS_DIR)) { JsonObject customWaypointsJson = new JsonObject(); customWaypoints.rowMap().forEach((room, waypoints) -> - customWaypointsJson.add(room, SecretWaypoint.LIST_CODEC.encodeStart(JsonOps.INSTANCE, new ArrayList<>(waypoints.values())).resultOrPartial(LOGGER::error).orElseThrow()) + customWaypointsJson.add(room, SecretWaypoint.LIST_CODEC.encodeStart(JsonOps.INSTANCE, new ArrayList<>(waypoints.values())).resultOrPartial(LOGGER::error).orElseGet(JsonArray::new)) ); SkyblockerMod.GSON.toJson(customWaypointsJson, writer); LOGGER.info("[Skyblocker Dungeon Secrets] Saved custom dungeon secret waypoints"); diff --git a/src/main/java/de/hysky/skyblocker/skyblock/dungeon/secrets/Room.java b/src/main/java/de/hysky/skyblocker/skyblock/dungeon/secrets/Room.java index ecfcf496..9b95f146 100644 --- a/src/main/java/de/hysky/skyblocker/skyblock/dungeon/secrets/Room.java +++ b/src/main/java/de/hysky/skyblocker/skyblock/dungeon/secrets/Room.java @@ -41,6 +41,7 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; public class Room { + private static final Pattern SECRET_INDEX = Pattern.compile("^(\\d+)"); private static final Pattern SECRETS = Pattern.compile("§7(\\d{1,2})/(\\d{1,2}) Secrets"); @NotNull private final Type type; @@ -70,11 +71,12 @@ public class Room { private int doubleCheckBlocks; /** * Represents the matching state of the room with the following possible values: - * <li>{@link TriState#DEFAULT} means that the room has not been checked, is being processed, or does not {@link Type#needsScanning() need to be processed}. - * <li>{@link TriState#FALSE} means that the room has been checked and there is no match. - * <li>{@link TriState#TRUE} means that the room has been checked and there is a match. + * <li>{@link MatchState#MATCHING} means that the room has not been checked, is being processed, or does not {@link Type#needsScanning() need to be processed}.</li> + * <li>{@link MatchState#DOUBLE_CHECKING} means that the room has a unique match and is being double checked.</li> + * <li>{@link MatchState#MATCHED} means that the room has a unique match ans has been double checked.</li> + * <li>{@link MatchState#FAILED} means that the room has been checked and there is no match.</li> */ - private TriState matched = TriState.DEFAULT; + private MatchState matchState = MatchState.MATCHING; private Table<Integer, BlockPos, SecretWaypoint> secretWaypoints; private String name; private Direction direction; @@ -96,7 +98,7 @@ public class Room { } public boolean isMatched() { - return matched == TriState.TRUE; + return matchState == MatchState.DOUBLE_CHECKING || matchState == MatchState.MATCHED; } /** @@ -108,7 +110,7 @@ public class Room { @Override public String toString() { - return "Room{type=" + type + ", shape=" + shape + ", matched=" + matched + ", segments=" + Arrays.toString(segments.toArray()) + "}"; + return "Room{type=%s, segments=%s, shape=%s, matchState=%s, name=%s, direction=%s, physicalCornerPos=%s}".formatted(type, Arrays.toString(segments.toArray()), shape, matchState, name, direction, physicalCornerPos); } @NotNull @@ -208,6 +210,7 @@ public class Room { /** * Removes a custom waypoint relative to this room from {@link DungeonSecrets#customWaypoints} and all existing instances of this room. + * * @param pos the position of the secret waypoint relative to this room * @return the removed secret waypoint or {@code null} if there was no secret waypoint at the given position */ @@ -223,6 +226,7 @@ public class Room { /** * Removes a custom waypoint relative to this room from this instance of the room. + * * @param secretIndex the index of the secret waypoint * @param relativePos the position of the secret waypoint relative to this room */ @@ -237,7 +241,7 @@ public class Room { * This method returns immediately if any of the following conditions are met: * <ul> * <li> The room does not need to be scanned and matched. (When the room is not of type {@link Type.ROOM}, {@link Type.PUZZLE}, or {@link Type.TRAP}. See {@link Type#needsScanning()}) </li> - * <li> The room has been matched or failed to match and is on cooldown. See {@link #matched}. </li> + * <li> The room has been matched or failed to match and is on cooldown. See {@link #matchState}. </li> * <li> {@link #findRoom The previous update} has not completed. </li> * </ul> * Then this method tries to match this room through: @@ -251,7 +255,7 @@ public class Room { @SuppressWarnings("JavadocReference") protected void update() { // Logical AND has higher precedence than logical OR - if (!type.needsScanning() || matched != TriState.DEFAULT || !DungeonSecrets.isRoomsLoaded() || findRoom != null && !findRoom.isDone()) { + if (!type.needsScanning() || matchState != MatchState.MATCHING && matchState != MatchState.DOUBLE_CHECKING || !DungeonSecrets.isRoomsLoaded() || findRoom != null && !findRoom.isDone()) { return; } MinecraftClient client = MinecraftClient.getInstance(); @@ -266,6 +270,9 @@ public class Room { break; } } + }).exceptionally(e -> { + DungeonSecrets.LOGGER.error("[Skyblocker Dungeon Secrets] Encountered an unknown exception while matching room {}", this, e); + return null; }); } @@ -297,16 +304,24 @@ public class Room { * </ul> * <li> If there are no matching rooms left: </li> * <ul> - * <li> Terminate matching by setting {@link #matched} to {@link TriState#FALSE}. </li> + * <li> Terminate matching by setting {@link #matchState} to {@link TriState#FALSE}. </li> * <li> Schedule another matching attempt in 50 ticks (2.5 seconds). </li> * <li> Reset {@link #possibleRooms} and {@link #checkedBlocks} with {@link #reset()}. </li> * <li> Return {@code true} </li> * </ul> * <li> If there are exactly one room matching: </li> * <ul> - * <li> Call {@link #roomMatched()}. </li> - * <li> Discard the no longer needed fields to save memory. </li> - * <li> Return {@code true} </li> + * <li> If {@link #matchState} is {@link MatchState#MATCHING}: </li> + * <ul> + * <li> Call {@link #roomMatched()}. </li> + * <li> Return {@code false}. </li> + * </ul> + * <li> If {@link #matchState} is {@link MatchState#DOUBLE_CHECKING}: </li> + * <ul> + * <li> Set the match state to {@link MatchState#MATCHED}. </li> + * <li> Discard the no longer needed fields to save memory. </li> + * <li> Return {@code true}. </li> + * </ul> * </ul> * <li> Return {@code false} </li> * </ul> @@ -334,26 +349,29 @@ public class Room { int matchingRoomsSize = possibleRooms.stream().map(Triple::getRight).mapToInt(Collection::size).sum(); if (matchingRoomsSize == 0) { // If no rooms match, reset the fields and scan again after 50 ticks. - matched = TriState.FALSE; - DungeonSecrets.LOGGER.warn("[Skyblocker] No dungeon room matches after checking {} block(s)", checkedBlocks.size()); - Scheduler.INSTANCE.schedule(() -> matched = TriState.DEFAULT, 50); + DungeonSecrets.LOGGER.warn("[Skyblocker Dungeon Secrets] No dungeon room matched after checking {} block(s) including double checking {} block(s)", checkedBlocks.size(), doubleCheckBlocks); + Scheduler.INSTANCE.schedule(() -> matchState = MatchState.MATCHING, 50); reset(); return true; - } else if (matchingRoomsSize == 1 && ++doubleCheckBlocks >= 10) { - // If one room matches, load the secrets for that room and discard the no longer needed fields. - for (Triple<Direction, Vector2ic, List<String>> directionRooms : possibleRooms) { - if (directionRooms.getRight().size() == 1) { - name = directionRooms.getRight().get(0); - direction = directionRooms.getLeft(); - physicalCornerPos = directionRooms.getMiddle(); - roomMatched(); - discard(); - return true; - } + } else if (matchingRoomsSize == 1) { + if (matchState == MatchState.MATCHING) { + // If one room matches, load the secrets for that room and set state to double-checking. + Triple<Direction, Vector2ic, List<String>> directionRoom = possibleRooms.stream().filter(directionRooms -> directionRooms.getRight().size() == 1).findAny().orElseThrow(); + name = directionRoom.getRight().get(0); + direction = directionRoom.getLeft(); + physicalCornerPos = directionRoom.getMiddle(); + DungeonSecrets.LOGGER.info("[Skyblocker Dungeon Secrets] Room {} matched after checking {} block(s), starting double checking", name, checkedBlocks.size()); + roomMatched(); + return false; + } else if (matchState == MatchState.DOUBLE_CHECKING && ++doubleCheckBlocks >= 10) { + // If double-checked, set state to matched and discard the no longer needed fields. + DungeonSecrets.LOGGER.info("[Skyblocker Dungeon Secrets] Room {} matched after checking {} block(s) including double checking {} block(s)", name, checkedBlocks.size(), doubleCheckBlocks); + discard(); + return true; } - return false; // This should never happen, we just checked that there is one possible room, and the return true in the loop should activate + return false; } else { - DungeonSecrets.LOGGER.debug("[Skyblocker] {} room(s) remaining after checking {} block(s)", matchingRoomsSize, checkedBlocks.size()); + DungeonSecrets.LOGGER.debug("[Skyblocker Dungeon Secrets] {} room(s) remaining after checking {} block(s)", matchingRoomsSize, checkedBlocks.size()); return false; } } @@ -371,7 +389,7 @@ public class Room { /** * Loads the secret waypoints for the room from {@link DungeonSecrets#waypointsJson} once it has been matched - * and sets {@link #matched} to {@link TriState#TRUE}. + * and sets {@link #matchState} to {@link MatchState#DOUBLE_CHECKING}. * * @param directionRooms the direction, position, and name of the room */ @@ -381,25 +399,29 @@ public class Room { for (JsonElement waypointElement : DungeonSecrets.getRoomWaypoints(name)) { JsonObject waypoint = waypointElement.getAsJsonObject(); String secretName = waypoint.get("secretName").getAsString(); - int secretIndex = Integer.parseInt(secretName.substring(0, Character.isDigit(secretName.charAt(1)) ? 2 : 1)); + Matcher secretIndexMatcher = SECRET_INDEX.matcher(secretName); + int secretIndex = secretIndexMatcher.find() ? Integer.parseInt(secretIndexMatcher.group(1)) : 0; BlockPos pos = DungeonMapUtils.relativeToActual(direction, physicalCornerPos, waypoint); secretWaypoints.put(secretIndex, pos, new SecretWaypoint(secretIndex, waypoint, secretName, pos)); } DungeonSecrets.getCustomWaypoints(name).values().forEach(this::addCustomWaypoint); - matched = TriState.TRUE; - - DungeonSecrets.LOGGER.info("[Skyblocker] Room {} matched after checking {} block(s)", name, checkedBlocks.size()); + matchState = MatchState.DOUBLE_CHECKING; } /** * Resets fields for another round of matching after room matching fails. */ private void reset() { + matchState = MatchState.FAILED; IntSortedSet segmentsX = IntSortedSets.unmodifiable(new IntRBTreeSet(segments.stream().mapToInt(Vector2ic::x).toArray())); IntSortedSet segmentsY = IntSortedSets.unmodifiable(new IntRBTreeSet(segments.stream().mapToInt(Vector2ic::y).toArray())); possibleRooms = getPossibleRooms(segmentsX, segmentsY); checkedBlocks = new HashSet<>(); doubleCheckBlocks = 0; + secretWaypoints = null; + name = null; + direction = null; + physicalCornerPos = null; } /** @@ -407,6 +429,7 @@ public class Room { * These fields are no longer needed and are discarded to save memory. */ private void discard() { + matchState = MatchState.MATCHED; roomsData = null; possibleRooms = null; checkedBlocks = null; @@ -473,7 +496,7 @@ public class Room { BlockState state = world.getBlockState(hitResult.getBlockPos()); if (state.isOf(Blocks.CHEST) || state.isOf(Blocks.PLAYER_HEAD) || state.isOf(Blocks.PLAYER_WALL_HEAD)) { secretWaypoints.column(hitResult.getBlockPos()).values().stream().filter(SecretWaypoint::needsInteraction).findAny() - .ifPresent(secretWaypoint -> onSecretFound(secretWaypoint, "[Skyblocker] Detected {} interaction, setting secret #{} as found", secretWaypoint.category, secretWaypoint.secretIndex)); + .ifPresent(secretWaypoint -> onSecretFound(secretWaypoint, "[Skyblocker Dungeon Secrets] Detected {} interaction, setting secret #{} as found", secretWaypoint.category, secretWaypoint.secretIndex)); } else if (state.isOf(Blocks.LEVER)) { secretWaypoints.column(hitResult.getBlockPos()).values().stream().filter(SecretWaypoint::isLever).forEach(SecretWaypoint::setFound); } @@ -491,7 +514,7 @@ public class Room { return; } secretWaypoints.values().stream().filter(SecretWaypoint::needsItemPickup).min(Comparator.comparingDouble(SecretWaypoint.getSquaredDistanceToFunction(collector))).filter(SecretWaypoint.getRangePredicate(collector)) - .ifPresent(secretWaypoint -> onSecretFound(secretWaypoint, "[Skyblocker] Detected {} picked up a {} from a {} secret, setting secret #{} as found", collector.getName().getString(), itemEntity.getName().getString(), secretWaypoint.category, secretWaypoint.secretIndex)); + .ifPresent(secretWaypoint -> onSecretFound(secretWaypoint, "[Skyblocker Dungeon Secrets] Detected {} picked up a {} from a {} secret, setting secret #{} as found", collector.getName().getString(), itemEntity.getName().getString(), secretWaypoint.category, secretWaypoint.secretIndex)); } /** @@ -502,7 +525,7 @@ public class Room { */ protected void onBatRemoved(AmbientEntity bat) { secretWaypoints.values().stream().filter(SecretWaypoint::isBat).min(Comparator.comparingDouble(SecretWaypoint.getSquaredDistanceToFunction(bat))) - .ifPresent(secretWaypoint -> onSecretFound(secretWaypoint, "[Skyblocker] Detected {} killed for a {} secret, setting secret #{} as found", bat.getName().getString(), secretWaypoint.category, secretWaypoint.secretIndex)); + .ifPresent(secretWaypoint -> onSecretFound(secretWaypoint, "[Skyblocker Dungeon Secrets] Detected {} killed for a {} secret, setting secret #{} as found", bat.getName().getString(), secretWaypoint.category, secretWaypoint.secretIndex)); } /** @@ -575,4 +598,8 @@ public class Room { public enum Direction { NW, NE, SW, SE } + + public enum MatchState { + MATCHING, DOUBLE_CHECKING, MATCHED, FAILED + } } diff --git a/src/main/java/de/hysky/skyblocker/skyblock/dungeon/secrets/SecretWaypoint.java b/src/main/java/de/hysky/skyblocker/skyblock/dungeon/secrets/SecretWaypoint.java index 0c2d1b34..43f624f6 100644 --- a/src/main/java/de/hysky/skyblocker/skyblock/dungeon/secrets/SecretWaypoint.java +++ b/src/main/java/de/hysky/skyblocker/skyblock/dungeon/secrets/SecretWaypoint.java @@ -20,6 +20,8 @@ import net.minecraft.util.dynamic.Codecs; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.List; import java.util.function.Predicate; @@ -27,6 +29,7 @@ import java.util.function.Supplier; import java.util.function.ToDoubleFunction; public class SecretWaypoint extends Waypoint { + protected static final Logger LOGGER = LoggerFactory.getLogger(SecretWaypoint.class); public static final Codec<SecretWaypoint> CODEC = RecordCodecBuilder.create(instance -> instance.group( Codec.INT.fieldOf("secretIndex").forGetter(secretWaypoint -> secretWaypoint.secretIndex), Category.CODEC.fieldOf("category").forGetter(secretWaypoint -> secretWaypoint.category), @@ -35,8 +38,8 @@ public class SecretWaypoint extends Waypoint { ).apply(instance, SecretWaypoint::new)); public static final Codec<List<SecretWaypoint>> LIST_CODEC = CODEC.listOf(); static final List<String> SECRET_ITEMS = List.of("Decoy", "Defuse Kit", "Dungeon Chest Key", "Healing VIII", "Inflatable Jerry", "Spirit Leap", "Training Weights", "Trap", "Treasure Talisman"); - private static final SkyblockerConfig.SecretWaypoints CONFIG = SkyblockerConfigManager.get().locations.dungeons.secretWaypoints; - private static final Supplier<Type> TYPE_SUPPLIER = () -> CONFIG.waypointType; + private static final Supplier<SkyblockerConfig.SecretWaypoints> CONFIG = () -> SkyblockerConfigManager.get().locations.dungeons.secretWaypoints; + private static final Supplier<Type> TYPE_SUPPLIER = () -> CONFIG.get().waypointType; final int secretIndex; final Category category; final Text name; @@ -95,7 +98,7 @@ public class SecretWaypoint extends Waypoint { //TODO In the future, shrink the box for wither essence and items so its more realistic super.render(context); - if (CONFIG.showSecretText) { + if (CONFIG.get().showSecretText) { Vec3d posUp = centerPos.add(0, 1, 0); RenderHelper.renderText(context, name, posUp, true); double distance = context.camera().getPos().distanceTo(centerPos); @@ -135,8 +138,8 @@ public class SecretWaypoint extends Waypoint { } } - private static Category get(JsonObject waypointJson) { - return CODEC.parse(JsonOps.INSTANCE, waypointJson.get("category")).resultOrPartial(DungeonSecrets.LOGGER::error).orElseThrow(); + static Category get(JsonObject waypointJson) { + return CODEC.parse(JsonOps.INSTANCE, waypointJson.get("category")).resultOrPartial(LOGGER::error).orElse(Category.DEFAULT); } boolean needsInteraction() { diff --git a/src/main/java/de/hysky/skyblocker/skyblock/dwarven/DwarvenHudConfigScreen.java b/src/main/java/de/hysky/skyblocker/skyblock/dwarven/DwarvenHudConfigScreen.java index 9bd6bef1..6f281ba9 100644 --- a/src/main/java/de/hysky/skyblocker/skyblock/dwarven/DwarvenHudConfigScreen.java +++ b/src/main/java/de/hysky/skyblocker/skyblock/dwarven/DwarvenHudConfigScreen.java @@ -23,7 +23,7 @@ public class DwarvenHudConfigScreen extends Screen { protected DwarvenHudConfigScreen() { this(null); } - + public DwarvenHudConfigScreen(Screen parent) { super(Text.of("Dwarven HUD Config")); this.parent = parent; @@ -62,7 +62,7 @@ public class DwarvenHudConfigScreen extends Screen { SkyblockerConfigManager.get().locations.dwarvenMines.dwarvenHud.x = hudX; SkyblockerConfigManager.get().locations.dwarvenMines.dwarvenHud.y = hudY; SkyblockerConfigManager.save(); - + client.setScreen(parent); } } diff --git a/src/main/java/de/hysky/skyblocker/skyblock/entity/MobGlow.java b/src/main/java/de/hysky/skyblocker/skyblock/entity/MobGlow.java new file mode 100644 index 00000000..5e0995e6 --- /dev/null +++ b/src/main/java/de/hysky/skyblocker/skyblock/entity/MobGlow.java @@ -0,0 +1,83 @@ +package de.hysky.skyblocker.skyblock.entity; + +import java.util.List; + +import de.hysky.skyblocker.config.SkyblockerConfigManager; +import de.hysky.skyblocker.skyblock.dungeon.LividColor; +import de.hysky.skyblocker.utils.Utils; +import de.hysky.skyblocker.utils.render.culling.OcclusionCulling; +import net.minecraft.entity.Entity; +import net.minecraft.entity.decoration.ArmorStandEntity; +import net.minecraft.entity.passive.BatEntity; +import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.predicate.entity.EntityPredicates; +import net.minecraft.util.Formatting; +import net.minecraft.util.math.Box; +import net.minecraft.world.World; + +public class MobGlow { + public static boolean shouldMobGlow(Entity entity) { + Box box = entity.getBoundingBox(); + + if (!entity.isInvisible() && OcclusionCulling.isVisible(box.minX, box.minY, box.minZ, box.maxX, box.maxY, box.maxZ)) { + String name = entity.getName().getString(); + + // Dungeons + if (Utils.isInDungeons()) { + + // Minibosses + if (entity instanceof PlayerEntity) { + switch (name) { + case "Lost Adventurer", "Shadow Assassin", "Diamond Guy": return SkyblockerConfigManager.get().locations.dungeons.starredMobGlow; + case "Arcade Livid", "Crossed Livid", "Doctor Livid", "Frog Livid", "Hockey Livid", + "Purple Livid", "Scream Livid", "Smile Livid", "Vendetta Livid": return LividColor.shouldGlow(name); + } + } + + // Regular Mobs + if (!(entity instanceof ArmorStandEntity)) { + List<ArmorStandEntity> armorStands = getArmorStands(entity.getWorld(), box); + + if (!armorStands.isEmpty() && armorStands.get(0).getName().getString().contains("✯")) return SkyblockerConfigManager.get().locations.dungeons.starredMobGlow; + } + + // Bats + return SkyblockerConfigManager.get().locations.dungeons.starredMobGlow && entity instanceof BatEntity; + } + + // Rift + if (Utils.isInTheRift()) { + if (entity instanceof PlayerEntity) { + switch (name) { + // They have a space in their name for some reason... + case "Blobbercyst ": return SkyblockerConfigManager.get().locations.rift.blobbercystGlow; + } + } + } + } + + return false; + } + + private static List<ArmorStandEntity> getArmorStands(World world, Box box) { + return world.getEntitiesByClass(ArmorStandEntity.class, box.expand(0, 2, 0), EntityPredicates.NOT_MOUNTED); + } + + public static int getGlowColor(Entity entity) { + String name = entity.getName().getString(); + + if (entity instanceof PlayerEntity) { + return switch (name) { + case "Lost Adventurer" -> 0xfee15c; + case "Shadow Assassin" -> 0x5b2cb2; + case "Diamond Guy" -> 0x57c2f7; + case "Arcade Livid", "Crossed Livid", "Doctor Livid", "Frog Livid", "Hockey Livid", + "Purple Livid", "Scream Livid", "Smile Livid", "Vendetta Livid" -> LividColor.getGlowColor(name); + case "Blobbercyst " -> Formatting.GREEN.getColorValue(); + default -> 0xf57738; + }; + } + + return 0xf57738; + } +} diff --git a/src/main/java/de/hysky/skyblocker/skyblock/filters/ComboFilter.java b/src/main/java/de/hysky/skyblocker/skyblock/filters/ComboFilter.java index 5fd6f741..d6a40d2d 100644 --- a/src/main/java/de/hysky/skyblocker/skyblock/filters/ComboFilter.java +++ b/src/main/java/de/hysky/skyblocker/skyblock/filters/ComboFilter.java @@ -5,8 +5,8 @@ import de.hysky.skyblocker.utils.chat.ChatFilterResult; public class ComboFilter extends SimpleChatFilter { public ComboFilter() { - super("^(\\+\\d+ Kill Combo \\+\\d+(% ✯ Magic Find| coins per kill|% Combat Exp)" + - "|Your Kill Combo has expired! You reached a \\d+ Kill Combo!)$"); + // ^(\+\d+ Kill Combo( \+\d+(✯ Magic Find| coins per kill|☯ Combat Wisdom))?|Your Kill Combo has expired! You reached a \d+ Kill Combo!)$ + super("^(\\+\\d+ Kill Combo( \\+\\d+(✯ Magic Find| coins per kill|☯ Combat Wisdom))?|Your Kill Combo has expired! You reached a \\d+ Kill Combo!)$"); } @Override diff --git a/src/main/java/de/hysky/skyblocker/skyblock/item/CustomArmorTrims.java b/src/main/java/de/hysky/skyblocker/skyblock/item/CustomArmorTrims.java index cec84b38..3434f026 100644 --- a/src/main/java/de/hysky/skyblocker/skyblock/item/CustomArmorTrims.java +++ b/src/main/java/de/hysky/skyblocker/skyblock/item/CustomArmorTrims.java @@ -145,7 +145,7 @@ public class CustomArmorTrims { Identifier.CODEC.fieldOf("material").forGetter(ArmorTrimId::material), Identifier.CODEC.fieldOf("pattern").forGetter(ArmorTrimId::pattern)) .apply(instance, ArmorTrimId::new)); - + @Override public Identifier left() { return material(); diff --git a/src/main/java/de/hysky/skyblocker/skyblock/item/ItemRarityBackgrounds.java b/src/main/java/de/hysky/skyblocker/skyblock/item/ItemRarityBackgrounds.java index 9e1df2bb..8867af91 100644 --- a/src/main/java/de/hysky/skyblocker/skyblock/item/ItemRarityBackgrounds.java +++ b/src/main/java/de/hysky/skyblocker/skyblock/item/ItemRarityBackgrounds.java @@ -1,8 +1,14 @@ package de.hysky.skyblocker.skyblock.item; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.function.Supplier; + import com.google.common.collect.ImmutableMap; import com.mojang.blaze3d.systems.RenderSystem; -import de.hysky.skyblocker.SkyblockerMod; + +import de.hysky.skyblocker.config.SkyblockerConfig; import de.hysky.skyblocker.config.SkyblockerConfigManager; import de.hysky.skyblocker.utils.ItemUtils; import de.hysky.skyblocker.utils.Utils; @@ -16,16 +22,10 @@ import net.minecraft.client.network.ClientPlayerEntity; import net.minecraft.client.texture.Sprite; import net.minecraft.item.ItemStack; import net.minecraft.text.Text; -import net.minecraft.util.Identifier; - -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.function.Supplier; public class ItemRarityBackgrounds { - private static final Identifier RARITY_BG_TEX = new Identifier(SkyblockerMod.NAMESPACE, "item_rarity_background"); - private static final Supplier<Sprite> SPRITE = () -> MinecraftClient.getInstance().getGuiAtlasManager().getSprite(RARITY_BG_TEX); + private static final SkyblockerConfig.ItemInfoDisplay CONFIG = SkyblockerConfigManager.get().general.itemInfoDisplay; + private static final Supplier<Sprite> SPRITE = () -> MinecraftClient.getInstance().getGuiAtlasManager().getSprite(CONFIG.itemRarityBackgroundStyle.tex); private static final ImmutableMap<String, SkyblockItemRarity> LORE_RARITIES = ImmutableMap.ofEntries( Map.entry("ADMIN", SkyblockItemRarity.ADMIN), Map.entry("SPECIAL", SkyblockItemRarity.SPECIAL), //Very special is the same color so this will cover it @@ -39,27 +39,27 @@ public class ItemRarityBackgrounds { Map.entry("COMMON", SkyblockItemRarity.COMMON) ); private static final Int2ReferenceOpenHashMap<SkyblockItemRarity> CACHE = new Int2ReferenceOpenHashMap<>(); - + public static void init() { //Clear the cache every 5 minutes, ints are very compact! Scheduler.INSTANCE.scheduleCyclic(CACHE::clear, 4800); - + //Clear cache after a screen where items can be upgraded in rarity closes ScreenEvents.BEFORE_INIT.register((client, screen, scaledWidth, scaledHeight) -> { String title = screen.getTitle().getString(); - + if (Utils.isOnSkyblock() && (title.equals("The Hex") || title.equals("Craft Item") || title.equals("Anvil") || title.equals("Reforge Anvil"))) { ScreenEvents.remove(screen).register(screen1 -> CACHE.clear()); } }); } - + public static void tryDraw(ItemStack stack, DrawContext context, int x, int y) { MinecraftClient client = MinecraftClient.getInstance(); - + if (client.player != null) { SkyblockItemRarity itemRarity = getItemRarity(stack, client.player); - + if (itemRarity != null) draw(context, x, y, itemRarity); } } @@ -73,30 +73,30 @@ public class ItemRarityBackgrounds { int hashCode = itemUuid.isEmpty() ? System.identityHashCode(stack) : itemUuid.hashCode(); if (CACHE.containsKey(hashCode)) return CACHE.get(hashCode); - + List<Text> tooltip = stack.getTooltip(player, TooltipContext.BASIC); String[] stringifiedTooltip = tooltip.stream().map(Text::getString).toArray(String[]::new); - + for (String rarityString : LORE_RARITIES.keySet()) { if (Arrays.stream(stringifiedTooltip).anyMatch(line -> line.contains(rarityString))) { SkyblockItemRarity rarity = LORE_RARITIES.get(rarityString); - + CACHE.put(hashCode, rarity); return rarity; } } - + CACHE.put(hashCode, null); return null; } - + private static void draw(DrawContext context, int x, int y, SkyblockItemRarity rarity) { //Enable blending to handle HUD translucency RenderSystem.enableBlend(); RenderSystem.defaultBlendFunc(); context.drawSprite(x, y, 0, 16, 16, SPRITE.get(), rarity.r, rarity.g, rarity.b, SkyblockerConfigManager.get().general.itemInfoDisplay.itemRarityBackgroundsOpacity); - + RenderSystem.disableBlend(); } } diff --git a/src/main/java/de/hysky/skyblocker/skyblock/item/MuseumItemCache.java b/src/main/java/de/hysky/skyblocker/skyblock/item/MuseumItemCache.java index ac9b1bf0..823c4c99 100644 --- a/src/main/java/de/hysky/skyblocker/skyblock/item/MuseumItemCache.java +++ b/src/main/java/de/hysky/skyblocker/skyblock/item/MuseumItemCache.java @@ -40,18 +40,19 @@ public class MuseumItemCache { private static final Path CACHE_FILE = SkyblockerMod.CONFIG_DIR.resolve("museum_item_cache.json"); private static final Object2ObjectOpenHashMap<String, Object2ObjectOpenHashMap<String, ProfileMuseumData>> MUSEUM_ITEM_CACHE = new Object2ObjectOpenHashMap<>(); private static final Type MAP_TYPE = new TypeToken<Object2ObjectOpenHashMap<String, Object2ObjectOpenHashMap<String, ProfileMuseumData>>>() {}.getType(); - + private static final String ERROR_LOG_TEMPLATE = "[Skyblocker] Failed to refresh museum item data for profile {}"; + private static CompletableFuture<Void> loaded; public static void init() { ClientLifecycleEvents.CLIENT_STARTED.register(MuseumItemCache::load); } - + private static void load(MinecraftClient client) { loaded = CompletableFuture.runAsync(() -> { try (BufferedReader reader = Files.newBufferedReader(CACHE_FILE)) { Object2ObjectOpenHashMap<String, Object2ObjectOpenHashMap<String, ProfileMuseumData>> cachedData = SkyblockerMod.GSON.fromJson(reader, MAP_TYPE); - + MUSEUM_ITEM_CACHE.putAll(cachedData); LOGGER.info("[Skyblocker] Loaded museum items cache"); } catch (NoSuchFileException ignored) { @@ -60,7 +61,7 @@ public class MuseumItemCache { } }); } - + private static void save() { CompletableFuture.runAsync(() -> { try (BufferedWriter writer = Files.newBufferedWriter(CACHE_FILE)) { @@ -70,48 +71,70 @@ public class MuseumItemCache { } }); } - + private static void updateData4ProfileMember(String uuid, String profileId) { CompletableFuture.runAsync(() -> { try (ApiResponse response = Http.sendHypixelRequest("skyblock/museum", "?profile=" + profileId)) { //The request was successful if (response.ok()) { JsonObject profileData = JsonParser.parseString(response.content()).getAsJsonObject(); - JsonObject memberData = profileData.get("members").getAsJsonObject().get(uuid).getAsJsonObject(); - - //We call them sets because it could either be a singular item or an entire armour set - Map<String, JsonElement> donatedSets = memberData.get("items").getAsJsonObject().asMap(); - - //Set of all found item ids on profile - ObjectOpenHashSet<String> itemIds = new ObjectOpenHashSet<>(); - - for (Map.Entry<String, JsonElement> donatedSet : donatedSets.entrySet()) { - //Item is plural here because the nbt is a list - String itemsData = donatedSet.getValue().getAsJsonObject().get("items").getAsJsonObject().get("data").getAsString(); - NbtList items = NbtIo.readCompressed(new ByteArrayInputStream(Base64.getDecoder().decode(itemsData))).getList("i", NbtElement.COMPOUND_TYPE); - - for (int i = 0; i < items.size(); i++) { - NbtCompound tag = items.getCompound(i).getCompound("tag"); - - if (tag.contains("ExtraAttributes")) { - NbtCompound extraAttributes = tag.getCompound("ExtraAttributes"); - - if (extraAttributes.contains("id")) itemIds.add(extraAttributes.getString("id")); + JsonObject members = profileData.getAsJsonObject("members"); + + if (members.has(uuid)) { + JsonObject memberData = members.get(uuid).getAsJsonObject(); + + //We call them sets because it could either be a singular item or an entire armour set + Map<String, JsonElement> donatedSets = memberData.get("items").getAsJsonObject().asMap(); + + //Set of all found item ids on profile + ObjectOpenHashSet<String> itemIds = new ObjectOpenHashSet<>(); + + for (Map.Entry<String, JsonElement> donatedSet : donatedSets.entrySet()) { + //Item is plural here because the nbt is a list + String itemsData = donatedSet.getValue().getAsJsonObject().get("items").getAsJsonObject().get("data").getAsString(); + NbtList items = NbtIo.readCompressed(new ByteArrayInputStream(Base64.getDecoder().decode(itemsData))).getList("i", NbtElement.COMPOUND_TYPE); + + for (int i = 0; i < items.size(); i++) { + NbtCompound tag = items.getCompound(i).getCompound("tag"); + + if (tag.contains("ExtraAttributes")) { + NbtCompound extraAttributes = tag.getCompound("ExtraAttributes"); + + if (extraAttributes.contains("id")) itemIds.add(extraAttributes.getString("id")); + } } } + + MUSEUM_ITEM_CACHE.get(uuid).put(profileId, new ProfileMuseumData(System.currentTimeMillis(), itemIds)); + save(); + + LOGGER.info("[Skyblocker] Successfully updated museum item cache for profile {}", profileId); + } else { + //If the player's Museum API is disabled + putEmpty(uuid, profileId); + + LOGGER.warn(ERROR_LOG_TEMPLATE + " because the Museum API is disabled!", profileId); } - - MUSEUM_ITEM_CACHE.get(uuid).put(profileId, new ProfileMuseumData(System.currentTimeMillis(), itemIds)); - save(); - - LOGGER.info("[Skyblocker] Successfully updated museum item cache for profile {}", profileId); + } else { + //If the request returns a non 200 status code + putEmpty(uuid, profileId); + + LOGGER.error(ERROR_LOG_TEMPLATE + " because a non 200 status code was encountered! Status Code: {}", profileId, response.statusCode()); } } catch (Exception e) { - LOGGER.error("[Skyblocker] Failed to refresh museum item data for profile {}", profileId, e); + //If an exception was somehow thrown + putEmpty(uuid, profileId); + + LOGGER.error(ERROR_LOG_TEMPLATE, profileId, e); } }); } - + + private static void putEmpty(String uuid, String profileId) { + MUSEUM_ITEM_CACHE.get(uuid).put(profileId, new ProfileMuseumData(System.currentTimeMillis(), ObjectOpenHashSet.of())); + save(); + } + /** * The cache is ticked upon switching skyblock servers */ @@ -121,22 +144,22 @@ public class MuseumItemCache { Object2ObjectOpenHashMap<String, ProfileMuseumData> playerData = MUSEUM_ITEM_CACHE.computeIfAbsent(uuid, uuid1 -> Util.make(new Object2ObjectOpenHashMap<>(), map -> { map.put(profileId, ProfileMuseumData.EMPTY); })); - + if (playerData.get(profileId).stale()) updateData4ProfileMember(uuid, profileId); } } - + public static boolean hasItemInMuseum(String id) { String uuid = UndashedUuid.toString(MinecraftClient.getInstance().getSession().getUuidOrNull()); - ObjectOpenHashSet<String> collectedItemIds = MUSEUM_ITEM_CACHE.get(uuid).get(Utils.getProfileId()).collectedItemIds(); - + ObjectOpenHashSet<String> collectedItemIds = (!MUSEUM_ITEM_CACHE.containsKey(uuid) || Utils.getProfileId().isBlank() || !MUSEUM_ITEM_CACHE.get(uuid).containsKey(Utils.getProfileId())) ? null : MUSEUM_ITEM_CACHE.get(uuid).get(Utils.getProfileId()).collectedItemIds(); + return collectedItemIds != null && collectedItemIds.contains(id); } - + private record ProfileMuseumData(long lastUpdated, ObjectOpenHashSet<String> collectedItemIds) { private static final ProfileMuseumData EMPTY = new ProfileMuseumData(0L, null); private static final long MAX_AGE = 86_400_000; - + private boolean stale() { return System.currentTimeMillis() > lastUpdated + MAX_AGE; } diff --git a/src/main/java/de/hysky/skyblocker/skyblock/item/SkyblockItemRarity.java b/src/main/java/de/hysky/skyblocker/skyblock/item/SkyblockItemRarity.java index 08cc5377..07a566af 100644 --- a/src/main/java/de/hysky/skyblocker/skyblock/item/SkyblockItemRarity.java +++ b/src/main/java/de/hysky/skyblocker/skyblock/item/SkyblockItemRarity.java @@ -13,7 +13,7 @@ public enum SkyblockItemRarity { RARE(Formatting.BLUE), UNCOMMON(Formatting.GREEN), COMMON(Formatting.WHITE); - + public final float r; public final float g; public final float b; diff --git a/src/main/java/de/hysky/skyblocker/skyblock/item/tooltip/ItemTooltip.java b/src/main/java/de/hysky/skyblocker/skyblock/item/tooltip/ItemTooltip.java index e050aff5..adc23bbb 100644 --- a/src/main/java/de/hysky/skyblocker/skyblock/item/tooltip/ItemTooltip.java +++ b/src/main/java/de/hysky/skyblocker/skyblock/item/tooltip/ItemTooltip.java @@ -4,6 +4,7 @@ import com.google.gson.JsonObject; import de.hysky.skyblocker.SkyblockerMod; import de.hysky.skyblocker.config.SkyblockerConfig; import de.hysky.skyblocker.config.SkyblockerConfigManager; +import de.hysky.skyblocker.skyblock.item.MuseumItemCache; import de.hysky.skyblocker.utils.Constants; import de.hysky.skyblocker.utils.ItemUtils; import de.hysky.skyblocker.utils.Utils; @@ -146,26 +147,41 @@ public class ItemTooltip { .append(getMotesMessage(TooltipInfoType.MOTES.getData().get(internalID).getAsInt(), count))); } - if (TooltipInfoType.MUSEUM.isTooltipEnabled() && !bazaarOpened) { + if (TooltipInfoType.OBTAINED.isTooltipEnabled()) { String timestamp = getTimestamp(stack); - if (TooltipInfoType.MUSEUM.hasOrNullWarning(internalID)) { - String itemCategory = TooltipInfoType.MUSEUM.getData().get(internalID).getAsString(); - String format = switch (itemCategory) { - case "Weapons" -> "%-18s"; - case "Armor" -> "%-19s"; - default -> "%-20s"; - }; - lines.add(Text.literal(String.format(format, "Museum: (" + itemCategory + ")")) - .formatted(Formatting.LIGHT_PURPLE) - .append(Text.literal(timestamp).formatted(Formatting.RED))); - } else if (!timestamp.isEmpty()) { + if (!timestamp.isEmpty()) { lines.add(Text.literal(String.format("%-21s", "Obtained: ")) .formatted(Formatting.LIGHT_PURPLE) .append(Text.literal(timestamp).formatted(Formatting.RED))); } } + if (TooltipInfoType.MUSEUM.isTooltipEnabledAndHasOrNullWarning(internalID) && !bazaarOpened) { + String itemCategory = TooltipInfoType.MUSEUM.getData().get(internalID).getAsString(); + String format = switch (itemCategory) { + case "Weapons" -> "%-18s"; + case "Armor" -> "%-19s"; + default -> "%-20s"; + }; + + //Special case the special category so that it doesn't always display not donated + if (itemCategory.equals("Special")) { + lines.add(Text.literal(String.format(format, "Museum: (" + itemCategory + ")")) + .formatted(Formatting.LIGHT_PURPLE)); + } else { + NbtCompound extraAttributes = ItemUtils.getExtraAttributes(stack); + boolean isInMuseum = (extraAttributes.contains("donated_museum") && extraAttributes.getBoolean("donated_museum")) || MuseumItemCache.hasItemInMuseum(internalID); + + Formatting donatedIndicatorFormatting = isInMuseum ? Formatting.GREEN : Formatting.RED; + + lines.add(Text.literal(String.format(format, "Museum (" + itemCategory + "):")) + .formatted(Formatting.LIGHT_PURPLE) + .append(Text.literal(isInMuseum ? "✔" : "✖").formatted(donatedIndicatorFormatting, Formatting.BOLD)) + .append(Text.literal(isInMuseum ? " Donated" : " Not Donated").formatted(donatedIndicatorFormatting))); + } + } + if (TooltipInfoType.COLOR.isTooltipEnabledAndHasOrNullWarning(internalID) && stack.getNbt() != null) { final NbtElement color = stack.getNbt().getCompound("display").get("color"); diff --git a/src/main/java/de/hysky/skyblocker/skyblock/item/tooltip/TooltipInfoType.java b/src/main/java/de/hysky/skyblocker/skyblock/item/tooltip/TooltipInfoType.java index 086fcb00..38dcb762 100644 --- a/src/main/java/de/hysky/skyblocker/skyblock/item/tooltip/TooltipInfoType.java +++ b/src/main/java/de/hysky/skyblocker/skyblock/item/tooltip/TooltipInfoType.java @@ -20,7 +20,8 @@ public enum TooltipInfoType implements Runnable { ONE_DAY_AVERAGE("https://moulberry.codes/auction_averages_lbin/1day.json", itemTooltip -> itemTooltip.enableAvgBIN, false), THREE_DAY_AVERAGE("https://moulberry.codes/auction_averages_lbin/3day.json", itemTooltip -> itemTooltip.enableAvgBIN, false), MOTES("https://hysky.de/api/motesprice", itemTooltip -> itemTooltip.enableMotesPrice, itemTooltip -> itemTooltip.enableMotesPrice && Utils.isInTheRift(), true), - MUSEUM("https://hysky.de/api/museum", itemTooltip -> itemTooltip.enableMuseumDate, true), + OBTAINED(itemTooltip -> itemTooltip.enableObtainedDate), + MUSEUM("https://hysky.de/api/museum", itemTooltip -> itemTooltip.enableMuseumInfo, true), COLOR("https://hysky.de/api/color", itemTooltip -> itemTooltip.enableExoticTooltip, true); private final String address; @@ -31,6 +32,13 @@ public enum TooltipInfoType implements Runnable { private long hash; /** + * Use this for when you're adding tooltip info that has no data associated with it + */ + TooltipInfoType(Predicate<SkyblockerConfig.ItemTooltip> enabled) { + this(null, itemTooltip -> false, enabled, null, false); + } + + /** * @param address the address to download the data from * @param enabled the predicate to check if the data should be downloaded and the tooltip should be shown * @param cacheable whether the data should be cached diff --git a/src/main/java/de/hysky/skyblocker/skyblock/rift/EffigyWaypoints.java b/src/main/java/de/hysky/skyblocker/skyblock/rift/EffigyWaypoints.java index a0e1a0f2..95e08c80 100644 --- a/src/main/java/de/hysky/skyblocker/skyblock/rift/EffigyWaypoints.java +++ b/src/main/java/de/hysky/skyblocker/skyblock/rift/EffigyWaypoints.java @@ -30,15 +30,15 @@ public class EffigyWaypoints { if (!SkyblockerConfigManager.get().slayer.vampireSlayer.enableEffigyWaypoints || !Utils.isOnSkyblock() || !Utils.isInTheRift() || !Utils.getIslandArea().contains("Stillgore Château")) return; UNBROKEN_EFFIGIES.clear(); - + try { for (int i = 0; i < Utils.STRING_SCOREBOARD.size(); i++) { String line = Utils.STRING_SCOREBOARD.get(i); - + if (line.contains("Effigies")) { List<Text> effigiesText = new ArrayList<>(); List<Text> prefixAndSuffix = Utils.TEXT_SCOREBOARD.get(i).getSiblings(); - + //Add contents of prefix and suffix to list effigiesText.addAll(prefixAndSuffix.get(0).getSiblings()); effigiesText.addAll(prefixAndSuffix.get(1).getSiblings()); @@ -58,11 +58,11 @@ public class EffigyWaypoints { for (BlockPos effigy : UNBROKEN_EFFIGIES) { float[] colorComponents = DyeColor.RED.getColorComponents(); if (SkyblockerConfigManager.get().slayer.vampireSlayer.compactEffigyWaypoints) { - RenderHelper.renderFilledThroughWallsWithBeaconBeam(context, effigy.down(6), colorComponents, 0.5F); + RenderHelper.renderFilledWithBeaconBeam(context, effigy.down(6), colorComponents, 0.5F, true); } else { - RenderHelper.renderFilledThroughWallsWithBeaconBeam(context, effigy, colorComponents, 0.5F); + RenderHelper.renderFilledWithBeaconBeam(context, effigy, colorComponents, 0.5F, true); for (int i = 1; i < 6; i++) { - RenderHelper.renderFilledThroughWalls(context, effigy.down(i), colorComponents, 0.5F - (0.075F * i)); + RenderHelper.renderFilled(context, effigy.down(i), colorComponents, 0.5F - (0.075F * i), true); } } } diff --git a/src/main/java/de/hysky/skyblocker/skyblock/rift/EnigmaSouls.java b/src/main/java/de/hysky/skyblocker/skyblock/rift/EnigmaSouls.java index 744edd4c..aa55a4e3 100644 --- a/src/main/java/de/hysky/skyblocker/skyblock/rift/EnigmaSouls.java +++ b/src/main/java/de/hysky/skyblocker/skyblock/rift/EnigmaSouls.java @@ -1,38 +1,19 @@ package de.hysky.skyblocker.skyblock.rift; -import static net.fabricmc.fabric.api.client.command.v2.ClientCommandManager.literal; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.NoSuchFileException; -import java.nio.file.Path; -import java.util.Arrays; -import java.util.Comparator; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CompletableFuture; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.mojang.brigadier.Command; import com.mojang.brigadier.CommandDispatcher; - import de.hysky.skyblocker.SkyblockerMod; import de.hysky.skyblocker.config.SkyblockerConfig; import de.hysky.skyblocker.config.SkyblockerConfigManager; import de.hysky.skyblocker.utils.Constants; import de.hysky.skyblocker.utils.PosUtils; import de.hysky.skyblocker.utils.Utils; -import de.hysky.skyblocker.utils.render.RenderHelper; -import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; -import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; +import de.hysky.skyblocker.utils.waypoint.ProfileAwareWaypoint; +import de.hysky.skyblocker.utils.waypoint.Waypoint; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; import net.fabricmc.fabric.api.client.rendering.v1.WorldRenderContext; import net.minecraft.client.MinecraftClient; @@ -43,13 +24,27 @@ import net.minecraft.util.DyeColor; import net.minecraft.util.Formatting; import net.minecraft.util.Identifier; import net.minecraft.util.math.BlockPos; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.NoSuchFileException; +import java.nio.file.Path; +import java.util.*; +import java.util.concurrent.CompletableFuture; +import java.util.function.Supplier; + +import static net.fabricmc.fabric.api.client.command.v2.ClientCommandManager.literal; public class EnigmaSouls { private static final Logger LOGGER = LoggerFactory.getLogger(EnigmaSouls.class); + private static final Supplier<Waypoint.Type> TYPE_SUPPLIER = () -> SkyblockerConfigManager.get().general.waypoints.waypointType; private static final Identifier WAYPOINTS_JSON = new Identifier(SkyblockerMod.NAMESPACE, "rift/enigma_soul_waypoints.json"); - private static final BlockPos[] SOUL_WAYPOINTS = new BlockPos[42]; + private static final Map<BlockPos, ProfileAwareWaypoint> SOUL_WAYPOINTS = new HashMap<>(42); private static final Path FOUND_SOULS_FILE = SkyblockerMod.CONFIG_DIR.resolve("found_enigma_souls.json"); - private static final Object2ObjectOpenHashMap<String, ObjectOpenHashSet<BlockPos>> FOUND_SOULS = new Object2ObjectOpenHashMap<>(); private static final float[] GREEN = DyeColor.GREEN.getColorComponents(); private static final float[] RED = DyeColor.RED.getColorComponents(); @@ -64,7 +59,8 @@ public class EnigmaSouls { for (int i = 0; i < waypoints.size(); i++) { JsonObject waypoint = waypoints.get(i).getAsJsonObject(); - SOUL_WAYPOINTS[i] = new BlockPos(waypoint.get("x").getAsInt(), waypoint.get("y").getAsInt(), waypoint.get("z").getAsInt()); + BlockPos pos = new BlockPos(waypoint.get("x").getAsInt(), waypoint.get("y").getAsInt(), waypoint.get("z").getAsInt()); + SOUL_WAYPOINTS.put(pos, new ProfileAwareWaypoint(pos, TYPE_SUPPLIER, GREEN, RED)); } } catch (IOException e) { @@ -74,13 +70,9 @@ public class EnigmaSouls { //Load found souls try (BufferedReader reader = Files.newBufferedReader(FOUND_SOULS_FILE)) { for (Map.Entry<String, JsonElement> profile : JsonParser.parseReader(reader).getAsJsonObject().asMap().entrySet()) { - ObjectOpenHashSet<BlockPos> foundSoulsOnProfile = new ObjectOpenHashSet<>(); - for (JsonElement foundSoul : profile.getValue().getAsJsonArray().asList()) { - foundSoulsOnProfile.add(PosUtils.parsePosString(foundSoul.getAsString())); + SOUL_WAYPOINTS.get(PosUtils.parsePosString(foundSoul.getAsString())).setFound(); } - - FOUND_SOULS.put(profile.getKey(), foundSoulsOnProfile); } } catch (NoSuchFileException ignored) { } catch (IOException e) { @@ -90,9 +82,16 @@ public class EnigmaSouls { } static void save(MinecraftClient client) { - JsonObject json = new JsonObject(); + Map<String, Set<BlockPos>> foundSouls = new HashMap<>(); + for (ProfileAwareWaypoint soul : SOUL_WAYPOINTS.values()) { + for (String profile : soul.foundProfiles) { + foundSouls.computeIfAbsent(profile, profile_ -> new HashSet<>()); + foundSouls.get(profile).add(soul.pos); + } + } - for (Map.Entry<String, ObjectOpenHashSet<BlockPos>> foundSoulsForProfile : FOUND_SOULS.entrySet()) { + JsonObject json = new JsonObject(); + for (Map.Entry<String, Set<BlockPos>> foundSoulsForProfile : foundSouls.entrySet()) { JsonArray foundSoulsJson = new JsonArray(); for (BlockPos foundSoul : foundSoulsForProfile.getValue()) { @@ -109,15 +108,15 @@ public class EnigmaSouls { } } - static void render(WorldRenderContext wrc) { + static void render(WorldRenderContext context) { SkyblockerConfig.Rift config = SkyblockerConfigManager.get().locations.rift; if (Utils.isInTheRift() && config.enigmaSoulWaypoints && soulsLoaded.isDone()) { - for (BlockPos pos : SOUL_WAYPOINTS) { - if (isSoulMissing(pos)) { - RenderHelper.renderFilledThroughWallsWithBeaconBeam(wrc, pos, GREEN, 0.5f); + for (Waypoint soul : SOUL_WAYPOINTS.values()) { + if (soul.shouldRender()) { + soul.render(context); } else if (config.highlightFoundEnigmaSouls) { - RenderHelper.renderFilledThroughWallsWithBeaconBeam(wrc, pos, RED, 0.5f); + soul.render(context); } } } @@ -127,7 +126,8 @@ public class EnigmaSouls { if (Utils.isInTheRift() && !overlay) { String message = text.getString(); - if (message.equals("You have already found that Enigma Soul!") || Formatting.strip(message).equals("SOUL! You unlocked an Enigma Soul!")) markClosestSoulAsFound(); + if (message.equals("You have already found that Enigma Soul!") || Formatting.strip(message).equals("SOUL! You unlocked an Enigma Soul!")) + markClosestSoulAsFound(); } } @@ -136,13 +136,13 @@ public class EnigmaSouls { .then(literal("rift") .then(literal("enigmaSouls") .then(literal("markAllFound").executes(context -> { - markAllFound(); + SOUL_WAYPOINTS.values().forEach(Waypoint::setFound); context.getSource().sendFeedback(Constants.PREFIX.get().append(Text.translatable("skyblocker.rift.enigmaSouls.markAllFound"))); return Command.SINGLE_SUCCESS; })) .then(literal("markAllMissing").executes(context -> { - markAllMissing(); + SOUL_WAYPOINTS.values().forEach(Waypoint::setMissing); context.getSource().sendFeedback(Constants.PREFIX.get().append(Text.translatable("skyblocker.rift.enigmaSouls.markAllMissing"))); return Command.SINGLE_SUCCESS; @@ -154,30 +154,10 @@ public class EnigmaSouls { if (!soulsLoaded.isDone() || player == null) return; - Arrays.stream(SOUL_WAYPOINTS) - .filter(EnigmaSouls::isSoulMissing) - .min(Comparator.comparingDouble(soulPos -> soulPos.getSquaredDistance(player.getPos()))) - .filter(soulPos -> soulPos.getSquaredDistance(player.getPos()) <= 16) - .ifPresent(soulPos -> { - FOUND_SOULS.computeIfAbsent(Utils.getProfile(), profile -> new ObjectOpenHashSet<>()); - FOUND_SOULS.get(Utils.getProfile()).add(soulPos); - }); - } - - private static boolean isSoulMissing(BlockPos soulPos) { - ObjectOpenHashSet<BlockPos> foundSoulsOnProfile = FOUND_SOULS.get(Utils.getProfile()); - - return foundSoulsOnProfile == null || !foundSoulsOnProfile.contains(soulPos); - } - - private static void markAllFound() { - FOUND_SOULS.computeIfAbsent(Utils.getProfile(), profile -> new ObjectOpenHashSet<>()); - FOUND_SOULS.get(Utils.getProfile()).addAll(List.of(SOUL_WAYPOINTS)); - } - - private static void markAllMissing() { - ObjectOpenHashSet<BlockPos> foundSoulsOnProfile = FOUND_SOULS.get(Utils.getProfile()); - - if (foundSoulsOnProfile != null) foundSoulsOnProfile.clear(); + SOUL_WAYPOINTS.values().stream() + .filter(Waypoint::shouldRender) + .min(Comparator.comparingDouble(soul -> soul.pos.getSquaredDistance(player.getPos()))) + .filter(soul -> soul.pos.getSquaredDistance(player.getPos()) <= 16) + .ifPresent(Waypoint::setFound); } } diff --git a/src/main/java/de/hysky/skyblocker/skyblock/rift/MirrorverseWaypoints.java b/src/main/java/de/hysky/skyblocker/skyblock/rift/MirrorverseWaypoints.java index 7dda741f..83199e99 100644 --- a/src/main/java/de/hysky/skyblocker/skyblock/rift/MirrorverseWaypoints.java +++ b/src/main/java/de/hysky/skyblocker/skyblock/rift/MirrorverseWaypoints.java @@ -6,7 +6,7 @@ import com.google.gson.JsonParser; import de.hysky.skyblocker.SkyblockerMod; import de.hysky.skyblocker.config.SkyblockerConfigManager; import de.hysky.skyblocker.utils.Utils; -import de.hysky.skyblocker.utils.render.RenderHelper; +import de.hysky.skyblocker.utils.waypoint.Waypoint; import net.fabricmc.fabric.api.client.rendering.v1.WorldRenderContext; import net.minecraft.client.MinecraftClient; import net.minecraft.util.DyeColor; @@ -18,13 +18,15 @@ import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.IOException; import java.util.concurrent.CompletableFuture; +import java.util.function.Supplier; public class MirrorverseWaypoints { private static final Logger LOGGER = LoggerFactory.getLogger("skyblocker"); + private static final Supplier<Waypoint.Type> WAYPOINT_TYPE = () -> Waypoint.Type.HIGHLIGHT; private static final Identifier WAYPOINTS_JSON = new Identifier(SkyblockerMod.NAMESPACE, "rift/mirrorverse_waypoints.json"); - private static final BlockPos[] LAVA_PATH_WAYPOINTS = new BlockPos[107]; - private static final BlockPos[] UPSIDE_DOWN_WAYPOINTS = new BlockPos[66]; - private static final BlockPos[] TURBULATOR_WAYPOINTS = new BlockPos[27]; + private static Waypoint[] LAVA_PATH_WAYPOINTS; + private static Waypoint[] UPSIDE_DOWN_WAYPOINTS; + private static Waypoint[] TURBULATOR_WAYPOINTS; private static final float[] COLOR_COMPONENTS = DyeColor.RED.getColorComponents(); private static CompletableFuture<Void> waypointsLoaded; @@ -35,51 +37,44 @@ public class MirrorverseWaypoints { static void load(MinecraftClient client) { waypointsLoaded = CompletableFuture.runAsync(() -> { try (BufferedReader reader = client.getResourceManager().openAsReader(WAYPOINTS_JSON)) { - JsonObject file = JsonParser.parseReader(reader).getAsJsonObject(); - JsonArray sections = file.get("sections").getAsJsonArray(); + JsonArray sections = JsonParser.parseReader(reader).getAsJsonObject().get("sections").getAsJsonArray(); /// Lava Path - JsonArray lavaPathWaypoints = sections.get(0).getAsJsonObject().get("waypoints").getAsJsonArray(); - - for (int i = 0; i < lavaPathWaypoints.size(); i++) { - JsonObject point = lavaPathWaypoints.get(i).getAsJsonObject(); - LAVA_PATH_WAYPOINTS[i] = new BlockPos(point.get("x").getAsInt(), point.get("y").getAsInt(), point.get("z").getAsInt()); - } + LAVA_PATH_WAYPOINTS = loadWaypoints(sections.get(0).getAsJsonObject().get("waypoints").getAsJsonArray()); /// Upside Down Parkour - JsonArray upsideDownParkourWaypoints = sections.get(1).getAsJsonObject().get("waypoints").getAsJsonArray(); - - for (int i = 0; i < upsideDownParkourWaypoints.size(); i++) { - JsonObject point = upsideDownParkourWaypoints.get(i).getAsJsonObject(); - UPSIDE_DOWN_WAYPOINTS[i] = new BlockPos(point.get("x").getAsInt(), point.get("y").getAsInt(), point.get("z").getAsInt()); - } + UPSIDE_DOWN_WAYPOINTS = loadWaypoints(sections.get(1).getAsJsonObject().get("waypoints").getAsJsonArray()); /// Turbulator Parkour - JsonArray turbulatorParkourWaypoints = sections.get(2).getAsJsonObject().get("waypoints").getAsJsonArray(); - - for (int i = 0; i < turbulatorParkourWaypoints.size(); i++) { - JsonObject point = turbulatorParkourWaypoints.get(i).getAsJsonObject(); - TURBULATOR_WAYPOINTS[i] = new BlockPos(point.get("x").getAsInt(), point.get("y").getAsInt(), point.get("z").getAsInt()); - } + TURBULATOR_WAYPOINTS = loadWaypoints(sections.get(2).getAsJsonObject().get("waypoints").getAsJsonArray()); } catch (IOException e) { LOGGER.error("[Skyblocker] Mirrorverse Waypoints failed to load ;(", e); } }); } + private static Waypoint[] loadWaypoints(JsonArray waypointsJson) { + Waypoint[] waypoints = new Waypoint[waypointsJson.size()]; + for (int i = 0; i < waypointsJson.size(); i++) { + JsonObject point = waypointsJson.get(i).getAsJsonObject(); + waypoints[i] = new Waypoint(new BlockPos(point.get("x").getAsInt(), point.get("y").getAsInt(), point.get("z").getAsInt()), WAYPOINT_TYPE, COLOR_COMPONENTS, false); + } + return waypoints; + } + 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() && SkyblockerConfigManager.get().locations.rift.mirrorverseWaypoints && waypointsLoaded.isDone()) { - for (BlockPos pos : LAVA_PATH_WAYPOINTS) { - RenderHelper.renderFilledIfVisible(wrc, pos, COLOR_COMPONENTS, 0.5f); + for (Waypoint waypoint : LAVA_PATH_WAYPOINTS) { + waypoint.render(wrc); } - for (BlockPos pos : UPSIDE_DOWN_WAYPOINTS) { - RenderHelper.renderFilledIfVisible(wrc, pos, COLOR_COMPONENTS, 0.5f); + for (Waypoint waypoint : UPSIDE_DOWN_WAYPOINTS) { + waypoint.render(wrc); } - for (BlockPos pos : TURBULATOR_WAYPOINTS) { - RenderHelper.renderFilledIfVisible(wrc, pos, COLOR_COMPONENTS, 0.5f); + for (Waypoint waypoint : TURBULATOR_WAYPOINTS) { + waypoint.render(wrc); } } } diff --git a/src/main/java/de/hysky/skyblocker/skyblock/shortcut/Shortcuts.java b/src/main/java/de/hysky/skyblocker/skyblock/shortcut/Shortcuts.java index 9c058a4f..c2c952cf 100644 --- a/src/main/java/de/hysky/skyblocker/skyblock/shortcut/Shortcuts.java +++ b/src/main/java/de/hysky/skyblocker/skyblock/shortcut/Shortcuts.java @@ -21,6 +21,9 @@ import org.slf4j.LoggerFactory; import java.io.*; import java.lang.reflect.Type; +import java.nio.file.Files; +import java.nio.file.NoSuchFileException; +import java.nio.file.Path; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CompletableFuture; @@ -30,7 +33,7 @@ import static net.fabricmc.fabric.api.client.command.v2.ClientCommandManager.lit public class Shortcuts { private static final Logger LOGGER = LoggerFactory.getLogger(Shortcuts.class); - private static final File SHORTCUTS_FILE = SkyblockerMod.CONFIG_DIR.resolve("shortcuts.json").toFile(); + private static final Path SHORTCUTS_FILE = SkyblockerMod.CONFIG_DIR.resolve("shortcuts.json"); @Nullable private static CompletableFuture<Void> shortcutsLoaded; public static final Map<String, String> commands = new HashMap<>(); @@ -52,7 +55,7 @@ public class Shortcuts { return; } shortcutsLoaded = CompletableFuture.runAsync(() -> { - try (BufferedReader reader = new BufferedReader(new FileReader(SHORTCUTS_FILE))) { + try (BufferedReader reader = Files.newBufferedReader(SHORTCUTS_FILE)) { Type shortcutsType = new TypeToken<Map<String, Map<String, String>>>() { }.getType(); Map<String, Map<String, String>> shortcuts = SkyblockerMod.GSON.fromJson(reader, shortcutsType); @@ -61,7 +64,7 @@ public class Shortcuts { commands.putAll(shortcuts.get("commands")); commandArgs.putAll(shortcuts.get("commandArgs")); LOGGER.info("[Skyblocker] Loaded {} command shortcuts and {} command argument shortcuts", commands.size(), commandArgs.size()); - } catch (FileNotFoundException e) { + } catch (NoSuchFileException e) { registerDefaultShortcuts(); LOGGER.warn("[Skyblocker] Shortcuts file not found, using default shortcuts. This is normal when using for the first time."); } catch (IOException e) { @@ -140,7 +143,7 @@ public class Shortcuts { JsonObject shortcutsJson = new JsonObject(); shortcutsJson.add("commands", SkyblockerMod.GSON.toJsonTree(commands)); shortcutsJson.add("commandArgs", SkyblockerMod.GSON.toJsonTree(commandArgs)); - try (BufferedWriter writer = new BufferedWriter(new FileWriter(SHORTCUTS_FILE))) { + try (BufferedWriter writer = Files.newBufferedWriter(SHORTCUTS_FILE)) { SkyblockerMod.GSON.toJson(shortcutsJson, writer); LOGGER.info("[Skyblocker] Saved {} command shortcuts and {} command argument shortcuts", commands.size(), commandArgs.size()); } catch (IOException e) { diff --git a/src/main/java/de/hysky/skyblocker/skyblock/shortcut/ShortcutsConfigScreen.java b/src/main/java/de/hysky/skyblocker/skyblock/shortcut/ShortcutsConfigScreen.java index 196ad0d6..a5f8ae2d 100644 --- a/src/main/java/de/hysky/skyblocker/skyblock/shortcut/ShortcutsConfigScreen.java +++ b/src/main/java/de/hysky/skyblocker/skyblock/shortcut/ShortcutsConfigScreen.java @@ -19,7 +19,7 @@ public class ShortcutsConfigScreen extends Screen { private boolean initialized; private double scrollAmount; private final Screen parent; - + public ShortcutsConfigScreen() { this(null); } diff --git a/src/main/java/de/hysky/skyblocker/skyblock/special/SpecialEffects.java b/src/main/java/de/hysky/skyblocker/skyblock/special/SpecialEffects.java index fba447ea..bc4f98c2 100644 --- a/src/main/java/de/hysky/skyblocker/skyblock/special/SpecialEffects.java +++ b/src/main/java/de/hysky/skyblocker/skyblock/special/SpecialEffects.java @@ -1,8 +1,8 @@ package de.hysky.skyblocker.skyblock.special; -import com.mojang.blaze3d.systems.RenderSystem; import de.hysky.skyblocker.config.SkyblockerConfigManager; import de.hysky.skyblocker.utils.Utils; +import de.hysky.skyblocker.utils.render.RenderHelper; import net.fabricmc.fabric.api.client.message.v1.ClientReceiveMessageEvents; import net.minecraft.client.MinecraftClient; import net.minecraft.enchantment.Enchantments; @@ -58,15 +58,10 @@ public class SpecialEffects { ItemStack stack = getStackFromName(matcher.group("item")); if (!stack.isEmpty()) { - if (RenderSystem.isOnRenderThread()) { + RenderHelper.runOnRenderThread(() -> { client.particleManager.addEmitter(client.player, ParticleTypes.PORTAL, 30); client.gameRenderer.showFloatingItem(stack); - } else { - RenderSystem.recordRenderCall(() -> { - client.particleManager.addEmitter(client.player, ParticleTypes.PORTAL, 30); - client.gameRenderer.showFloatingItem(stack); - }); - } + }); } } } diff --git a/src/main/java/de/hysky/skyblocker/skyblock/tabhud/util/Colors.java b/src/main/java/de/hysky/skyblocker/skyblock/tabhud/util/Colors.java new file mode 100644 index 00000000..0de3e45f --- /dev/null +++ b/src/main/java/de/hysky/skyblocker/skyblock/tabhud/util/Colors.java @@ -0,0 +1,14 @@ +package de.hysky.skyblocker.skyblock.tabhud.util; + +import net.minecraft.util.math.MathHelper; + +public class Colors { + + /** + * @param pcnt Percentage between 0% and 100%, NOT 0-1! + * @return an int representing a color, where 100% = green and 0% = red + */ + public static int pcntToCol(float pcnt) { + return MathHelper.hsvToRgb(pcnt / 300f, 0.9f, 0.9f); + } +} diff --git a/src/main/java/de/hysky/skyblocker/skyblock/tabhud/util/Ico.java b/src/main/java/de/hysky/skyblocker/skyblock/tabhud/util/Ico.java index 24883d77..82394a78 100644 --- a/src/main/java/de/hysky/skyblocker/skyblock/tabhud/util/Ico.java +++ b/src/main/java/de/hysky/skyblocker/skyblock/tabhud/util/Ico.java @@ -10,6 +10,7 @@ public class Ico { public static final ItemStack MAP = new ItemStack(Items.FILLED_MAP); public static final ItemStack NTAG = new ItemStack(Items.NAME_TAG); public static final ItemStack EMERALD = new ItemStack(Items.EMERALD); + public static final ItemStack AMETHYST_SHARD = new ItemStack(Items.AMETHYST_SHARD); public static final ItemStack CLOCK = new ItemStack(Items.CLOCK); public static final ItemStack DIASWORD = new ItemStack(Items.DIAMOND_SWORD); public static final ItemStack DBUSH = new ItemStack(Items.DEAD_BUSH); @@ -48,8 +49,10 @@ public class Ico { public static final ItemStack B_ROD = new ItemStack(Items.BLAZE_ROD); public static final ItemStack BOW = new ItemStack(Items.BOW); public static final ItemStack COPPER = new ItemStack(Items.COPPER_INGOT); + public static final ItemStack NETHERITE_UPGRADE_ST = new ItemStack(Items.NETHERITE_UPGRADE_SMITHING_TEMPLATE); public static final ItemStack COMPOSTER = new ItemStack(Items.COMPOSTER); public static final ItemStack SAPLING = new ItemStack(Items.OAK_SAPLING); + public static final ItemStack SEEDS = new ItemStack(Items.WHEAT_SEEDS); public static final ItemStack MILESTONE = new ItemStack(Items.LODESTONE); public static final ItemStack PICKAXE = new ItemStack(Items.IRON_PICKAXE); public static final ItemStack NETHER_STAR = new ItemStack(Items.NETHER_STAR); diff --git a/src/main/java/de/hysky/skyblocker/skyblock/tabhud/util/PlayerListMgr.java b/src/main/java/de/hysky/skyblocker/skyblock/tabhud/util/PlayerListMgr.java index f577f2d3..3ef968a3 100644 --- a/src/main/java/de/hysky/skyblocker/skyblock/tabhud/util/PlayerListMgr.java +++ b/src/main/java/de/hysky/skyblocker/skyblock/tabhud/util/PlayerListMgr.java @@ -35,7 +35,7 @@ public class PlayerListMgr { ClientPlayNetworkHandler cpnwh = MinecraftClient.getInstance().getNetworkHandler(); - // check is needed, else game crash on server leave + // check is needed, else game crashes on server leave if (cpnwh != null) { playerList = cpnwh.getPlayerList().stream().sorted(PlayerListHudAccessor.getOrdering()).toList(); } diff --git a/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/CommsWidget.java b/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/CommsWidget.java index e8bf91ab..a5fb4d32 100644 --- a/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/CommsWidget.java +++ b/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/CommsWidget.java @@ -3,14 +3,14 @@ package de.hysky.skyblocker.skyblock.tabhud.widget; import java.util.regex.Matcher; import java.util.regex.Pattern; -import de.hysky.skyblocker.skyblock.tabhud.widget.component.IcoTextComponent; -import de.hysky.skyblocker.skyblock.tabhud.widget.component.ProgressComponent; +import de.hysky.skyblocker.skyblock.tabhud.util.Colors; import de.hysky.skyblocker.skyblock.tabhud.util.Ico; import de.hysky.skyblocker.skyblock.tabhud.util.PlayerListMgr; +import de.hysky.skyblocker.skyblock.tabhud.widget.component.IcoTextComponent; +import de.hysky.skyblocker.skyblock.tabhud.widget.component.ProgressComponent; import net.minecraft.text.MutableText; import net.minecraft.text.Text; import net.minecraft.util.Formatting; -import net.minecraft.util.math.MathHelper; // this widget shows the status of the king's commissions. // (dwarven mines and crystal hollows) @@ -47,17 +47,13 @@ public class CommsWidget extends Widget { String progress = m.group("progress"); if (progress.equals("DONE")) { - pc = new ProgressComponent(Ico.BOOK, Text.of(name), Text.of(progress), 100f, pcntToCol(100)); + pc = new ProgressComponent(Ico.BOOK, Text.of(name), Text.of(progress), 100f, Colors.pcntToCol(100)); } else { float pcnt = Float.parseFloat(progress.substring(0, progress.length() - 1)); - pc = new ProgressComponent(Ico.BOOK, Text.of(name), pcnt, pcntToCol(pcnt)); + pc = new ProgressComponent(Ico.BOOK, Text.of(name), pcnt, Colors.pcntToCol(pcnt)); } this.addComponent(pc); } } - private int pcntToCol(float pcnt) { - return MathHelper.hsvToRgb(pcnt / 300f, 0.9f, 0.9f); - } - } diff --git a/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/ComposterWidget.java b/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/ComposterWidget.java index fbeb5ae5..f50b617b 100644 --- a/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/ComposterWidget.java +++ b/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/ComposterWidget.java @@ -2,7 +2,7 @@ package de.hysky.skyblocker.skyblock.tabhud.widget; import de.hysky.skyblocker.skyblock.tabhud.util.Ico; - +import de.hysky.skyblocker.skyblock.tabhud.util.PlayerListMgr; import net.minecraft.text.MutableText; import net.minecraft.text.Text; import net.minecraft.util.Formatting; @@ -20,11 +20,11 @@ public class ComposterWidget extends Widget { @Override public void updateContent() { - this.addSimpleIcoText(Ico.SAPLING, "Organic Matter:", Formatting.YELLOW, 48); - this.addSimpleIcoText(Ico.FURNACE, "Fuel:", Formatting.BLUE, 49); - this.addSimpleIcoText(Ico.CLOCK, "Time Left:", Formatting.RED, 50); - this.addSimpleIcoText(Ico.COMPOSTER, "Stored Compost:", Formatting.DARK_GREEN, 51); + int offset = (PlayerListMgr.strAt(46) != null) ? 1 : 0; + this.addSimpleIcoText(Ico.SAPLING, "Organic Matter:", Formatting.YELLOW, 48 + offset); + this.addSimpleIcoText(Ico.FURNACE, "Fuel:", Formatting.BLUE, 49 + offset); + this.addSimpleIcoText(Ico.CLOCK, "Time Left:", Formatting.RED, 50 + offset); + this.addSimpleIcoText(Ico.COMPOSTER, "Stored Compost:", Formatting.DARK_GREEN, 51 + offset); } - } diff --git a/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/DungeonPuzzleWidget.java b/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/DungeonPuzzleWidget.java index 1b3b8644..53f84f71 100644 --- a/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/DungeonPuzzleWidget.java +++ b/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/DungeonPuzzleWidget.java @@ -37,16 +37,21 @@ public class DungeonPuzzleWidget extends Widget { if (m == null) { break; } + + Formatting statcol = switch (m.group("status")) { + case "✦" -> Formatting.GOLD; // Unsolved + case "✔" -> Formatting.GREEN; // Solved + case "✖" -> Formatting.RED; // Failed + default -> Formatting.WHITE; // Who knows if they'll add another puzzle state or not? + }; + Text t = Text.literal(m.group("name") + ": ") .append(Text.literal("[").formatted(Formatting.GRAY)) - .append(m.group("status")) + .append(Text.literal(m.group("status")).formatted(statcol, Formatting.BOLD)) .append(Text.literal("]").formatted(Formatting.GRAY)); IcoTextComponent itc = new IcoTextComponent(Ico.SIGN, t); this.addComponent(itc); pos++; - // code points for puzzle status chars unsolved and solved: 10022, 10004 - // not sure which one is which - // still need to find out codepoint for the puzzle failed char } if (pos == 48) { this.addComponent( diff --git a/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/FireSaleWidget.java b/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/FireSaleWidget.java index 0211cbd6..e08b4acf 100644 --- a/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/FireSaleWidget.java +++ b/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/FireSaleWidget.java @@ -3,14 +3,13 @@ package de.hysky.skyblocker.skyblock.tabhud.widget; import java.util.regex.Matcher; import java.util.regex.Pattern; +import de.hysky.skyblocker.skyblock.tabhud.util.Colors; import de.hysky.skyblocker.skyblock.tabhud.util.Ico; import de.hysky.skyblocker.skyblock.tabhud.util.PlayerListMgr; import de.hysky.skyblocker.skyblock.tabhud.widget.component.PlainTextComponent; import de.hysky.skyblocker.skyblock.tabhud.widget.component.ProgressComponent; - import net.minecraft.text.MutableText; import net.minecraft.text.Text; -import net.minecraft.util.math.MathHelper; import net.minecraft.util.Formatting; // this widget shows info about fire sales when in the hub. @@ -55,14 +54,10 @@ public class FireSaleWidget extends Widget { float total = Float.parseFloat(m.group("total")) * 1000; Text prgressTxt = Text.literal(String.format("%s/%.0f", avail, total)); float pcnt = (Float.parseFloat(avail) / (total)) * 100f; - ProgressComponent pc = new ProgressComponent(Ico.GOLD, itemTxt, prgressTxt, pcnt, pcntToCol(pcnt)); + ProgressComponent pc = new ProgressComponent(Ico.GOLD, itemTxt, prgressTxt, pcnt, Colors.pcntToCol(pcnt)); this.addComponent(pc); } } - private int pcntToCol(float pcnt) { - return MathHelper.hsvToRgb( pcnt / 300f, 0.9f, 0.9f); - } - } diff --git a/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/ForgeWidget.java b/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/ForgeWidget.java index 1a4683f5..adae7daf 100644 --- a/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/ForgeWidget.java +++ b/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/ForgeWidget.java @@ -69,7 +69,11 @@ public class ForgeWidget extends Widget { c = new IcoFatTextComponent(); } else { l1 = Text.literal(parts[0].substring(3)).formatted(Formatting.YELLOW); - l2 = Text.literal("Done in: ").formatted(Formatting.GRAY).append(Text.literal(parts[1]).formatted(Formatting.WHITE)); + if (parts[1].equals("Ready!")) { + l2 = Text.literal("Done!").formatted(Formatting.GREEN); + } else { + l2 = Text.literal("Done in: ").formatted(Formatting.GRAY).append(Text.literal(parts[1]).formatted(Formatting.WHITE)); + } c = new IcoFatTextComponent(Ico.FIRE, l1, l2); } } diff --git a/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/GardenServerWidget.java b/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/GardenServerWidget.java index 221f8b08..b6b65896 100644 --- a/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/GardenServerWidget.java +++ b/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/GardenServerWidget.java @@ -6,7 +6,7 @@ import java.util.regex.Pattern; import de.hysky.skyblocker.skyblock.tabhud.util.Ico; import de.hysky.skyblocker.skyblock.tabhud.util.PlayerListMgr; import de.hysky.skyblocker.skyblock.tabhud.widget.component.IcoTextComponent; - +import de.hysky.skyblocker.utils.Constants; import net.minecraft.text.MutableText; import net.minecraft.text.Text; import net.minecraft.util.Formatting; @@ -14,13 +14,14 @@ import net.minecraft.util.Formatting; // this widget shows info about the garden server public class GardenServerWidget extends Widget { - private static final MutableText TITLE = Text.literal("Server Info").formatted(Formatting.DARK_AQUA, Formatting.BOLD); + //From the armor trim tooltip + private static final int COPPER_COLOR = 11823181; // match the next visitor in the garden // group 1: visitor name - private static final Pattern VISITOR_PATTERN = Pattern.compile("Next Visitor: (?<vis>.*)"); + private static final Pattern VISITOR_PATTERN = Pattern.compile("Visitors: (?<vis>.*)"); public GardenServerWidget() { super(TITLE, Formatting.DARK_AQUA.getColorValue()); @@ -31,17 +32,29 @@ public class GardenServerWidget extends Widget { this.addSimpleIcoText(Ico.MAP, "Area:", Formatting.DARK_AQUA, 41); this.addSimpleIcoText(Ico.NTAG, "Server ID:", Formatting.GRAY, 42); this.addSimpleIcoText(Ico.EMERALD, "Gems:", Formatting.GREEN, 43); - this.addSimpleIcoText(Ico.COPPER, "Copper:", Formatting.GOLD, 44); - Matcher m = PlayerListMgr.regexAt(45, VISITOR_PATTERN); + Text copperText = Widget.simpleEntryText(44, "Copper:", Formatting.WHITE); + ((MutableText) copperText.getSiblings().get(0)).styled(Constants.WITH_COLOR.apply(COPPER_COLOR)); + + this.addComponent(new IcoTextComponent(Ico.COPPER, copperText)); + + boolean hasPesthunterBonus = PlayerListMgr.strAt(46) != null; + + if (hasPesthunterBonus) { + this.addComponent(new IcoTextComponent(Ico.NETHERITE_UPGRADE_ST, PlayerListMgr.textAt(46))); + } + + int offset = hasPesthunterBonus ? 1 : 0; + + Matcher m = PlayerListMgr.regexAt(53 + offset, VISITOR_PATTERN); if (m == null ) { this.addComponent(new IcoTextComponent()); return; } - String vis = m.group("vis"); + String vis = m.group("vis").replaceAll("[()]*", ""); Formatting col; - if (vis.equals("Not Unlocked!")) { + if (vis.equals("Not Unlocked!") || vis.equals("Queue Full!")) { col = Formatting.RED; } else { col = Formatting.GREEN; diff --git a/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/GardenSkillsWidget.java b/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/GardenSkillsWidget.java index 41eee8d6..75652b33 100644 --- a/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/GardenSkillsWidget.java +++ b/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/GardenSkillsWidget.java @@ -26,6 +26,8 @@ public class GardenSkillsWidget extends Widget { private static final Pattern SKILL_PATTERN = Pattern .compile("Skills: (?<skill>[A-Za-z]* [0-9]*): (?<progress>[0-9.MAX]*)%?"); + private static final Pattern GARDEN_LEVEL_PATTERN = Pattern.compile("Garden Level: (?<level>[IVX0-9]+)(?: \\((?<progress>[0-9.]+)% to [IVX0-9]+\\))?"); + // same, more or less private static final Pattern MS_PATTERN = Pattern .compile("Milestone: (?<milestone>[A-Za-z ]* [0-9]*): (?<progress>[0-9.]*)%"); @@ -36,26 +38,46 @@ public class GardenSkillsWidget extends Widget { @Override public void updateContent() { - ProgressComponent pc; - Matcher m = PlayerListMgr.regexAt(66, SKILL_PATTERN); - if (m == null) { - pc = new ProgressComponent(); + ProgressComponent spc; + Matcher skillMatcher = PlayerListMgr.regexAt(66, SKILL_PATTERN); + if (skillMatcher == null) { + spc = new ProgressComponent(); } else { - String strpcnt = m.group("progress"); - String skill = m.group("skill"); + String strpcnt = skillMatcher.group("progress"); + String skill = skillMatcher.group("skill"); if (strpcnt.equals("MAX")) { - pc = new ProgressComponent(Ico.LANTERN, Text.of(skill), Text.of("MAX"), 100f, + spc = new ProgressComponent(Ico.LANTERN, Text.of(skill), Text.of("MAX"), 100f, Formatting.RED.getColorValue()); } else { float pcnt = Float.parseFloat(strpcnt); - pc = new ProgressComponent(Ico.LANTERN, Text.of(skill), pcnt, + spc = new ProgressComponent(Ico.LANTERN, Text.of(skill), pcnt, Formatting.GOLD.getColorValue()); } } - this.addComponent(pc); + this.addComponent(spc); + + ProgressComponent glpc; + Matcher glMatcher = PlayerListMgr.regexAt(45, GARDEN_LEVEL_PATTERN); + + if (glMatcher == null) { + glpc = new ProgressComponent(); + } else { + String level = glMatcher.group("level"); + + if (level.equals("15") || level.equals("XV")) { + glpc = new ProgressComponent(Ico.SEEDS, Text.literal("Garden Level " + level), 100f, Formatting.RED.getColorValue()); + } else { + String strpcnt = glMatcher.group("progress"); + float pcnt = Float.parseFloat(strpcnt); + + glpc = new ProgressComponent(Ico.SEEDS, Text.literal("Garden Level " + level), pcnt, Formatting.DARK_GREEN.getColorValue()); + } + } + + this.addComponent(glpc); Text speed = Widget.simpleEntryText(67, "SPD", Formatting.WHITE); IcoTextComponent spd = new IcoTextComponent(Ico.SUGAR, speed); @@ -66,22 +88,21 @@ public class GardenSkillsWidget extends Widget { tc.addToCell(0, 0, spd); tc.addToCell(1, 0, ffo); this.addComponent(tc); + + this.addComponent(new IcoTextComponent(Ico.HOE, PlayerListMgr.textAt(70))); ProgressComponent pc2; - m = PlayerListMgr.regexAt(69, MS_PATTERN); - if (m == null) { + Matcher milestoneMatcher = PlayerListMgr.regexAt(69, MS_PATTERN); + if (milestoneMatcher == null) { pc2 = new ProgressComponent(); } else { - String strpcnt = m.group("progress"); - String milestone = m.group("milestone"); + String strpcnt = milestoneMatcher.group("progress"); + String milestone = milestoneMatcher.group("milestone"); float pcnt = Float.parseFloat(strpcnt); pc2 = new ProgressComponent(Ico.MILESTONE, Text.of(milestone), pcnt, Formatting.GREEN.getColorValue()); - } this.addComponent(pc2); - } - } diff --git a/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/GardenVisitorsWidget.java b/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/GardenVisitorsWidget.java index cfbd6cd0..2b0036ad 100644 --- a/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/GardenVisitorsWidget.java +++ b/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/GardenVisitorsWidget.java @@ -15,16 +15,17 @@ public class GardenVisitorsWidget extends Widget { @Override public void updateContent() { - if (PlayerListMgr.textAt(54) == null) { + int offset = (PlayerListMgr.strAt(46) != null) ? 1 : 0; + + if (PlayerListMgr.textAt(54 + offset) == null) { this.addComponent(new PlainTextComponent(Text.literal("No visitors!").formatted(Formatting.GRAY))); return; } - for (int i = 54; i < 59; i++) { + for (int i = 54 + offset; i < 59 + offset; i++) { String text = PlayerListMgr.strAt(i); if (text != null) this.addComponent(new PlainTextComponent(Text.literal(text))); } - } } diff --git a/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/JacobsContestWidget.java b/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/JacobsContestWidget.java index 5ae0bd3d..472e6d61 100644 --- a/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/JacobsContestWidget.java +++ b/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/JacobsContestWidget.java @@ -1,6 +1,8 @@ package de.hysky.skyblocker.skyblock.tabhud.widget; import java.util.HashMap; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import de.hysky.skyblocker.skyblock.tabhud.util.Ico; import de.hysky.skyblocker.skyblock.tabhud.util.PlayerListMgr; @@ -19,6 +21,9 @@ public class JacobsContestWidget extends Widget { private static final MutableText TITLE = Text.literal("Jacob's Contest").formatted(Formatting.YELLOW, Formatting.BOLD); + //TODO Properly match the contest placement and display it + private static final Pattern CROP_PATTERN = Pattern.compile("(?:☘|○) (?<crop>[A-Za-z ]+)(?:.+)?"); + private static final HashMap<String, ItemStack> FARM_DATA = new HashMap<>(); // again, there HAS to be a better way to do this @@ -41,22 +46,27 @@ public class JacobsContestWidget extends Widget { @Override public void updateContent() { - this.addSimpleIcoText(Ico.CLOCK, "Starts in:", Formatting.GOLD, 76); + Text jacobStatus = PlayerListMgr.textAt(76); + + if (jacobStatus.getString().equals("ACTIVE")) { + this.addComponent(new IcoTextComponent(Ico.CLOCK, jacobStatus)); + } else { + this.addSimpleIcoText(Ico.CLOCK, "Starts in:", Formatting.GOLD, 76); + } TableComponent tc = new TableComponent(1, 3, Formatting.YELLOW .getColorValue()); for (int i = 77; i < 80; i++) { - String item = PlayerListMgr.strAt(i); + Matcher item = PlayerListMgr.regexAt(i, CROP_PATTERN); IcoTextComponent itc; if (item == null) { itc = new IcoTextComponent(); } else { - itc = new IcoTextComponent(FARM_DATA.get(item), Text.of(item)); + String cropName = item.group("crop").trim(); //Trimming is needed because during a contest the space separator will be caught + itc = new IcoTextComponent(FARM_DATA.get(cropName), Text.of(cropName)); } tc.addToCell(0, i - 77, itc); } this.addComponent(tc); - } - } diff --git a/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/PowderWidget.java b/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/PowderWidget.java index 44635fbe..ec176a98 100644 --- a/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/PowderWidget.java +++ b/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/PowderWidget.java @@ -22,7 +22,7 @@ public class PowderWidget extends Widget { @Override public void updateContent() { this.addSimpleIcoText(Ico.MITHRIL, "Mithril:", Formatting.AQUA, 46); - this.addSimpleIcoText(Ico.EMERALD, "Gemstone:", Formatting.DARK_PURPLE, 47); + this.addSimpleIcoText(Ico.AMETHYST_SHARD, "Gemstone:", Formatting.DARK_PURPLE, 47); } diff --git a/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/hud/HudCommsWidget.java b/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/hud/HudCommsWidget.java index 6aa363c9..442f12ca 100644 --- a/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/hud/HudCommsWidget.java +++ b/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/hud/HudCommsWidget.java @@ -2,16 +2,16 @@ package de.hysky.skyblocker.skyblock.tabhud.widget.hud; import java.util.List; -import de.hysky.skyblocker.skyblock.tabhud.widget.Widget; import de.hysky.skyblocker.skyblock.dwarven.DwarvenHud.Commission; +import de.hysky.skyblocker.skyblock.tabhud.util.Colors; import de.hysky.skyblocker.skyblock.tabhud.util.Ico; +import de.hysky.skyblocker.skyblock.tabhud.widget.Widget; import de.hysky.skyblocker.skyblock.tabhud.widget.component.Component; import de.hysky.skyblocker.skyblock.tabhud.widget.component.PlainTextComponent; import de.hysky.skyblocker.skyblock.tabhud.widget.component.ProgressComponent; import net.minecraft.text.MutableText; import net.minecraft.text.Text; import net.minecraft.util.Formatting; -import net.minecraft.util.math.MathHelper; // this widget shows the status of the king's commissions. // (dwarven mines and crystal hollows) @@ -56,7 +56,7 @@ public class HudCommsWidget extends Widget { Component comp; if (isFancy) { - comp = new ProgressComponent(Ico.BOOK, c, p, pcntToCol(p)); + comp = new ProgressComponent(Ico.BOOK, c, p, Colors.pcntToCol(p)); } else { comp = new PlainTextComponent( Text.literal(comm.commission() + ": ") @@ -66,8 +66,4 @@ public class HudCommsWidget extends Widget { } } - private int pcntToCol(float pcnt) { - return MathHelper.hsvToRgb(pcnt / 300f, 0.9f, 0.9f); - } - } diff --git a/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/rift/RiftProgressWidget.java b/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/rift/RiftProgressWidget.java index 93ade5cb..6cd7736b 100644 --- a/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/rift/RiftProgressWidget.java +++ b/src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/rift/RiftProgressWidget.java @@ -3,15 +3,15 @@ package de.hysky.skyblocker.skyblock.tabhud.widget.rift; import java.util.regex.Matcher; import java.util.regex.Pattern; -import de.hysky.skyblocker.skyblock.tabhud.widget.Widget; +import de.hysky.skyblocker.skyblock.tabhud.util.Colors; import de.hysky.skyblocker.skyblock.tabhud.util.Ico; import de.hysky.skyblocker.skyblock.tabhud.util.PlayerListMgr; +import de.hysky.skyblocker.skyblock.tabhud.widget.Widget; import de.hysky.skyblocker.skyblock.tabhud.widget.component.PlainTextComponent; import de.hysky.skyblocker.skyblock.tabhud.widget.component.ProgressComponent; import net.minecraft.text.MutableText; import net.minecraft.text.Text; import net.minecraft.util.Formatting; -import net.minecraft.util.math.MathHelper; public class RiftProgressWidget extends Widget { @@ -75,10 +75,6 @@ public class RiftProgressWidget extends Widget { } - private static int pcntToCol(float pcnt) { - return MathHelper.hsvToRgb(pcnt / 300f, 0.9f, 0.9f); - } - private void addTimecharmsComponent(int pos) { Matcher m = PlayerListMgr.regexAt(pos, TIMECHARMS_PATTERN); @@ -88,7 +84,7 @@ public class RiftProgressWidget extends Widget { Text progressText = Text.literal(current + "/" + total); ProgressComponent pc = new ProgressComponent(Ico.NETHER_STAR, Text.literal("Timecharms"), progressText, - pcnt, pcntToCol(pcnt)); + pcnt, Colors.pcntToCol(pcnt)); this.addComponent(pc); } @@ -102,7 +98,7 @@ public class RiftProgressWidget extends Widget { Text progressText = Text.literal(current + "/" + total); ProgressComponent pc = new ProgressComponent(Ico.HEART_OF_THE_SEA, Text.literal("Enigma Souls"), - progressText, pcnt, pcntToCol(pcnt)); + progressText, pcnt, Colors.pcntToCol(pcnt)); this.addComponent(pc); } @@ -116,7 +112,7 @@ public class RiftProgressWidget extends Widget { Text progressText = Text.literal(current + "/" + total); ProgressComponent pc = new ProgressComponent(Ico.BONE, Text.literal("Montezuma"), progressText, pcnt, - pcntToCol(pcnt)); + Colors.pcntToCol(pcnt)); this.addComponent(pc); } diff --git a/src/main/java/de/hysky/skyblocker/skyblock/FairySouls.java b/src/main/java/de/hysky/skyblocker/skyblock/waypoint/FairySouls.java index cef17d8e..f0e94770 100644 --- a/src/main/java/de/hysky/skyblocker/skyblock/FairySouls.java +++ b/src/main/java/de/hysky/skyblocker/skyblock/waypoint/FairySouls.java @@ -1,4 +1,4 @@ -package de.hysky.skyblocker.skyblock; +package de.hysky.skyblocker.skyblock.waypoint; import com.google.gson.JsonArray; import com.google.gson.JsonElement; @@ -12,7 +12,8 @@ import de.hysky.skyblocker.utils.Constants; import de.hysky.skyblocker.utils.NEURepoManager; import de.hysky.skyblocker.utils.PosUtils; import de.hysky.skyblocker.utils.Utils; -import de.hysky.skyblocker.utils.render.RenderHelper; +import de.hysky.skyblocker.utils.waypoint.ProfileAwareWaypoint; +import de.hysky.skyblocker.utils.waypoint.Waypoint; import net.fabricmc.fabric.api.client.command.v2.ClientCommandRegistrationCallback; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientLifecycleEvents; @@ -29,19 +30,24 @@ import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.*; +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.NoSuchFileException; import java.util.*; import java.util.concurrent.CompletableFuture; +import java.util.function.Supplier; import java.util.stream.Collectors; import static net.fabricmc.fabric.api.client.command.v2.ClientCommandManager.literal; public class FairySouls { private static final Logger LOGGER = LoggerFactory.getLogger(FairySouls.class); + private static final Supplier<Waypoint.Type> TYPE_SUPPLIER = () -> SkyblockerConfigManager.get().general.waypoints.waypointType; private static CompletableFuture<Void> fairySoulsLoaded; private static int maxSouls = 0; - private static final Map<String, Set<BlockPos>> fairySouls = new HashMap<>(); - private static final Map<String, Map<String, Set<BlockPos>>> foundFairies = new HashMap<>(); + private static final Map<String, Map<BlockPos, ProfileAwareWaypoint>> fairySouls = new HashMap<>(); @SuppressWarnings("UnusedReturnValue") public static CompletableFuture<Void> runAsyncAfterFairySoulsLoad(Runnable runnable) { @@ -67,32 +73,41 @@ public class FairySouls { private static void loadFairySouls() { fairySoulsLoaded = NEURepoManager.runAsyncAfterLoad(() -> { maxSouls = NEURepoManager.NEU_REPO.getConstants().getFairySouls().getMaxSouls(); - NEURepoManager.NEU_REPO.getConstants().getFairySouls().getSoulLocations().forEach((location, fairySoulsForLocation) -> fairySouls.put(location, fairySoulsForLocation.stream().map(coordinate -> new BlockPos(coordinate.getX(), coordinate.getY(), coordinate.getZ())).collect(Collectors.toUnmodifiableSet()))); - LOGGER.debug("[Skyblocker] Loaded {} fairy souls across {} locations", fairySouls.values().stream().mapToInt(Set::size).sum(), fairySouls.size()); + NEURepoManager.NEU_REPO.getConstants().getFairySouls().getSoulLocations().forEach((location, fairiesForLocation) -> fairySouls.put(location, fairiesForLocation.stream().map(coordinate -> new BlockPos(coordinate.getX(), coordinate.getY(), coordinate.getZ())).collect(Collectors.toUnmodifiableMap(pos -> pos, pos -> new ProfileAwareWaypoint(pos, TYPE_SUPPLIER, DyeColor.GREEN.getColorComponents(), DyeColor.RED.getColorComponents()))))); + LOGGER.debug("[Skyblocker] Loaded {} fairy souls across {} locations", fairySouls.values().stream().mapToInt(Map::size).sum(), fairySouls.size()); - try (BufferedReader reader = new BufferedReader(new FileReader(SkyblockerMod.CONFIG_DIR.resolve("found_fairy_souls.json").toFile()))) { + try (BufferedReader reader = Files.newBufferedReader(SkyblockerMod.CONFIG_DIR.resolve("found_fairy_souls.json"))) { for (Map.Entry<String, JsonElement> foundFairiesForProfileJson : JsonParser.parseReader(reader).getAsJsonObject().asMap().entrySet()) { - Map<String, Set<BlockPos>> foundFairiesForProfile = new HashMap<>(); for (Map.Entry<String, JsonElement> foundFairiesForLocationJson : foundFairiesForProfileJson.getValue().getAsJsonObject().asMap().entrySet()) { - Set<BlockPos> foundFairiesForLocation = new HashSet<>(); + String profile = foundFairiesForLocationJson.getKey(); + Map<BlockPos, ProfileAwareWaypoint> fairiesForLocation = fairySouls.get(profile); for (JsonElement foundFairy : foundFairiesForLocationJson.getValue().getAsJsonArray().asList()) { - foundFairiesForLocation.add(PosUtils.parsePosString(foundFairy.getAsString())); + fairiesForLocation.get(PosUtils.parsePosString(foundFairy.getAsString())).setFound(profile); } - foundFairiesForProfile.put(foundFairiesForLocationJson.getKey(), foundFairiesForLocation); } - foundFairies.put(foundFairiesForProfileJson.getKey(), foundFairiesForProfile); } LOGGER.debug("[Skyblocker] Loaded found fairy souls"); - } catch (FileNotFoundException ignored) { + } catch (NoSuchFileException ignored) { } catch (IOException e) { LOGGER.error("[Skyblocker] Failed to load found fairy souls", e); } - LOGGER.info("[Skyblocker] Loaded {} fairy souls across {} locations and {} found fairy souls across {} locations in {} profiles", fairySouls.values().stream().mapToInt(Set::size).sum(), fairySouls.size(), foundFairies.values().stream().map(Map::values).flatMap(Collection::stream).mapToInt(Set::size).sum(), foundFairies.values().stream().mapToInt(Map::size).sum(), foundFairies.size()); + LOGGER.info("[Skyblocker] Loaded {} fairy souls across {} locations", fairySouls.values().stream().mapToInt(Map::size).sum(), fairySouls.size()); }); } private static void saveFoundFairySouls(MinecraftClient client) { - try (BufferedWriter writer = new BufferedWriter(new FileWriter(SkyblockerMod.CONFIG_DIR.resolve("found_fairy_souls.json").toFile()))) { + Map<String, Map<String, Set<BlockPos>>> foundFairies = new HashMap<>(); + for (Map.Entry<String, Map<BlockPos, ProfileAwareWaypoint>> fairiesForLocation : fairySouls.entrySet()) { + for (ProfileAwareWaypoint fairySoul : fairiesForLocation.getValue().values()) { + for (String profile : fairySoul.foundProfiles) { + foundFairies.computeIfAbsent(profile, profile_ -> new HashMap<>()); + foundFairies.get(profile).computeIfAbsent(fairiesForLocation.getKey(), location_ -> new HashSet<>()); + foundFairies.get(profile).get(fairiesForLocation.getKey()).add(fairySoul.pos); + } + } + } + + try (BufferedWriter writer = Files.newBufferedWriter(SkyblockerMod.CONFIG_DIR.resolve("found_fairy_souls.json"))) { JsonObject foundFairiesJson = new JsonObject(); for (Map.Entry<String, Map<String, Set<BlockPos>>> foundFairiesForProfile : foundFairies.entrySet()) { JsonObject foundFairiesForProfileJson = new JsonObject(); @@ -106,7 +121,6 @@ public class FairySouls { foundFairiesJson.add(foundFairiesForProfile.getKey(), foundFairiesForProfileJson); } SkyblockerMod.GSON.toJson(foundFairiesJson, writer); - writer.close(); LOGGER.info("[Skyblocker] Saved found fairy souls"); } catch (IOException e) { LOGGER.error("[Skyblocker] Failed to write found fairy souls to file", e); @@ -132,13 +146,12 @@ public class FairySouls { SkyblockerConfig.FairySouls fairySoulsConfig = SkyblockerConfigManager.get().general.fairySouls; if (fairySoulsConfig.enableFairySoulsHelper && fairySoulsLoaded.isDone() && fairySouls.containsKey(Utils.getLocationRaw())) { - for (BlockPos fairySoulPos : fairySouls.get(Utils.getLocationRaw())) { - boolean fairySoulNotFound = isFairySoulMissing(fairySoulPos); - if (!fairySoulsConfig.highlightFoundSouls && !fairySoulNotFound || fairySoulsConfig.highlightOnlyNearbySouls && fairySoulPos.getSquaredDistance(context.camera().getPos()) > 2500) { + for (Waypoint fairySoul : fairySouls.get(Utils.getLocationRaw()).values()) { + boolean fairySoulNotFound = fairySoul.shouldRender(); + if (!fairySoulsConfig.highlightFoundSouls && !fairySoulNotFound || fairySoulsConfig.highlightOnlyNearbySouls && fairySoul.pos.getSquaredDistance(context.camera().getPos()) > 2500) { continue; } - float[] colorComponents = fairySoulNotFound ? DyeColor.GREEN.getColorComponents() : DyeColor.RED.getColorComponents(); - RenderHelper.renderFilledThroughWallsWithBeaconBeam(context, fairySoulPos, colorComponents, 0.5F); + fairySoul.render(context); } } } @@ -152,51 +165,37 @@ public class FairySouls { private static void markClosestFairyFound() { if (!fairySoulsLoaded.isDone()) return; + PlayerEntity player = MinecraftClient.getInstance().player; if (player == null) { LOGGER.warn("[Skyblocker] Failed to mark closest fairy soul as found because player is null"); return; } - fairySouls.get(Utils.getLocationRaw()).stream() - .filter(FairySouls::isFairySoulMissing) - .min(Comparator.comparingDouble(fairySoulPos -> fairySoulPos.getSquaredDistance(player.getPos()))) - .filter(fairySoulPos -> fairySoulPos.getSquaredDistance(player.getPos()) <= 16) - .ifPresent(fairySoulPos -> { - initializeFoundFairiesForCurrentProfileAndLocation(); - foundFairies.get(Utils.getProfile()).get(Utils.getLocationRaw()).add(fairySoulPos); - }); - } - private static boolean isFairySoulMissing(BlockPos fairySoulPos) { - Map<String, Set<BlockPos>> foundFairiesForProfile = foundFairies.get(Utils.getProfile()); - if (foundFairiesForProfile == null) { - return true; - } - Set<BlockPos> foundFairiesForProfileAndLocation = foundFairiesForProfile.get(Utils.getLocationRaw()); - if (foundFairiesForProfileAndLocation == null) { - return true; + Map<BlockPos, ProfileAwareWaypoint> fairiesOnCurrentIsland = fairySouls.get(Utils.getLocationRaw()); + if (fairiesOnCurrentIsland == null) { + LOGGER.warn("[Skyblocker] Failed to mark closest fairy soul as found because there are no fairy souls loaded on the current island. NEU repo probably failed to load."); + return; } - return !foundFairiesForProfileAndLocation.contains(fairySoulPos); + + fairiesOnCurrentIsland.values().stream() + .filter(Waypoint::shouldRender) + .min(Comparator.comparingDouble(fairySoul -> fairySoul.pos.getSquaredDistance(player.getPos()))) + .filter(fairySoul -> fairySoul.pos.getSquaredDistance(player.getPos()) <= 16) + .ifPresent(Waypoint::setFound); } public static void markAllFairiesOnCurrentIslandFound() { - initializeFoundFairiesForCurrentProfileAndLocation(); - foundFairies.get(Utils.getProfile()).get(Utils.getLocationRaw()).addAll(fairySouls.get(Utils.getLocationRaw())); + Map<BlockPos, ProfileAwareWaypoint> fairiesForLocation = fairySouls.get(Utils.getLocationRaw()); + if (fairiesForLocation != null) { + fairiesForLocation.values().forEach(ProfileAwareWaypoint::setFound); + } } public static void markAllFairiesOnCurrentIslandMissing() { - Map<String, Set<BlockPos>> foundFairiesForProfile = foundFairies.get(Utils.getProfile()); - if (foundFairiesForProfile != null) { - foundFairiesForProfile.remove(Utils.getLocationRaw()); + Map<BlockPos, ProfileAwareWaypoint> fairiesForLocation = fairySouls.get(Utils.getLocationRaw()); + if (fairiesForLocation != null) { + fairiesForLocation.values().forEach(ProfileAwareWaypoint::setMissing); } } - - private static void initializeFoundFairiesForCurrentProfileAndLocation() { - initializeFoundFairiesForProfileAndLocation(Utils.getProfile(), Utils.getLocationRaw()); - } - - private static void initializeFoundFairiesForProfileAndLocation(String profile, String location) { - foundFairies.computeIfAbsent(profile, profileKey -> new HashMap<>()); - foundFairies.get(profile).computeIfAbsent(location, locationKey -> new HashSet<>()); - } } diff --git a/src/main/java/de/hysky/skyblocker/skyblock/diana/MythologicalRitual.java b/src/main/java/de/hysky/skyblocker/skyblock/waypoint/MythologicalRitual.java index e2962702..5b5f4715 100644 --- a/src/main/java/de/hysky/skyblocker/skyblock/diana/MythologicalRitual.java +++ b/src/main/java/de/hysky/skyblocker/skyblock/waypoint/MythologicalRitual.java @@ -1,4 +1,4 @@ -package de.hysky.skyblocker.skyblock.diana; +package de.hysky.skyblocker.skyblock.waypoint; import com.mojang.brigadier.Command; import de.hysky.skyblocker.SkyblockerMod; @@ -108,7 +108,7 @@ public class MythologicalRitual { burrow.nextBurrowPlane[1] = Vec3d.of(pos).subtract(nextBurrowDirection).subtract(0, 50, 0); burrow.nextBurrowPlane[2] = burrow.nextBurrowPlane[1].add(0, 100, 0); burrow.nextBurrowPlane[3] = burrow.nextBurrowPlane[0].add(0, 100, 0); - } else if (ParticleTypes.DRIPPING_LAVA.equals(packet.getParameters().getType())) { + } else if (ParticleTypes.DRIPPING_LAVA.equals(packet.getParameters().getType()) && packet.getCount() == 2) { if (System.currentTimeMillis() > lastEchoTime + 10_000) { return; } diff --git a/src/main/java/de/hysky/skyblocker/skyblock/spidersden/Relics.java b/src/main/java/de/hysky/skyblocker/skyblock/waypoint/Relics.java index aaf4d77c..952f2f59 100644 --- a/src/main/java/de/hysky/skyblocker/skyblock/spidersden/Relics.java +++ b/src/main/java/de/hysky/skyblocker/skyblock/waypoint/Relics.java @@ -1,4 +1,4 @@ -package de.hysky.skyblocker.skyblock.spidersden; +package de.hysky.skyblocker.skyblock.waypoint; import com.google.gson.JsonArray; import com.google.gson.JsonElement; @@ -11,7 +11,8 @@ import de.hysky.skyblocker.config.SkyblockerConfigManager; import de.hysky.skyblocker.utils.Constants; import de.hysky.skyblocker.utils.PosUtils; import de.hysky.skyblocker.utils.Utils; -import de.hysky.skyblocker.utils.render.RenderHelper; +import de.hysky.skyblocker.utils.waypoint.ProfileAwareWaypoint; +import de.hysky.skyblocker.utils.waypoint.Waypoint; import net.fabricmc.fabric.api.client.command.v2.ClientCommandRegistrationCallback; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientLifecycleEvents; @@ -28,19 +29,24 @@ import net.minecraft.util.math.BlockPos; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.*; +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.NoSuchFileException; import java.util.*; import java.util.concurrent.CompletableFuture; +import java.util.function.Supplier; import static net.fabricmc.fabric.api.client.command.v2.ClientCommandManager.literal; public class Relics { private static final Logger LOGGER = LoggerFactory.getLogger(Relics.class); + private static final Supplier<Waypoint.Type> TYPE_SUPPLIER = () -> SkyblockerConfigManager.get().general.waypoints.waypointType; private static CompletableFuture<Void> relicsLoaded; @SuppressWarnings({"unused", "FieldCanBeLocal"}) private static int totalRelics = 0; - private static final List<BlockPos> relics = new ArrayList<>(); - private static final Map<String, Set<BlockPos>> foundRelics = new HashMap<>(); + private static final Map<BlockPos, ProfileAwareWaypoint> relics = new HashMap<>(); public static void init() { ClientLifecycleEvents.CLIENT_STARTED.register(Relics::loadRelics); @@ -59,7 +65,8 @@ public class Relics { } else if (json.getKey().equals("locations")) { for (JsonElement locationJson : json.getValue().getAsJsonArray().asList()) { JsonObject posData = locationJson.getAsJsonObject(); - relics.add(new BlockPos(posData.get("x").getAsInt(), posData.get("y").getAsInt(), posData.get("z").getAsInt())); + BlockPos pos = new BlockPos(posData.get("x").getAsInt(), posData.get("y").getAsInt(), posData.get("z").getAsInt()); + relics.put(pos, new ProfileAwareWaypoint(pos, TYPE_SUPPLIER, DyeColor.YELLOW.getColorComponents(), DyeColor.BROWN.getColorComponents())); } } } @@ -68,16 +75,14 @@ public class Relics { LOGGER.error("[Skyblocker] Failed to load relics locations", e); } - try (BufferedReader reader = new BufferedReader(new FileReader(SkyblockerMod.CONFIG_DIR.resolve("found_relics.json").toFile()))) { + try (BufferedReader reader = Files.newBufferedReader(SkyblockerMod.CONFIG_DIR.resolve("found_relics.json"))) { for (Map.Entry<String, JsonElement> profileJson : JsonParser.parseReader(reader).getAsJsonObject().asMap().entrySet()) { - Set<BlockPos> foundRelicsForProfile = new HashSet<>(); for (JsonElement foundRelicsJson : profileJson.getValue().getAsJsonArray().asList()) { - foundRelicsForProfile.add(PosUtils.parsePosString(foundRelicsJson.getAsString())); + relics.get(PosUtils.parsePosString(foundRelicsJson.getAsString())).setFound(profileJson.getKey()); } - foundRelics.put(profileJson.getKey(), foundRelicsForProfile); } LOGGER.debug("[Skyblocker] Loaded found relics"); - } catch (FileNotFoundException ignored) { + } catch (NoSuchFileException ignored) { } catch (IOException e) { LOGGER.error("[Skyblocker] Failed to load found relics", e); } @@ -85,7 +90,15 @@ public class Relics { } private static void saveFoundRelics(MinecraftClient client) { - try (BufferedWriter writer = new BufferedWriter(new FileWriter(SkyblockerMod.CONFIG_DIR.resolve("found_relics.json").toFile()))) { + Map<String, Set<BlockPos>> foundRelics = new HashMap<>(); + for (ProfileAwareWaypoint relic : relics.values()) { + for (String profile : relic.foundProfiles) { + foundRelics.computeIfAbsent(profile, profile_ -> new HashSet<>()); + foundRelics.get(profile).add(relic.pos); + } + } + + try (BufferedWriter writer = Files.newBufferedWriter(SkyblockerMod.CONFIG_DIR.resolve("found_relics.json"))) { JsonObject json = new JsonObject(); for (Map.Entry<String, Set<BlockPos>> foundRelicsForProfile : foundRelics.entrySet()) { JsonArray foundRelicsJson = new JsonArray(); @@ -105,12 +118,12 @@ public class Relics { dispatcher.register(literal(SkyblockerMod.NAMESPACE) .then(literal("relics") .then(literal("markAllFound").executes(context -> { - Relics.markAllFound(); + relics.values().forEach(ProfileAwareWaypoint::setFound); context.getSource().sendFeedback(Constants.PREFIX.get().append(Text.translatable("skyblocker.relics.markAllFound"))); return 1; })) .then(literal("markAllMissing").executes(context -> { - Relics.markAllMissing(); + relics.values().forEach(ProfileAwareWaypoint::setMissing); context.getSource().sendFeedback(Constants.PREFIX.get().append(Text.translatable("skyblocker.relics.markAllMissing"))); return 1; })))); @@ -120,11 +133,10 @@ public class Relics { SkyblockerConfig.Relics config = SkyblockerConfigManager.get().locations.spidersDen.relics; if (config.enableRelicsHelper && relicsLoaded.isDone() && Utils.getLocationRaw().equals("combat_1")) { - for (BlockPos fairySoulPos : relics) { - boolean isRelicMissing = isRelicMissing(fairySoulPos); + for (ProfileAwareWaypoint relic : relics.values()) { + boolean isRelicMissing = relic.shouldRender(); if (!isRelicMissing && !config.highlightFoundRelics) continue; - float[] colorComponents = isRelicMissing ? DyeColor.YELLOW.getColorComponents() : DyeColor.BROWN.getColorComponents(); - RenderHelper.renderFilledThroughWallsWithBeaconBeam(context, fairySoulPos, colorComponents, 0.5F); + relic.render(context); } } } @@ -143,30 +155,10 @@ public class Relics { LOGGER.warn("[Skyblocker] Failed to mark closest relic as found because player is null"); return; } - relics.stream() - .filter(Relics::isRelicMissing) - .min(Comparator.comparingDouble(relicPos -> relicPos.getSquaredDistance(player.getPos()))) - .filter(relicPos -> relicPos.getSquaredDistance(player.getPos()) <= 16) - .ifPresent(relicPos -> { - foundRelics.computeIfAbsent(Utils.getProfile(), profileKey -> new HashSet<>()); - foundRelics.get(Utils.getProfile()).add(relicPos); - }); - } - - private static boolean isRelicMissing(BlockPos relicPos) { - Set<BlockPos> foundRelicsForProfile = foundRelics.get(Utils.getProfile()); - return foundRelicsForProfile == null || !foundRelicsForProfile.contains(relicPos); - } - - private static void markAllFound() { - foundRelics.computeIfAbsent(Utils.getProfile(), profileKey -> new HashSet<>()); - foundRelics.get(Utils.getProfile()).addAll(relics); - } - - private static void markAllMissing() { - Set<BlockPos> foundRelicsForProfile = foundRelics.get(Utils.getProfile()); - if (foundRelicsForProfile != null) { - foundRelicsForProfile.clear(); - } + relics.values().stream() + .filter(Waypoint::shouldRender) + .min(Comparator.comparingDouble(relic -> relic.pos.getSquaredDistance(player.getPos()))) + .filter(relic -> relic.pos.getSquaredDistance(player.getPos()) <= 16) + .ifPresent(Waypoint::setFound); } } |