diff options
author | Kevinthegreat <92656833+kevinthegreat1@users.noreply.github.com> | 2023-05-22 20:30:12 -0400 |
---|---|---|
committer | Kevinthegreat <92656833+kevinthegreat1@users.noreply.github.com> | 2023-06-22 11:32:58 +0800 |
commit | 027426aacac048b85cd310e9e3d4101e0156a917 (patch) | |
tree | ea7fb5c02d8ef8b22c547565694e0ab69d15fbe0 /src/main/java/me | |
parent | 4c987071fbc4dc2898afaa0f45f4887808a56de3 (diff) | |
download | Skyblocker-027426aacac048b85cd310e9e3d4101e0156a917.tar.gz Skyblocker-027426aacac048b85cd310e9e3d4101e0156a917.tar.bz2 Skyblocker-027426aacac048b85cd310e9e3d4101e0156a917.zip |
Add Fairy Souls Helper
Diffstat (limited to 'src/main/java/me')
11 files changed, 444 insertions, 142 deletions
diff --git a/src/main/java/me/xmrvizzy/skyblocker/SkyblockerMod.java b/src/main/java/me/xmrvizzy/skyblocker/SkyblockerMod.java index 189ecca3..04ab384f 100644 --- a/src/main/java/me/xmrvizzy/skyblocker/SkyblockerMod.java +++ b/src/main/java/me/xmrvizzy/skyblocker/SkyblockerMod.java @@ -1,14 +1,12 @@ package me.xmrvizzy.skyblocker; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; import me.xmrvizzy.skyblocker.chat.ChatMessageListener; import me.xmrvizzy.skyblocker.config.SkyblockerConfig; import me.xmrvizzy.skyblocker.discord.DiscordRPCManager; import me.xmrvizzy.skyblocker.gui.ContainerSolverManager; -import me.xmrvizzy.skyblocker.skyblock.BackpackPreview; -import me.xmrvizzy.skyblocker.skyblock.FishingHelper; -import me.xmrvizzy.skyblocker.skyblock.HotbarSlotLock; -import me.xmrvizzy.skyblocker.skyblock.StatusBarTracker; -import me.xmrvizzy.skyblocker.skyblock.api.RepositoryUpdate; +import me.xmrvizzy.skyblocker.skyblock.*; import me.xmrvizzy.skyblocker.skyblock.api.StatsCommand; import me.xmrvizzy.skyblocker.skyblock.dungeon.DungeonBlaze; import me.xmrvizzy.skyblocker.skyblock.dungeon.DungeonMap; @@ -20,14 +18,14 @@ import me.xmrvizzy.skyblocker.skyblock.itemlist.ItemRegistry; import me.xmrvizzy.skyblocker.skyblock.quicknav.QuickNav; import me.xmrvizzy.skyblocker.skyblock.tabhud.TabHud; import me.xmrvizzy.skyblocker.skyblock.tabhud.util.PlayerListMgr; -import me.xmrvizzy.skyblocker.utils.MessageScheduler; -import me.xmrvizzy.skyblocker.utils.Scheduler; -import me.xmrvizzy.skyblocker.utils.UpdateChecker; -import me.xmrvizzy.skyblocker.utils.Utils; +import me.xmrvizzy.skyblocker.utils.*; import net.fabricmc.api.ClientModInitializer; import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents; +import net.fabricmc.loader.api.FabricLoader; import net.minecraft.client.MinecraftClient; +import java.nio.file.Path; + /** * Main class for Skyblocker which initializes features, registers events, and * manages ticks. This class will be instantiated by Fabric. Do not instantiate @@ -35,6 +33,8 @@ import net.minecraft.client.MinecraftClient; */ public class SkyblockerMod implements ClientModInitializer { public static final String NAMESPACE = "skyblocker"; + public static final Path CONFIG_DIR = FabricLoader.getInstance().getConfigDir().resolve(NAMESPACE); + public static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); private static SkyblockerMod INSTANCE; @SuppressWarnings("deprecation") @@ -63,12 +63,13 @@ public class SkyblockerMod implements ClientModInitializer { @Override public void onInitializeClient() { ClientTickEvents.END_CLIENT_TICK.register(this::tick); + Utils.init(); HotbarSlotLock.init(); SkyblockerConfig.init(); PriceInfoTooltip.init(); WikiLookup.init(); ItemRegistry.init(); - RepositoryUpdate.init(); + NEURepo.init(); BackpackPreview.init(); QuickNav.init(); StatsCommand.init(); @@ -78,6 +79,7 @@ public class SkyblockerMod implements ClientModInitializer { DiscordRPCManager.init(); LividColor.init(); FishingHelper.init(); + FairySouls.init(); TabHud.init(); containerSolverManager.init(); DungeonMap.init(); diff --git a/src/main/java/me/xmrvizzy/skyblocker/config/SkyblockerConfig.java b/src/main/java/me/xmrvizzy/skyblocker/config/SkyblockerConfig.java index b1bc2001..f296e487 100644 --- a/src/main/java/me/xmrvizzy/skyblocker/config/SkyblockerConfig.java +++ b/src/main/java/me/xmrvizzy/skyblocker/config/SkyblockerConfig.java @@ -150,6 +150,10 @@ public class SkyblockerConfig implements ConfigData { @ConfigEntry.Gui.CollapsibleObject() public Fishing fishing = new Fishing(); + @ConfigEntry.Category("fairySouls") + @ConfigEntry.Gui.CollapsibleObject() + public FairySouls fairySouls = new FairySouls(); + @ConfigEntry.Category("itemList") @ConfigEntry.Gui.CollapsibleObject() public ItemList itemList = new ItemList(); @@ -219,6 +223,10 @@ public class SkyblockerConfig implements ConfigData { public boolean enableFishingHelper = true; } + public static class FairySouls { + public boolean enableFairySouls = true; + } + public static class Hitbox { public boolean oldFarmlandHitbox = true; public boolean oldLeverHitbox = false; diff --git a/src/main/java/me/xmrvizzy/skyblocker/mixin/accessor/BeaconBlockEntityRendererInvoker.java b/src/main/java/me/xmrvizzy/skyblocker/mixin/accessor/BeaconBlockEntityRendererInvoker.java new file mode 100644 index 00000000..ff7c7cbc --- /dev/null +++ b/src/main/java/me/xmrvizzy/skyblocker/mixin/accessor/BeaconBlockEntityRendererInvoker.java @@ -0,0 +1,16 @@ +package me.xmrvizzy.skyblocker.mixin.accessor; + +import net.minecraft.client.render.VertexConsumerProvider; +import net.minecraft.client.render.block.entity.BeaconBlockEntityRenderer; +import net.minecraft.client.util.math.MatrixStack; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Invoker; + +@Mixin(BeaconBlockEntityRenderer.class) +public interface BeaconBlockEntityRendererInvoker { + @SuppressWarnings("unused") + @Invoker("renderBeam") + static void renderBeam(MatrixStack matrices, VertexConsumerProvider vertexConsumers, float tickDelta, long worldTime, int yOffset, int maxY, float[] color) { + throw new IllegalStateException("Mixin invoker failed to apply."); + } +} diff --git a/src/main/java/me/xmrvizzy/skyblocker/skyblock/FairySouls.java b/src/main/java/me/xmrvizzy/skyblocker/skyblock/FairySouls.java new file mode 100644 index 00000000..4480c5e1 --- /dev/null +++ b/src/main/java/me/xmrvizzy/skyblocker/skyblock/FairySouls.java @@ -0,0 +1,184 @@ +package me.xmrvizzy.skyblocker.skyblock; + +import com.google.common.collect.ImmutableSet; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import me.xmrvizzy.skyblocker.SkyblockerMod; +import me.xmrvizzy.skyblocker.config.SkyblockerConfig; +import me.xmrvizzy.skyblocker.utils.NEURepo; +import me.xmrvizzy.skyblocker.utils.RenderHelper; +import me.xmrvizzy.skyblocker.utils.Utils; +import net.fabricmc.fabric.api.client.command.v2.ClientCommandRegistrationCallback; +import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientLifecycleEvents; +import net.fabricmc.fabric.api.client.message.v1.ClientReceiveMessageEvents; +import net.fabricmc.fabric.api.client.rendering.v1.WorldRenderContext; +import net.fabricmc.fabric.api.client.rendering.v1.WorldRenderEvents; +import net.minecraft.client.MinecraftClient; +import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.text.Text; +import net.minecraft.util.DyeColor; +import net.minecraft.util.math.BlockPos; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.*; +import java.util.*; +import java.util.concurrent.CompletableFuture; + +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 CompletableFuture<Void> fairySoulsLoaded; + private static final Map<String, Set<BlockPos>> fairySouls = new HashMap<>(); + private static final Map<String, Map<String, Set<BlockPos>>> foundFairies = new HashMap<>(); + + public static void init() { + fairySoulsLoaded = NEURepo.runAsyncAfterLoad(() -> { + try { + BufferedReader reader = new BufferedReader(new FileReader(NEURepo.LOCAL_REPO_DIR.resolve("constants").resolve("fairy_souls.json").toFile())); + for (Map.Entry<String, JsonElement> fairySoulJson : JsonParser.parseReader(reader).getAsJsonObject().asMap().entrySet()) { + if (fairySoulJson.getKey().equals("//") || fairySoulJson.getKey().equals("Max Souls")) { + continue; + } + ImmutableSet.Builder<BlockPos> fairySoulsForLocation = ImmutableSet.builder(); + for (JsonElement fairySoul : fairySoulJson.getValue().getAsJsonArray().asList()) { + fairySoulsForLocation.add(parseBlockPos(fairySoul)); + } + fairySouls.put(fairySoulJson.getKey(), fairySoulsForLocation.build()); + } + reader = new BufferedReader(new FileReader(SkyblockerMod.CONFIG_DIR.resolve("found_fairy_souls.json").toFile())); + 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<>(); + for (JsonElement foundFairy : foundFairiesForLocationJson.getValue().getAsJsonArray().asList()) { + foundFairiesForLocation.add(parseBlockPos(foundFairy)); + } + foundFairiesForProfile.put(foundFairiesForLocationJson.getKey(), foundFairiesForLocation); + } + foundFairies.put(foundFairiesForProfileJson.getKey(), foundFairiesForProfile); + } + reader.close(); + } catch (IOException e) { + e.printStackTrace(); + LOGGER.error("Failed to load found fairy souls."); + } catch (Exception e) { + e.printStackTrace(); + } + }); + ClientLifecycleEvents.CLIENT_STOPPING.register(FairySouls::saveFoundFairySouls); + WorldRenderEvents.AFTER_TRANSLUCENT.register(FairySouls::render); + ClientReceiveMessageEvents.GAME.register(FairySouls::onChatMessage); + ClientCommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) -> dispatcher.register(literal(SkyblockerMod.NAMESPACE) + .then(literal("fairySouls") + .then(literal("markAllInCurrentIslandFound").executes(context -> { + FairySouls.markAllFairiesFound(); + context.getSource().sendFeedback(Text.translatable("skyblocker.fairySouls.markAllFound")); + return 1; + })) + .then(literal("markAllInCurrentIslandMissing").executes(context -> { + FairySouls.markAllFairiesNotFound(); + context.getSource().sendFeedback(Text.translatable("skyblocker.fairySouls.markAllMissing")); + return 1; + }))))); + } + + private static BlockPos parseBlockPos(JsonElement posJson) { + String[] posArray = posJson.getAsString().split(","); + return new BlockPos(Integer.parseInt(posArray[0]), Integer.parseInt(posArray[1]), Integer.parseInt(posArray[2])); + } + + public static void saveFoundFairySouls(MinecraftClient client) { + try { + BufferedWriter writer = new BufferedWriter(new FileWriter(SkyblockerMod.CONFIG_DIR.resolve("found_fairy_souls.json").toFile())); + JsonObject foundFairiesJson = new JsonObject(); + for (Map.Entry<String, Map<String, Set<BlockPos>>> foundFairiesForProfile : foundFairies.entrySet()) { + JsonObject foundFairiesForProfileJson = new JsonObject(); + for (Map.Entry<String, Set<BlockPos>> foundFairiesForLocation : foundFairiesForProfile.getValue().entrySet()) { + JsonArray foundFairiesForLocationJson = new JsonArray(); + for (BlockPos foundFairy : foundFairiesForLocation.getValue()) { + foundFairiesForLocationJson.add(foundFairy.getX() + "," + foundFairy.getY() + "," + foundFairy.getZ()); + } + foundFairiesForProfileJson.add(foundFairiesForLocation.getKey(), foundFairiesForLocationJson); + } + foundFairiesJson.add(foundFairiesForProfile.getKey(), foundFairiesForProfileJson); + } + SkyblockerMod.GSON.toJson(foundFairiesJson, writer); + writer.close(); + } catch (IOException e) { + LOGGER.error("Failed to write found fairy souls to file."); + } + } + + public static void render(WorldRenderContext context) { + if (!SkyblockerConfig.get().general.fairySouls.enableFairySouls) { + return; + } + if (!fairySoulsLoaded.isDone()) { + LOGGER.warn("Fairy souls are not loaded yet."); + return; + } + if (!fairySouls.containsKey(Utils.getLocationRaw())) { + return; + } + for (BlockPos fairySoul : fairySouls.get(Utils.getLocationRaw())) { + float[] colorComponents = isFairySoulNotFound(fairySoul) ? DyeColor.GREEN.getColorComponents() : DyeColor.RED.getColorComponents(); + RenderHelper.renderFilledThroughWallsWithBeaconBeam(context, fairySoul, colorComponents, 0.5F); + } + } + + private static boolean isFairySoulNotFound(BlockPos fairySoul) { + 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; + } + return !foundFairiesForProfileAndLocation.contains(fairySoul); + } + + public static void onChatMessage(Text text, boolean overlay) { + String message = text.getString(); + if (message.equals("You have already found that Fairy Soul!") || message.equals("SOUL! You found a Fairy Soul!")) { + markClosestFairyFound(); + } + } + + private static void markClosestFairyFound() { + PlayerEntity player = MinecraftClient.getInstance().player; + if (player == null) { + LOGGER.warn("Failed to mark closest fairy soul as found because player is null."); + return; + } + fairySouls.get(Utils.getLocationRaw()).stream().filter(FairySouls::isFairySoulNotFound).min(Comparator.comparingDouble(fairySoul -> fairySoul.getSquaredDistance(player.getPos()))).ifPresent(fairySoul -> { + initializeFoundFairiesForCurrentProfileAndLocation(); + foundFairies.get(Utils.getProfile()).get(Utils.getLocationRaw()).add(fairySoul); + }); + } + + public static void markAllFairiesFound() { + initializeFoundFairiesForCurrentProfileAndLocation(); + foundFairies.get(Utils.getProfile()).get(Utils.getLocationRaw()).addAll(fairySouls.get(Utils.getLocationRaw())); + } + + public static void markAllFairiesNotFound() { + Map<String, Set<BlockPos>> foundFairiesForProfile = foundFairies.get(Utils.getProfile()); + if (foundFairiesForProfile != null) { + foundFairiesForProfile.remove(Utils.getLocationRaw()); + } + } + + 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/me/xmrvizzy/skyblocker/skyblock/api/RepositoryUpdate.java b/src/main/java/me/xmrvizzy/skyblocker/skyblock/api/RepositoryUpdate.java deleted file mode 100644 index e08cb1c0..00000000 --- a/src/main/java/me/xmrvizzy/skyblocker/skyblock/api/RepositoryUpdate.java +++ /dev/null @@ -1,62 +0,0 @@ -package me.xmrvizzy.skyblocker.skyblock.api; - -import me.xmrvizzy.skyblocker.skyblock.itemlist.ItemRegistry; -import net.fabricmc.fabric.api.client.command.v2.ClientCommandManager; -import net.fabricmc.fabric.api.client.command.v2.ClientCommandRegistrationCallback; -import net.minecraft.client.MinecraftClient; -import net.minecraft.text.Text; - -import java.io.File; -import java.nio.file.Files; -import java.util.concurrent.CompletableFuture; - -public class RepositoryUpdate { - public static final MinecraftClient client = MinecraftClient.getInstance(); - - /** - * Adds command to update repository manually from ingame. - * <p></p> - * TODO A button could be added to the settings menu that will trigger this command. - */ - public static void init(){ - ClientCommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) -> dispatcher.register( - ClientCommandManager.literal("skyblocker") - .then(ClientCommandManager.literal("updaterepository") - .executes(context -> { - updateRepository(); - return 1; - }) - ) - ) - ); - - } - - public static void updateRepository() { - CompletableFuture.runAsync(() -> { - try { - ItemRegistry.filesImported = false; - File dir = ItemRegistry.LOCAL_ITEM_REPO_DIR.toFile(); - recursiveDelete(dir); - } catch (Exception ex) { - if (client.player != null) - client.player.sendMessage( - Text.translatable("skyblocker.updaterepository.failed") - , false - ); - return; - } - - ItemRegistry.init(); - }); - } - - private static void recursiveDelete(File dir) { - if (dir.isDirectory() && !Files.isSymbolicLink(dir.toPath())) { - for (File child : dir.listFiles()) { - recursiveDelete(child); - } - } - dir.delete(); - } -} diff --git a/src/main/java/me/xmrvizzy/skyblocker/skyblock/dungeon/LividColor.java b/src/main/java/me/xmrvizzy/skyblocker/skyblock/dungeon/LividColor.java index 276a41b6..4701c485 100644 --- a/src/main/java/me/xmrvizzy/skyblocker/skyblock/dungeon/LividColor.java +++ b/src/main/java/me/xmrvizzy/skyblocker/skyblock/dungeon/LividColor.java @@ -11,11 +11,10 @@ public class LividColor { private static int tenTicks = 0; public static void init() { - ClientReceiveMessageEvents.ALLOW_GAME.register((message, overlay) -> { + ClientReceiveMessageEvents.GAME.register((message, overlay) -> { if (SkyblockerConfig.get().locations.dungeons.lividColor.enableLividColor && message.getString().equals("[BOSS] Livid: I respect you for making it to here, but I'll be your undoing.")) { tenTicks = 8; } - return true; }); } diff --git a/src/main/java/me/xmrvizzy/skyblocker/skyblock/itemlist/ItemRegistry.java b/src/main/java/me/xmrvizzy/skyblocker/skyblock/itemlist/ItemRegistry.java index d9f3b473..13ca356a 100644 --- a/src/main/java/me/xmrvizzy/skyblocker/skyblock/itemlist/ItemRegistry.java +++ b/src/main/java/me/xmrvizzy/skyblocker/skyblock/itemlist/ItemRegistry.java @@ -2,32 +2,23 @@ package me.xmrvizzy.skyblocker.skyblock.itemlist; import com.google.gson.JsonObject; import com.google.gson.JsonParser; - -import me.xmrvizzy.skyblocker.skyblock.api.RepositoryUpdate; -import net.fabricmc.loader.api.FabricLoader; +import me.xmrvizzy.skyblocker.utils.NEURepo; import net.minecraft.client.MinecraftClient; import net.minecraft.item.ItemStack; import net.minecraft.item.Items; import net.minecraft.text.Text; -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.PullResult; -import org.eclipse.jgit.errors.RepositoryNotFoundException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.util.*; -import java.util.concurrent.CompletableFuture; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public class ItemRegistry { - private static final Logger LOGGER = LoggerFactory.getLogger(ItemRegistry.class); - protected static final String REMOTE_ITEM_REPO = "https://github.com/NotEnoughUpdates/NotEnoughUpdates-REPO"; - public static final Path LOCAL_ITEM_REPO_DIR = FabricLoader.getInstance().getConfigDir().resolve("skyblocker/item-repo"); - - protected static final Path ITEM_LIST_DIR = LOCAL_ITEM_REPO_DIR.resolve("items"); + protected static final Path ITEM_LIST_DIR = NEURepo.LOCAL_REPO_DIR.resolve("items"); protected static final List<ItemStack> items = new ArrayList<>(); protected static final Map<String, ItemStack> itemsMap = new HashMap<>(); @@ -36,52 +27,8 @@ public class ItemRegistry { public static boolean filesImported = false; public static void init() { - CompletableFuture.runAsync(ItemRegistry::updateItemRepo) - .whenComplete((result, ex) -> { - if (ex == null) { - ItemStackBuilder.init(); - importItemFiles(); - } - else { - LOGGER.error("[Skyblocker-ItemRegistry] " + ex); - } - }); - } - - private static void updateItemRepo() { - Git git; - if (!Files.isDirectory(LOCAL_ITEM_REPO_DIR)) { - try { - git = Git.cloneRepository() - .setURI(REMOTE_ITEM_REPO) - .setDirectory(LOCAL_ITEM_REPO_DIR.toFile()) - .setBranchesToClone(List.of("refs/heads/master")) - .setBranch("refs/heads/master") - .call(); - git.close(); - LOGGER.info("[Skyblocker Repository Update] Repository updated."); - } catch (Exception e) { - e.printStackTrace(); - } - } else { - try { - git = Git.open(LOCAL_ITEM_REPO_DIR.toFile()); - PullResult pull = git.pull().setRebase(true).call(); - git.close(); - - if (pull.getRebaseResult() == null) { - LOGGER.info("[Skyblocker Repository Update] No update result"); - } else if (pull.getRebaseResult().getStatus().isSuccessful()) { - LOGGER.info("[Skyblocker Repository Update] Status: " + pull.getRebaseResult().getStatus().name()); - } else if (!pull.getRebaseResult().getStatus().isSuccessful()) { - LOGGER.warn("[Skyblocker Repository Update] Status: " + pull.getRebaseResult().getStatus().name()); - } - } catch (RepositoryNotFoundException e) { - RepositoryUpdate.updateRepository(); - } catch (Exception e) { - e.printStackTrace(); - } - } + NEURepo.runAsyncAfterLoad(ItemStackBuilder::loadPetNums); + NEURepo.runAsyncAfterLoad(ItemRegistry::importItemFiles); } private static void importItemFiles() { @@ -119,8 +66,7 @@ public class ItemRegistry { if (lhsFamilyName.equals(rhsFamilyName)) { if (lhsInternalName.length() != rhsInternalName.length()) return lhsInternalName.length() - rhsInternalName.length(); - else - return lhsInternalName.compareTo(rhsInternalName); + else return lhsInternalName.compareTo(rhsInternalName); } return lhsFamilyName.compareTo(rhsFamilyName); }); @@ -147,8 +93,7 @@ public class ItemRegistry { public static List<SkyblockCraftingRecipe> getRecipes(String internalName) { List<SkyblockCraftingRecipe> result = new ArrayList<>(); for (SkyblockCraftingRecipe recipe : recipes) - if (getInternalName(recipe.result).equals(internalName)) - result.add(recipe); + if (getInternalName(recipe.result).equals(internalName)) result.add(recipe); for (SkyblockCraftingRecipe recipe : recipes) for (ItemStack ingredient : recipe.grid) if (!ingredient.getItem().equals(Items.AIR) && getInternalName(ingredient).equals(internalName)) { diff --git a/src/main/java/me/xmrvizzy/skyblocker/skyblock/itemlist/ItemStackBuilder.java b/src/main/java/me/xmrvizzy/skyblocker/skyblock/itemlist/ItemStackBuilder.java index b2d909a8..d420d54f 100644 --- a/src/main/java/me/xmrvizzy/skyblocker/skyblock/itemlist/ItemStackBuilder.java +++ b/src/main/java/me/xmrvizzy/skyblocker/skyblock/itemlist/ItemStackBuilder.java @@ -4,6 +4,7 @@ import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; +import me.xmrvizzy.skyblocker.utils.NEURepo; import net.minecraft.item.ItemStack; import net.minecraft.nbt.*; import net.minecraft.text.Text; @@ -16,10 +17,10 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; public class ItemStackBuilder { - private final static Path PETNUMS_PATH = ItemRegistry.LOCAL_ITEM_REPO_DIR.resolve("constants/petnums.json"); + private final static Path PETNUMS_PATH = NEURepo.LOCAL_REPO_DIR.resolve("constants/petnums.json"); private static JsonObject petNums; - public static void init() { + public static void loadPetNums() { try { petNums = JsonParser.parseString(Files.readString(PETNUMS_PATH)).getAsJsonObject(); } catch (Exception e) { diff --git a/src/main/java/me/xmrvizzy/skyblocker/utils/NEURepo.java b/src/main/java/me/xmrvizzy/skyblocker/utils/NEURepo.java new file mode 100644 index 00000000..027cfa7a --- /dev/null +++ b/src/main/java/me/xmrvizzy/skyblocker/utils/NEURepo.java @@ -0,0 +1,90 @@ +package me.xmrvizzy.skyblocker.utils; + +import me.xmrvizzy.skyblocker.SkyblockerMod; +import me.xmrvizzy.skyblocker.skyblock.itemlist.ItemRegistry; +import net.fabricmc.fabric.api.client.command.v2.ClientCommandManager; +import net.fabricmc.fabric.api.client.command.v2.ClientCommandRegistrationCallback; +import net.minecraft.client.MinecraftClient; +import net.minecraft.text.Text; +import org.eclipse.jgit.api.Git; +import org.eclipse.jgit.errors.RepositoryNotFoundException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.concurrent.CompletableFuture; + +public class NEURepo { + private static final Logger LOGGER = LoggerFactory.getLogger(NEURepo.class); + public static final String REMOTE_REPO_URL = "https://github.com/NotEnoughUpdates/NotEnoughUpdates-REPO.git"; + public static final Path LOCAL_REPO_DIR = SkyblockerMod.CONFIG_DIR.resolve("item-repo"); + private static final CompletableFuture<Void> REPO_INITIALIZED = initRepository(); + + /** + * Adds command to update repository manually from ingame. + * <p></p> + * TODO A button could be added to the settings menu that will trigger this command. + */ + public static void init() { + ClientCommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) -> + dispatcher.register(ClientCommandManager.literal(SkyblockerMod.NAMESPACE) + .then(ClientCommandManager.literal("updaterepository").executes(context -> { + deleteAndDownloadRepository(); + return 1; + })))); + } + + public static CompletableFuture<Void> initRepository() { + return CompletableFuture.runAsync(() -> { + try { + if (Files.isDirectory(NEURepo.LOCAL_REPO_DIR)) { + try (Git localRepo = Git.open(NEURepo.LOCAL_REPO_DIR.toFile())) { + localRepo.pull().setRebase(true).call(); + LOGGER.info("[Skyblocker] NEU Repository Updated"); + } + } else { + Git.cloneRepository().setURI(REMOTE_REPO_URL).setDirectory(NEURepo.LOCAL_REPO_DIR.toFile()).setBranchesToClone(List.of("refs/heads/master")).setBranch("refs/heads/master").call().close(); + LOGGER.info("[Skyblocker] NEU Repository Downloaded"); + } + } catch (RepositoryNotFoundException e) { + LOGGER.warn("Local NEU Repository not found or corrupted, downloading new one", e); + deleteAndDownloadRepository(); + } catch (Exception e) { + LOGGER.error("Encountered unknown exception while initializing NEU Repository", e); + } + }); + } + + public static void deleteAndDownloadRepository() { + CompletableFuture.runAsync(() -> { + try { + ItemRegistry.filesImported = false; + File dir = NEURepo.LOCAL_REPO_DIR.toFile(); + recursiveDelete(dir); + } catch (Exception ex) { + if (MinecraftClient.getInstance().player != null) + MinecraftClient.getInstance().player.sendMessage(Text.translatable("skyblocker.updaterepository.failed"), false); + return; + } + initRepository(); + }); + } + + @SuppressWarnings("ResultOfMethodCallIgnored") + private static void recursiveDelete(File dir) { + File[] children; + if (dir.isDirectory() && !Files.isSymbolicLink(dir.toPath()) && (children = dir.listFiles()) != null) { + for (File child : children) { + recursiveDelete(child); + } + } + dir.delete(); + } + + public static CompletableFuture<Void> runAsyncAfterLoad(Runnable runnable) { + return REPO_INITIALIZED.thenRunAsync(runnable); + } +} diff --git a/src/main/java/me/xmrvizzy/skyblocker/utils/RenderHelper.java b/src/main/java/me/xmrvizzy/skyblocker/utils/RenderHelper.java new file mode 100644 index 00000000..79308dc3 --- /dev/null +++ b/src/main/java/me/xmrvizzy/skyblocker/utils/RenderHelper.java @@ -0,0 +1,30 @@ +package me.xmrvizzy.skyblocker.utils; + +import me.x150.renderer.render.Renderer3d; +import me.xmrvizzy.skyblocker.mixin.accessor.BeaconBlockEntityRendererInvoker; +import net.fabricmc.fabric.api.client.rendering.v1.WorldRenderContext; +import net.minecraft.client.render.block.entity.BeaconBlockEntityRenderer; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.Vec3d; + +import java.awt.*; + +public class RenderHelper { + public static void renderFilledThroughWallsWithBeaconBeam(WorldRenderContext context, BlockPos pos, float[] colorComponents, float alpha) { + renderFilledThroughWalls(context, pos, colorComponents, alpha); + renderBeaconBeam(context, pos, colorComponents); + } + + public static void renderFilledThroughWalls(WorldRenderContext context, BlockPos pos, float[] colorComponents, float alpha) { + Renderer3d.renderThroughWalls(); + Renderer3d.renderFilled(context.matrixStack(), new Color(colorComponents[0], colorComponents[1], colorComponents[2], alpha), Vec3d.of(pos), new Vec3d(1, 1, 1)); + Renderer3d.stopRenderThroughWalls(); + } + + public static void renderBeaconBeam(WorldRenderContext context, BlockPos pos, float[] colorComponents) { + context.matrixStack().push(); + context.matrixStack().translate(pos.getX() - context.camera().getPos().x, pos.getY() - context.camera().getPos().y, pos.getZ() - context.camera().getPos().z); + BeaconBlockEntityRendererInvoker.renderBeam(context.matrixStack(), context.consumers(), context.tickDelta(), context.world().getTime(), 0, BeaconBlockEntityRenderer.MAX_BEAM_HEIGHT, colorComponents); + context.matrixStack().pop(); + } +} diff --git a/src/main/java/me/xmrvizzy/skyblocker/utils/Utils.java b/src/main/java/me/xmrvizzy/skyblocker/utils/Utils.java index a4e403fc..40c96660 100644 --- a/src/main/java/me/xmrvizzy/skyblocker/utils/Utils.java +++ b/src/main/java/me/xmrvizzy/skyblocker/utils/Utils.java @@ -1,13 +1,21 @@ package me.xmrvizzy.skyblocker.utils; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import me.xmrvizzy.skyblocker.SkyblockerMod; import me.xmrvizzy.skyblocker.skyblock.item.PriceInfoTooltip; import net.fabricmc.fabric.api.client.item.v1.ItemTooltipCallback; +import net.fabricmc.fabric.api.client.message.v1.ClientReceiveMessageEvents; +import net.fabricmc.fabric.api.client.networking.v1.ClientPlayConnectionEvents; +import net.fabricmc.fabric.api.networking.v1.PacketSender; import net.minecraft.client.MinecraftClient; +import net.minecraft.client.network.ClientPlayNetworkHandler; import net.minecraft.client.network.ClientPlayerEntity; import net.minecraft.scoreboard.Scoreboard; import net.minecraft.scoreboard.ScoreboardObjective; import net.minecraft.scoreboard.ScoreboardPlayerScore; import net.minecraft.scoreboard.Team; +import net.minecraft.text.Text; import net.minecraft.util.Formatting; import java.util.ArrayList; @@ -21,6 +29,14 @@ public class Utils { private static boolean isOnSkyblock = false; private static boolean isInDungeons = false; private static boolean isInjected = false; + private static String profile = ""; + private static String server = ""; + private static String gameType = ""; + private static String locationRaw = ""; + private static String map = ""; + private static long clientWorldJoinTime = 0; + private static boolean sentLocRaw = false; + private static long lastLocRaw = 0; public static boolean isOnSkyblock() { return isOnSkyblock; @@ -34,6 +50,31 @@ public class Utils { return isInjected; } + public static String getProfile() { + return profile; + } + + public static String getServer() { + return server; + } + + public static String getGameType() { + return gameType; + } + + public static String getLocationRaw() { + return locationRaw; + } + + public static String getMap() { + return map; + } + + public static void init() { + ClientPlayConnectionEvents.JOIN.register(Utils::onClientWorldJoin); + ClientReceiveMessageEvents.ALLOW_GAME.register(Utils::onChatMessage); + } + public static void sbChecker() { MinecraftClient client = MinecraftClient.getInstance(); List<String> sidebar; @@ -61,13 +102,14 @@ public class Utils { SkyblockEvents.LEAVE.invoker().onSkyblockLeave(); } isInDungeons = isOnSkyblock && string.contains("The Catacombs"); + updateLocRaw(); } public static String getLocation() { String location = null; List<String> sidebarLines = getSidebar(); try { - if( sidebarLines != null) { + if (sidebarLines != null) { for (String sidebarLine : sidebarLines) { if (sidebarLine.contains("⏣")) location = sidebarLine; } @@ -149,4 +191,51 @@ public class Utils { return null; } } + + public static void onClientWorldJoin(ClientPlayNetworkHandler handler, PacketSender sender, MinecraftClient client) { + clientWorldJoinTime = System.currentTimeMillis(); + resetLocRawInfo(); + } + + private static void updateLocRaw() { + if (isOnSkyblock) { + long currentTime = System.currentTimeMillis(); + if (!sentLocRaw && currentTime > clientWorldJoinTime + 1000 && currentTime > lastLocRaw + 15000) { + SkyblockerMod.getInstance().messageScheduler.sendMessageAfterCooldown("/locraw"); + sentLocRaw = true; + lastLocRaw = currentTime; + } + } else { + resetLocRawInfo(); + } + } + + public static boolean onChatMessage(Text text, boolean overlay) { + String message = text.getString(); + if (message.startsWith("{\"server\":") && message.endsWith("}")) { + JsonObject locRaw = JsonParser.parseString(message).getAsJsonObject(); + if (locRaw.has("server")) { + server = locRaw.get("server").getAsString(); + if (locRaw.has("gameType")) { + gameType = locRaw.get("gameType").getAsString(); + } + if (locRaw.has("mode")) { + locationRaw = locRaw.get("mode").getAsString(); + } + if (locRaw.has("map")) { + map = locRaw.get("map").getAsString(); + } + return !sentLocRaw; + } + } + return true; + } + + private static void resetLocRawInfo() { + sentLocRaw = false; + server = ""; + gameType = ""; + locationRaw = ""; + map = ""; + } }
\ No newline at end of file |