diff --git a/build.gradle.kts b/build.gradle.kts index b86ddd543..ec6246af4 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -72,10 +72,16 @@ toolkitGitHubPublishing { repository.set("partly-sane-skies") } +tasks { + fatJar { + relocate("com.jagrosh.discordipc", "me.partlysanestudios.partlysaneskies.deps.discordipc") + } +} + bloom { val dogfood: String by project val releaseChannel: String by project replacement("@DOGFOOD@", dogfood) replacement("@RELEASE_CHANNEL@", releaseChannel) -} \ No newline at end of file +} diff --git a/gradle.properties b/gradle.properties index 5cd116acb..c70efcfb0 100644 --- a/gradle.properties +++ b/gradle.properties @@ -7,7 +7,7 @@ mod.name=Partly Sane Skies mod.id=partlysaneskies mod.description=Developed by Partly Sane Studios. Discord: https://discord.gg/v4PU3WeH7z -mod.version=beta-v0.6.2-prerelease-5 +mod.version=beta-v0.6.2-prerelease-8 # -----------------------CHANGE TO FALSE BEFORE RELEASING dogfood=false # Release Channel: diff --git a/src/main/java/me/partlysanestudios/partlysaneskies/features/chat/ChatAlertsManager.java b/src/main/java/me/partlysanestudios/partlysaneskies/features/chat/ChatAlertsManager.java deleted file mode 100644 index 79689d67c..000000000 --- a/src/main/java/me/partlysanestudios/partlysaneskies/features/chat/ChatAlertsManager.java +++ /dev/null @@ -1,339 +0,0 @@ -// -// Written by Su386. -// See LICENSE for copyright and license notices. -// - -package me.partlysanestudios.partlysaneskies.features.chat; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import me.partlysanestudios.partlysaneskies.PartlySaneSkies; -import me.partlysanestudios.partlysaneskies.commands.PSSCommand; -import me.partlysanestudios.partlysaneskies.system.SystemNotification; -import me.partlysanestudios.partlysaneskies.utils.ChatUtils; -import me.partlysanestudios.partlysaneskies.utils.StringUtils; -import net.minecraft.util.ChatComponentText; -import net.minecraft.util.IChatComponent; -import org.lwjgl.opengl.Display; - -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.Reader; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.Arrays; - -public class ChatAlertsManager { - static String DATA_PATH_NAME = "./config/partly-sane-skies/chatAlertsData.json"; - static ArrayList chatAlertsList = new ArrayList<>(); - // All the different message prefixes - static String[] MESSAGE_PREFIXES = new String[]{"§r§7: ", "§r§f: ", "§f: "}; - /// All the none color format codes - static String[] NON_COLOR_CODES = new String[]{"§r", "§o", "§n", "§m", "§l", "§k"}; - - // Loads all the chat alerts data - public static void load() throws IOException { - File file = new File(DATA_PATH_NAME); - - // If the file doesn't exist, fill it with an empty array list to prevent NullPointerException - if (file.createNewFile()) { - file.setWritable(true); - FileWriter writer = new FileWriter(file); - writer.write(new Gson().toJson(new ArrayList())); - writer.close(); - } - - // Make a new reader - file.setWritable(true); - Reader reader = Files.newBufferedReader(Paths.get(file.getPath())); - - // Reads the file and set it as the list - @SuppressWarnings("unchecked") - ArrayList list = (ArrayList) new Gson().fromJson(reader, ArrayList.class); - chatAlertsList = list; - - } - - public static void registerCommand() { - new PSSCommand("chatalerts") - .addAlias("ca") - .addAlias("chatAlert") - .addAlias("chal") - .setDescription("Operates the chat alerts feature: /chatalerts ") - .setRunnable(args -> { - // If the user doesn't provide any arguments whatsoever print message - if (args.length == 0) { - ChatUtils.INSTANCE.sendClientMessage("§cIncorrect usage. Correct usage: /chatalerts add/remove/list"); - return; - } - - // Looks at the first argument given - switch (args[0]) { - // If the user does /chatalerts list - case "list": - ChatAlertsManager.listAlerts(); - break; - - // If the user does /chatalerts add - case "add": - // Prints error message if no message alert is given - if (args.length == 1) { - ChatUtils.INSTANCE.sendClientMessage("§cIncorrect usage. Correct usage: /chatalerts add [alert]"); - break; - } - - // Adds each argument as a space - StringBuilder alert = new StringBuilder(); - for (int i = 1; i < args.length; i++) { - alert.append(args[i]); - alert.append(" "); - } - - // Removes any leading or trailing spaces - alert = new StringBuilder(StringUtils.INSTANCE.stripLeading(alert.toString())); - alert = new StringBuilder(StringUtils.INSTANCE.stripTrailing(alert.toString())); - - ChatAlertsManager.addAlert(alert.toString()); - - break; - - // If the user does /chatalerts remove - case "remove": - // If no number is given - if (args.length == 1) { - ChatUtils.INSTANCE.sendClientMessage("§cIncorrect usage. Correct usage: /chatalerts remove [number]"); - break; - } - - // Tries to parse the number given as a number - int id; - try { - id = Integer.parseInt(args[1]); - } catch ( - NumberFormatException e) { // If the number cannot be parsed, prints an error message - ChatUtils.INSTANCE.sendClientMessage("§c\"" + args[1] + "\" could not be read as a number. Correct Usage: /chatalerts remove [number]"); - break; - } - - // Removes the chat alert - ChatAlertsManager.removeAlert(id); - break; - - // If none of the above are given - default: - ChatUtils.INSTANCE.sendClientMessage("§cIncorrect usage. Correct usage: /chatalerts add/remove/list"); - break; - } - }) - .register(); - } - - // Saves all the chat alerts data - public static void save() throws IOException { - // Creates a new file and Gson instance - File file = new File(DATA_PATH_NAME); - GsonBuilder builder = new GsonBuilder(); - builder.setPrettyPrinting(); - builder.serializeSpecialFloatingPointValues(); - Gson gson = builder.create(); - - // Converts list to JSON string - String json = gson.toJson(chatAlertsList); - - // Writes string to file - FileWriter writer = new FileWriter(file); - writer.write(json); - writer.close(); - - } - - // Adds the given alert to the list - public static void addAlert(String alert) { - // Adds the alert - chatAlertsList.add(alert); - - // Tries to save - try { - save(); - } catch (IOException e) { // If unable to save, warn user - ChatUtils.INSTANCE.sendClientMessage("§cChat Alerts was unable to save. Please try again."); - e.printStackTrace(); - } - - // Print success message - ChatUtils.INSTANCE.sendClientMessage("§b\"§d" + alert + "§b\" was successfully added as alert number §d" + chatAlertsList.size() + "§b."); - } - - public static int getChatAlertCount() { - return chatAlertsList.size(); - } - - // Lists all the alerts to the chat - public static void listAlerts() { - // Creates header message - StringBuilder message = new StringBuilder("§d§m-----------------------------------------------------\n§bChat Alerts:" + - "\n§d§m-----------------------------------------------------\n"); - - // Creates the index number on the left of the message - int i = 1; - - // For each alert, format it so its ##. [alert] - for (String alert : chatAlertsList) { - message.append(StringUtils.INSTANCE.formatNumber(i)).append(": ").append(alert).append("\n"); - i++; - } - - // Sends a message to the client - ChatUtils.INSTANCE.sendClientMessage(message.toString()); - } - - // Removes an alert given a number - public static void removeAlert(int id) { - // Checks if the number is in the list - if (id > chatAlertsList.size() || id < 0) { - ChatUtils.INSTANCE.sendClientMessage("§cChat alert number " + id + " was not found. Please enter a valid number."); - return; - } - - // Gets the chat alert that was removed - String message = chatAlertsList.get(id - 1); - - // Removes the given alert - chatAlertsList.remove(id - 1); - - // Tries to save - try { - save(); - } catch (IOException e) { // Warns user if unable to save - ChatUtils.INSTANCE.sendClientMessage("§cChat Alerts was unable to save. Please try again."); - e.printStackTrace(); - } - // Prints a success message - ChatUtils.INSTANCE.sendClientMessage("§bChat Alert number §d" + id + " §b(\"§d" + message + "§b\") was successfully removed."); - } - - // I love overloading - public static IChatComponent checkChatAlert(IChatComponent message) { - return checkChatAlert(message, false); - } - - // Runs when a chat message is received - public static IChatComponent checkChatAlert(IChatComponent message, Boolean sendSystemNotification) { - String formattedMessage = message.getFormattedText(); - - // Finds the location after the username starts - // Ex: "[MVP+] Su386: " - int beginMessageIndex = -1; - // Checks all the different message prefixes so that it works with nons - for (String messagePrefix : MESSAGE_PREFIXES) { - beginMessageIndex = formattedMessage.indexOf(messagePrefix); - - // If it finds it, stops checking the rest - if (beginMessageIndex != -1) { - break; - } - } - - // If the message does not have ":" at the beginning - if (beginMessageIndex == -1) { - return message; - } - - String unformattedMessage = StringUtils.INSTANCE.removeColorCodes(formattedMessage); - String rawMessage = formattedMessage.substring(beginMessageIndex); - - // Removes all formatting and extra spaces from the message - rawMessage = StringUtils.INSTANCE.removeColorCodes(rawMessage); - rawMessage = rawMessage.replaceFirst(": ", ""); - rawMessage = StringUtils.INSTANCE.stripLeading(rawMessage); - rawMessage = StringUtils.INSTANCE.stripTrailing(rawMessage); - - String lowerCaseMessage = rawMessage.toLowerCase(); - - - // Checks each alert, seeing if the message contains it - for (String alert : chatAlertsList) { - // If the message doesn't contain the alert, continue - if (!lowerCaseMessage.contains(alert.toLowerCase())) { - continue; - } - - // Creates a new message that will be shown to the user - StringBuilder messageBuilder = new StringBuilder(formattedMessage); - - // Gets index of alert in unformatted text - int alertIndexUnformatted = unformattedMessage.toLowerCase().indexOf(alert.toLowerCase(), unformattedMessage.indexOf(rawMessage)); - - // Number of color codes in the whole string - int numOfColorCodeTotal = numOfColorCodes(formattedMessage); - // Number of color codes not including the last §r - int numOfColorCodeBefore = numOfColorCodeTotal - 1; - // Index of the alert in formatted string - int alertIndexFormatted = numOfColorCodeBefore * 2 + alertIndexUnformatted; - - // Inserts the previous color code right after the alert - char[] charsToAdd = getLastColorCode(formattedMessage.substring(0, alertIndexFormatted + 1)).toCharArray(); - messageBuilder.insert(alertIndexFormatted + alert.length(), charsToAdd, 0, charsToAdd.length); - - // Inserts a purple and bold color code to highlight the message right before the alert - charsToAdd = ("§d§l").toCharArray(); - messageBuilder.insert(alertIndexFormatted, charsToAdd, 0, charsToAdd.length); - - // Sends System Tray - if (PartlySaneSkies.Companion.getConfig().getChatAlertSendSystemNotification() && !Display.isActive() && sendSystemNotification) { - SystemNotification.INSTANCE.showNotification(StringUtils.INSTANCE.removeColorCodes(message.getFormattedText())); - } - - // Shows a message to user - return new ChatComponentText(messageBuilder.toString()); - } - return message; - } - - // Returns the number of color codes in a String - private static int numOfColorCodes(String str) { - int i = 0; - - // Counts each instance of § - StringBuilder textBuilder = new StringBuilder(str); - while (textBuilder.indexOf("§") != -1) { - textBuilder.deleteCharAt(textBuilder.indexOf("§") + 1); - textBuilder.deleteCharAt(textBuilder.indexOf("§")); - i++; - } - - return i; - } - - // Returns the last color code in a string - private static String getLastColorCode(String str) { - String currentCode = ""; - StringBuilder textBuilder = new StringBuilder(str); - while (textBuilder.indexOf("§") != -1) { - boolean shouldContinue = false; - // Checks if the color code is a non-color code - for (String code : NON_COLOR_CODES) { - if (textBuilder.indexOf("§") == -1 || !textBuilder.substring(textBuilder.indexOf("§"), textBuilder.indexOf("§") + 2).equalsIgnoreCase(code)) { - continue; - } - textBuilder.deleteCharAt(textBuilder.indexOf("§") + 1); - textBuilder.deleteCharAt(textBuilder.indexOf("§")); - shouldContinue = true; - break; - } - - - if (shouldContinue || textBuilder.indexOf("§") == -1) { - continue; - } - - // Sets current code to the current format code - currentCode = textBuilder.substring(textBuilder.indexOf("§"), textBuilder.indexOf("§") + 2); - textBuilder.deleteCharAt(textBuilder.indexOf("§") + 1); - textBuilder.deleteCharAt(textBuilder.indexOf("§")); - } - return currentCode; - } -} diff --git a/src/main/java/me/partlysanestudios/partlysaneskies/features/chat/ChatColors.java b/src/main/java/me/partlysanestudios/partlysaneskies/features/chat/ChatColors.java deleted file mode 100644 index 16565dc90..000000000 --- a/src/main/java/me/partlysanestudios/partlysaneskies/features/chat/ChatColors.java +++ /dev/null @@ -1,150 +0,0 @@ -// -// Written by Su386. -// See LICENSE for copyright and license notices. -// - -package me.partlysanestudios.partlysaneskies.features.chat; - -import me.partlysanestudios.partlysaneskies.PartlySaneSkies; -import me.partlysanestudios.partlysaneskies.utils.StringUtils; -import net.minecraft.util.ChatComponentText; -import net.minecraft.util.IChatComponent; - -public class ChatColors { - public static IChatComponent detectColorMessage(IChatComponent message) { - String formattedMessage = message.getFormattedText(); - String prefix = getPrefix(formattedMessage); - if (prefix.isEmpty()) { - return message; - } - - String color = getChatColor(prefix); - if (color.isEmpty()) { - return message; - } - - return new ChatComponentText(insertColor(formattedMessage, color)); - } - - public static IChatComponent detectNonMessage(IChatComponent message) { - if (!PartlySaneSkies.Companion.getConfig().getColorNonMessages()) { - return message; - } - - String formattedMessage = message.getFormattedText(); - // if it's not a non message, return - if (!formattedMessage.contains("§r§7: ")) { - return message; - } - - // If its private message, return - if (formattedMessage.startsWith("§dTo ") || formattedMessage.startsWith("§dFrom ")) { - return message; - } - - // Checks to see if the message has a rank - boolean containsRankNames = false; - String unformattedMessage = message.getUnformattedText(); - for (String rank : PartlySaneSkies.Companion.getRANK_NAMES()) { - if (!unformattedMessage.contains(rank)) { - continue; - } - containsRankNames = true; - break; - } - - // If it has a rank return - if (containsRankNames) { - return message; - } - - // If it does not, it highlights the nons message - return new ChatComponentText(insertColor(formattedMessage, "§r")); - } - - public static String getChatColor(String prefix) { - switch (prefix.toLowerCase()) { - case "party": - if (!PartlySaneSkies.Companion.getConfig().getColorPartyChat()) { - return ""; - } - if (PartlySaneSkies.Companion.getConfig().getVisibleColors()) { - return "§6"; - } - return "§9"; - - case "guild": - if (!PartlySaneSkies.Companion.getConfig().getColorGuildChat()) { - return ""; - } - if (PartlySaneSkies.Companion.getConfig().getVisibleColors()) { - return "§a"; - } - return "§2"; - - case "officer": - if (!PartlySaneSkies.Companion.getConfig().getColorOfficerChat()) { - return ""; - } - return "§3"; - - case "to": - case "from": - if (!PartlySaneSkies.Companion.getConfig().getColorPrivateMessages()) { - return ""; - } - return "§d"; - - case "co-op": - if (!PartlySaneSkies.Companion.getConfig().getColorCoopChat()) { - return ""; - } - return "§b"; - - default: - return ""; - } - } - - public static String getPrefix(String message) { - message = StringUtils.INSTANCE.removeColorCodes(message); - if (message.startsWith("Party >")) { - return "Party"; - } else if (message.startsWith("Guild >")) { - return "Guild"; - } else if (message.startsWith("Officer >")) { - return "Officer"; - } else if (message.startsWith("To ")) { - return "To"; - } else if (message.startsWith("From ")) { - return "From"; - } else if (message.startsWith("Co-op >")) { - return "Co-op"; - } - - return ""; - } - - public static String insertColor(String message, String color) { - int messageStartIndex = -1; - - for (String prefix : ChatAlertsManager.MESSAGE_PREFIXES) { - if (message.contains(prefix)) { - messageStartIndex = message.indexOf(prefix) + prefix.length(); - break; - } - } - - if (messageStartIndex == -1) { - return message; - } - - String messageString = message.substring(messageStartIndex); - String preMessageString = message.substring(0, messageStartIndex); - - messageString = StringUtils.INSTANCE.removeColorCodes(messageString); - messageString = color + messageString; - - return preMessageString + messageString; - } -} diff --git a/src/main/java/me/partlysanestudios/partlysaneskies/features/chat/OwO.java b/src/main/java/me/partlysanestudios/partlysaneskies/features/chat/OwO.java deleted file mode 100644 index 3978ba4cb..000000000 --- a/src/main/java/me/partlysanestudios/partlysaneskies/features/chat/OwO.java +++ /dev/null @@ -1,49 +0,0 @@ -// -// Written by J10a1n15 -// See LICENSE for copyright and license notices. -// - - -package me.partlysanestudios.partlysaneskies.features.chat; - -public class OwO { - public static String owoify(String text) { - return text - .replace("r", "w") - .replace("l", "w") - .replace("R", "W") - .replace("L", "W") - .replace("no", "nyo") - .replace("No", "Nyo") - .replace("NO", "NYO") - .replace("na", "nya") - .replace("Na", "Nya") - .replace("NA", "NYA") - .replace("ne", "nye") - .replace("Ne", "Nye") - .replace("NE", "NYE") - .replace("ni", "nyi") - .replace("Ni", "Nyi") - .replace("NI", "NYI") - .replace("nu", "nyu") - .replace("Nu", "Nyu") - .replace("NU", "NYU") - .replace("ne", "nye") - .replace("Ne", "Nye") - .replace("NE", "NYE") - .replace("no", "nyo") - .replace("No", "Nyo") - .replace("NO", "NYO") - .replace("n", "ny") - .replace("N", "Ny") - .replace("ove", "uv") - .replace("Ove", "Uv") - .replace("OVE", "UV") - .replace("o", "owo") - .replace("O", "OwO") - .replace("!", " >w<") - .replace("?", " owo?") - .replace(".", " owo.") - .replace(",", " owo,"); - } -} diff --git a/src/main/java/me/partlysanestudios/partlysaneskies/features/chat/WordEditor.java b/src/main/java/me/partlysanestudios/partlysaneskies/features/chat/WordEditor.java deleted file mode 100644 index e47dd786d..000000000 --- a/src/main/java/me/partlysanestudios/partlysaneskies/features/chat/WordEditor.java +++ /dev/null @@ -1,207 +0,0 @@ -// -// Written by J10a1n15, with a lot of help from Su386. -// See LICENSE for copyright and license notices. -// - -package me.partlysanestudios.partlysaneskies.features.chat; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import me.partlysanestudios.partlysaneskies.PartlySaneSkies; -import me.partlysanestudios.partlysaneskies.commands.PSSCommand; -import me.partlysanestudios.partlysaneskies.utils.ChatUtils; -import net.minecraft.util.IChatComponent; -import org.apache.commons.lang3.ArrayUtils; - -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.Reader; -import java.nio.file.Files; -import java.nio.file.Paths; - - -public class WordEditor { - - static String[][] wordsToEdit = {}; - /* - Structure: - { - [ - "word to replace", - "replacement word" - ], - [ - "word to replace", - "replacement word" - ] - } - */ - - - public static String handleWordEditorMessage(String message) { - if (!PartlySaneSkies.Companion.getConfig().getWordEditor()) return message; - - for (final String[] word : wordsToEdit) { - - // ChatUtils.INSTANCE.sendClientMessage("Trying to replace \"" + word[0] + "\" with \"" + word[1]); - final String wordToReplace = word[0]; - final String replacementWord = word[1]; - - // Quick while hes not looking! add the session id stealer code ~su - -/* - * - sjw _..----.._ _ - .' .--. "-.(0)_ -'-.__.-'"'=:| , _)_ \__ . c\'-.. - '''------'---''---'-" - */ - -// omg he copy pasted a rat lmao -//rat - -//i think these comments should stay, for history's sake -// i concur - - if (message.contains(wordToReplace)) { // If the to replace exists - message = message.replace(wordToReplace, replacementWord); - } - } - - return message; - } - - public static boolean shouldEditMessage(IChatComponent message) { - if (!PartlySaneSkies.Companion.getConfig().getWordEditor()) { - return false; - } - - String formattedMessage = message.getFormattedText(); - - for (final String[] word : wordsToEdit) { - final String wordToReplace = word[0]; - if (formattedMessage.contains(wordToReplace)) { - return true; - } - } - - return false; - } - - public static void listWords() { - if (WordEditor.wordsToEdit.length == 0) { - ChatUtils.INSTANCE.sendClientMessage("§7There are no words to replace."); - return; - } - - ChatUtils.INSTANCE.sendClientMessage("§7Words to replace:"); - for (int i = 0; i < WordEditor.wordsToEdit.length; i++) { - ChatUtils.INSTANCE.sendClientMessage("§b" + (i + 1) + ". §7" + wordsToEdit[i][0] + " §8-> §7" + wordsToEdit[i][1]); - } - } - - - public static void registerWordEditorCommand() { - new PSSCommand("wordeditor") - .addAlias("wordedit") - .addAlias("we") - .addAlias("wordreplace") - .addAlias("wr") - .setDescription("Operates the word editor: /wordeditor add , /wordeditor list or /wordeditor remove ") - .setRunnable(args -> { - if (args.length == 0 || args[0].equalsIgnoreCase("list")) { - - ChatUtils.INSTANCE.sendClientMessage("§7To add a word to replace, run §b/wordeditor add §7. To remove a word, run §b/wordeditor remove §7. To list all of the words, run §b/wordeditor list§7."); - - WordEditor.listWords(); - return; - } - - if (args[0].equalsIgnoreCase("remove")) { - if (args.length == 1) { - ChatUtils.INSTANCE.sendClientMessage("§cError: Must provide an index to remove"); - return; - } - - int i; - try { - i = Integer.parseInt(args[1]); - } catch (NumberFormatException e) { - ChatUtils.INSTANCE.sendClientMessage("§cPlease enter a valid number index and try again."); - return; - } - - if (i > WordEditor.wordsToEdit.length || i < 1) { - ChatUtils.INSTANCE.sendClientMessage("§cPlease select a valid index and try again."); - return; - } - ChatUtils.INSTANCE.sendClientMessage("§aRemoving: §b" + WordEditor.wordsToEdit[i - 1][0] + " §8-> §b" + WordEditor.wordsToEdit[i - 1][1]); - WordEditor.wordsToEdit = ArrayUtils.removeElement(WordEditor.wordsToEdit, WordEditor.wordsToEdit[i - 1]); // Removes the element from the array - try { - WordEditor.save(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - if (args[0].equalsIgnoreCase("add")) { - if (args.length < 3) { - ChatUtils.INSTANCE.sendClientMessage("§cError: Must provide a word and a replacement"); - return; - } - - String word = args[1]; - String replacement = args[2]; - - for (int i = 3; i < args.length; i++) { - replacement += " " + args[i]; - } - - ChatUtils.INSTANCE.sendClientMessage("§aAdding: §b" + word + " §8-> §b" + replacement); - WordEditor.wordsToEdit = ArrayUtils.add(WordEditor.wordsToEdit, new String[]{word, replacement}); - try { - WordEditor.save(); - } catch (IOException e) { - e.printStackTrace(); - } - } - }) - .register(); - } - - - public static void save() throws IOException { - // Declares the file - File file = new File("./config/partly-sane-skies/wordEditor.json"); - - file.createNewFile(); - // Creates a new Gson object to save the data - Gson gson = new GsonBuilder() - .setPrettyPrinting() - .serializeSpecialFloatingPointValues() - .create(); - // Saves teh data to the file - String json = gson.toJson(wordsToEdit); - FileWriter writer = new FileWriter(file); - writer.write(json); - writer.close(); - } - - public static void load() throws IOException { - // Declares file location - File file = new File("./config/partly-sane-skies/wordEditor.json"); - file.setWritable(true); - // If the file had to be created, fil it with an empty list to prevent null pointer error - if (file.createNewFile()) { - FileWriter writer = new FileWriter(file); - writer.write(new Gson().toJson(new String[][]{})); - writer.close(); - } - - // Creates a new file reader - Reader reader = Files.newBufferedReader(Paths.get(file.getPath())); - - wordsToEdit = new Gson().fromJson(reader, String[][].class); - } -} diff --git a/src/main/java/me/partlysanestudios/partlysaneskies/features/dungeons/party/PartyFriendManager.java b/src/main/java/me/partlysanestudios/partlysaneskies/features/dungeons/party/PartyFriendManager.java index 54685baec..b484a959d 100644 --- a/src/main/java/me/partlysanestudios/partlysaneskies/features/dungeons/party/PartyFriendManager.java +++ b/src/main/java/me/partlysanestudios/partlysaneskies/features/dungeons/party/PartyFriendManager.java @@ -7,9 +7,9 @@ import me.partlysanestudios.partlysaneskies.PartlySaneSkies; import me.partlysanestudios.partlysaneskies.commands.PSSCommand; +import me.partlysanestudios.partlysaneskies.events.SubscribePSSEvent; +import me.partlysanestudios.partlysaneskies.events.minecraft.PSSChatEvent; import me.partlysanestudios.partlysaneskies.utils.StringUtils; -import net.minecraftforge.client.event.ClientChatReceivedEvent; -import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import java.util.ArrayList; import java.util.List; @@ -28,13 +28,13 @@ public static void startPartyManager() { public static void registerCommand() { new PSSCommand("friendparty") - .addAlias("fp") - .addAlias("pf") - .setDescription("Parties all friends in the friend list") - .setRunnable(a -> { - PartyFriendManager.startPartyManager(); - }) - .register(); + .addAlias("fp") + .addAlias("pf") + .setDescription("Parties all friends in the friend list") + .setRunnable(a -> { + PartyFriendManager.startPartyManager(); + }) + .register(); } public static void partyAll() { @@ -57,15 +57,15 @@ public static void partyAll() { } } - @SubscribeEvent - public void getMembers(ClientChatReceivedEvent event) { + @SubscribePSSEvent + public void onChat(PSSChatEvent event) { if (!isWaitingForMembers) { return; } - if (event.message.getUnformattedText().startsWith("-----------------------------------------------------")) { + if (event.getComponent().getUnformattedText().startsWith("-----------------------------------------------------")) { isWaitingForMembers = false; } - String message = StringUtils.INSTANCE.removeColorCodes(event.message.getFormattedText()); + String message = StringUtils.INSTANCE.removeColorCodes(event.getMessage()); String[] rows = message.split("\n"); diff --git a/src/main/java/me/partlysanestudios/partlysaneskies/features/dungeons/party/partymanager/PartyManager.java b/src/main/java/me/partlysanestudios/partlysaneskies/features/dungeons/party/partymanager/PartyManager.java index f9f28b129..b31a1adcf 100644 --- a/src/main/java/me/partlysanestudios/partlysaneskies/features/dungeons/party/partymanager/PartyManager.java +++ b/src/main/java/me/partlysanestudios/partlysaneskies/features/dungeons/party/partymanager/PartyManager.java @@ -7,6 +7,8 @@ import me.partlysanestudios.partlysaneskies.PartlySaneSkies; import me.partlysanestudios.partlysaneskies.commands.PSSCommand; +import me.partlysanestudios.partlysaneskies.events.SubscribePSSEvent; +import me.partlysanestudios.partlysaneskies.events.minecraft.PSSChatEvent; import me.partlysanestudios.partlysaneskies.utils.ChatUtils; import me.partlysanestudios.partlysaneskies.utils.StringUtils; import net.minecraftforge.client.event.ClientChatReceivedEvent; @@ -59,13 +61,10 @@ public static void startPartyManager() { public static void registerCommand() { new PSSCommand("partymanager") - .addAlias("pm") - .addAlias("partym") - .setDescription("Opens the Party Manager") - .setRunnable(a -> { - PartyManager.startPartyManager(); - }) - .register(); + .addAlias("pm", "partypm") + .setDescription("Opens the Party Manager") + .setRunnable(a -> PartyManager.startPartyManager()) + .register(); } private static void processList(String str, PartyMember.PartyRank rank) { @@ -166,13 +165,13 @@ public static void reparty(List partyMembers) { } } - @SubscribeEvent - public void onMemberJoin(ClientChatReceivedEvent event) { + @SubscribePSSEvent + public void onChatMemberJoin(PSSChatEvent event) { if (!PartlySaneSkies.Companion.getConfig().getGetDataOnJoin()) { return; } - String unformattedMessage = event.message.getUnformattedText(); + String unformattedMessage = event.getComponent().getUnformattedText(); // If the message is not a join dungeon message if (!(unformattedMessage.startsWith("Party Finder >") || unformattedMessage.contains("joined the dungeon group!"))) { return; @@ -265,8 +264,8 @@ else if (event.message.getUnformattedText().startsWith("You are not currently in event.setCanceled(true); // Sends an error message ChatUtils.INSTANCE.sendClientMessage(("§9§m-----------------------------------------------------\n " + - "§r§cError: Could not run Party Manager." + - "\n§r§cYou are not currently in a party." + "§r§cError: Could not run Party Manager." + + "\n§r§cYou are not currently in a party." )); // Resets isMembersListed = false; diff --git a/src/main/java/me/partlysanestudios/partlysaneskies/features/dungeons/party/partymanager/PartyManagerGui.java b/src/main/java/me/partlysanestudios/partlysaneskies/features/dungeons/party/partymanager/PartyManagerGui.java index c98172ef0..99b8afc6f 100644 --- a/src/main/java/me/partlysanestudios/partlysaneskies/features/dungeons/party/partymanager/PartyManagerGui.java +++ b/src/main/java/me/partlysanestudios/partlysaneskies/features/dungeons/party/partymanager/PartyManagerGui.java @@ -8,8 +8,11 @@ import gg.essential.elementa.ElementaVersion; import gg.essential.elementa.UIComponent; import gg.essential.elementa.WindowScreen; +import gg.essential.elementa.components.ScrollComponent; +import gg.essential.elementa.components.UIBlock; +import gg.essential.elementa.components.UIText; +import gg.essential.elementa.components.UIWrappedText; import gg.essential.elementa.components.Window; -import gg.essential.elementa.components.*; import gg.essential.elementa.constraints.CenterConstraint; import gg.essential.elementa.constraints.PixelConstraint; import gg.essential.elementa.constraints.ScaleConstraint; @@ -17,9 +20,10 @@ import me.partlysanestudios.partlysaneskies.PartlySaneSkies; import me.partlysanestudios.partlysaneskies.features.themes.ThemeManager; import me.partlysanestudios.partlysaneskies.render.gui.components.PSSButton; +import me.partlysanestudios.partlysaneskies.render.gui.constraints.TextScaledPixelConstraint; import me.partlysanestudios.partlysaneskies.utils.ElementaUtils; -import java.awt.*; +import java.awt.Color; import java.net.MalformedURLException; import java.util.HashMap; import java.util.List; @@ -29,18 +33,18 @@ public class PartyManagerGui extends WindowScreen { // Creates the background UIComponent background = new UIBlock() - .setX(new CenterConstraint()) - .setY(new CenterConstraint()) - .setWidth(new PixelConstraint(getWindow().getWidth() * .9f)) - .setHeight(new PixelConstraint(getWindow().getHeight() * .9f)) - .setChildOf(getWindow()) - .setColor(new Color(0, 0, 0, 0)); + .setX(new CenterConstraint()) + .setY(new CenterConstraint()) + .setWidth(new PixelConstraint(getWindow().getWidth() * .9f)) + .setHeight(new PixelConstraint(getWindow().getHeight() * .9f)) + .setChildOf(getWindow()) + .setColor(new Color(0, 0, 0, 0)); // Creates the scrollable list UIComponent list = new ScrollComponent("", 0f, ThemeManager.INSTANCE.getPrimaryColor().toJavaColor(), false, true, false, false, 15f, 1f, null) - .setWidth(new PixelConstraint(background.getWidth())) - .setHeight(new PixelConstraint(background.getHeight())) - .setChildOf(background); + .setWidth(new PixelConstraint(background.getWidth())) + .setHeight(new PixelConstraint(background.getHeight())) + .setChildOf(background); UIWrappedText partyBreakdownComponent; List partyMembers; @@ -61,12 +65,12 @@ public void populateGui(List partyMembers) { float height = 180f * scaleFactor; // Creates the first top black UIComponent topBarBlock = new UIBlock() - .setWidth(new PixelConstraint(list.getWidth() - 20f)) - .setHeight(new ScaleConstraint(new PixelConstraint(150f), scaleFactor)) - .setColor(new Color(0, 0, 0, 0)) - .setX(new CenterConstraint()) - .setY(new PixelConstraint(10)) - .setChildOf(list); + .setWidth(new PixelConstraint(list.getWidth() - 20f)) + .setHeight(new ScaleConstraint(new PixelConstraint(150f), scaleFactor)) + .setColor(new Color(0, 0, 0, 0)) + .setX(new CenterConstraint()) + .setY(new PixelConstraint(10)) + .setChildOf(list); ElementaUtils.INSTANCE.applyBackground(topBarBlock); @@ -76,12 +80,12 @@ public void populateGui(List partyMembers) { for (PartyMember member : partyMembers) { UIComponent memberBlock = new UIBlock() - .setWidth(new PixelConstraint(list.getWidth() - 20f)) - .setHeight(new ScaleConstraint(new PixelConstraint(200f), scaleFactor)) - .setColor(new Color(0, 0, 0, 0)) - .setX(new CenterConstraint()) - .setY(new PixelConstraint(height)) - .setChildOf(list); + .setWidth(new PixelConstraint(list.getWidth() - 20f)) + .setHeight(new ScaleConstraint(new PixelConstraint(200f), scaleFactor)) + .setColor(new Color(0, 0, 0, 0)) + .setX(new CenterConstraint()) + .setY(new PixelConstraint(height)) + .setChildOf(list); ElementaUtils.INSTANCE.applyBackground(memberBlock); @@ -105,44 +109,44 @@ public void createPartyManagementButtons(UIComponent topBarBlock, float scaleFac List partyMembers) { new PSSButton(new Color(255, 0, 0)) - .setX(new PixelConstraint(10f * scaleFactor)) - .setY(new PixelConstraint(10f * scaleFactor)) - .setWidth(new PixelConstraint(75f * scaleFactor)) - .setHeight(new PixelConstraint(55f * scaleFactor)) - .setChildOf(topBarBlock) - .setText("Disband") - .setTextScale(new PixelConstraint(1.5f)) - .onMouseClickConsumer(event -> PartlySaneSkies.Companion.getMinecraft().thePlayer.sendChatMessage("/party disband")); + .setX(new PixelConstraint(10f * scaleFactor)) + .setY(new PixelConstraint(10f * scaleFactor)) + .setWidth(new PixelConstraint(75f * scaleFactor)) + .setHeight(new PixelConstraint(55f * scaleFactor)) + .setChildOf(topBarBlock) + .setText("Disband") + .setTextScale(new TextScaledPixelConstraint(1.5f)) + .onMouseClickConsumer(event -> PartlySaneSkies.Companion.getMinecraft().thePlayer.sendChatMessage("/party disband")); new PSSButton() - .setX(new PixelConstraint(95f * scaleFactor)) - .setY(new PixelConstraint(10 * scaleFactor)) - .setWidth(new PixelConstraint(75f * scaleFactor)) - .setHeight(new PixelConstraint(55f * scaleFactor)) - .setChildOf(topBarBlock) - .setText("Kick Offline") - .setTextScale(new PixelConstraint(1.25f)) - .onMouseClickConsumer(event -> PartlySaneSkies.Companion.getMinecraft().thePlayer.sendChatMessage("/party kickoffline")); + .setX(new PixelConstraint(95f * scaleFactor)) + .setY(new PixelConstraint(10 * scaleFactor)) + .setWidth(new PixelConstraint(75f * scaleFactor)) + .setHeight(new PixelConstraint(55f * scaleFactor)) + .setChildOf(topBarBlock) + .setText("Kick Offline") + .setTextScale(new TextScaledPixelConstraint(1.25f)) + .onMouseClickConsumer(event -> PartlySaneSkies.Companion.getMinecraft().thePlayer.sendChatMessage("/party kickoffline")); new PSSButton() - .setX(new PixelConstraint(205f * scaleFactor)) - .setY(new PixelConstraint(10 * scaleFactor)) - .setWidth(new PixelConstraint(100f * scaleFactor)) - .setHeight(new PixelConstraint(55f * scaleFactor)) - .setChildOf(topBarBlock) - .setText("Reparty") - .setTextScale(new PixelConstraint(1.5f)) - .onMouseClickConsumer(event -> PartyManager.reparty(partyMembers)); + .setX(new PixelConstraint(205f * scaleFactor)) + .setY(new PixelConstraint(10 * scaleFactor)) + .setWidth(new PixelConstraint(100f * scaleFactor)) + .setHeight(new PixelConstraint(55f * scaleFactor)) + .setChildOf(topBarBlock) + .setText("Reparty") + .setTextScale(new TextScaledPixelConstraint(1.5f)) + .onMouseClickConsumer(event -> PartyManager.reparty(partyMembers)); new PSSButton() - .setX(new PixelConstraint(315f * scaleFactor)) - .setY(new PixelConstraint(10 * scaleFactor)) - .setWidth(new PixelConstraint(100f * scaleFactor)) - .setHeight(new PixelConstraint(55f * scaleFactor)) - .setChildOf(topBarBlock) - .setText("Ask if ready") - .setTextScale(new PixelConstraint(1.25f)) - .onMouseClickConsumer(event -> PartlySaneSkies.Companion.getMinecraft().thePlayer.sendChatMessage("/pc Ready?")); + .setX(new PixelConstraint(315f * scaleFactor)) + .setY(new PixelConstraint(10 * scaleFactor)) + .setWidth(new PixelConstraint(100f * scaleFactor)) + .setHeight(new PixelConstraint(55f * scaleFactor)) + .setChildOf(topBarBlock) + .setText("Ask if ready") + .setTextScale(new TextScaledPixelConstraint(1.25f)) + .onMouseClickConsumer(event -> PartlySaneSkies.Companion.getMinecraft().thePlayer.sendChatMessage("/pc Ready?")); String partyBreakdown = "Party Size: " + partyMembers.size() + "\n"; @@ -156,11 +160,11 @@ public void createPartyManagementButtons(UIComponent topBarBlock, float scaleFac } partyBreakdownComponent = (UIWrappedText) new UIWrappedText("Party Size: " + partyMembers.size() + "\n") - .setTextScale(new PixelConstraint(1 * scaleFactor)) - .setX(new PixelConstraint(425f * scaleFactor)) - .setY(new PixelConstraint(10f * scaleFactor)) - .setColor(Color.white) - .setChildOf(topBarBlock); + .setTextScale(new TextScaledPixelConstraint(1)) + .setX(new PixelConstraint(425f * scaleFactor)) + .setY(new PixelConstraint(10f * scaleFactor)) + .setColor(Color.white) + .setChildOf(topBarBlock); updatePartyBreakdown(); } @@ -189,151 +193,151 @@ public void updatePartyBreakdown() { public void createJoinFloorButtons(UIComponent topBarBlock, float scaleFactor) { new UIText("Join Dungeon Floor:") - .setTextScale(new PixelConstraint(2 * scaleFactor)) - .setX(new PixelConstraint(20f * scaleFactor)) - .setY(new PixelConstraint(115f * scaleFactor)) - .setChildOf(topBarBlock); + .setTextScale(new TextScaledPixelConstraint(2)) + .setX(new PixelConstraint(20f * scaleFactor)) + .setY(new PixelConstraint(115f * scaleFactor)) + .setChildOf(topBarBlock); new PSSButton() - .setX(new PixelConstraint(265f * scaleFactor)) - .setY(new PixelConstraint(100 * scaleFactor)) - .setWidth(new PixelConstraint(35f * scaleFactor)) - .setHeight(new PixelConstraint(35f * scaleFactor)) - .setChildOf(topBarBlock) - .setText("F1") - .setTextScale(new PixelConstraint(scaleFactor)) - .onMouseClickConsumer(event -> PartlySaneSkies.Companion.getMinecraft().thePlayer.sendChatMessage("/joindungeon CATACOMBS_FLOOR_ONE")); + .setX(new PixelConstraint(265f * scaleFactor)) + .setY(new PixelConstraint(100 * scaleFactor)) + .setWidth(new PixelConstraint(35f * scaleFactor)) + .setHeight(new PixelConstraint(35f * scaleFactor)) + .setChildOf(topBarBlock) + .setText("F1") + .setTextScale(new TextScaledPixelConstraint(1)) + .onMouseClickConsumer(event -> PartlySaneSkies.Companion.getMinecraft().thePlayer.sendChatMessage("/joindungeon CATACOMBS_FLOOR_ONE")); new PSSButton() - .setX(new PixelConstraint(315f * scaleFactor)) - .setY(new PixelConstraint(100 * scaleFactor)) - .setWidth(new PixelConstraint(35f * scaleFactor)) - .setHeight(new PixelConstraint(35f * scaleFactor)) - .setChildOf(topBarBlock) - .setText("F2") - .setTextScale(new PixelConstraint(scaleFactor)) - .onMouseClickConsumer(event -> PartlySaneSkies.Companion.getMinecraft().thePlayer.sendChatMessage("/joindungeon CATACOMBS_FLOOR_TWO")); + .setX(new PixelConstraint(315f * scaleFactor)) + .setY(new PixelConstraint(100 * scaleFactor)) + .setWidth(new PixelConstraint(35f * scaleFactor)) + .setHeight(new PixelConstraint(35f * scaleFactor)) + .setChildOf(topBarBlock) + .setText("F2") + .setTextScale(new TextScaledPixelConstraint(1)) + .onMouseClickConsumer(event -> PartlySaneSkies.Companion.getMinecraft().thePlayer.sendChatMessage("/joindungeon CATACOMBS_FLOOR_TWO")); new PSSButton() - .setX(new PixelConstraint(365f * scaleFactor)) - .setY(new PixelConstraint(100 * scaleFactor)) - .setWidth(new PixelConstraint(35f * scaleFactor)) - .setHeight(new PixelConstraint(35f * scaleFactor)) - .setChildOf(topBarBlock) - .setText("F3") - .setTextScale(new PixelConstraint(scaleFactor)) - .onMouseClickConsumer(event -> PartlySaneSkies.Companion.getMinecraft().thePlayer.sendChatMessage("/joindungeon CATACOMBS_FLOOR_THREE")); + .setX(new PixelConstraint(365f * scaleFactor)) + .setY(new PixelConstraint(100 * scaleFactor)) + .setWidth(new PixelConstraint(35f * scaleFactor)) + .setHeight(new PixelConstraint(35f * scaleFactor)) + .setChildOf(topBarBlock) + .setText("F3") + .setTextScale(new TextScaledPixelConstraint(1)) + .onMouseClickConsumer(event -> PartlySaneSkies.Companion.getMinecraft().thePlayer.sendChatMessage("/joindungeon CATACOMBS_FLOOR_THREE")); new PSSButton() - .setX(new PixelConstraint(415f * scaleFactor)) - .setY(new PixelConstraint(100 * scaleFactor)) - .setWidth(new PixelConstraint(35f * scaleFactor)) - .setHeight(new PixelConstraint(35f * scaleFactor)) - .setChildOf(topBarBlock) - .setText("F4") - .setTextScale(new PixelConstraint(scaleFactor)) - .onMouseClickConsumer(event -> PartlySaneSkies.Companion.getMinecraft().thePlayer.sendChatMessage("/joindungeon CATACOMBS_FLOOR_FOUR")); + .setX(new PixelConstraint(415f * scaleFactor)) + .setY(new PixelConstraint(100 * scaleFactor)) + .setWidth(new PixelConstraint(35f * scaleFactor)) + .setHeight(new PixelConstraint(35f * scaleFactor)) + .setChildOf(topBarBlock) + .setText("F4") + .setTextScale(new TextScaledPixelConstraint(1)) + .onMouseClickConsumer(event -> PartlySaneSkies.Companion.getMinecraft().thePlayer.sendChatMessage("/joindungeon CATACOMBS_FLOOR_FOUR")); new PSSButton() - .setX(new PixelConstraint(465f * scaleFactor)) - .setY(new PixelConstraint(100 * scaleFactor)) - .setWidth(new PixelConstraint(35f * scaleFactor)) - .setHeight(new PixelConstraint(35f * scaleFactor)) - .setChildOf(topBarBlock) - .setText("F5") - .setTextScale(new PixelConstraint(scaleFactor)) - .onMouseClickConsumer(event -> PartlySaneSkies.Companion.getMinecraft().thePlayer.sendChatMessage("/joindungeon CATACOMBS_FLOOR_FIVE")); + .setX(new PixelConstraint(465f * scaleFactor)) + .setY(new PixelConstraint(100 * scaleFactor)) + .setWidth(new PixelConstraint(35f * scaleFactor)) + .setHeight(new PixelConstraint(35f * scaleFactor)) + .setChildOf(topBarBlock) + .setText("F5") + .setTextScale(new TextScaledPixelConstraint(1)) + .onMouseClickConsumer(event -> PartlySaneSkies.Companion.getMinecraft().thePlayer.sendChatMessage("/joindungeon CATACOMBS_FLOOR_FIVE")); new PSSButton() - .setX(new PixelConstraint(515f * scaleFactor)) - .setY(new PixelConstraint(100 * scaleFactor)) - .setWidth(new PixelConstraint(35f * scaleFactor)) - .setHeight(new PixelConstraint(35f * scaleFactor)) - .setChildOf(topBarBlock) - .setText("F6") - .setTextScale(new PixelConstraint(scaleFactor)) - .onMouseClickConsumer(event -> PartlySaneSkies.Companion.getMinecraft().thePlayer.sendChatMessage("/joindungeon CATACOMBS_FLOOR_SIX")); + .setX(new PixelConstraint(515f * scaleFactor)) + .setY(new PixelConstraint(100 * scaleFactor)) + .setWidth(new PixelConstraint(35f * scaleFactor)) + .setHeight(new PixelConstraint(35f * scaleFactor)) + .setChildOf(topBarBlock) + .setText("F6") + .setTextScale(new TextScaledPixelConstraint(1)) + .onMouseClickConsumer(event -> PartlySaneSkies.Companion.getMinecraft().thePlayer.sendChatMessage("/joindungeon CATACOMBS_FLOOR_SIX")); new PSSButton() - .setX(new PixelConstraint(565f * scaleFactor)) - .setY(new PixelConstraint(100 * scaleFactor)) - .setWidth(new PixelConstraint(35f * scaleFactor)) - .setHeight(new PixelConstraint(35f * scaleFactor)) - .setChildOf(topBarBlock) - .setText("F7") - .setTextScale(new PixelConstraint(scaleFactor)) - .onMouseClickConsumer(event -> PartlySaneSkies.Companion.getMinecraft().thePlayer.sendChatMessage("/joindungeon CATACOMBS_FLOOR_SEVEN")); + .setX(new PixelConstraint(565f * scaleFactor)) + .setY(new PixelConstraint(100 * scaleFactor)) + .setWidth(new PixelConstraint(35f * scaleFactor)) + .setHeight(new PixelConstraint(35f * scaleFactor)) + .setChildOf(topBarBlock) + .setText("F7") + .setTextScale(new TextScaledPixelConstraint(1)) + .onMouseClickConsumer(event -> PartlySaneSkies.Companion.getMinecraft().thePlayer.sendChatMessage("/joindungeon CATACOMBS_FLOOR_SEVEN")); new PSSButton() - .setX(new PixelConstraint(615f * scaleFactor)) - .setY(new PixelConstraint(100 * scaleFactor)) - .setWidth(new PixelConstraint(35f * scaleFactor)) - .setHeight(new PixelConstraint(35f * scaleFactor)) - .setChildOf(topBarBlock) - .setText("M1") - .setTextScale(new PixelConstraint(scaleFactor)) - .onMouseClickConsumer(event -> PartlySaneSkies.Companion.getMinecraft().thePlayer.sendChatMessage("/joindungeon MASTER_CATACOMBS_FLOOR_ONE")); + .setX(new PixelConstraint(615f * scaleFactor)) + .setY(new PixelConstraint(100 * scaleFactor)) + .setWidth(new PixelConstraint(35f * scaleFactor)) + .setHeight(new PixelConstraint(35f * scaleFactor)) + .setChildOf(topBarBlock) + .setText("M1") + .setTextScale(new TextScaledPixelConstraint(1)) + .onMouseClickConsumer(event -> PartlySaneSkies.Companion.getMinecraft().thePlayer.sendChatMessage("/joindungeon MASTER_CATACOMBS_FLOOR_ONE")); new PSSButton() - .setX(new PixelConstraint(665f * scaleFactor)) - .setY(new PixelConstraint(100 * scaleFactor)) - .setWidth(new PixelConstraint(35f * scaleFactor)) - .setHeight(new PixelConstraint(35f * scaleFactor)) - .setChildOf(topBarBlock) - .setText("M2") - .setTextScale(new PixelConstraint(scaleFactor)) - .onMouseClickConsumer(event -> PartlySaneSkies.Companion.getMinecraft().thePlayer.sendChatMessage("/joindungeon MASTER_CATACOMBS_FLOOR_TWO")); + .setX(new PixelConstraint(665f * scaleFactor)) + .setY(new PixelConstraint(100 * scaleFactor)) + .setWidth(new PixelConstraint(35f * scaleFactor)) + .setHeight(new PixelConstraint(35f * scaleFactor)) + .setChildOf(topBarBlock) + .setText("M2") + .setTextScale(new TextScaledPixelConstraint(1)) + .onMouseClickConsumer(event -> PartlySaneSkies.Companion.getMinecraft().thePlayer.sendChatMessage("/joindungeon MASTER_CATACOMBS_FLOOR_TWO")); new PSSButton() - .setX(new PixelConstraint(715f * scaleFactor)) - .setY(new PixelConstraint(100 * scaleFactor)) - .setWidth(new PixelConstraint(35f * scaleFactor)) - .setHeight(new PixelConstraint(35f * scaleFactor)) - .setChildOf(topBarBlock) - .setText("M3") - .setTextScale(new PixelConstraint(scaleFactor)) - .onMouseClickConsumer(event -> PartlySaneSkies.Companion.getMinecraft().thePlayer.sendChatMessage("/joindungeon MASTER_CATACOMBS_FLOOR_THREE")); + .setX(new PixelConstraint(715f * scaleFactor)) + .setY(new PixelConstraint(100 * scaleFactor)) + .setWidth(new PixelConstraint(35f * scaleFactor)) + .setHeight(new PixelConstraint(35f * scaleFactor)) + .setChildOf(topBarBlock) + .setText("M3") + .setTextScale(new TextScaledPixelConstraint(1)) + .onMouseClickConsumer(event -> PartlySaneSkies.Companion.getMinecraft().thePlayer.sendChatMessage("/joindungeon MASTER_CATACOMBS_FLOOR_THREE")); new PSSButton() - .setX(new PixelConstraint(765f * scaleFactor)) - .setY(new PixelConstraint(100 * scaleFactor)) - .setWidth(new PixelConstraint(35f * scaleFactor)) - .setHeight(new PixelConstraint(35f * scaleFactor)) - .setChildOf(topBarBlock) - .setText("M4") - .setTextScale(new PixelConstraint(scaleFactor)) - .onMouseClickConsumer(event -> PartlySaneSkies.Companion.getMinecraft().thePlayer.sendChatMessage("/joindungeon MASTER_CATACOMBS_FLOOR_FOUR")); + .setX(new PixelConstraint(765f * scaleFactor)) + .setY(new PixelConstraint(100 * scaleFactor)) + .setWidth(new PixelConstraint(35f * scaleFactor)) + .setHeight(new PixelConstraint(35f * scaleFactor)) + .setChildOf(topBarBlock) + .setText("M4") + .setTextScale(new TextScaledPixelConstraint(1)) + .onMouseClickConsumer(event -> PartlySaneSkies.Companion.getMinecraft().thePlayer.sendChatMessage("/joindungeon MASTER_CATACOMBS_FLOOR_FOUR")); new PSSButton() - .setX(new PixelConstraint(815f * scaleFactor)) - .setY(new PixelConstraint(100 * scaleFactor)) - .setWidth(new PixelConstraint(35f * scaleFactor)) - .setHeight(new PixelConstraint(35f * scaleFactor)) - .setChildOf(topBarBlock) - .setText("M5") - .setTextScale(new PixelConstraint(scaleFactor)) - .onMouseClickConsumer(event -> PartlySaneSkies.Companion.getMinecraft().thePlayer.sendChatMessage("/joindungeon MASTER_CATACOMBS_FLOOR_FIVE")); + .setX(new PixelConstraint(815f * scaleFactor)) + .setY(new PixelConstraint(100 * scaleFactor)) + .setWidth(new PixelConstraint(35f * scaleFactor)) + .setHeight(new PixelConstraint(35f * scaleFactor)) + .setChildOf(topBarBlock) + .setText("M5") + .setTextScale(new TextScaledPixelConstraint(1)) + .onMouseClickConsumer(event -> PartlySaneSkies.Companion.getMinecraft().thePlayer.sendChatMessage("/joindungeon MASTER_CATACOMBS_FLOOR_FIVE")); new PSSButton() - .setX(new PixelConstraint(865f * scaleFactor)) - .setY(new PixelConstraint(100 * scaleFactor)) - .setWidth(new PixelConstraint(35f * scaleFactor)) - .setHeight(new PixelConstraint(35f * scaleFactor)) - .setChildOf(topBarBlock) - .setText("M6") - .setTextScale(new PixelConstraint(scaleFactor)) - .onMouseClickConsumer(event -> PartlySaneSkies.Companion.getMinecraft().thePlayer.sendChatMessage("/joindungeon MASTER_CATACOMBS_FLOOR_SIX")); + .setX(new PixelConstraint(865f * scaleFactor)) + .setY(new PixelConstraint(100 * scaleFactor)) + .setWidth(new PixelConstraint(35f * scaleFactor)) + .setHeight(new PixelConstraint(35f * scaleFactor)) + .setChildOf(topBarBlock) + .setText("M6") + .setTextScale(new TextScaledPixelConstraint(1)) + .onMouseClickConsumer(event -> PartlySaneSkies.Companion.getMinecraft().thePlayer.sendChatMessage("/joindungeon MASTER_CATACOMBS_FLOOR_SIX")); new PSSButton() - .setX(new PixelConstraint(915f * scaleFactor)) - .setY(new PixelConstraint(100 * scaleFactor)) - .setWidth(new PixelConstraint(35f * scaleFactor)) - .setHeight(new PixelConstraint(35f * scaleFactor)) - .setChildOf(topBarBlock) - .setText("M7") - .setTextScale(new PixelConstraint(scaleFactor)) - .onMouseClickConsumer(event -> PartlySaneSkies.Companion.getMinecraft().thePlayer.sendChatMessage("/joindungeon MASTER_CATACOMBS_FLOOR_SEVEN")); + .setX(new PixelConstraint(915f * scaleFactor)) + .setY(new PixelConstraint(100 * scaleFactor)) + .setWidth(new PixelConstraint(35f * scaleFactor)) + .setHeight(new PixelConstraint(35f * scaleFactor)) + .setChildOf(topBarBlock) + .setText("M7") + .setTextScale(new TextScaledPixelConstraint(1)) + .onMouseClickConsumer(event -> PartlySaneSkies.Companion.getMinecraft().thePlayer.sendChatMessage("/joindungeon MASTER_CATACOMBS_FLOOR_SEVEN")); } } diff --git a/src/main/java/me/partlysanestudios/partlysaneskies/features/dungeons/party/partymanager/PartyMember.java b/src/main/java/me/partlysanestudios/partlysaneskies/features/dungeons/party/partymanager/PartyMember.java index 322dc72cd..407745c25 100644 --- a/src/main/java/me/partlysanestudios/partlysaneskies/features/dungeons/party/partymanager/PartyMember.java +++ b/src/main/java/me/partlysanestudios/partlysaneskies/features/dungeons/party/partymanager/PartyMember.java @@ -15,12 +15,13 @@ import me.partlysanestudios.partlysaneskies.data.skyblockdata.SkyblockDataManager; import me.partlysanestudios.partlysaneskies.data.skyblockdata.SkyblockPlayer; import me.partlysanestudios.partlysaneskies.render.gui.components.PSSButton; +import me.partlysanestudios.partlysaneskies.render.gui.constraints.TextScaledPixelConstraint; import me.partlysanestudios.partlysaneskies.utils.ElementaUtils; import me.partlysanestudios.partlysaneskies.utils.MathUtils; import me.partlysanestudios.partlysaneskies.utils.StringUtils; import net.minecraft.util.ResourceLocation; -import java.awt.*; +import java.awt.Color; import java.net.MalformedURLException; public class PartyMember { @@ -60,6 +61,7 @@ public class PartyMember { public double intelligence; public double effectHealth; SkyblockPlayer player; + // Creates a new party member based on the username and partyRank public PartyMember(String username, PartyRank partyRank) { this.username = username; @@ -155,19 +157,19 @@ public void populateData() throws MalformedURLException { public void createBlock(UIComponent memberBlock, float scaleFactor, PartyManagerGui partyManagerGui) { // Name plate new UIText(this.username) - .setTextScale(new PixelConstraint(3f * scaleFactor)) - .setX(new PixelConstraint(20f * scaleFactor)) - .setY(new PixelConstraint(20f * scaleFactor)) - .setColor(Color.white) - .setChildOf(memberBlock); + .setTextScale(new TextScaledPixelConstraint(3f)) + .setX(new PixelConstraint(20f * scaleFactor)) + .setY(new PixelConstraint(20f * scaleFactor)) + .setColor(Color.white) + .setChildOf(memberBlock); new UIText(this.selectedDungeonClass) - .setTextScale(new PixelConstraint(scaleFactor)) - .setX(new PixelConstraint(150f * scaleFactor)) - .setY(new PixelConstraint(50f * scaleFactor)) - .setColor(Color.white) - .setChildOf(memberBlock); + .setTextScale(new TextScaledPixelConstraint(1)) + .setX(new PixelConstraint(150f * scaleFactor)) + .setY(new PixelConstraint(50f * scaleFactor)) + .setColor(Color.white) + .setChildOf(memberBlock); createMemberBlockColumnOne(memberBlock, scaleFactor); createMemberBlockColumnTwo(memberBlock, scaleFactor); createMemberBlockColumnThree(memberBlock, scaleFactor); @@ -179,76 +181,76 @@ public void createBlock(UIComponent memberBlock, float scaleFactor, PartyManager private void createMemberBlockColumnOne(UIComponent memberBlock, float scaleFactor) { new UIText("Catacombs Level: " + StringUtils.INSTANCE.formatNumber(MathUtils.INSTANCE.round(this.catacombsLevel, 2))) - .setTextScale((new PixelConstraint(1.333f * scaleFactor))) - .setX(new PixelConstraint(20f * scaleFactor)) - .setY(new PixelConstraint(135f * scaleFactor)) - .setColor(StringUtils.INSTANCE.colorCodeToColor("§c")) - .setChildOf(memberBlock); + .setTextScale((new TextScaledPixelConstraint(1.333f))) + .setX(new PixelConstraint(20f * scaleFactor)) + .setY(new PixelConstraint(135f * scaleFactor)) + .setColor(StringUtils.INSTANCE.colorCodeToColor("§c")) + .setChildOf(memberBlock); new UIText("Average Skill Level " + StringUtils.INSTANCE.formatNumber(MathUtils.INSTANCE.round(this.averageSkillLevel, 2))) - .setTextScale((new PixelConstraint(1.333f * scaleFactor))) - .setX(new PixelConstraint(20f * scaleFactor)) - .setY(new PixelConstraint(150f * scaleFactor)) - .setColor(Color.white) - .setChildOf(memberBlock); + .setTextScale((new TextScaledPixelConstraint(1.333f))) + .setX(new PixelConstraint(20f * scaleFactor)) + .setY(new PixelConstraint(150f * scaleFactor)) + .setColor(Color.white) + .setChildOf(memberBlock); new UIText("Combat Level: " + StringUtils.INSTANCE.formatNumber(MathUtils.INSTANCE.round(this.combatLevel, 2))) - .setTextScale((new PixelConstraint(1.333f * scaleFactor))) - .setX(new PixelConstraint(20f * scaleFactor)) - .setY(new PixelConstraint(165f * scaleFactor)) - .setColor(Color.white) - .setChildOf(memberBlock); + .setTextScale((new TextScaledPixelConstraint(1.333f))) + .setX(new PixelConstraint(20f * scaleFactor)) + .setY(new PixelConstraint(165f * scaleFactor)) + .setColor(Color.white) + .setChildOf(memberBlock); } private void createMemberBlockColumnTwo(UIComponent memberBlock, float scaleFactor) { new UIText("Secrets: " + StringUtils.INSTANCE.formatNumber(this.secretCount)) - .setTextScale((new PixelConstraint(1.333f * scaleFactor))) - .setX(new PixelConstraint(150f * scaleFactor)) - .setY(new PixelConstraint(74f * scaleFactor)) - .setColor(Color.white) - .setChildOf(memberBlock); + .setTextScale((new TextScaledPixelConstraint(1.333f))) + .setX(new PixelConstraint(150f * scaleFactor)) + .setY(new PixelConstraint(74f * scaleFactor)) + .setColor(Color.white) + .setChildOf(memberBlock); new UIText("Secrets Per Run: " + StringUtils.INSTANCE.formatNumber(MathUtils.INSTANCE.round(this.secretsPerRun, 2))) - .setTextScale((new PixelConstraint(1.333f * scaleFactor))) - .setX(new PixelConstraint(150f * scaleFactor)) - .setY(new PixelConstraint(90f * scaleFactor)) - .setColor(Color.white) - .setChildOf(memberBlock); + .setTextScale((new TextScaledPixelConstraint(1.333f))) + .setX(new PixelConstraint(150f * scaleFactor)) + .setY(new PixelConstraint(90f * scaleFactor)) + .setColor(Color.white) + .setChildOf(memberBlock); new UIText("SkyBlock Level: " + MathUtils.INSTANCE.round(this.skyblockLevel, 1)) - .setTextScale(new PixelConstraint(scaleFactor)) - .setX(new PixelConstraint(20f * scaleFactor)) - .setY(new PixelConstraint(50f * scaleFactor)) - .setColor(Color.white) - .setChildOf(memberBlock); + .setTextScale(new TextScaledPixelConstraint(1)) + .setX(new PixelConstraint(20f * scaleFactor)) + .setY(new PixelConstraint(50f * scaleFactor)) + .setColor(Color.white) + .setChildOf(memberBlock); new UIText("❤ " + StringUtils.INSTANCE.formatNumber(Math.round(this.health))) - .setTextScale((new PixelConstraint(1.333f * scaleFactor))) - .setX(new PixelConstraint(20f * scaleFactor)) - .setY(new PixelConstraint(75f * scaleFactor)) - .setColor(StringUtils.INSTANCE.colorCodeToColor("§c")) - .setChildOf(memberBlock); + .setTextScale((new TextScaledPixelConstraint(1.333f))) + .setX(new PixelConstraint(20f * scaleFactor)) + .setY(new PixelConstraint(75f * scaleFactor)) + .setColor(StringUtils.INSTANCE.colorCodeToColor("§c")) + .setChildOf(memberBlock); new UIText("❈ " + StringUtils.INSTANCE.formatNumber(Math.round(this.defense))) - .setTextScale((new PixelConstraint(1.333f * scaleFactor))) - .setX(new PixelConstraint(20f * scaleFactor)) - .setY(new PixelConstraint(90f * scaleFactor)) - .setColor(StringUtils.INSTANCE.colorCodeToColor("§a")) - .setChildOf(memberBlock); + .setTextScale((new TextScaledPixelConstraint(1.333f))) + .setX(new PixelConstraint(20f * scaleFactor)) + .setY(new PixelConstraint(90f * scaleFactor)) + .setColor(StringUtils.INSTANCE.colorCodeToColor("§a")) + .setChildOf(memberBlock); new UIText("EHP: " + StringUtils.INSTANCE.formatNumber(Math.round(this.effectHealth))) - .setTextScale((new PixelConstraint(1.3f * scaleFactor))) - .setX(new PixelConstraint(20f * scaleFactor)) - .setY(new PixelConstraint(105f * scaleFactor)) - .setColor(new Color(45, 133, 48)) - .setChildOf(memberBlock); + .setTextScale((new TextScaledPixelConstraint(1.3f))) + .setX(new PixelConstraint(20f * scaleFactor)) + .setY(new PixelConstraint(105f * scaleFactor)) + .setColor(new Color(45, 133, 48)) + .setChildOf(memberBlock); new UIText("✎ " + StringUtils.INSTANCE.formatNumber(Math.round(this.intelligence))) - .setTextScale((new PixelConstraint(1.333f * scaleFactor))) - .setX(new PixelConstraint(20f * scaleFactor)) - .setY(new PixelConstraint(120f * scaleFactor)) - .setColor(StringUtils.INSTANCE.colorCodeToColor("§b")) - .setChildOf(memberBlock); + .setTextScale((new TextScaledPixelConstraint(1.333f))) + .setX(new PixelConstraint(20f * scaleFactor)) + .setY(new PixelConstraint(120f * scaleFactor)) + .setColor(StringUtils.INSTANCE.colorCodeToColor("§b")) + .setChildOf(memberBlock); } @@ -268,151 +270,151 @@ public Color colorFloorRuns(int floorRuns) { private void createMemberBlockColumnThree(UIComponent memberBlock, float scaleFactor) { new UIText("Runs:") - .setTextScale(new PixelConstraint(2.5f * scaleFactor)) - .setX(new PixelConstraint(390f * scaleFactor)) - .setY(new PixelConstraint(20f * scaleFactor)) - .setColor(Color.white) - .setChildOf(memberBlock); + .setTextScale(new TextScaledPixelConstraint(2.5f)) + .setX(new PixelConstraint(390f * scaleFactor)) + .setY(new PixelConstraint(20f * scaleFactor)) + .setColor(Color.white) + .setChildOf(memberBlock); // TODO: please for the love of god automate this whenever you rewrite this code new UIText("Floor 1: " + StringUtils.INSTANCE.formatNumber(this.f1Runs)) - .setTextScale(new PixelConstraint(1.3f * scaleFactor)) - .setX(new PixelConstraint(340f * scaleFactor)) - .setY(new PixelConstraint(50f * scaleFactor)) - .setColor(colorFloorRuns(this.f1Runs)) - .setChildOf(memberBlock); + .setTextScale(new TextScaledPixelConstraint(1.3f)) + .setX(new PixelConstraint(340f * scaleFactor)) + .setY(new PixelConstraint(50f * scaleFactor)) + .setColor(colorFloorRuns(this.f1Runs)) + .setChildOf(memberBlock); new UIText("Floor 2: " + StringUtils.INSTANCE.formatNumber(this.f2Runs)) - .setTextScale(new PixelConstraint(1.3f * scaleFactor)) - .setX(new PixelConstraint(340f * scaleFactor)) - .setY(new PixelConstraint(70f * scaleFactor)) - .setColor(colorFloorRuns(this.f2Runs)) - .setChildOf(memberBlock); + .setTextScale(new TextScaledPixelConstraint(1.3f)) + .setX(new PixelConstraint(340f * scaleFactor)) + .setY(new PixelConstraint(70f * scaleFactor)) + .setColor(colorFloorRuns(this.f2Runs)) + .setChildOf(memberBlock); new UIText("Floor 3: " + StringUtils.INSTANCE.formatNumber(this.f3Runs)) - .setTextScale(new PixelConstraint(1.3f * scaleFactor)) - .setX(new PixelConstraint(340f * scaleFactor)) - .setY(new PixelConstraint(90f * scaleFactor)) - .setColor(colorFloorRuns(this.f3Runs)) - .setChildOf(memberBlock); + .setTextScale(new TextScaledPixelConstraint(1.3f)) + .setX(new PixelConstraint(340f * scaleFactor)) + .setY(new PixelConstraint(90f * scaleFactor)) + .setColor(colorFloorRuns(this.f3Runs)) + .setChildOf(memberBlock); new UIText("Floor 4: " + StringUtils.INSTANCE.formatNumber(this.f4Runs)) - .setTextScale(new PixelConstraint(1.3f * scaleFactor)) - .setX(new PixelConstraint(340f * scaleFactor)) - .setY(new PixelConstraint(110f * scaleFactor)) - .setColor(colorFloorRuns(this.f4Runs)) - .setChildOf(memberBlock); + .setTextScale(new TextScaledPixelConstraint(1.3f)) + .setX(new PixelConstraint(340f * scaleFactor)) + .setY(new PixelConstraint(110f * scaleFactor)) + .setColor(colorFloorRuns(this.f4Runs)) + .setChildOf(memberBlock); new UIText("Floor 5: " + StringUtils.INSTANCE.formatNumber(this.f5Runs)) - .setTextScale(new PixelConstraint(1.3f * scaleFactor)) - .setX(new PixelConstraint(340f * scaleFactor)) - .setY(new PixelConstraint(130f * scaleFactor)) - .setColor(colorFloorRuns(this.f5Runs)) - .setChildOf(memberBlock); + .setTextScale(new TextScaledPixelConstraint(1.3f)) + .setX(new PixelConstraint(340f * scaleFactor)) + .setY(new PixelConstraint(130f * scaleFactor)) + .setColor(colorFloorRuns(this.f5Runs)) + .setChildOf(memberBlock); new UIText("Floor 6: " + StringUtils.INSTANCE.formatNumber(this.f6Runs)) - .setTextScale(new PixelConstraint(1.3f * scaleFactor)) - .setX(new PixelConstraint(340f * scaleFactor)) - .setY(new PixelConstraint(150f * scaleFactor)) - .setColor(colorFloorRuns(this.f6Runs)) - .setChildOf(memberBlock); + .setTextScale(new TextScaledPixelConstraint(1.3f)) + .setX(new PixelConstraint(340f * scaleFactor)) + .setY(new PixelConstraint(150f * scaleFactor)) + .setColor(colorFloorRuns(this.f6Runs)) + .setChildOf(memberBlock); new UIText("Floor 7: " + StringUtils.INSTANCE.formatNumber(this.f7Runs)) - .setTextScale(new PixelConstraint(1.3f * scaleFactor)) - .setX(new PixelConstraint(340f * scaleFactor)) - .setY(new PixelConstraint(170f * scaleFactor)) - .setColor(colorFloorRuns(this.f7Runs)) - .setChildOf(memberBlock); + .setTextScale(new TextScaledPixelConstraint(1.3f)) + .setX(new PixelConstraint(340f * scaleFactor)) + .setY(new PixelConstraint(170f * scaleFactor)) + .setColor(colorFloorRuns(this.f7Runs)) + .setChildOf(memberBlock); new UIText("Master 1: " + StringUtils.INSTANCE.formatNumber(this.m1Runs)) - .setTextScale(new PixelConstraint(1.3f * scaleFactor)) - .setX(new PixelConstraint(460f * scaleFactor)) - .setY(new PixelConstraint(50f * scaleFactor)) - .setColor(colorFloorRuns(this.m1Runs)) - .setChildOf(memberBlock); + .setTextScale(new TextScaledPixelConstraint(1.3f)) + .setX(new PixelConstraint(460f * scaleFactor)) + .setY(new PixelConstraint(50f * scaleFactor)) + .setColor(colorFloorRuns(this.m1Runs)) + .setChildOf(memberBlock); new UIText("Master 2: " + StringUtils.INSTANCE.formatNumber(this.m2Runs)) - .setTextScale(new PixelConstraint(1.3f * scaleFactor)) - .setX(new PixelConstraint(460f * scaleFactor)) - .setY(new PixelConstraint(70f * scaleFactor)) - .setColor(colorFloorRuns(this.m2Runs)) - .setChildOf(memberBlock); + .setTextScale(new TextScaledPixelConstraint(1.3f)) + .setX(new PixelConstraint(460f * scaleFactor)) + .setY(new PixelConstraint(70f * scaleFactor)) + .setColor(colorFloorRuns(this.m2Runs)) + .setChildOf(memberBlock); new UIText("Master 3: " + StringUtils.INSTANCE.formatNumber(this.m3Runs)) - .setTextScale(new PixelConstraint(1.3f * scaleFactor)) - .setX(new PixelConstraint(460f * scaleFactor)) - .setY(new PixelConstraint(90f * scaleFactor)) - .setColor(colorFloorRuns(this.m3Runs)) - .setChildOf(memberBlock); + .setTextScale(new TextScaledPixelConstraint(1.3f)) + .setX(new PixelConstraint(460f * scaleFactor)) + .setY(new PixelConstraint(90f * scaleFactor)) + .setColor(colorFloorRuns(this.m3Runs)) + .setChildOf(memberBlock); new UIText("Master 4: " + StringUtils.INSTANCE.formatNumber(this.m4Runs)) - .setTextScale(new PixelConstraint(1.3f * scaleFactor)) - .setX(new PixelConstraint(460f * scaleFactor)) - .setY(new PixelConstraint(110f * scaleFactor)) - .setColor(colorFloorRuns(this.m4Runs)) - .setChildOf(memberBlock); + .setTextScale(new TextScaledPixelConstraint(1.3f)) + .setX(new PixelConstraint(460f * scaleFactor)) + .setY(new PixelConstraint(110f * scaleFactor)) + .setColor(colorFloorRuns(this.m4Runs)) + .setChildOf(memberBlock); new UIText("Master 5: " + StringUtils.INSTANCE.formatNumber(this.m5Runs)) - .setTextScale(new PixelConstraint(1.3f * scaleFactor)) - .setX(new PixelConstraint(460f * scaleFactor)) - .setY(new PixelConstraint(130f * scaleFactor)) - .setColor(colorFloorRuns(this.m5Runs)) - .setChildOf(memberBlock); + .setTextScale(new TextScaledPixelConstraint(1.3f)) + .setX(new PixelConstraint(460f * scaleFactor)) + .setY(new PixelConstraint(130f * scaleFactor)) + .setColor(colorFloorRuns(this.m5Runs)) + .setChildOf(memberBlock); new UIText("Master 6: " + StringUtils.INSTANCE.formatNumber(this.m6Runs)) - .setTextScale(new PixelConstraint(1.3f * scaleFactor)) - .setX(new PixelConstraint(460f * scaleFactor)) - .setY(new PixelConstraint(150f * scaleFactor)) - .setColor(colorFloorRuns(this.m6Runs)) - .setChildOf(memberBlock); + .setTextScale(new TextScaledPixelConstraint(1.3f)) + .setX(new PixelConstraint(460f * scaleFactor)) + .setY(new PixelConstraint(150f * scaleFactor)) + .setColor(colorFloorRuns(this.m6Runs)) + .setChildOf(memberBlock); new UIText("Master 7: " + StringUtils.INSTANCE.formatNumber(this.m7Runs)) - .setTextScale(new PixelConstraint(1.3f * scaleFactor)) - .setX(new PixelConstraint(460f * scaleFactor)) - .setY(new PixelConstraint(170f * scaleFactor)) - .setColor(colorFloorRuns(this.m7Runs)) - .setChildOf(memberBlock); + .setTextScale(new TextScaledPixelConstraint(1.3f)) + .setX(new PixelConstraint(460f * scaleFactor)) + .setY(new PixelConstraint(170f * scaleFactor)) + .setColor(colorFloorRuns(this.m7Runs)) + .setChildOf(memberBlock); } private void createMemberBlockColumnFour(UIComponent memberBlock, float scaleFactor) { new UIText("Gear:") - .setTextScale(new PixelConstraint(2.5f * scaleFactor)) - .setX(new PixelConstraint(580f * scaleFactor)) - .setY(new PixelConstraint(20f * scaleFactor)) - .setColor(Color.white) - .setChildOf(memberBlock); + .setTextScale(new TextScaledPixelConstraint(2.5f)) + .setX(new PixelConstraint(580f * scaleFactor)) + .setY(new PixelConstraint(20f * scaleFactor)) + .setColor(Color.white) + .setChildOf(memberBlock); new UIWrappedText(this.helmetName) - .setTextScale(new PixelConstraint(1.15f * scaleFactor)) - .setWidth(new PixelConstraint(200 * scaleFactor)) - .setX(new PixelConstraint(580f * scaleFactor)) - .setY(new PixelConstraint(50f * scaleFactor)) - .setColor(Color.white) - .setChildOf(memberBlock); + .setTextScale(new TextScaledPixelConstraint(1.15f)) + .setWidth(new PixelConstraint(200 * scaleFactor)) + .setX(new PixelConstraint(580f * scaleFactor)) + .setY(new PixelConstraint(50f * scaleFactor)) + .setColor(Color.white) + .setChildOf(memberBlock); new UIWrappedText(this.chestplateName) - .setTextScale(new PixelConstraint(1.15f * scaleFactor)) - .setWidth(new PixelConstraint(200 * scaleFactor)) - .setX(new PixelConstraint(580f * scaleFactor)) - .setY(new PixelConstraint(85f * scaleFactor)) - .setColor(Color.white) - .setChildOf(memberBlock); + .setTextScale(new TextScaledPixelConstraint(1.15f)) + .setWidth(new PixelConstraint(200 * scaleFactor)) + .setX(new PixelConstraint(580f * scaleFactor)) + .setY(new PixelConstraint(85f * scaleFactor)) + .setColor(Color.white) + .setChildOf(memberBlock); new UIWrappedText(this.leggingsName) - .setTextScale(new PixelConstraint(1.15f * scaleFactor)) - .setWidth(new PixelConstraint(200 * scaleFactor)) - .setX(new PixelConstraint(580f * scaleFactor)) - .setY(new PixelConstraint(120f * scaleFactor)) - .setColor(Color.white) - .setChildOf(memberBlock); + .setTextScale(new TextScaledPixelConstraint(1.15f)) + .setWidth(new PixelConstraint(200 * scaleFactor)) + .setX(new PixelConstraint(580f * scaleFactor)) + .setY(new PixelConstraint(120f * scaleFactor)) + .setColor(Color.white) + .setChildOf(memberBlock); new UIWrappedText(this.bootsName) - .setTextScale(new PixelConstraint(1.15f * scaleFactor)) - .setWidth(new PixelConstraint(200 * scaleFactor)) - .setX(new PixelConstraint(580f * scaleFactor)) - .setY(new PixelConstraint(155f * scaleFactor)) - .setColor(Color.white) - .setChildOf(memberBlock); + .setTextScale(new TextScaledPixelConstraint(1.15f)) + .setWidth(new PixelConstraint(200 * scaleFactor)) + .setX(new PixelConstraint(580f * scaleFactor)) + .setY(new PixelConstraint(155f * scaleFactor)) + .setColor(Color.white) + .setChildOf(memberBlock); Color arrowWarningColor = Color.white; if (this.arrowCount < PartlySaneSkies.Companion.getConfig().getArrowLowCount()) { @@ -425,58 +427,58 @@ private void createMemberBlockColumnFour(UIComponent memberBlock, float scaleFac } } new UIText("Arrows Remaining: " + this.arrowCountString) - .setTextScale(new PixelConstraint(1.15f * scaleFactor)) - .setX(new PixelConstraint(580f * scaleFactor)) - .setY(new PixelConstraint(190f * scaleFactor)) - .setColor(arrowWarningColor) - .setChildOf(memberBlock); + .setTextScale(new TextScaledPixelConstraint(1.15f)) + .setX(new PixelConstraint(580f * scaleFactor)) + .setY(new PixelConstraint(190f * scaleFactor)) + .setColor(arrowWarningColor) + .setChildOf(memberBlock); } private void createMemberBlockColumnFive(UIComponent memberBlock, float scaleFactor) { new PSSButton() - .setX(new PixelConstraint(800 * scaleFactor)) - .setY(new PixelConstraint(15 * scaleFactor)) - .setWidth(new PixelConstraint(125f * scaleFactor)) - .setHeight(new PixelConstraint(55f * scaleFactor)) - .setChildOf(memberBlock) - .setText("Kick") - .setTextScale(new PixelConstraint(scaleFactor)) - .onMouseClickConsumer(event -> PartlySaneSkies.Companion.getMinecraft().thePlayer.sendChatMessage("/party kick " + this.username)); + .setX(new PixelConstraint(800 * scaleFactor)) + .setY(new PixelConstraint(15 * scaleFactor)) + .setWidth(new PixelConstraint(125f * scaleFactor)) + .setHeight(new PixelConstraint(55f * scaleFactor)) + .setChildOf(memberBlock) + .setText("Kick") + .setTextScale(new TextScaledPixelConstraint(1)) + .onMouseClickConsumer(event -> PartlySaneSkies.Companion.getMinecraft().thePlayer.sendChatMessage("/party kick " + this.username)); new PSSButton() - .setX(new PixelConstraint(800 * scaleFactor)) - .setY(new PixelConstraint(75 * scaleFactor)) - .setWidth(new PixelConstraint(125f * scaleFactor)) - .setHeight(new PixelConstraint(55f * scaleFactor)) - .setChildOf(memberBlock) - .setText("Promote") - .setTextScale(new PixelConstraint(scaleFactor)) - .onMouseClickConsumer(event -> PartlySaneSkies.Companion.getMinecraft().thePlayer.sendChatMessage("/party promote " + this.username)); + .setX(new PixelConstraint(800 * scaleFactor)) + .setY(new PixelConstraint(75 * scaleFactor)) + .setWidth(new PixelConstraint(125f * scaleFactor)) + .setHeight(new PixelConstraint(55f * scaleFactor)) + .setChildOf(memberBlock) + .setText("Promote") + .setTextScale(new TextScaledPixelConstraint(1)) + .onMouseClickConsumer(event -> PartlySaneSkies.Companion.getMinecraft().thePlayer.sendChatMessage("/party promote " + this.username)); new PSSButton() - .setX(new PixelConstraint(800 * scaleFactor)) - .setY(new PixelConstraint(135 * scaleFactor)) - .setWidth(new PixelConstraint(125f * scaleFactor)) - .setHeight(new PixelConstraint(55f * scaleFactor)) - .setChildOf(memberBlock) - .setText("Transfer") - .setTextScale(new PixelConstraint(scaleFactor)) - .onMouseClickConsumer(event -> PartlySaneSkies.Companion.getMinecraft().thePlayer.sendChatMessage("/party transfer " + this.username)); + .setX(new PixelConstraint(800 * scaleFactor)) + .setY(new PixelConstraint(135 * scaleFactor)) + .setWidth(new PixelConstraint(125f * scaleFactor)) + .setHeight(new PixelConstraint(55f * scaleFactor)) + .setChildOf(memberBlock) + .setText("Transfer") + .setTextScale(new TextScaledPixelConstraint(1)) + .onMouseClickConsumer(event -> PartlySaneSkies.Companion.getMinecraft().thePlayer.sendChatMessage("/party transfer " + this.username)); UIComponent refreshButton = new UIRoundedRectangle(10f) - .setX(new PixelConstraint(memberBlock.getWidth() - 30f * scaleFactor)) - .setY(new PixelConstraint(10f * scaleFactor)) - .setWidth(new PixelConstraint(20f * scaleFactor)) - .setHeight(new PixelConstraint(20f * scaleFactor)) - .setColor(new Color(60, 222, 79)) - .setChildOf(memberBlock); + .setX(new PixelConstraint(memberBlock.getWidth() - 30f * scaleFactor)) + .setY(new PixelConstraint(10f * scaleFactor)) + .setWidth(new PixelConstraint(20f * scaleFactor)) + .setHeight(new PixelConstraint(20f * scaleFactor)) + .setColor(new Color(60, 222, 79)) + .setChildOf(memberBlock); ElementaUtils.INSTANCE.getUiImage(new ResourceLocation("partlysaneskies", "textures/gui/party_finder/refresh.png")) - .setX(new CenterConstraint()) - .setY(new CenterConstraint()) - .setWidth(new PixelConstraint(20f * scaleFactor)) - .setHeight(new PixelConstraint(20f * scaleFactor)) - .setChildOf(refreshButton); + .setX(new CenterConstraint()) + .setY(new CenterConstraint()) + .setWidth(new PixelConstraint(20f * scaleFactor)) + .setHeight(new PixelConstraint(20f * scaleFactor)) + .setChildOf(refreshButton); refreshButton.onMouseClickConsumer(event -> { player.setLastUpdateTime(0); diff --git a/src/main/java/me/partlysanestudios/partlysaneskies/features/dungeons/party/permpartyselector/PermPartyManager.java b/src/main/java/me/partlysanestudios/partlysaneskies/features/dungeons/party/permpartyselector/PermPartyManager.java index 4bbffe54f..d178c3b85 100644 --- a/src/main/java/me/partlysanestudios/partlysaneskies/features/dungeons/party/permpartyselector/PermPartyManager.java +++ b/src/main/java/me/partlysanestudios/partlysaneskies/features/dungeons/party/permpartyselector/PermPartyManager.java @@ -5,7 +5,12 @@ package me.partlysanestudios.partlysaneskies.features.dungeons.party.permpartyselector; -import com.google.gson.*; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; import me.partlysanestudios.partlysaneskies.commands.PSSCommand; import me.partlysanestudios.partlysaneskies.utils.ChatUtils; @@ -15,7 +20,11 @@ import java.io.Reader; import java.nio.file.Files; import java.nio.file.Paths; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import java.util.Map.Entry; public class PermPartyManager { @@ -67,131 +76,130 @@ public static void load() throws IOException { public static void registerCommand() { new PSSCommand("permparty") - .addAlias("pp") - .addAlias("permp") - .setDescription("Operates the perm party manager: /permparty [/add/remove/list/delete/new/fav]") - .setRunnable(args -> { - if (args.length == 0) { - ChatUtils.INSTANCE.sendClientMessage( - ( - "§3/pp \n§7Parties everyone in the perm party." + - "\n§3/pp add \n§7Adds a player to the perm party." + - "\n§3/pp list {partyid}\n§7Lists all of the members in a given party. If no party is specified, lists all perm parties." - + - "\n§3/pp delete \n§7Deletes a perm party. (Note: There is no way to undo this action)." - + - "\n§3/pp new {partymembers}\n§7Creates a new perm party." + - "\n§3/pp fav {partyid}\n§7Sets party as favorite. If no party is specified, parties everyone in the favorite perm party.")); - } else if (args[0].equalsIgnoreCase("add")) { - if (args.length == 3) { - if (PermPartyManager.permPartyMap.containsKey(args[1])) { - PermParty party = PermPartyManager.permPartyMap.get(args[1]); - party.addMember(args[2]); - PermPartyManager.permPartyMap.put(party.name, party); - ChatUtils.INSTANCE.sendClientMessage(("Added player " + args[2] + " to party " + args[1] + ".")); - } else { - ChatUtils.INSTANCE.sendClientMessage(("§cNo party was found with the ID " + args[1] - + ".\n§cCorrect usage: /pp add \n§7Adds a player to the perm party.")); - } + .addAlias("pp", "permp") + .setDescription("Operates the perm party manager: /permparty [/add/remove/list/delete/new/fav]") + .setRunnable(args -> { + if (args.length == 0) { + ChatUtils.INSTANCE.sendClientMessage( + ( + "§3/pp \n§7Parties everyone in the perm party." + + "\n§3/pp add \n§7Adds a player to the perm party." + + "\n§3/pp list {partyid}\n§7Lists all of the members in a given party. If no party is specified, lists all perm parties." + + + "\n§3/pp delete \n§7Deletes a perm party. (Note: There is no way to undo this action)." + + + "\n§3/pp new {partymembers}\n§7Creates a new perm party." + + "\n§3/pp fav {partyid}\n§7Sets party as favorite. If no party is specified, parties everyone in the favorite perm party.")); + } else if (args[0].equalsIgnoreCase("add")) { + if (args.length == 3) { + if (PermPartyManager.permPartyMap.containsKey(args[1])) { + PermParty party = PermPartyManager.permPartyMap.get(args[1]); + party.addMember(args[2]); + PermPartyManager.permPartyMap.put(party.name, party); + ChatUtils.INSTANCE.sendClientMessage(("Added player " + args[2] + " to party " + args[1] + ".")); } else { - ChatUtils.INSTANCE.sendClientMessage(( - "§cCorrect usage: /pp add \n§7Adds a player to the perm party.")); + ChatUtils.INSTANCE.sendClientMessage(("§cNo party was found with the ID " + args[1] + + ".\n§cCorrect usage: /pp add \n§7Adds a player to the perm party.")); } + } else { + ChatUtils.INSTANCE.sendClientMessage(( + "§cCorrect usage: /pp add \n§7Adds a player to the perm party.")); } + } - // Remove arg - else if (args[0].equalsIgnoreCase("remove")) { - if (args.length == 3) { - if (PermPartyManager.permPartyMap.containsKey(args[1])) { - - PermParty party = PermPartyManager.permPartyMap.get(args[1]); - if (party.partyMembers.contains(args[2])) { - party.removeMember(args[2]); - PermPartyManager.permPartyMap.put(party.name, party); - ChatUtils.INSTANCE.sendClientMessage("Removed member " + args[2] + " from party " + args[1] + "."); - } else { - ChatUtils.INSTANCE.sendClientMessage(("§cNo player was found with the name " + args[2] - + ".\n§cCorrect usage: /pp remove \n§7Removes a player from the perm party.")); - } + // Remove arg + else if (args[0].equalsIgnoreCase("remove")) { + if (args.length == 3) { + if (PermPartyManager.permPartyMap.containsKey(args[1])) { + PermParty party = PermPartyManager.permPartyMap.get(args[1]); + if (party.partyMembers.contains(args[2])) { + party.removeMember(args[2]); + PermPartyManager.permPartyMap.put(party.name, party); + ChatUtils.INSTANCE.sendClientMessage("Removed member " + args[2] + " from party " + args[1] + "."); } else { - ChatUtils.INSTANCE.sendClientMessage(("§cNo party was found with the ID " + args[1] - + ".\n§cCorrect usage: /pp remove \n§7Removes a player from the perm party.")); + ChatUtils.INSTANCE.sendClientMessage(("§cNo player was found with the name " + args[2] + + ".\n§cCorrect usage: /pp remove \n§7Removes a player from the perm party.")); } + } else { - ChatUtils.INSTANCE.sendClientMessage(( - "§cCorrect usage: /pp remove \n§7Removes a player from the perm party.")); + ChatUtils.INSTANCE.sendClientMessage(("§cNo party was found with the ID " + args[1] + + ".\n§cCorrect usage: /pp remove \n§7Removes a player from the perm party.")); } + } else { + ChatUtils.INSTANCE.sendClientMessage(( + "§cCorrect usage: /pp remove \n§7Removes a player from the perm party.")); } + } - // List arg - else if (args[0].equalsIgnoreCase("list")) { - if (args.length == 1) { - for (PermParty party : PermPartyManager.permPartyMap.values()) { - ChatUtils.INSTANCE.sendClientMessage(party.name + " | Members: " + party.getMemberString()); - } - } else { - if (PermPartyManager.permPartyMap.containsKey(args[1])) { - PermParty party = PermPartyManager.permPartyMap.get(args[0]); - ChatUtils.INSTANCE.sendClientMessage(party.name + " | Members: " + party.getMemberString()); - } else { - ChatUtils.INSTANCE.sendClientMessage(("§cNo party was found with the ID " + args[1] - + ".\n§cCorrect usage: /pp list {partyid}\n§7Lists all of the members in a given party. If no party is specified, lists all parties.")); - } + // List arg + else if (args[0].equalsIgnoreCase("list")) { + if (args.length == 1) { + for (PermParty party : PermPartyManager.permPartyMap.values()) { + ChatUtils.INSTANCE.sendClientMessage(party.name + " | Members: " + party.getMemberString()); } - } else if (args[0].equalsIgnoreCase("delete")) { - if (args.length == 2) { - if (PermPartyManager.permPartyMap.containsKey(args[1])) { - PermPartyManager.deleteParty(args[1]); - ChatUtils.INSTANCE.sendClientMessage("Deleted party " + args[1] + "."); - } else { - ChatUtils.INSTANCE.sendClientMessage(("§cNo party was found with the ID " + args[1] - + ".\n§cCorrect usage: /pp delete \n§7Deletes a perm party. (Note: There is no way to undo this action).")); - } + } else { + if (PermPartyManager.permPartyMap.containsKey(args[1])) { + PermParty party = PermPartyManager.permPartyMap.get(args[0]); + ChatUtils.INSTANCE.sendClientMessage(party.name + " | Members: " + party.getMemberString()); } else { - ChatUtils.INSTANCE.sendClientMessage(( - "§cCorrect usage: /pp delete \n§7Deletes a perm party. (Note: There is no way to undo this action).")); + ChatUtils.INSTANCE.sendClientMessage(("§cNo party was found with the ID " + args[1] + + ".\n§cCorrect usage: /pp list {partyid}\n§7Lists all of the members in a given party. If no party is specified, lists all parties.")); } - } else if (args[0].equalsIgnoreCase("new")) { - if (args.length >= 2) { - List partyMembers = new ArrayList<>(); - partyMembers.addAll(Arrays.asList(args).subList(2, args.length)); - PermPartyManager.addParty(args[1], partyMembers); - - ChatUtils.INSTANCE.sendClientMessage("Created party " + args[1] + "."); + } + } else if (args[0].equalsIgnoreCase("delete")) { + if (args.length == 2) { + if (PermPartyManager.permPartyMap.containsKey(args[1])) { + PermPartyManager.deleteParty(args[1]); + ChatUtils.INSTANCE.sendClientMessage("Deleted party " + args[1] + "."); } else { - ChatUtils.INSTANCE.sendClientMessage(("§cCorrect usage: /pp new {partymembers}\n§7Creates a new perm party.")); + ChatUtils.INSTANCE.sendClientMessage(("§cNo party was found with the ID " + args[1] + + ".\n§cCorrect usage: /pp delete \n§7Deletes a perm party. (Note: There is no way to undo this action).")); } - } else if (args[0].equalsIgnoreCase("fav")) { - if (args.length == 2) { - if (PermPartyManager.permPartyMap.containsKey(args[1])) { - PermPartyManager.favoriteParty(args[1]); - ChatUtils.INSTANCE.sendClientMessage("Set " + args[1] + " to your favorite."); - } else { - ChatUtils.INSTANCE.sendClientMessage(("§cNo party was found with the ID " + args[1] - + ".\n§cCorrect usage: /pp fav {partyid}\n§7Sets party as favorite. If no party is specified, parties everyone in the favorite perm party.")); - } - } else { - if (PermPartyManager.favoriteParty != null) { - PermParty party = PermPartyManager.favoriteParty; - party.partyAll(); - } else { - ChatUtils.INSTANCE.sendClientMessage(( - "§cCorrect usage: /pp fav {partyid}\n§7Sets party as favorite. If no party is specified, parties everyone in the favorite perm party.")); - } + } else { + ChatUtils.INSTANCE.sendClientMessage(( + "§cCorrect usage: /pp delete \n§7Deletes a perm party. (Note: There is no way to undo this action).")); + } + } else if (args[0].equalsIgnoreCase("new")) { + if (args.length >= 2) { + List partyMembers = new ArrayList<>(); + partyMembers.addAll(Arrays.asList(args).subList(2, args.length)); + PermPartyManager.addParty(args[1], partyMembers); + ChatUtils.INSTANCE.sendClientMessage("Created party " + args[1] + "."); + } else { + ChatUtils.INSTANCE.sendClientMessage(("§cCorrect usage: /pp new {partymembers}\n§7Creates a new perm party.")); + } + } else if (args[0].equalsIgnoreCase("fav")) { + if (args.length == 2) { + if (PermPartyManager.permPartyMap.containsKey(args[1])) { + PermPartyManager.favoriteParty(args[1]); + ChatUtils.INSTANCE.sendClientMessage("Set " + args[1] + " to your favorite."); + } else { + ChatUtils.INSTANCE.sendClientMessage(("§cNo party was found with the ID " + args[1] + + ".\n§cCorrect usage: /pp fav {partyid}\n§7Sets party as favorite. If no party is specified, parties everyone in the favorite perm party.")); } } else { - if (PermPartyManager.permPartyMap.containsKey(args[0])) { - PermParty party = PermPartyManager.permPartyMap.get(args[0]); + if (PermPartyManager.favoriteParty != null) { + PermParty party = PermPartyManager.favoriteParty; party.partyAll(); } else { - ChatUtils.INSTANCE.sendClientMessage( - ("§cCorrect usage: /pp \n§7Parties everyone in a party.")); + ChatUtils.INSTANCE.sendClientMessage(( + "§cCorrect usage: /pp fav {partyid}\n§7Sets party as favorite. If no party is specified, parties everyone in the favorite perm party.")); } + + } + } else { + if (PermPartyManager.permPartyMap.containsKey(args[0])) { + PermParty party = PermPartyManager.permPartyMap.get(args[0]); + party.partyAll(); + } else { + ChatUtils.INSTANCE.sendClientMessage( + ("§cCorrect usage: /pp \n§7Parties everyone in a party.")); } - }) - .register(); + } + }) + .register(); } // Saves all the party member data to a json file @@ -200,9 +208,9 @@ public static void save() throws IOException { File file = new File("./config/partly-sane-skies/permPartyData.json"); // Creates a new Gson object to save the data Gson gson = new GsonBuilder() - .setPrettyPrinting() - .serializeSpecialFloatingPointValues() - .create(); + .setPrettyPrinting() + .serializeSpecialFloatingPointValues() + .create(); // Saves teh data to the file String json = gson.toJson(permPartyMap); FileWriter writer = new FileWriter(file); diff --git a/src/main/java/me/partlysanestudios/partlysaneskies/features/mining/MiningEvents.java b/src/main/java/me/partlysanestudios/partlysaneskies/features/mining/MiningEvents.java deleted file mode 100644 index 18d28e7f2..000000000 --- a/src/main/java/me/partlysanestudios/partlysaneskies/features/mining/MiningEvents.java +++ /dev/null @@ -1,200 +0,0 @@ -// -// Written by J10a1n15. -// See LICENSE for copyright and license notices. -// -// Time spend afking in the mines: ~4h -// - -package me.partlysanestudios.partlysaneskies.features.mining; - -import me.partlysanestudios.partlysaneskies.PartlySaneSkies; -import me.partlysanestudios.partlysaneskies.render.gui.hud.BannerRenderer; -import me.partlysanestudios.partlysaneskies.render.gui.hud.PSSBanner; -import me.partlysanestudios.partlysaneskies.system.SystemNotification; -import net.minecraftforge.client.event.ClientChatReceivedEvent; -import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; -import org.lwjgl.opengl.Display; - -public class MiningEvents { - // TODO: lmao this needs a rewrite - // I was almost gonna convert to kt and then I realized I would have to rewrite it - private static boolean showBanner = false; - - @SubscribeEvent - public void onChat(ClientChatReceivedEvent event) { - if (!PartlySaneSkies.Companion.getConfig().getMiningEventsToggle()) return; - - String displayText = ""; - - String message = event.message.getFormattedText(); - - // 2x Powder - if (message.contains("The §b2x Powder §eevent starts in §a20 §eseconds!") && PartlySaneSkies.Companion.getConfig().getMining2xPowderSound() && PartlySaneSkies.Companion.getConfig().getMiningWarn20sBeforeEvent()) { - showBanner = true; - PartlySaneSkies.Companion.getMinecraft().thePlayer.playSound("partlysaneskies:bell", 100, 1); - if (PartlySaneSkies.Companion.getConfig().getMiningShowEventBanner()) displayText = "2x Powder Event in 20s!"; - if (PartlySaneSkies.Companion.getConfig().getMiningSendSystemNotifications() && !Display.isActive()) SystemNotification.INSTANCE.showNotification("2x Powder Event in 20s!"); - } - - if (message.contains("§l2X POWDER STARTED!") && PartlySaneSkies.Companion.getConfig().getMining2xPowderSound()) { - showBanner = true; - PartlySaneSkies.Companion.getMinecraft().thePlayer.playSound("partlysaneskies:bell", 100, 1); - if (PartlySaneSkies.Companion.getConfig().getMiningShowEventBanner()) displayText = "2x Powder Event Started!"; - if (PartlySaneSkies.Companion.getConfig().getMiningSendSystemNotifications() && !Display.isActive()) SystemNotification.INSTANCE.showNotification("2x Powder Event Started!"); - } - - // Gone with the wind - if (message.contains("The §9Gone with the Wind §eevent starts in §a20 §eseconds!") && PartlySaneSkies.Companion.getConfig().getMiningGoneWithTheWindSound() && PartlySaneSkies.Companion.getConfig().getMiningWarn20sBeforeEvent()) { - showBanner = true; - PartlySaneSkies.Companion.getMinecraft().thePlayer.playSound("partlysaneskies:bell", 100, 1); - if (PartlySaneSkies.Companion.getConfig().getMiningShowEventBanner()) displayText = "Gone with the Wind Event in 20s!"; - if (PartlySaneSkies.Companion.getConfig().getMiningSendSystemNotifications() && !Display.isActive()) SystemNotification.INSTANCE.showNotification("Gone with the Wind Event in 20s!"); - } - - if (message.contains("§r§9§lGONE WITH THE WIND STARTED!") && PartlySaneSkies.Companion.getConfig().getMiningGoneWithTheWindSound()) { - showBanner = true; - PartlySaneSkies.Companion.getMinecraft().thePlayer.playSound("partlysaneskies:bell", 100, 1); - if (PartlySaneSkies.Companion.getConfig().getMiningShowEventBanner()) displayText = "Gone with the Wind Event Started!"; - if (PartlySaneSkies.Companion.getConfig().getMiningSendSystemNotifications() && !Display.isActive()) SystemNotification.INSTANCE.showNotification("Gone with the Wind Event Started!"); - } - - // Better Together - if (message.contains("The §dBetter Together §eevent starts in §a20 §eseconds!") && PartlySaneSkies.Companion.getConfig().getMiningBetterTogetherSound() && PartlySaneSkies.Companion.getConfig().getMiningWarn20sBeforeEvent()) { - showBanner = true; - PartlySaneSkies.Companion.getMinecraft().thePlayer.playSound("partlysaneskies:bell", 100, 1); - if (PartlySaneSkies.Companion.getConfig().getMiningShowEventBanner()) displayText = "Better Together Event in 20s!"; - if (PartlySaneSkies.Companion.getConfig().getMiningSendSystemNotifications() && !Display.isActive()) SystemNotification.INSTANCE.showNotification("Better Together Event in 20s!"); - } - - if (message.contains("§r§d§lBETTER TOGETHER STARTED!") && PartlySaneSkies.Companion.getConfig().getMiningBetterTogetherSound()) { - showBanner = true; - PartlySaneSkies.Companion.getMinecraft().thePlayer.playSound("partlysaneskies:bell", 100, 1); - if (PartlySaneSkies.Companion.getConfig().getMiningShowEventBanner()) displayText = "Better Together Event Started!"; - if (PartlySaneSkies.Companion.getConfig().getMiningSendSystemNotifications() && !Display.isActive()) SystemNotification.INSTANCE.showNotification("Better Together Event Started!"); - } - - // Goblin Raid - if (message.contains("§eThe §cGoblin Raid §eevent starts in §a20 §eseconds!") && PartlySaneSkies.Companion.getConfig().getMiningGoblinRaidSound() && PartlySaneSkies.Companion.getConfig().getMiningWarn20sBeforeEvent()) { - showBanner = true; - PartlySaneSkies.Companion.getMinecraft().thePlayer.playSound("partlysaneskies:bell", 100, 1); - if (PartlySaneSkies.Companion.getConfig().getMiningShowEventBanner()) displayText = "Goblin Raid Event in 20s!"; - if (PartlySaneSkies.Companion.getConfig().getMiningSendSystemNotifications() && !Display.isActive()) SystemNotification.INSTANCE.showNotification("Goblin Raid Event in 20s!"); - } - - if (message.contains("§r§c§lGOBLIN RAID STARTED!") && PartlySaneSkies.Companion.getConfig().getMiningGoblinRaidSound()) { - showBanner = true; - PartlySaneSkies.Companion.getMinecraft().thePlayer.playSound("partlysaneskies:bell", 100, 1); - if (PartlySaneSkies.Companion.getConfig().getMiningShowEventBanner()) displayText = "Goblin Raid Event Started!"; - if (PartlySaneSkies.Companion.getConfig().getMiningSendSystemNotifications() && !Display.isActive()) SystemNotification.INSTANCE.showNotification("Goblin Raid Event Started!"); - } - - // Raffle - if (message.contains("The §6Raffle §eevent starts in §a20 §eseconds!") && PartlySaneSkies.Companion.getConfig().getMiningRaffleSound() && PartlySaneSkies.Companion.getConfig().getMiningWarn20sBeforeEvent()) { - showBanner = true; - PartlySaneSkies.Companion.getMinecraft().thePlayer.playSound("partlysaneskies:bell", 100, 1); - if (PartlySaneSkies.Companion.getConfig().getMiningShowEventBanner()) displayText = "Raffle Event in 20s!"; - if (PartlySaneSkies.Companion.getConfig().getMiningSendSystemNotifications() && !Display.isActive()) SystemNotification.INSTANCE.showNotification("Raffle Event in 20s!"); - } - - if (message.contains("§r§6§lRAFFLE STARTED!") && PartlySaneSkies.Companion.getConfig().getMiningRaffleSound()) { - showBanner = true; - PartlySaneSkies.Companion.getMinecraft().thePlayer.playSound("partlysaneskies:bell", 100, 1); - if (PartlySaneSkies.Companion.getConfig().getMiningShowEventBanner()) displayText = "Raffle Event Started!"; - if (PartlySaneSkies.Companion.getConfig().getMiningSendSystemNotifications() && !Display.isActive()) SystemNotification.INSTANCE.showNotification("Raffle Event Started!"); - } - - // Gourmand - if (message.contains("§eThe §bMithril Gourmand §eevent starts in §a20 §eseconds!") && PartlySaneSkies.Companion.getConfig().getMiningMithrilGourmandSound() && PartlySaneSkies.Companion.getConfig().getMiningWarn20sBeforeEvent()){ - showBanner = true; - PartlySaneSkies.Companion.getMinecraft().thePlayer.playSound("partlysaneskies:bell", 100, 1); - if (PartlySaneSkies.Companion.getConfig().getMiningShowEventBanner()) displayText = "Mithril Gourmand Event in 20s!"; - if (PartlySaneSkies.Companion.getConfig().getMiningSendSystemNotifications() && !Display.isActive()) SystemNotification.INSTANCE.showNotification("Mithril Gourmand Event in 20s!"); - } - - if (message.contains("§r§b§lMITHRIL GOURMAND STARTED!") && PartlySaneSkies.Companion.getConfig().getMiningMithrilGourmandSound()){ - showBanner = true; - PartlySaneSkies.Companion.getMinecraft().thePlayer.playSound("partlysaneskies:bell", 100, 1); - if (PartlySaneSkies.Companion.getConfig().getMiningShowEventBanner()) displayText = "Mithril Gourmand Event Started!"; - if (PartlySaneSkies.Companion.getConfig().getMiningSendSystemNotifications() && !Display.isActive()) SystemNotification.INSTANCE.showNotification("Mithril Gourmand Event Started!"); - } - - // Powder Ghast - if (message.contains("§6The sound of pickaxes clashing against the rock has attracted the attention of the §r§6§lPOWDER GHAST!") && PartlySaneSkies.Companion.getConfig().getMiningPowderGhastSound()){ - showBanner = true; - PartlySaneSkies.Companion.getMinecraft().thePlayer.playSound("partlysaneskies:bell", 100, 1); - if (PartlySaneSkies.Companion.getConfig().getMiningShowEventBanner()) displayText = "Powder Ghast Spawned!"; - if (PartlySaneSkies.Companion.getConfig().getMiningSendSystemNotifications() && !Display.isActive()) SystemNotification.INSTANCE.showNotification("Powder Ghast Spawned!"); - } - - // Fallen Star - if (message.contains("§eA §r§5Fallen Star §r§ehas crashed at") && PartlySaneSkies.Companion.getConfig().getMiningFallenStarSound()){ - showBanner = true; - PartlySaneSkies.Companion.getMinecraft().thePlayer.playSound("partlysaneskies:bell", 100, 1); - if (PartlySaneSkies.Companion.getConfig().getMiningShowEventBanner()) displayText = "Fallen Star Spawned!"; - if (PartlySaneSkies.Companion.getConfig().getMiningSendSystemNotifications() && !Display.isActive()) SystemNotification.INSTANCE.showNotification("Fallen Star Spawned!"); - } - - if (showBanner) { - BannerRenderer.INSTANCE.renderNewBanner(new PSSBanner(displayText, (long) (PartlySaneSkies.Companion.getConfig().getMiningEventBannerTime() * 1000), 4.0f, PartlySaneSkies.Companion.getConfig().getMiningEventBannerColor().toJavaColor())); - } - showBanner = false; - } -} - -/* ALL THE MINING EVENTS RELATED MESSAGES - - **MAJOR EVENTS** - - 2x POWDER - §b⚑ §eThe §b2x Powder §eevent starts in §a20 §eseconds! - §eThis is a passive event! §bIt's happening everywhere in the §bCrystal Hollows!§r - - §r§r§r §r§b§l2X POWDER STARTED!§r - - - WIND - §9⚑ §eThe §9Gone with the Wind §eevent starts in §a20 §eseconds! - §eThis is a passive event! §bIt's happening everywhere in the §bCrystal Hollows!§r - - §r§r§r §r§9§lGONE WITH THE WIND STARTED!§r - - - BETTER TOGETHER - §d⚑ §eThe §dBetter Together §eevent starts in §a20 §eseconds! - §eThis is a passive event! §bIt's happening everywhere in the §bCrystal Hollows!§r - - §r§r§r §r§d§lBETTER TOGETHER STARTED!§r - - - RAID - §c⚑ §eThe §cGoblin Raid §eevent starts in §a20 §eseconds! - §aClick here §eto teleport to §bGarry §eand prepare!§r - - §r§r§r §r§c§lGOBLIN RAID STARTED!§r - - - RAFFLE - §6⚑ §eThe §6Raffle §eevent starts in §a20 §eseconds! - §aClick here §eto teleport to §bGarry §eand prepare!§r - - §r§r§r §r§6§lRAFFLE STARTED!§r - - - GOURMAND - §b⚑ §eThe §bMithril Gourmand §eevent starts in §a20 §eseconds! - §aClick here §eto teleport to §bGarry §eand prepare!§r - - §r§r§r §r§b§lMITHRIL GOURMAND STARTED!§r - - - **MINOR EVENTS** - - POWDER GHAST - §r§6The sound of pickaxes clashing against the rock has attracted the attention of the §r§6§lPOWDER GHAST!§r - §r§eFind the §r§6Powder Ghast§r§e near the §r§bCliffside Veins§r§e!§r - - - FALLEN STAR - §r§5§l✯ §r§eA §r§5Fallen Star §r§ehas crashed at §r§bRoyal Mines§r§e! Nearby ore and Powder drops are amplified!§r - - */ \ No newline at end of file diff --git a/src/main/java/me/partlysanestudios/partlysaneskies/features/skills/SkillUpgradeRecommendation.java b/src/main/java/me/partlysanestudios/partlysaneskies/features/skills/SkillUpgradeRecommendation.java deleted file mode 100644 index ec865faa1..000000000 --- a/src/main/java/me/partlysanestudios/partlysaneskies/features/skills/SkillUpgradeRecommendation.java +++ /dev/null @@ -1,234 +0,0 @@ -// -// Written by Su386. -// See LICENSE for copyright and license notices. -// - -package me.partlysanestudios.partlysaneskies.features.skills; - -import me.partlysanestudios.partlysaneskies.PartlySaneSkies; -import me.partlysanestudios.partlysaneskies.commands.PSSCommand; -import me.partlysanestudios.partlysaneskies.data.skyblockdata.SkyblockDataManager; -import me.partlysanestudios.partlysaneskies.data.skyblockdata.SkyblockPlayer; -import me.partlysanestudios.partlysaneskies.utils.ChatUtils; -import me.partlysanestudios.partlysaneskies.utils.MathUtils; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Map.Entry; - -import static java.util.Comparator.naturalOrder; - -public class SkillUpgradeRecommendation { - - private static final HashMap weightConstants = new HashMap<>(); - - public static LinkedHashMap getRecommendedSkills(String username) throws IOException { - HashMap map = new HashMap<>(); - - SkyblockPlayer player = SkyblockDataManager.INSTANCE.getPlayer(username); - - for (String skill : weightConstants.keySet()) { - if (getSkillLevel(skill, player) == SkyblockDataManager.INSTANCE.getSkill(skill.toUpperCase()).getMaxLevel()) { - continue; - } - - double level = getSkillLevel(skill, player); - - // If the level is under 5, all levels have equals importance - if (level < 5) { - map.put(skill, 100000d); - continue; - } - - double score = calculateScore(skill, player); - map.put(skill, score); - } - - double catacombsLevel = player.getCatacombsLevel(); - - double maxCatacombsLevel = 50; - - if (catacombsLevel < maxCatacombsLevel) { - if (catacombsLevel < 5) { - map.put("catacombs", 100000d); - } else { - map.put("catacombs", (maxCatacombsLevel - catacombsLevel) / (calculateCatacombsWeight(catacombsLevel) - - calculateCatacombsWeight(Math.ceil(catacombsLevel))) * 1.10 + 10); - } - } - - return sortWeightMap(map); - } - - private static double getSkillLevel(String skill, SkyblockPlayer player) { - switch (skill) { - case "mining": - return player.getMiningLevel(); - - case "foraging": - return player.getForagingLevel(); - - case "enchanting": - return player.getEnchantingLevel(); - - case "combat": - return player.getCombatLevel(); - - case "fishing": - return player.getFishingLevel(); - - case "alchemy": - return player.getAlchemyLevel(); - - case "farming": - return player.getFarmingLevel(); - } - - return -1; - } - - - // Prints the final message with the weight. - public static void printMessage(HashMap map) { - // Message header - StringBuilder message = new StringBuilder("§3§m-----------------------------------------------------§r\n" + - "§b§l§nRecommended skills to level up (In Order):§r" + - "\n\n§7This calculation is based off of the amount of weight each skill will add when you level it up. Lower level skills will be prioritized.§r" - + - "\n§7§oNote: Sometimes, low level skills such as alchemy will show up first. These skills are less important but due to the mathematical approach, they will appear first. \n" - + - "\n\n§8(Skill) : (Upgrade Importance Score)\n"); - - // Convert the entry set to an array for easier handling - @SuppressWarnings("unchecked") - Entry[] entryArray = new Entry[map.size()]; - entryArray = map.entrySet().toArray(entryArray); - - // Loops through the array backwards to get the biggest value first - for (int i = entryArray.length - 1; i >= 0; i--) { - Entry entry = entryArray[i]; - message.append("\n").append(formatWord(entry.getKey())).append(" : ").append(MathUtils.INSTANCE.round(entry.getValue(), 2)); - } - - message.append("\n§3§m-----------------------------------------------------§r"); - - // Send message - ChatUtils.INSTANCE.sendClientMessage((message.toString())); - } - - // Populates the constant hashmap - public static void populateSkillMap() { - weightConstants.put("mining", 1.68207448); - weightConstants.put("foraging", 1.732826); - weightConstants.put("enchanting", 1.46976583); - weightConstants.put("combat", 1.65797687265); - weightConstants.put("fishing", 1.906418); - weightConstants.put("alchemy", 1.5); - weightConstants.put("farming", 1.717848139); - } - - public static void registerCommand() { - new PSSCommand("skillup") - .addAlias("skillu") - .addAlias("su") - .setDescription("Recommends which skill to upgrade: /skillup [username]") - .setRunnable(a -> { - ChatUtils.INSTANCE.sendClientMessage("Loading..."); - - new Thread(() -> { - HashMap map; - if (a.length > 0) { - try { - map = SkillUpgradeRecommendation.getRecommendedSkills(a[0]); - } catch (IOException e) { - ChatUtils.INSTANCE.sendClientMessage(("Error getting data for " + a[0] - + ". Maybe the player is nicked or there is an invalid API key.")); - return; - } - } else { - try { - map = SkillUpgradeRecommendation.getRecommendedSkills(PartlySaneSkies.Companion.getMinecraft().thePlayer.getName()); - } catch (IOException e) { - ChatUtils.INSTANCE.sendClientMessage(("Error getting data for " - + PartlySaneSkies.Companion.getMinecraft().thePlayer.getName() - + ". Maybe the player is nicked or there is an invalid API key.")); - return; - } - } - - PartlySaneSkies.Companion.getMinecraft().addScheduledTask(() -> { - SkillUpgradeRecommendation.printMessage(map); - }); - - }).start(); - }) - .register(); - } - - // Sorts a double hashmap by its values - private static LinkedHashMap sortWeightMap(HashMap unsortedHashMap) { - LinkedHashMap sortedMap = new LinkedHashMap<>(); - ArrayList valueList = new ArrayList<>(); - for (Map.Entry entry : unsortedHashMap.entrySet()) { - valueList.add(entry.getValue()); - } - - valueList.sort(naturalOrder()); - - for (Double value : valueList) { - for (Entry entry : unsortedHashMap.entrySet()) { - if (entry.getValue().equals(value)) { - sortedMap.put(entry.getKey(), value); - } - } - } - - return sortedMap; - } - - - // Returns the weight contributed to a given skill given their constant - private static double calculateSkillWeight(double level, double constant) { - return Math.pow(level * 10, constant + level / 100) / 1250; - } - - // Returns the weight contributed to catacombs by a given skill - private static double calculateCatacombsWeight(double level) { - return Math.pow(level, 4.5) * 0.0002149604615; - } - - // Calculates the importance of upgrading skill. - private static double calculateScore(String skill, SkyblockPlayer player) { - // Current skill level - double currentSkillLevel = getSkillLevel(skill, player); - - // Senither weight constant - double weightConstant = weightConstants.get(skill); - - // Math - double awayFromMaxComponent = getSkillLevel(skill, player) - SkyblockDataManager.INSTANCE.getSkill(skill.toUpperCase()).getMaxLevel(); - double currentSenitherWeight = calculateSkillWeight(currentSkillLevel - 5, weightConstant); - double nextLevelSenitherWeight = calculateSkillWeight(Math.ceil(currentSkillLevel - 5), weightConstant); - double levelUpSenitherWeightComponent; - levelUpSenitherWeightComponent = currentSenitherWeight - nextLevelSenitherWeight; - - return awayFromMaxComponent / levelUpSenitherWeightComponent + 10; - } - - // Formats a word to have correct capitalization - private static String formatWord(String text) { - while (Character.isWhitespace(text.charAt(0))) { - text = new StringBuilder(text) - .replace(0, 1, "") - .toString(); - } - text = text.toLowerCase(); - text = new StringBuilder(text) - .replace(0, 1, String.valueOf(Character.toUpperCase(text.charAt(0)))) - .toString(); - return text; - } -} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/PartlySaneSkies.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/PartlySaneSkies.kt index 37d18a6ca..4e2d6c48f 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/PartlySaneSkies.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/PartlySaneSkies.kt @@ -77,16 +77,17 @@ import me.partlysanestudios.partlysaneskies.features.farming.garden.VisitorTrade import me.partlysanestudios.partlysaneskies.features.foraging.TreecapitatorCooldown import me.partlysanestudios.partlysaneskies.features.gui.RefreshKeybinds import me.partlysanestudios.partlysaneskies.features.gui.hud.CooldownHud +import me.partlysanestudios.partlysaneskies.features.gui.hud.DropBannerDisplay import me.partlysanestudios.partlysaneskies.features.gui.hud.LocationBannerDisplay -import me.partlysanestudios.partlysaneskies.features.gui.hud.rngdropbanner.DropBannerDisplay -import me.partlysanestudios.partlysaneskies.features.gui.hud.rngdropbanner.DropWebhook import me.partlysanestudios.partlysaneskies.features.gui.mainmenu.PSSMainMenu import me.partlysanestudios.partlysaneskies.features.information.WikiArticleOpener -import me.partlysanestudios.partlysaneskies.features.mining.MiningEvents +import me.partlysanestudios.partlysaneskies.features.items.rngdrop.DropWebhook +import me.partlysanestudios.partlysaneskies.features.items.rngdrop.RareDropGUIManager import me.partlysanestudios.partlysaneskies.features.mining.PickaxeWarning import me.partlysanestudios.partlysaneskies.features.mining.crystalhollows.WormWarning import me.partlysanestudios.partlysaneskies.features.mining.crystalhollows.gemstonewaypoints.GemstoneData import me.partlysanestudios.partlysaneskies.features.mining.crystalhollows.gemstonewaypoints.GemstoneWaypointRender +import me.partlysanestudios.partlysaneskies.features.mining.events.MiningEventNotifier import me.partlysanestudios.partlysaneskies.features.security.PrivacyMode import me.partlysanestudios.partlysaneskies.features.security.modschecker.ModChecker import me.partlysanestudios.partlysaneskies.features.skills.BestiaryLevelUpWebhook @@ -101,6 +102,7 @@ import me.partlysanestudios.partlysaneskies.features.themes.ThemeManager import me.partlysanestudios.partlysaneskies.render.gui.hud.BannerRenderer import me.partlysanestudios.partlysaneskies.render.gui.hud.cooldown.CooldownManager import me.partlysanestudios.partlysaneskies.utils.ChatUtils.sendClientMessage +import me.partlysanestudios.partlysaneskies.utils.HypixelUtils import me.partlysanestudios.partlysaneskies.utils.SystemUtils.log import net.minecraft.client.Minecraft import net.minecraft.event.ClickEvent @@ -147,24 +149,33 @@ class PartlySaneSkies { // Names of all the ranks to remove from people's names val RANK_NAMES = arrayOf( - "[VIP]", "[VIP+]", "[MVP]", "[MVP+]", "[MVP++]", "[YOUTUBE]", "[MOJANG]", - "[EVENTS]", "[MCP]", "[PIG]", "[PIG+]", "[PIG++]", "[PIG+++]", "[GM]", "[ADMIN]", "[OWNER]", "[NPC]" + "[VIP]", + "[VIP+]", + "[MVP]", + "[MVP+]", + "[MVP++]", + "[YOUTUBE]", + "[MOJANG]", + "[EVENTS]", + "[MCP]", + "[PIG]", + "[PIG+]", + "[PIG++]", + "[PIG+++]", + "[GM]", + "[ADMIN]", + "[OWNER]", + "[NPC]", ) val time: Long - // Returns the time in milliseconds get() = System.currentTimeMillis() + + private const val UNKNOWN_VERSION = "(Unknown)" + val isLatestVersion: Boolean - get() { - return if (DOGFOOD) { - true - } else if (latestVersion == "(Unknown)") { - true - } else { - VERSION == latestVersion - } - } + get() = DOGFOOD || latestVersion == UNKNOWN_VERSION || VERSION == latestVersion - var latestVersion = "(Unknown)" + var latestVersion = UNKNOWN_VERSION val coreConfig = Config() .registerOption("alreadyStarted", Toggle("Already Started", "Has this already been started with PSS enabled?", false)) @@ -221,14 +232,18 @@ class PartlySaneSkies { } catch (e: IOException) { e.printStackTrace() } + try { + RareDropGUIManager.loadData() + } catch (e: IOException) { + e.printStackTrace() + } }.start() - // Registers all the events registerEvent(this) + registerEvent(HypixelUtils) registerEvent(PartyManager()) registerEvent(PartyFriendManager()) - registerEvent(MiningEvents()) registerEvent(MinionData) registerEvent(SkyblockDataManager) registerEvent(DropBannerDisplay) @@ -271,13 +286,13 @@ class PartlySaneSkies { registerEvent(PSSMainMenu) registerEvent(WrongToolCropWarning.CropToolData) registerEvent(PetAlert) + registerEvent(MiningEventNotifier) registerEvent(SkillUpgradeWebhook) registerEvent(CropMilestoneWebhook) registerEvent(BestiaryMilestoneWebhook) registerEvent(BestiaryLevelUpWebhook) registerEvent(PetLevelUpWebhook) - // Registers all client side commands HelpCommand.registerPSSCommand() HelpCommand.registerHelpCommand() @@ -304,6 +319,7 @@ class PartlySaneSkies { PlayerRating.registerReprintCommand() ModChecker.registerModCheckCommand() ItemRefill.registerCommand() + RareDropGUIManager.registerCommand() WebhookMenu.registerWebhookCommand() registerCoreConfig() @@ -315,18 +331,13 @@ class PartlySaneSkies { BestiaryLevelUpWebhook.register() PetLevelUpWebhook.register() - - ConfigManager.loadAllConfigs() - - //Use Polyfrost EventManager cuz chatSendEvent makes transforming chat messages may easier + // Use Polyfrost EventManager cuz chatSendEvent makes transforming chat messages may easier cc.polyfrost.oneconfig.events.EventManager.INSTANCE.register(ChatTransformer) DebugKey.init() - // Initializes skill upgrade recommendation - SkillUpgradeRecommendation.populateSkillMap() try { SkyblockDataManager.updateAll() } catch (e: IOException) { @@ -341,13 +352,16 @@ class PartlySaneSkies { LoadPublicDataEvent.onDataLoad() // Loads user player data for PartyManager - Thread({ - try { - SkyblockDataManager.getPlayer(minecraft.session?.username ?: "") - } catch (e: MalformedURLException) { - e.printStackTrace() - } - }, "Init Data").start() + Thread( + { + try { + SkyblockDataManager.getPlayer(minecraft.session?.username ?: "") + } catch (e: MalformedURLException) { + e.printStackTrace() + } + }, + "Init Data", + ).start() Thread { DiscordRPC.init() }.start() if (config.privacyMode == 2) { @@ -357,7 +371,7 @@ class PartlySaneSkies { checkFirstLaunch() // Finished loading - log(Level.INFO, "Partly Sane Skies has loaded (Version: ${VERSION}).") + log(Level.INFO, "Partly Sane Skies has loaded (Version: $VERSION).") } private fun registerEvent(obj: Any) { @@ -385,10 +399,10 @@ class PartlySaneSkies { PetData.tick() VisitorLogbookData.scanForVisitors() HealthAlert.checkPlayerTick() - RequiredSecretsFound.tick() NoCookieWarning.checkCoinsTick() Prank.checkPrankTick() AuctionHouseGui.tick() + EventManager.tick() } @SubscribePSSEvent @@ -396,23 +410,24 @@ class PartlySaneSkies { val data = PublicDataManager.getFile("main_menu.json") val jsonObj = JsonParser().parse(data).asJsonObject try { - latestVersion = if (config.releaseChannel == 0) { - val modInfo: JsonObject = jsonObj.getAsJsonObject("mod_info") - modInfo["latest_version"].asString - } else { - val modInfo: JsonObject = jsonObj.getAsJsonObject("prerelease_channel") - modInfo["latest_version"].asString - } + latestVersion = + if (config.releaseChannel == 0) { + val modInfo: JsonObject = jsonObj.getAsJsonObject("mod_info") + modInfo["latest_version"].asString + } else { + val modInfo: JsonObject = jsonObj.getAsJsonObject("prerelease_channel") + modInfo["latest_version"].asString + } // latestVersionDescription = modInfo.get("latest_version_description").getAsString(); // latestVersionDate = modInfo.get("latest_version_release_date").getAsString(); } catch (e: NullPointerException) { - latestVersion = "(Unknown)" + latestVersion = UNKNOWN_VERSION e.printStackTrace() // latestVersionDate = "(Unknown)"; // latestVersionDescription = ""; } catch (e: IllegalStateException) { - latestVersion = "(Unknown)" + latestVersion = UNKNOWN_VERSION e.printStackTrace() } @@ -438,7 +453,6 @@ class PartlySaneSkies { } } - private fun registerCoreConfig() { ConfigManager.registerNewConfig("psscore.json", coreConfig) } @@ -455,7 +469,7 @@ class PartlySaneSkies { val discordMessage: IChatComponent = ChatComponentText("§9The Partly Sane Skies PSSDiscord server: https://discord.gg/$discordCode") discordMessage.chatStyle.setChatClickEvent( - ClickEvent(ClickEvent.Action.OPEN_URL, "https://discord.gg/$discordCode") + ClickEvent(ClickEvent.Action.OPEN_URL, "https://discord.gg/$discordCode"), ) sendClientMessage("§b§m--------------------------------------------------", true) sendClientMessage("§cWe noticed you're using a dogfood version of Partly Sane Skies.", false) @@ -485,18 +499,18 @@ class PartlySaneSkies { .chatGUI .printChatMessage(skyclientMessage) val githubMessage = - ChatComponentText("§9If you are not using SkyClient, click here go to the github and download the latest version.") + ChatComponentText("§9If you are not using SkyClient, click here go to the GitHub and download the latest version.") githubMessage.chatStyle.setChatClickEvent( ClickEvent( ClickEvent.Action.OPEN_URL, - "https://github.com/PartlySaneStudios/partly-sane-skies/releases" - ) + "https://github.com/PartlySaneStudios/partly-sane-skies/releases", + ), ) githubMessage.chatStyle.setChatHoverEvent( HoverEvent( HoverEvent.Action.SHOW_TEXT, - ChatComponentText("Click here to open the downloads page") - ) + ChatComponentText("Click here to open the downloads page"), + ), ) minecraft.ingameGUI .chatGUI @@ -508,5 +522,4 @@ class PartlySaneSkies { // Sends a ping to the count API to track the number of users per day private fun trackLoad() {} - } diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/commands/CommandManager.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/commands/CommandManager.kt index e842335c2..626a71d3b 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/commands/CommandManager.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/commands/CommandManager.kt @@ -11,42 +11,37 @@ import net.minecraft.util.BlockPos import net.minecraftforge.client.ClientCommandHandler object CommandManager { - var commandList = HashMap() fun getCommand(commandName: String): PSSCommand? = commandList[commandName] fun registerCommand(pssCommand: PSSCommand): ICommand? { if (pssCommand.isRegistered) return null - val iCommand: ICommand = object : ICommand { - override fun getCommandName(): String = pssCommand.name + val iCommand: ICommand = + object : ICommand { + override fun getCommandName(): String = pssCommand.name - override fun getCommandUsage(sender: ICommandSender): String = pssCommand.description + override fun getCommandUsage(sender: ICommandSender): String = pssCommand.description - override fun getCommandAliases(): List = pssCommand.aliases + override fun getCommandAliases(): List = pssCommand.aliases - @Throws(CommandException::class) - override fun processCommand(sender: ICommandSender, args: Array) { - pssCommand.runRunnable(args) - } + @Throws(CommandException::class) + override fun processCommand(sender: ICommandSender, args: Array) { + pssCommand.runRunnable(args) + } - override fun canCommandSenderUseCommand(sender: ICommandSender): Boolean = true + override fun canCommandSenderUseCommand(sender: ICommandSender): Boolean = true - override fun addTabCompletionOptions( - sender: ICommandSender, - args: Array, - pos: BlockPos - ): List = ArrayList() + override fun addTabCompletionOptions(sender: ICommandSender, args: Array, pos: BlockPos): List = ArrayList() - override fun isUsernameIndex(args: Array, index: Int): Boolean = false + override fun isUsernameIndex(args: Array, index: Int): Boolean = false - override fun compareTo(other: ICommand): Int = commandName.compareTo(other.commandName) - } + override fun compareTo(other: ICommand): Int = commandName.compareTo(other.commandName) + } pssCommand.iCommand = iCommand ClientCommandHandler.instance.registerCommand(iCommand) pssCommand.isRegistered = true commandList[pssCommand.name] = pssCommand return iCommand } - } diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/commands/PSSCommand.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/commands/PSSCommand.kt index 10d261af8..cb8861f5c 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/commands/PSSCommand.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/commands/PSSCommand.kt @@ -8,12 +8,11 @@ import me.partlysanestudios.partlysaneskies.commands.CommandManager.registerComm import net.minecraft.command.ICommand class PSSCommand(val name: String) { - var aliases: MutableList = mutableListOf() private set var description: String = "" private set - private var runnable = PSSCommandRunnable{} + private var runnable = PSSCommandRunnable {} var iCommand: ICommand? = null var isRegistered = false diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/config/Keybinds.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/config/Keybinds.kt index 559c80888..225e6b89f 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/config/Keybinds.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/config/Keybinds.kt @@ -3,7 +3,6 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.config import me.partlysanestudios.partlysaneskies.PartlySaneSkies @@ -39,17 +38,22 @@ object Keybinds { if (OneConfigScreen.favouritePetKeybind.isActive()) { PetAlert.favouritePet() } + if (!Keyboard.isCreated()) return if (Keyboard.isKeyDown(Keyboard.KEY_LEFT)) { - if (PartlySaneSkies.minecraft.currentScreen is AuctionHouseGui || PartlySaneSkies.minecraft.currentScreen is GuiChest && isAhGui( - (PartlySaneSkies.minecraft.currentScreen as GuiChest).containerInventory + if (PartlySaneSkies.minecraft.currentScreen is AuctionHouseGui || + PartlySaneSkies.minecraft.currentScreen is GuiChest && + isAhGui( + (PartlySaneSkies.minecraft.currentScreen as GuiChest).containerInventory, ) ) { clickOnSlot(46) } } if (Keyboard.isKeyDown(Keyboard.KEY_RIGHT)) { - if (PartlySaneSkies.minecraft.currentScreen is AuctionHouseGui || PartlySaneSkies.minecraft.currentScreen is GuiChest && isAhGui( - (PartlySaneSkies.minecraft.currentScreen as GuiChest).containerInventory + if (PartlySaneSkies.minecraft.currentScreen is AuctionHouseGui || + PartlySaneSkies.minecraft.currentScreen is GuiChest && + isAhGui( + (PartlySaneSkies.minecraft.currentScreen as GuiChest).containerInventory, ) ) { clickOnSlot(53) @@ -84,27 +88,33 @@ object Keybinds { PartlySaneSkies.minecraft.thePlayer.sendChatMessage("/storage") } if (OneConfigScreen.allowHoeRightClickKeybind.isActive()) { - val canRightClickHoe = onCooldown( - MathematicalHoeRightClicks.lastAllowHoeRightClickTime, - (OneConfigScreen.allowRightClickTime * 60L * 1000L).toLong() - ) - if (canRightClickHoe) { - val message: IChatComponent = ChatComponentText( - PartlySaneSkies.CHAT_PREFIX + """§dThe ability to right-click with a hoe has been §cdisabled§d again. -§dClick this message or run /allowhoerightclick to allow right-clicks for ${OneConfigScreen.allowRightClickTime} again.""" + val canRightClickHoe = + onCooldown( + MathematicalHoeRightClicks.lastAllowHoeRightClickTime, + (OneConfigScreen.allowRightClickTime * 60L * 1000L).toLong(), ) + if (canRightClickHoe) { + val message: IChatComponent = + ChatComponentText( + PartlySaneSkies.CHAT_PREFIX + """§dThe ability to right-click with a hoe has been §cdisabled§d again. +§dClick this message or run /allowhoerightclick to allow right-clicks for ${OneConfigScreen.allowRightClickTime} again.""", + ) message.chatStyle.setChatClickEvent(ClickEvent(ClickEvent.Action.RUN_COMMAND, "/allowhoerightclick")) - PartlySaneSkies.minecraft.ingameGUI.chatGUI.printChatMessage(message) + PartlySaneSkies.minecraft.ingameGUI.chatGUI + .printChatMessage(message) MathematicalHoeRightClicks.lastAllowHoeRightClickTime = 0 } else { - val message: IChatComponent = ChatComponentText( - PartlySaneSkies.CHAT_PREFIX + """§dThe ability to right-click with a hoe has been §aenabled§d for ${OneConfigScreen.allowRightClickTime} minutes. -§dClick this message or run /allowhoerightclick to disable right-clicks again.""" - ) + val message: IChatComponent = + ChatComponentText( + PartlySaneSkies.CHAT_PREFIX + + """§dThe ability to right-click with a hoe has been §aenabled§d for ${OneConfigScreen.allowRightClickTime} minutes. +§dClick this message or run /allowhoerightclick to disable right-clicks again.""", + ) message.chatStyle.setChatClickEvent(ClickEvent(ClickEvent.Action.RUN_COMMAND, "/allowhoerightclick")) - PartlySaneSkies.minecraft.ingameGUI.chatGUI.printChatMessage(message) + PartlySaneSkies.minecraft.ingameGUI.chatGUI + .printChatMessage(message) MathematicalHoeRightClicks.lastAllowHoeRightClickTime = PartlySaneSkies.time } } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/config/OneConfigScreen.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/config/OneConfigScreen.kt index 8ab1fa63d..e5f70afb4 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/config/OneConfigScreen.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/config/OneConfigScreen.kt @@ -3,25 +3,35 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.config import cc.polyfrost.oneconfig.config.Config -import cc.polyfrost.oneconfig.config.annotations.* +import cc.polyfrost.oneconfig.config.annotations.Button +import cc.polyfrost.oneconfig.config.annotations.Color +import cc.polyfrost.oneconfig.config.annotations.Dropdown +import cc.polyfrost.oneconfig.config.annotations.HUD +import cc.polyfrost.oneconfig.config.annotations.Info +import cc.polyfrost.oneconfig.config.annotations.KeyBind import cc.polyfrost.oneconfig.config.annotations.Number +import cc.polyfrost.oneconfig.config.annotations.Slider +import cc.polyfrost.oneconfig.config.annotations.Switch +import cc.polyfrost.oneconfig.config.annotations.Text import cc.polyfrost.oneconfig.config.core.OneColor import cc.polyfrost.oneconfig.config.core.OneKeyBind import cc.polyfrost.oneconfig.config.data.InfoType import cc.polyfrost.oneconfig.config.data.Mod import cc.polyfrost.oneconfig.config.data.ModType import me.partlysanestudios.partlysaneskies.features.debug.ExampleHud +import me.partlysanestudios.partlysaneskies.features.discord.webhooks.WebhookMenu import me.partlysanestudios.partlysaneskies.features.gui.hud.CooldownHud +import me.partlysanestudios.partlysaneskies.features.items.rngdrop.RareDropGUI +import me.partlysanestudios.partlysaneskies.utils.MinecraftUtils import org.lwjgl.input.Keyboard object OneConfigScreen : Config( // Available mod types: PVP, HUD, UTIL_QOL, HYPIXEL, SKYBLOCK Mod("Partly Sane Skies", ModType.SKYBLOCK, "/assets/partlysaneskies/textures/logo_oneconfig.png"), - "partly-sane-skies/config.json" + "partly-sane-skies/config.json", ) { fun resetBrokenStringsTick() { if (arrowLowChatMessage.isEmpty()) { @@ -88,11 +98,10 @@ object OneConfigScreen : Config( * // SUBCATEGORY_NAME */ - // ------------- Category: General --------------------------------- @Info( type = InfoType.INFO, - text = "Hover over an option to see a description and more information." + text = "Hover over an option to see a description and more information.", ) var ignored = false @@ -101,53 +110,67 @@ object OneConfigScreen : Config( description = "Select the update channel you want to use.", category = "General", subcategory = "Updates", - options = ["Release", "Pre-release"] + options = ["Release", "Pre-release"], ) var releaseChannel = "@RELEASE_CHANNEL@".toInt() - // Discord + // Discord RPC @Switch( name = "Discord RPC", category = "General", - subcategory = "Discord" + subcategory = "Discord RPC", ) var discordRPC = true @Switch( name = "Only show Discord RPC when in Skyblock", category = "General", - subcategory = "Discord" + subcategory = "Discord RPC", ) var discordRPCOnlySkyblock = false @Dropdown( name = "Playing...", category = "General", - subcategory = "Discord", - options = ["Hypixel Skyblock", "sbe bad"] + subcategory = "Discord RPC", + options = ["Hypixel Skyblock", "sbe bad"], ) var discordPlayingMode = 0 @Text( name = "Discord Game Name", category = "General", - subcategory = "Discord" + subcategory = "Discord RPC", ) var discordRPCName = "sbe bad" @Text( name = "Discord Game Description", category = "General", - subcategory = "Discord" + subcategory = "Discord RPC", ) var discordRPCDescription = "Playing Hypixel Skyblock" + // Discord Webhooks + @Button( + name = "Enable, Disable, and Manage Webhooks", + text = "Open Menu", + description = "Manage individual webhooks", + category = "General", + subcategory = "Discord Webhooks", + size = 2, + ) + val openDiscordWebhooks = Runnable { + MinecraftUtils.displayGuiScreen(WebhookMenu()) + } + @Text( name = "Discord Webhook URL", description = "The URL of the discord webhook to send the message to.", category = "General", - subcategory = "Discord", - size = 2 + subcategory = "Discord Webhooks", + secure = true, + size = 2, ) var discordWebhookURL = "" @@ -157,7 +180,7 @@ object OneConfigScreen : Config( description = "The separator between different hundreds places.", category = "General", subcategory = "Appearance", - options = ["Commas (1,000,000)", "Spaces (1 000 000)", "Periods (1.000.000)"] + options = ["Commas (1,000,000)", "Spaces (1 000 000)", "Periods (1.000.000)"], ) var hundredsPlaceFormat = 1 @@ -166,7 +189,7 @@ object OneConfigScreen : Config( description = "The character to represent decimal places.", category = "General", subcategory = "Appearance", - options = ["Commas (1,52)", "Periods (1.52)"] + options = ["Commas (1,52)", "Periods (1.52)"], ) var decimalPlaceFormat = 1 @@ -174,16 +197,26 @@ object OneConfigScreen : Config( name = "24 hour time", description = "Display time in 24-hour hour time (15:30) instead of 12 hour time (3:30 PM).", category = "General", - subcategory = "Appearance" + subcategory = "Appearance", ) var hour24time = false + @Slider( + name = "Text Scale", + description = "Increase the global text scale across most Partly Sane Skies menus", + category = "General", + subcategory = "Appearance", + min = 0.0f, + max = 3.0f, + ) + var textScale = 1.0f + @Dropdown( name = "Preferred Currency", description = "Select your preferred currency conversion for the /c2c command. Currencies are listed in alphabetical order. Default currency is USD.", category = "General", subcategory = "Appearance", - options = ["AUD (Australian Dollar)", "BRL (Brazilian Real)", "CAD (Canadian Dollar)", "DKK (Danish Krone)", "EUR (Euro)", "KPW (North Korean Won)", "NOK (Norwegian Krone)", "NZD (New Zealand Dollar)", "PLN (Polish Zloty)", "GBP (Pound Sterling)", "SEK (Swedish Krona)", "USD (United States Dollar)"] + options = ["AUD (Australian Dollar)", "BRL (Brazilian Real)", "CAD (Canadian Dollar)", "DKK (Danish Krone)", "EUR (Euro)", "KPW (North Korean Won)", "NOK (Norwegian Krone)", "NZD (New Zealand Dollar)", "PLN (Polish Zloty)", "GBP (Pound Sterling)", "SEK (Swedish Krona)", "USD (United States Dollar)"], ) var prefCurr = 11 @@ -193,16 +226,26 @@ object OneConfigScreen : Config( category = "General", subcategory = "Appearance", min = 0.1f, - max = 2f + max = 2f, ) var bannerSize = 1f + @Slider( + name = "Side Panel Padding", + description = "The padding between the side panel and the edge of the Inventory.", + category = "General", + subcategory = "Appearance", + min = 0f, + max = 50f, + ) + var sidePanelPadding = 10f + // Main Menu @Switch( name = "Show a Custom Minecraft Main Menu", description = "Show a custom main menu with a background image and announcements", category = "General", - subcategory = "Main Menu" + subcategory = "Main Menu", ) var customMainMenu = true @@ -210,7 +253,7 @@ object OneConfigScreen : Config( name = "Announcements on Main Menu", description = "Display announcements such as recent skyblock updates on the main menu.", category = "General", - subcategory = "Main Menu" + subcategory = "Main Menu", ) var displayAnnouncementsCustomMainMenu = true @@ -218,7 +261,7 @@ object OneConfigScreen : Config( name = "Fun Facts on Main Menu", description = "Display cool facts on the main menu.", category = "General", - subcategory = "Main Menu" + subcategory = "Main Menu", ) var displayFunFactsOnCustomMainMenu = true @@ -228,35 +271,34 @@ object OneConfigScreen : Config( category = "General", subcategory = "Main Menu", size = 2, - options = ["Random Image", "View of Main Hub Mountain", "Aerial View of Hub from Community House", "Stunning Aerial View of Hub", "View from Hub Portal (Day)", "Hub Portal (Night)", "Wolf Ruins", "Custom Image"] + options = ["Random Image", "View of Main Hub Mountain", "Aerial View of Hub from Community House", "Stunning Aerial View of Hub", "View from Hub Portal (Day)", "Hub Portal (Night)", "Wolf Ruins", "Custom Image"], ) var customMainMenuImage = 1 - // Mods Checker @Switch( name = "Check Mods On Startup", description = "Automatically Send Message on Startup.", category = "General", - subcategory = "Mods Checker" + subcategory = "Mods Checker", ) var checkModsOnStartup = true + // if someone boots their game the first time when after this got added, + // it will default to true, so it will check for beta mods @Switch( name = "Use Beta Versions", description = "Use the beta version of mods instead of normal versions.", category = "General", - subcategory = "Mods Checker" + subcategory = "Mods Checker", ) - // if someone boots their game the first time when after this got added, - // it will default to true, so it will check for beta mods var lookForBetaMods = "0" != "@RELEASE_CHANNEL@" @Switch( name = "Show up to date mods", description = "Show mods that are up to date.", category = "General", - subcategory = "Mods Checker" + subcategory = "Mods Checker", ) var showUpToDateMods = true @@ -270,8 +312,8 @@ object OneConfigScreen : Config( "[Off] Always allow mods to send telemetry", "[Protected] Block telemetry after startup (recommended)", "[Strong] Block telemetry after mod initialization ", - "[Strict] Always block telemetry (May causes crashes)" - ] + "[Strict] Always block telemetry (May causes crashes)", + ], ) var privacyMode = 1 @@ -280,7 +322,7 @@ object OneConfigScreen : Config( name = "Config Hotkey", description = "The keybind to open the config menu.", category = "General", - subcategory = "Config" + subcategory = "Config", ) var oneConfigKeybind = OneKeyBind(Keyboard.KEY_F7) @@ -289,7 +331,7 @@ object OneConfigScreen : Config( name = "Help Hotkey", description = "The keybind to show the mod commands.", category = "General", - subcategory = "Help" + subcategory = "Help", ) var helpKeybind = OneKeyBind(Keyboard.KEY_H) @@ -300,7 +342,7 @@ object OneConfigScreen : Config( description = "Pick from one of our 9 custom designed themes.", category = "Themes", subcategory = "Theme", - options = ["Classic (Dark)", "Royal Dark (Dark)", "Midnight Forest (Dark)", "Moonless Night (Very Dark)", "Stormy Night (Very Dark)", "The Void (Very Dark)", "Classic (Light)", "Royal Light (Light)", "Partly Cloudy (Light)", "Waterfall (Colorful)", "Jungle (Colorful)", "Dunes (Colorful)"] + options = ["Classic (Dark)", "Royal Dark (Dark)", "Midnight Forest (Dark)", "Moonless Night (Very Dark)", "Stormy Night (Very Dark)", "The Void (Very Dark)", "Classic (Light)", "Royal Light (Light)", "Partly Cloudy (Light)", "Waterfall (Colorful)", "Jungle (Colorful)", "Dunes (Colorful)"], ) var themeIndex = 0 @@ -309,7 +351,7 @@ object OneConfigScreen : Config( name = "Use custom accent color", description = "Uses the default Partly Sane Skies accent color.", category = "Themes", - subcategory = "Accent Color" + subcategory = "Accent Color", ) var useCustomAccentColor = false @@ -317,7 +359,7 @@ object OneConfigScreen : Config( name = "Custom Accent Color", description = "Choose a custom accent color for your game.", category = "Themes", - subcategory = "Accent Color" + subcategory = "Accent Color", ) var accentColor = OneColor(1, 255, 255, 255) @@ -326,7 +368,7 @@ object OneConfigScreen : Config( name = "Create your own Theme", description = "Enable to be able to create your own custom themes.", category = "Themes", - subcategory = "Custom Themes" + subcategory = "Custom Themes", ) var customTheme = false @@ -334,7 +376,7 @@ object OneConfigScreen : Config( name = "Custom Primary Color", description = "Choose a custom primary color for your game.", category = "Themes", - subcategory = "Custom Themes" + subcategory = "Custom Themes", ) var primaryColor = OneColor(42, 43, 46, 255) @@ -342,7 +384,7 @@ object OneConfigScreen : Config( name = "Custom Secondary Color", description = "Choose a custom secondary color for your game.", category = "Themes", - subcategory = "Custom Themes" + subcategory = "Custom Themes", ) var secondaryColor = OneColor(42, 43, 46, 255) @@ -351,7 +393,7 @@ object OneConfigScreen : Config( name = "Disable themes to use resource packs", description = "Disable themes to be able to use resource packs to modify Partly Sane Skies menus.", category = "Themes", - subcategory = "Resource Packs" + subcategory = "Resource Packs", ) var disableThemes = false @@ -361,7 +403,7 @@ object OneConfigScreen : Config( name = "Rare Drop Banner", description = "On rare drop, get a Pumpkin Dicer like banner.", category = "SkyBlock", - subcategory = "Rare Drop" + subcategory = "Rare Drop", ) var rareDropBanner = false @@ -371,7 +413,7 @@ object OneConfigScreen : Config( category = "SkyBlock", subcategory = "Rare Drop", min = 1f, - max = 7f + max = 7f, ) var rareDropBannerTime = 3.5f @@ -379,7 +421,7 @@ object OneConfigScreen : Config( name = "Custom Rare Drop Sound", description = "Plays a custom sound when you get a rare drop.", category = "SkyBlock", - subcategory = "Rare Drop" + subcategory = "Rare Drop", ) var rareDropBannerSound = false @@ -387,7 +429,7 @@ object OneConfigScreen : Config( name = "Block Common Drops", description = "Blocks Drops with the rarity of Common.", category = "SkyBlock", - subcategory = "Rare Drop" + subcategory = "Rare Drop", ) var blockCommonDrops = false @@ -395,7 +437,7 @@ object OneConfigScreen : Config( name = "Block Uncommon Drops", description = "Blocks Drops with the rarity of Uncommon.", category = "SkyBlock", - subcategory = "Rare Drop" + subcategory = "Rare Drop", ) var blockUncommonDrops = false @@ -403,7 +445,7 @@ object OneConfigScreen : Config( name = "Block Rare Drops", description = "Blocks Drops with the rarity of Rare.", category = "SkyBlock", - subcategory = "Rare Drop" + subcategory = "Rare Drop", ) var blockRareDrops = false @@ -411,7 +453,7 @@ object OneConfigScreen : Config( name = "Block Epic Drops", description = "Blocks Drops with the rarity of Epic.", category = "SkyBlock", - subcategory = "Rare Drop" + subcategory = "Rare Drop", ) var blockEpicDrops = false @@ -419,16 +461,28 @@ object OneConfigScreen : Config( name = "Block Legendary Drops", description = "Blocks Drops with the rarity of Legendary.", category = "SkyBlock", - subcategory = "Rare Drop" + subcategory = "Rare Drop", ) var blockLegendaryDrops = false + @Button( + name = "Filter Individual Items", + text = "Open Menu", + description = "Click to open a menu to blacklist individual items.", + category = "SkyBlock", + subcategory = "Rare Drop", + size = 2 + ) + val rareDropFilterButton = Runnable { + MinecraftUtils.displayGuiScreen(RareDropGUI()) + } + // Location Banner @Switch( name = "Location Banner", description = "An MMO RPG style banner shows up when you switch locations.", category = "SkyBlock", - subcategory = "Location Banner" + subcategory = "Location Banner", ) var locationBannerDisplay = false @@ -438,7 +492,7 @@ object OneConfigScreen : Config( category = "SkyBlock", subcategory = "Location Banner", min = 1f, - max = 7f + max = 7f, ) var locationBannerTime = 3.5f @@ -447,7 +501,7 @@ object OneConfigScreen : Config( name = "Open Wiki Automatically", description = "When the Open Wiki Article Keybind is used, automatically open the article without confirmation first.", category = "SkyBlock", - subcategory = "Open Wiki" + subcategory = "Open Wiki", ) var openWikiAutomatically = true @@ -455,7 +509,7 @@ object OneConfigScreen : Config( name = "Wiki Article Opener Hotkey", description = "The keybind to open the wiki article.", category = "SkyBlock", - subcategory = "Open Wiki" + subcategory = "Open Wiki", ) var wikiKeybind = OneKeyBind(Keyboard.KEY_NONE) @@ -464,7 +518,7 @@ object OneConfigScreen : Config( name = "Incorrect Pet for Minion Alert", description = "Warns you if you don't have the right pet for leveling up the minions, that way you never lose any pet EXP because you still have your level 100 dungeon pet activated.\nRequires pets to be visible.", category = "SkyBlock", - subcategory = "Incorrect Pet for Minion Alert" + subcategory = "Incorrect Pet for Minion Alert", ) var incorrectPetForMinionAlert = false @@ -472,7 +526,7 @@ object OneConfigScreen : Config( name = "Selected Pet Information", description = "Gives you information about the currently selected pet while in the minion menu.\nRequires pets to be visible.", category = "SkyBlock", - subcategory = "Incorrect Pet for Minion Alert" + subcategory = "Incorrect Pet for Minion Alert", ) var selectedPetInformation = false @@ -480,7 +534,7 @@ object OneConfigScreen : Config( name = "Air Raid Siren", description = "Plays a WWII air raid siren when you have the wrong pet. \nPros: \nKeeps you up at late night grinds \n(RECOMMENDED, ESPECIALLY AT 3 AM).", category = "SkyBlock", - subcategory = "Incorrect Pet for Minion Alert" + subcategory = "Incorrect Pet for Minion Alert", ) var incorrectPetForMinionAlertSiren = false @@ -488,7 +542,7 @@ object OneConfigScreen : Config( name = "Refresh Keybind (Ctrl + R / Command + R / F5)", description = "Refresh any menu with a \"Refresh\" button with (Ctrl + R) or (Command + R), depending on your operating system.\nOr just use (F5).", category = "SkyBlock", - subcategory = "Refresh Keybind" + subcategory = "Refresh Keybind", ) var refreshKeybind = false @@ -498,7 +552,7 @@ object OneConfigScreen : Config( category = "SkyBlock", subcategory = "Incorrect Pet for Minion Alert", size = 2, - secure = true + secure = true, ) var selectedPet = "" @@ -508,7 +562,7 @@ object OneConfigScreen : Config( category = "SkyBlock", subcategory = "Incorrect Pet for Minion Alert", min = 1f, - max = 15f + max = 15f, ) var petAlertMuteTime = 7.5f @@ -516,7 +570,7 @@ object OneConfigScreen : Config( name = "Favorite Pet Hotkey", description = "The keybind to favorite the pet you have selected.", category = "SkyBlock", - subcategory = "Incorrect Pet for Minion Alert" + subcategory = "Incorrect Pet for Minion Alert", ) var favouritePetKeybind = OneKeyBind(Keyboard.KEY_NONE) @@ -526,7 +580,7 @@ object OneConfigScreen : Config( description = "Choose the instrument type for the note block sounds.", category = "SkyBlock", subcategory = "Enhanced SkyBlock Sounds", - options = ["Default SkyBlock Noteblocks", "Clarinet (Live)", "Clarinet (Computer)", "Electric Piano", "Flute", "Organ", "Piano", "String Orchestra", "Trombone", "Trumpet", "Violin", "Wind Ensemble", "Discord New Message Sound", "Kazoo"] + options = ["Default SkyBlock Noteblocks", "Clarinet (Live)", "Clarinet (Computer)", "Electric Piano", "Flute", "Organ", "Piano", "String Orchestra", "Trombone", "Trumpet", "Violin", "Wind Ensemble", "Discord New Message Sound", "Kazoo"], ) var customSoundOption = 0 @@ -535,7 +589,7 @@ object OneConfigScreen : Config( description = "Choose the explosion sound.", category = "SkyBlock", subcategory = "Enhanced SkyBlock Sounds", - options = ["Default", "Off", "Realistic"] + options = ["Default", "Off", "Realistic"], ) var customExplosion = 0 @@ -544,7 +598,7 @@ object OneConfigScreen : Config( name = "Wardrobe Menu Hotkey", description = "The keybind to open the wardrobe menu.", category = "SkyBlock", - subcategory = "Shortcuts" + subcategory = "Shortcuts", ) var wardrobeKeybind = OneKeyBind(Keyboard.KEY_NONE) @@ -552,7 +606,7 @@ object OneConfigScreen : Config( name = "Pet Menu Hotkey", description = "The keybind to open the pet menu.", category = "SkyBlock", - subcategory = "Shortcuts" + subcategory = "Shortcuts", ) var petKeybind = OneKeyBind(Keyboard.KEY_NONE) @@ -560,7 +614,7 @@ object OneConfigScreen : Config( name = "Crafting Menu Hotkey", description = "The keybind to open the crafting menu.", category = "SkyBlock", - subcategory = "Shortcuts" + subcategory = "Shortcuts", ) var craftKeybind = OneKeyBind(Keyboard.KEY_NONE) @@ -568,7 +622,7 @@ object OneConfigScreen : Config( name = "Storage Menu Hotkey", description = "The keybind to open the storage menu.", category = "SkyBlock", - subcategory = "Shortcuts" + subcategory = "Shortcuts", ) var storageKeybind = OneKeyBind(Keyboard.KEY_NONE) @@ -576,7 +630,7 @@ object OneConfigScreen : Config( @HUD( name = "Cooldown HUD", category = "SkyBlock", - subcategory = "Cooldown HUD" + subcategory = "Cooldown HUD", ) var cooldownHud = CooldownHud.oneConfigHud @@ -586,7 +640,7 @@ object OneConfigScreen : Config( name = "Automatically kick offline on party manager load", description = "Automatically kicks offline members in your party when you open party manager.", category = "Dungeons", - subcategory = "Party Manager" + subcategory = "Party Manager", ) var autoKickOfflinePartyManager = false @@ -594,7 +648,7 @@ object OneConfigScreen : Config( name = "Warn Low Arrows in Chat", description = "Warns you party when a member has low arrows.", category = "Dungeons", - subcategory = "Party Manager" + subcategory = "Party Manager", ) var warnLowArrowsInChat = false @@ -603,7 +657,7 @@ object OneConfigScreen : Config( description = "Message to send when a player has low arrows.\nUse {player} to signify the player's username, and {count} to signify the remaining arrow count.", category = "Dungeons", subcategory = "Party Manager", - size = 2 + size = 2, ) var arrowLowChatMessage = "Partly Sane Skies > Warning! {player} only has {count} arrows remaining!" @@ -613,7 +667,7 @@ object OneConfigScreen : Config( description = "The amount of arrows you must have to be considered low on arrows.", category = "Dungeons", min = 0f, - max = 1000f + max = 1000f, ) var arrowLowCount = 300 @@ -621,7 +675,7 @@ object OneConfigScreen : Config( name = "Get data on party join", description = "Automatically gets the data for party members someone joins the party. This saves time and reduces the chance of the data not being able to be accessed.", category = "Dungeons", - subcategory = "Party Manager" + subcategory = "Party Manager", ) var getDataOnJoin = true @@ -629,7 +683,7 @@ object OneConfigScreen : Config( name = "Arrow Low Warning Upon Player Join", description = "Automatically sends the low arrow warning when the player joins the party, as opposed to waiting for the menu to open.", category = "Dungeons", - subcategory = "Party Manager" + subcategory = "Party Manager", ) var warnLowArrowsOnPlayerJoin = false @@ -637,7 +691,7 @@ object OneConfigScreen : Config( name = "Toggle Run Colors in Partymanager", description = "Toggles the colors of the runs in the party manager.", category = "Dungeons", - subcategory = "Party Manager" + subcategory = "Party Manager", ) var toggleRunColors = true @@ -647,7 +701,7 @@ object OneConfigScreen : Config( category = "Dungeons", subcategory = "Party Manager", min = 0f, - max = Int.MAX_VALUE.toFloat() + max = Int.MAX_VALUE.toFloat(), ) var runColorsRedMax = 1 @@ -657,7 +711,7 @@ object OneConfigScreen : Config( category = "Dungeons", subcategory = "Party Manager", min = 0f, - max = Int.MAX_VALUE.toFloat() + max = Int.MAX_VALUE.toFloat(), ) var runColorsYellowMax = 9 @@ -665,7 +719,7 @@ object OneConfigScreen : Config( name = "Hotkey", description = "The keybind to open the party manager.", subcategory = "Party Manager", - category = "Dungeons" + category = "Dungeons", ) var partyManagerKeybind = OneKeyBind(Keyboard.KEY_M) @@ -674,7 +728,7 @@ object OneConfigScreen : Config( name = "Watcher Ready Warning", description = "Sends a warning when the watcher is done spawning mobs.", category = "Dungeons", - subcategory = "Watcher Ready" + subcategory = "Watcher Ready", ) var watcherReadyBanner = false @@ -682,7 +736,7 @@ object OneConfigScreen : Config( name = "Watcher Ready Sound", description = "Plays a sound when the watcher is done spawning mobs.", category = "Dungeons", - subcategory = "Watcher Ready" + subcategory = "Watcher Ready", ) var watcherReadySound = false @@ -692,7 +746,7 @@ object OneConfigScreen : Config( category = "Dungeons", subcategory = "Watcher Ready", min = 1f, - max = 7f + max = 7f, ) var watcherReadyBannerTime = 3.5f @@ -700,7 +754,7 @@ object OneConfigScreen : Config( name = "Watcher Ready Banner Color", description = "The color of the watcher ready text.", category = "Dungeons", - subcategory = "Watcher Ready" + subcategory = "Watcher Ready", ) var watcherReadyBannerColor = OneColor(255, 45, 6) @@ -708,7 +762,7 @@ object OneConfigScreen : Config( name = "Watcher Ready Chat Message", description = "Send a message to your party when watcher is done spawning mobs.", category = "Dungeons", - subcategory = "Watcher Ready" + subcategory = "Watcher Ready", ) var watcherReadyChatMessage = false @@ -717,7 +771,7 @@ object OneConfigScreen : Config( description = "Message to send when the watcher is ready to clear.", category = "Dungeons", subcategory = "Watcher Ready", - size = 2 + size = 2, ) var watcherChatMessage = "Partly Sane Skies > The watcher is done spawning mobs. Ready to clear." @@ -725,7 +779,7 @@ object OneConfigScreen : Config( name = "Air Raid Siren", description = "Plays a WWII air raid siren when the watcher is done spawning mobs. \nPros: \nKeeps you up at late night grinds \n(RECOMMENDED, ESPECIALLY AT 3 AM)", category = "Dungeons", - subcategory = "Watcher Ready" + subcategory = "Watcher Ready", ) var watcherReadyAirRaidSiren = false @@ -734,7 +788,7 @@ object OneConfigScreen : Config( name = "Pretty Mimic Killed", description = "Changes the Skytils mimic killed message to be more visually appealing", category = "Dungeons", - subcategory = "Pretty Mimic Killed Message" + subcategory = "Pretty Mimic Killed Message", ) var prettyMimicKilled = true @@ -743,7 +797,7 @@ object OneConfigScreen : Config( name = "Pretty Mimic Killed Message", description = "Changes the Skytils mimic killed message to be more visually appealing", category = "Dungeons", - subcategory = "Pretty Mimic Killed Message" + subcategory = "Pretty Mimic Killed Message", ) var prettyMimicKilledString = "Mimic Killed!" @@ -752,7 +806,7 @@ object OneConfigScreen : Config( name = "Enable Waypoints for Terminals, Devices and Levers", description = "Enables waypoints for terminals, devices and levers in Phase 3 of Floor 7.", category = "Dungeons", - subcategory = "Terminal Waypoints" + subcategory = "Terminal Waypoints", ) var terminalWaypoints = true @@ -761,7 +815,7 @@ object OneConfigScreen : Config( name = "Auto Pearl Refill", description = "Automatically refills your pearls when a run starts.", category = "Dungeons", - subcategory = "Pearl Refill" + subcategory = "Pearl Refill", ) var autoPearlRefill = false @@ -769,7 +823,7 @@ object OneConfigScreen : Config( name = "Refill Pearls Hotkey", description = "The keybind to automatically refill your pearls.", category = "Dungeons", - subcategory = "Pearl Refill" + subcategory = "Pearl Refill", ) var pearlRefillKeybind = OneKeyBind(Keyboard.KEY_P) @@ -778,7 +832,7 @@ object OneConfigScreen : Config( name = "Auto Item Refill", description = "Automatically refills your utility items when a run starts.", category = "Dungeons", - subcategory = "Item Refill" + subcategory = "Item Refill", ) var autoItemRefill = false @@ -786,7 +840,7 @@ object OneConfigScreen : Config( name = "Refill Items Hotkey", description = "The keybind to automatically refill your pearls.", category = "Dungeons", - subcategory = "Item Refill" + subcategory = "Item Refill", ) var itemRefillKeybind = OneKeyBind(Keyboard.KEY_P) @@ -794,7 +848,7 @@ object OneConfigScreen : Config( name = "Refill Ender Pearls", description = "Refills ender pearls", category = "Dungeons", - subcategory = "Item Refill" + subcategory = "Item Refill", ) var refillPearls = true @@ -802,7 +856,7 @@ object OneConfigScreen : Config( name = "Refill Superboom Tnt", description = "Refills superboom tnt", category = "Dungeons", - subcategory = "Item Refill" + subcategory = "Item Refill", ) var refillSuperboomTnt = true @@ -810,7 +864,7 @@ object OneConfigScreen : Config( name = "Refill Spirit Leaps", description = "Refills spirit leaps", category = "Dungeons", - subcategory = "Item Refill" + subcategory = "Item Refill", ) var refillSpiritLeaps = true @@ -818,7 +872,7 @@ object OneConfigScreen : Config( name = "Refill Decoys", description = "Refills decoy", category = "Dungeons", - subcategory = "Item Refill" + subcategory = "Item Refill", ) var refillDecoys = false @@ -827,7 +881,7 @@ object OneConfigScreen : Config( name = "Alert when dungeon team members are low", description = "Displays a banner when a teammate in Dungeons has low health.", category = "Dungeons", - subcategory = "Health Alert" + subcategory = "Health Alert", ) var healerAlert = false @@ -835,7 +889,7 @@ object OneConfigScreen : Config( name = "Alert when you are low", description = "Displays a banner when you are low on health.", category = "Dungeons", - subcategory = "Health Alert" + subcategory = "Health Alert", ) var alertWhenPlayerLow = false @@ -843,7 +897,7 @@ object OneConfigScreen : Config( name = "Alert outside of dungeons", description = "Alert outside of dungeons.", category = "Dungeons", - subcategory = "Health Alert" + subcategory = "Health Alert", ) var alertOutsideDungeons = false @@ -852,7 +906,7 @@ object OneConfigScreen : Config( description = "Choose at what percentage healer alert will trigger.", category = "Dungeons", subcategory = "Health Alert", - options = ["25% Health", "50% Health"] + options = ["25% Health", "50% Health"], ) var colouredHealerAlert = 0 @@ -862,11 +916,10 @@ object OneConfigScreen : Config( category = "Dungeons", subcategory = "Health Alert", min = 1f, - max = 15f + max = 15f, ) var healerAlertCooldownSlider = 3.5f - @Color( name = "Party Members Low Color", category = "Dungeons", @@ -886,7 +939,7 @@ object OneConfigScreen : Config( name = "Required Secrets Found Banner", description = "Sends a warning when all required secrets have been found.", category = "Dungeons", - subcategory = "Required Secrets Found" + subcategory = "Required Secrets Found", ) var secretsBanner = false @@ -894,7 +947,7 @@ object OneConfigScreen : Config( name = "Required Secrets Found Sound", description = "Plays a sound when all required secrets have been found.", category = "Dungeons", - subcategory = "Required Secrets Found" + subcategory = "Required Secrets Found", ) var secretsSound = false @@ -904,7 +957,7 @@ object OneConfigScreen : Config( category = "Dungeons", subcategory = "Required Secrets Found", min = 1f, - max = 7f + max = 7f, ) var secretsBannerTime = 3.5f @@ -912,7 +965,7 @@ object OneConfigScreen : Config( name = "Required Secrets Found Banner Color", description = "The color of the required secrets found text.", category = "Dungeons", - subcategory = "Required Secrets Found" + subcategory = "Required Secrets Found", ) var secretsBannerColor = OneColor(255, 45, 6) @@ -920,7 +973,7 @@ object OneConfigScreen : Config( name = "Required Secrets Found Chat Message", description = "Send a message to your party when all required secrets have been found.", category = "Dungeons", - subcategory = "Required Secrets Found" + subcategory = "Required Secrets Found", ) var secretsChatMessage = false @@ -929,7 +982,7 @@ object OneConfigScreen : Config( description = "Message to send when all required secrets have been found.", category = "Dungeons", subcategory = "Required Secrets Found", - size = 2 + size = 2, ) var secretsChatMessageString = "Partly Sane Skies > All required secrets have been found!" @@ -937,7 +990,7 @@ object OneConfigScreen : Config( name = "Air Raid Siren", description = "Plays a WWII air raid siren when all required secrets have been found. \nPros: \nKeeps you up at late night grinds \n(RECOMMENDED, ESPECIALLY AT 3 AM)", category = "Dungeons", - subcategory = "Required Secrets Found" + subcategory = "Required Secrets Found", ) var secretsAirRaidSiren = false @@ -946,7 +999,7 @@ object OneConfigScreen : Config( name = "Dungeon Player Breakdown", description = "At the end of the dungeon, send a message informing you how much of the dungeon each player has completed.", category = "Dungeons", - subcategory = "Dungeon Player Breakdown" + subcategory = "Dungeon Player Breakdown", ) var dungeonPlayerBreakdown = false @@ -955,7 +1008,7 @@ object OneConfigScreen : Config( description = "Shows more information about how many blessings and secrets each player collected.", category = "Dungeons", subcategory = "Dungeon Player Breakdown", - options = ["Condensed", "Standard", "Enhanced"] + options = ["Condensed", "Standard", "Enhanced"], ) var enhancedDungeonPlayerBreakdown = 1 @@ -965,7 +1018,7 @@ object OneConfigScreen : Config( category = "Dungeons", subcategory = "Dungeon Player Breakdown", min = 0f, - max = 20f + max = 20f, ) var dungeonPlayerBreakdownDelay = 1f @@ -973,7 +1026,7 @@ object OneConfigScreen : Config( name = "Send in Party Chat", description = "Send a condensed version to the rest of your party.", category = "Dungeons", - subcategory = "Dungeon Player Breakdown" + subcategory = "Dungeon Player Breakdown", ) var partyChatDungeonPlayerBreakdown = false @@ -981,7 +1034,7 @@ object OneConfigScreen : Config( name = "Dungeon Snitcher", description = "Automatically sends messages recommending to kick party members.", category = "Dungeons", - subcategory = "Dungeon Player Breakdown" + subcategory = "Dungeon Player Breakdown", ) var dungeonSnitcher = false @@ -991,7 +1044,7 @@ object OneConfigScreen : Config( category = "Dungeons", subcategory = "Dungeon Player Breakdown", min = 0f, - max = 50f + max = 50f, ) var dungeonSnitcherPercent = 7.5f @@ -1000,7 +1053,7 @@ object OneConfigScreen : Config( name = "Enable Automatic GG message", description = "Sends an automatic gg message of your choosing whenever a dungeon is complete.", category = "Dungeons", - subcategory = "Auto GG" + subcategory = "Auto GG", ) var autoGgEnabled = false @@ -1010,7 +1063,7 @@ object OneConfigScreen : Config( category = "Dungeons", subcategory = "Auto GG", min = 0f, - max = 10f + max = 10f, ) var autoGGCooldown = 1.5f @@ -1019,7 +1072,7 @@ object OneConfigScreen : Config( description = "Where to send the auto gg message.", category = "Dungeons", subcategory = "Auto GG", - options = ["Party Chat", "All Chat"] + options = ["Party Chat", "All Chat"], ) var sendAutoGGInWhatChat = 0 @@ -1027,7 +1080,7 @@ object OneConfigScreen : Config( name = "Text when S+ score", description = "Sends this message whenever a dungeon is complete and the score is S+.", category = "Dungeons", - subcategory = "Auto GG" + subcategory = "Auto GG", ) var autoGGMessageSPlus = "GG Easy" @@ -1035,7 +1088,7 @@ object OneConfigScreen : Config( name = "Text when S score", description = "Sends this message whenever a dungeon is complete and the score is S.", category = "Dungeons", - subcategory = "Auto GG" + subcategory = "Auto GG", ) var autoGGMessageS = "GG" @@ -1043,7 +1096,7 @@ object OneConfigScreen : Config( name = "Text when other score", description = "Sends this message whenever a dungeon is complete and the score is not S+/S.", category = "Dungeons", - subcategory = "Auto GG" + subcategory = "Auto GG", ) var autoGGMessageOther = "Welp, GG" @@ -1053,7 +1106,7 @@ object OneConfigScreen : Config( name = "Worm Warning Banner", description = "A banner appears on your screen when a worm spawns.", category = "Mining", - subcategory = "Worm Warning" + subcategory = "Worm Warning", ) var wormWarningBanner = false @@ -1061,7 +1114,7 @@ object OneConfigScreen : Config( name = "Worm Warning Banner Color", description = "The color of the worm warning text.", category = "Mining", - subcategory = "Worm Warning" + subcategory = "Worm Warning", ) var wormWarningBannerColor = OneColor(34, 255, 0) @@ -1071,7 +1124,7 @@ object OneConfigScreen : Config( category = "Mining", subcategory = "Worm Warning", min = 1f, - max = 7f + max = 7f, ) var wormWarningBannerTime = 3.5f @@ -1079,16 +1132,16 @@ object OneConfigScreen : Config( name = "Worm Warning Sound", description = "Plays a sound when a worm spawns.", category = "Mining", - subcategory = "Worm Warning" + subcategory = "Worm Warning", ) var wormWarningBannerSound = false - //Pickaxes + // Pickaxes @Switch( name = "Pickaxe Ability Ready Banner", description = "A banner appears on your screen when your pickaxe ability is ready.", category = "Mining", - subcategory = "Pickaxes" + subcategory = "Pickaxes", ) var pickaxeAbilityReadyBanner = true @@ -1096,7 +1149,7 @@ object OneConfigScreen : Config( name = "Banner Text", description = "The text that appears on the banner when your pickaxe ability is ready.", category = "Mining", - subcategory = "Pickaxes" + subcategory = "Pickaxes", ) var pickaxeAbilityReadyBannerText = "Pickaxe Ability Ready!" @@ -1104,7 +1157,7 @@ object OneConfigScreen : Config( name = "Pickaxe Ability Ready Sound", description = "Plays a sound when your pickaxe ability is ready.", category = "Mining", - subcategory = "Pickaxes" + subcategory = "Pickaxes", ) var pickaxeAbilityReadySound = false @@ -1112,7 +1165,7 @@ object OneConfigScreen : Config( name = "Use Air Raid Siren for Pickaxe Ability Ready", description = "Plays a WWII air raid siren when your pickaxe ability is ready. \nPros: \nKeeps you up at late night grinds \n(RECOMMENDED, ESPECIALLY AT 3 AM)", category = "Mining", - subcategory = "Pickaxes" + subcategory = "Pickaxes", ) var pickaxeAbilityReadySiren = false @@ -1120,7 +1173,7 @@ object OneConfigScreen : Config( name = "Hide Ready Message from Chat", description = "Hides the message that appears in chat when your pickaxe ability is ready.", category = "Mining", - subcategory = "Pickaxes" + subcategory = "Pickaxes", ) var hideReadyMessageFromChat = false @@ -1128,7 +1181,7 @@ object OneConfigScreen : Config( name = "Warn only on mining islands.", description = "Makes it less annoying when you don't want to mine.", category = "Mining", - subcategory = "Pickaxes" + subcategory = "Pickaxes", ) var onlyGiveWarningOnMiningIsland = true @@ -1138,7 +1191,7 @@ object OneConfigScreen : Config( category = "Mining", subcategory = "Pickaxes", min = 1f, - max = 7f + max = 7f, ) var pickaxeBannerTime = 3.5f @@ -1146,7 +1199,7 @@ object OneConfigScreen : Config( name = "Ready Banner Color", description = "The color of the ready banner text.", category = "Mining", - subcategory = "Pickaxes" + subcategory = "Pickaxes", ) var pickaxeBannerColor = OneColor(255, 255, 0) @@ -1154,7 +1207,7 @@ object OneConfigScreen : Config( name = "Block Ability on Private Island (UAYOR)", description = "Blocks the use of pickaxe abilities on your private island. (Use at your own risk)", category = "Mining", - subcategory = "Pickaxes" + subcategory = "Pickaxes", ) var blockAbilityOnPrivateIsland = false @@ -1164,7 +1217,7 @@ object OneConfigScreen : Config( description = "Shows Topaz waypoints", category = "Mining", subcategory = "Gemstone Waypoints", - size = 2 + size = 2, ) var renderGemstoneWaypoints = false @@ -1174,7 +1227,7 @@ object OneConfigScreen : Config( category = "Mining", subcategory = "Gemstone Waypoints", min = 1f, - max = 16f + max = 16f, ) var gemstoneWaypointRenderDistance = 6 @@ -1184,7 +1237,7 @@ object OneConfigScreen : Config( category = "Mining", subcategory = "Gemstone Waypoints", min = 0f, - max = 100f + max = 100f, ) var gemstoneMinSize = 15 @@ -1193,7 +1246,7 @@ object OneConfigScreen : Config( description = "Show a beam going from the waypoint to the top of the world. Disable with large amounts of waypoints", category = "Mining", subcategory = "Gemstone Waypoints", - size = 2 + size = 2, ) var showGemstoneBeam = false @@ -1203,7 +1256,7 @@ object OneConfigScreen : Config( category = "Mining", subcategory = "Gemstone Waypoints", min = 0f, - max = 1f + max = 1f, ) var gemstoneBrightness = 1f @@ -1211,7 +1264,7 @@ object OneConfigScreen : Config( name = "Show Topaz Waypoints", description = "Shows Topaz waypoints", category = "Mining", - subcategory = "Gemstone Waypoints" + subcategory = "Gemstone Waypoints", ) var topazWaypoints = true @@ -1219,7 +1272,7 @@ object OneConfigScreen : Config( name = "Show Ruby Waypoints", description = "Shows Ruby waypoints", category = "Mining", - subcategory = "Gemstone Waypoints" + subcategory = "Gemstone Waypoints", ) var rubyWaypoints = true @@ -1227,7 +1280,7 @@ object OneConfigScreen : Config( name = "Show Sapphire Waypoints", description = "Shows Sapphire waypoints", category = "Mining", - subcategory = "Gemstone Waypoints" + subcategory = "Gemstone Waypoints", ) var sapphireWaypoints = true @@ -1235,7 +1288,7 @@ object OneConfigScreen : Config( name = "Show Amethyst Waypoints", description = "Shows Amethyst waypoints", category = "Mining", - subcategory = "Gemstone Waypoints" + subcategory = "Gemstone Waypoints", ) var amethystWaypoints = true @@ -1243,7 +1296,7 @@ object OneConfigScreen : Config( name = "Show Amber Waypoints", description = "Shows Amber waypoints", category = "Mining", - subcategory = "Gemstone Waypoints" + subcategory = "Gemstone Waypoints", ) var amberWaypoints = true @@ -1251,27 +1304,31 @@ object OneConfigScreen : Config( name = "Show Jade Waypoints", description = "Shows Jade waypoints", category = "Mining", - subcategory = "Gemstone Waypoints" + subcategory = "Gemstone Waypoints", ) var jadeWaypoints = true - - //Events + // Events @Info( type = InfoType.INFO, text = "Some Events may not trigger, not all have been tested. If you find an event that doesn't trigger, please report it on our discord server.", category = "Mining", subcategory = "Events", - size = 2 + size = 2, + ) + @Switch( + name = "Main Toggle", + description = "Toggles the events.", + category = "Mining", + subcategory = "Events" ) - @Switch(name = "Main Toggle", description = "Toggles the events.", category = "Mining", subcategory = "Events") var miningEventsToggle = true @Switch( name = "Show Event Banner", description = "Shows a banner when an enabled event is going active.", category = "Mining", - subcategory = "Events" + subcategory = "Events", ) var miningShowEventBanner = true @@ -1279,7 +1336,7 @@ object OneConfigScreen : Config( name = "Send System Notifications", description = "Sends a system notification when an event is going active.", category = "Mining", - subcategory = "Events" + subcategory = "Events", ) var miningSendSystemNotifications = false @@ -1287,7 +1344,7 @@ object OneConfigScreen : Config( name = "Also warn 20s before event activation", description = "Shows a banner and plays sound 20s before an enabled event is going active.", category = "Mining", - subcategory = "Events" + subcategory = "Events", ) var miningWarn20sBeforeEvent = false @@ -1295,7 +1352,7 @@ object OneConfigScreen : Config( name = "2x Powder activation sound", description = "Plays a sound when 2x Powder event is going active.", category = "Mining", - subcategory = "Events" + subcategory = "Events", ) var mining2xPowderSound = false @@ -1303,7 +1360,7 @@ object OneConfigScreen : Config( name = "Gone with the wind activation sound", description = "Plays a sound when Gone with the wind event is going active.", category = "Mining", - subcategory = "Events" + subcategory = "Events", ) var miningGoneWithTheWindSound = false @@ -1311,7 +1368,7 @@ object OneConfigScreen : Config( name = "Better Together activation sound", description = "Plays a sound when Better Together event is going active.", category = "Mining", - subcategory = "Events" + subcategory = "Events", ) var miningBetterTogetherSound = false @@ -1319,7 +1376,7 @@ object OneConfigScreen : Config( name = "Goblin Raid activation sound", description = "Plays a sound when Goblin Raid event is going active.", category = "Mining", - subcategory = "Events" + subcategory = "Events", ) var miningGoblinRaidSound = false @@ -1327,7 +1384,7 @@ object OneConfigScreen : Config( name = "Raffle activation sound", description = "Plays a sound when Raffle event is going active.", category = "Mining", - subcategory = "Events" + subcategory = "Events", ) var miningRaffleSound = false @@ -1335,7 +1392,7 @@ object OneConfigScreen : Config( name = "Mithril Gourmand activation sound", description = "Plays a sound when Mithril Gourmand event is going active.", category = "Mining", - subcategory = "Events" + subcategory = "Events", ) var miningMithrilGourmandSound = false @@ -1343,7 +1400,7 @@ object OneConfigScreen : Config( name = "Powder Ghast activation sound", description = "Plays a sound when Powder Ghast is about to spawn.", category = "Mining", - subcategory = "Events" + subcategory = "Events", ) var miningPowderGhastSound = false @@ -1351,7 +1408,7 @@ object OneConfigScreen : Config( name = "Fallen Star activation sound", description = "Plays a sound when Fallen Star is about to spawn.", category = "Mining", - subcategory = "Events" + subcategory = "Events", ) var miningFallenStarSound = false @@ -1361,25 +1418,17 @@ object OneConfigScreen : Config( category = "Mining", subcategory = "Events", min = 1f, - max = 7f + max = 7f, ) var miningEventBannerTime = 3.5f - @Color( - name = "Event Banner Color", - description = "The color of the event banner text.", - category = "Mining", - subcategory = "Events" - ) - var miningEventBannerColor = OneColor(255, 255, 255) - // ------------- Category: Farming --------------------------------- // Hoes @Switch( name = "Stop right clicks on Mathematical Hoes", description = "Cancels the right click on mathematical hoes to prevent it from opening the recipes list. (Use at your own risk)", category = "Farming", - subcategory = "Hoes" + subcategory = "Hoes", ) var blockHoeRightClicks = false @@ -1389,7 +1438,7 @@ object OneConfigScreen : Config( category = "Farming", subcategory = "Hoes", min = 1f, - max = 15f + max = 15f, ) var allowRightClickTime = 3f @@ -1397,7 +1446,7 @@ object OneConfigScreen : Config( name = "Allow Hoe Right Clicks Opener Hotkey", description = "The keybind to open the allow hoe right click menu.", category = "Farming", - subcategory = "Hoes" + subcategory = "Hoes", ) var allowHoeRightClickKeybind = OneKeyBind(Keyboard.KEY_NONE) @@ -1406,7 +1455,7 @@ object OneConfigScreen : Config( name = "Show end of farm regions", description = "Highlights your regions.", category = "Farming", - subcategory = "End of Farm Notifier" + subcategory = "End of Farm Notifier", ) var showFarmRegions = true @@ -1416,7 +1465,7 @@ object OneConfigScreen : Config( category = "Farming", subcategory = "End of Farm Notifier", min = 1f, - max = 5f + max = 5f, ) var farmnotifierChimeTime = 3f @@ -1426,7 +1475,7 @@ object OneConfigScreen : Config( category = "Farming", subcategory = "End of Farm Notifier", min = 1f, - max = 120f + max = 120f, ) var farmHightlightTime = 30f @@ -1435,7 +1484,7 @@ object OneConfigScreen : Config( name = "Visitor Trade Cost", description = "Gives you information about the cost of visitor trades.", category = "Farming", - subcategory = "Garden Visitors" + subcategory = "Garden Visitors", ) var gardenShopTradeInfo = false @@ -1443,7 +1492,7 @@ object OneConfigScreen : Config( name = "Display Garden Visitor Stats", description = "Shows visited/accepted stats per NPC rarity.\nPros: based on item tooltips, which might capture more Garden visitor data\n(especially if you had Garden visitors before you installed SkyHanni).\nCons: Only shows for current Visitor's Logbook page and not all pages.", category = "Farming", - subcategory = "Garden Visitors" + subcategory = "Garden Visitors", ) var visitorLogbookStats = false @@ -1452,7 +1501,7 @@ object OneConfigScreen : Config( name = "Wrong Tool for Crop Enabled", description = "When enabled, a warning will appear, notifying you that you are using the wrong tool for the current crop.", category = "Farming", - subcategory = "Wrong Tool for Crop" + subcategory = "Wrong Tool for Crop", ) var wrongToolForCropEnabled = false @@ -1460,7 +1509,7 @@ object OneConfigScreen : Config( name = "Allow Mathematical Hoes", description = "When enabled, mathematical hoes will be considered a valid tool.", category = "Farming", - subcategory = "Wrong Tool for Crop" + subcategory = "Wrong Tool for Crop", ) var mathematicalHoeValid = true @@ -1468,7 +1517,7 @@ object OneConfigScreen : Config( name = "Allow Other SkyBlock Tools", description = "When enabled, other SkyBlock tools will be considered a valid tool.", category = "Farming", - subcategory = "Wrong Tool for Crop" + subcategory = "Wrong Tool for Crop", ) var otherSkyblockToolsValid = true @@ -1476,7 +1525,7 @@ object OneConfigScreen : Config( name = "Allow Right Tool Type", description = "When enabled, the system only looks for the right tool type (hoes, etc.).", category = "Farming", - subcategory = "Wrong Tool for Crop" + subcategory = "Wrong Tool for Crop", ) var vanillaToolsValid = false @@ -1484,7 +1533,7 @@ object OneConfigScreen : Config( name = "Require Replenish", description = "When enabled, the tool must have replenish if it is to be used on a replenishable crop.", category = "Farming", - subcategory = "Wrong Tool for Crop" + subcategory = "Wrong Tool for Crop", ) var requireReplenish = true @@ -1492,7 +1541,7 @@ object OneConfigScreen : Config( name = "Air Raid Siren", description = "When enabled, the warning will contain an air raid siren.", category = "Farming", - subcategory = "Wrong Tool for Crop" + subcategory = "Wrong Tool for Crop", ) var wrongToolForCropAirRaid = false @@ -1502,7 +1551,7 @@ object OneConfigScreen : Config( category = "Farming", subcategory = "Wrong Tool for Crop", min = 1f, - max = 7f + max = 7f, ) var wrongToolForCropBannerTime = 3.5f @@ -1512,7 +1561,7 @@ object OneConfigScreen : Config( category = "Farming", subcategory = "Wrong Tool for Crop", min = 1f, - max = 7f + max = 7f, ) var wrongToolForCropCooldown = 3.5f @@ -1521,7 +1570,7 @@ object OneConfigScreen : Config( name = "Best Crops to Compost", description = "Gives you information about which crops are the best to compost.", category = "Farming", - subcategory = "Composter" + subcategory = "Composter", ) var bestCropsToCompost = false @@ -1530,7 +1579,7 @@ object OneConfigScreen : Config( name = "SkyMart Value", description = "Gives you information about the best value crops to compost.", category = "Farming", - subcategory = "SkyMart" + subcategory = "SkyMart", ) var skymartValue = false @@ -1540,7 +1589,7 @@ object OneConfigScreen : Config( name = "Treecapitator Cooldown Indicator Enabled", description = "Displays a cooldown indicator below your crosshair whenever your treecapitator is on cooldown.", category = "Foraging", - subcategory = "Treecapitator Cooldown Indicator" + subcategory = "Treecapitator Cooldown Indicator", ) var treecapCooldown = false @@ -1548,7 +1597,7 @@ object OneConfigScreen : Config( name = "Use Monkey Pet", description = "Use the monkey pet to dynamically adjust the length of the cooldown.", category = "Foraging", - subcategory = "Treecapitator Cooldown Indicator" + subcategory = "Treecapitator Cooldown Indicator", ) var treecapCooldownMonkeyPet = true @@ -1558,7 +1607,7 @@ object OneConfigScreen : Config( name = "Best Item for Bits", description = "Gives you information about which item in the Bits Shop is the best to sell.", category = "Economy", - subcategory = "Community Center" + subcategory = "Community Center", ) var bestBitShopItem = false @@ -1566,7 +1615,7 @@ object OneConfigScreen : Config( name = "Only Show Affordable Items", description = "When making recommendations for what you can buy, only recommend the items that you are able to afford.", category = "Economy", - subcategory = "Community Center" + subcategory = "Community Center", ) var bitShopOnlyShowAffordable = true @@ -1576,7 +1625,7 @@ object OneConfigScreen : Config( category = "Economy", subcategory = "BIN Sniper", min = 0f, - max = 100f + max = 100f, ) var BINSniperPercent = 87f @@ -1585,7 +1634,7 @@ object OneConfigScreen : Config( name = "Custom Auction House GUI", description = "Toggle using the custom Auction House GUI and BIN Sniper Helper.", category = "Economy", - subcategory = "Auction House" + subcategory = "Auction House", ) var customAhGui = true @@ -1594,7 +1643,7 @@ object OneConfigScreen : Config( description = "Use either the Partly Sane Studios developed textures, or the FurfSky Reborn developed textures\n\nAll of the textures under FurfSky Reborn are fully developed by the FurfSky Reborn team.\nhttps://furfsky.net/", category = "Economy", subcategory = "Auction House", - options = ["Partly Sane Studios", "FurfSky Reborn"] + options = ["Partly Sane Studios", "FurfSky Reborn"], ) var customAhGuiTextures = 1 @@ -1604,7 +1653,7 @@ object OneConfigScreen : Config( category = "Economy", subcategory = "Auction House", min = .1f, - max = 1f + max = 1f, ) var masterAuctionHouseScale = .333333f @@ -1613,7 +1662,7 @@ object OneConfigScreen : Config( category = "Economy", subcategory = "Auction House", min = 0f, - max = .2f + max = .2f, ) var auctionHouseItemPadding = .075f @@ -1622,7 +1671,7 @@ object OneConfigScreen : Config( category = "Economy", subcategory = "Auction House", min = .25f, - max = 2f + max = 2f, ) var auctionHouseSideBarHeight = 1.333f @@ -1631,7 +1680,7 @@ object OneConfigScreen : Config( category = "Economy", subcategory = "Auction House", min = .25f, - max = 2f + max = 2f, ) var auctionHouseSideBarWidth = .667f @@ -1640,7 +1689,7 @@ object OneConfigScreen : Config( category = "Economy", subcategory = "Auction House", min = -.5f, - max = .5f + max = .5f, ) var auctionSideBarPadding = .05f @@ -1649,7 +1698,7 @@ object OneConfigScreen : Config( category = "Economy", subcategory = "Auction House", min = .11f, - max = 2f + max = 2f, ) var auctionHouseTextScale = .75f @@ -1658,7 +1707,7 @@ object OneConfigScreen : Config( name = "Excessive Coin and No Booster Cookie", description = "Warns you if you have a lot of coins in your purse and no booster cookie.", category = "Economy", - subcategory = "Excessive Coin Warning" + subcategory = "Excessive Coin Warning", ) var noCookieWarning = false @@ -1668,7 +1717,7 @@ object OneConfigScreen : Config( category = "Economy", subcategory = "Excessive Coin Warning", min = 0f, - max = Int.MAX_VALUE.toFloat() + max = Int.MAX_VALUE.toFloat(), ) var maxWithoutCookie = 750000 @@ -1678,7 +1727,7 @@ object OneConfigScreen : Config( category = "Economy", subcategory = "Excessive Coin Warning", min = 1f, - max = 7f + max = 7f, ) var noCookieWarnTime = 3.5f @@ -1688,7 +1737,7 @@ object OneConfigScreen : Config( category = "Economy", subcategory = "Excessive Coin Warning", min = 1f, - max = 300f + max = 300f, ) var noCookieWarnCooldown = 20f @@ -1698,7 +1747,7 @@ object OneConfigScreen : Config( name = "Word Editor Main Toggle", description = "Allows you to edit words in chat. Can be configured with /wordeditor.", category = "Chat", - subcategory = "Word Editor" + subcategory = "Word Editor", ) var wordEditor = true @@ -1707,16 +1756,16 @@ object OneConfigScreen : Config( name = "Send System Notification", description = "Sends a system notification when a message triggered by the Chat Alert was send.", category = "Chat", - subcategory = "Chat Alerts" + subcategory = "Chat Alerts", ) var chatAlertSendSystemNotification = false - //Chat Colors + // Chat Colors @Switch( name = "Color Private Messages", description = "Private messages pink to make them more visible in busy lobbies.", category = "Chat", - subcategory = "Chat Color" + subcategory = "Chat Color", ) var colorPrivateMessages = false @@ -1724,7 +1773,7 @@ object OneConfigScreen : Config( name = "Color Nons Messages", description = "Color messages from the non-ranked players to white to make them more visible in busy lobbies.", category = "Chat", - subcategory = "Chat Color" + subcategory = "Chat Color", ) var colorNonMessages = false @@ -1732,7 +1781,7 @@ object OneConfigScreen : Config( name = "Color Party Chat", description = "Color messages from the party chat blue to make them more visible in busy lobbies.", category = "Chat", - subcategory = "Chat Color" + subcategory = "Chat Color", ) var colorPartyChat = false @@ -1740,7 +1789,7 @@ object OneConfigScreen : Config( name = "Color Guild Chat", description = "Color messages from the guild chat green to make them more visible in busy lobbies.", category = "Chat", - subcategory = "Chat Color" + subcategory = "Chat Color", ) var colorGuildChat = false @@ -1748,7 +1797,7 @@ object OneConfigScreen : Config( name = "Color Guild Officer Chat", description = "Color messages from the guild officer chat aqua to make them more visible in busy lobbies.", category = "Chat", - subcategory = "Chat Color" + subcategory = "Chat Color", ) var colorOfficerChat = false @@ -1756,7 +1805,7 @@ object OneConfigScreen : Config( name = "SkyBlock Co-op Chat", description = "Color messages from the SkyBlock coop chat aqua to make them more visible in busy lobbies.", category = "Chat", - subcategory = "Chat Color" + subcategory = "Chat Color", ) var colorCoopChat = false @@ -1764,16 +1813,16 @@ object OneConfigScreen : Config( name = "Visible Colors", description = "Converts the custom colors mentioned above to more visible colors. Dark Green -> Light Green and Blue -> Gold. (Recommended)", category = "Chat", - subcategory = "Chat Color" + subcategory = "Chat Color", ) var visibleColors = false - //Fun + // Fun @Switch( name = "OwO Language toggle", description = "Replaces all chat messages with OwO language.\nThis feature basically breaks the whole chat, so please be warned.", category = "Chat", - subcategory = "Fun" + subcategory = "Fun", ) var owoLanguage = false @@ -1781,7 +1830,7 @@ object OneConfigScreen : Config( name = "OwO Chat Transformer", description = "Transforms every chat message you send into OwO language.", category = "Chat", - subcategory = "Fun" + subcategory = "Fun", ) var transformOWO = false @@ -1789,94 +1838,94 @@ object OneConfigScreen : Config( @KeyBind( name = "Debug Hotkey", description = "The keybind to toggle the debug mode.", - category = "Dev" + category = "Dev", ) var debugKeybind = OneKeyBind(Keyboard.KEY_NONE) @Switch( name = "Debug Mode", description = "Toggles the debug mode.", - category = "Dev" + category = "Dev", ) var debugMode = false @Switch( name = "Render TEST Banner", description = "Renders a test banner on your screen.", - category = "Dev" + category = "Dev", ) var debugRenderTestBanner = false @Switch( name = "Chat Analyser", description = "Analyse chat messages and print them to the console.", - category = "Dev" + category = "Dev", ) var debugChatAnalyser = false @Switch( name = "Add a slacker to the party", description = "Adds a slacker to the party.", - category = "Dev" + category = "Dev", ) var debugAddSlacker = false @Switch( name = "Spawn Waypoint", description = "Spawns a waypoint at your current location.", - category = "Dev" + category = "Dev", ) var debugSpawnWaypoint = false @Switch( name = "Send a system notification", description = "Sends a system notification.", - category = "Dev" + category = "Dev", ) var debugSendSystemNotification = false @Switch( name = "Print pet world parsing information", description = "Prints information about the pet world parsing.", - category = "Dev" + category = "Dev", ) var debugPrintPetWorldParsingInformation = false @Switch( name = "Print current location from Island Type", description = "Prints your current location from the island type.", - category = "Dev" + category = "Dev", ) var debugPrintCurrentLocationFromIslandType = false @Switch( name = "Log cached F7 puzzles", description = "Logs cached F7 puzzles.", - category = "Dev" + category = "Dev", ) var debugLogCachedF7Puzzles = false @Switch( name = "Print Current Cached Stats", description = "Prints the current cached stats.", - category = "Dev" + category = "Dev", ) var debugPrintCurrentCachedStats = false @Switch( name = "Render RNG Drop Banner", description = "Renders an RNG Drop Banner.", - category = "Dev" + category = "Dev", ) var debugRenderRNGBanner = false @Switch( name = "Send Discord Webhook", description = "Sends a discord webhook.", - category = "Dev" + category = "Dev", ) var debugSendDiscordWebhook = false - + @Switch( name = "Generate Cylinder", description = "Generates a cylinder.", @@ -1901,21 +1950,21 @@ object OneConfigScreen : Config( @Switch( name = "Remove Crystal Nucleus Coords from Crystal hollows pretty data", description = "Don't use this pt. 3", - category = "Dev" + category = "Dev", ) var debugConvertPrettyDataToNoNucleus = false @Switch( name = "Log display size", description = "Logs the width and height of the display", - category = "Dev" + category = "Dev", ) var debugLogDisplaySize = false @Switch( name = "Display inventory information", description = "Logs the chest contents, xSize and ySize of a GuiChest", - category = "Dev" + category = "Dev", ) var testDevEnv = false @@ -1923,7 +1972,7 @@ object OneConfigScreen : Config( @Switch( name = "Show hidden webhooks in webhook menu", category = "Dev", - subcategory = "Discord" + subcategory = "Discord", ) var showHiddenWebhooks = false @@ -1931,7 +1980,7 @@ object OneConfigScreen : Config( @HUD( name = "Test Hud Element", category = "Dev", - subcategory = "Example HUD" + subcategory = "Example HUD", ) var hud = ExampleHud.oneConfigHud @@ -1940,7 +1989,7 @@ object OneConfigScreen : Config( name = "Percy Mode", description = "Toggles Percy Mode.", category = "Dev", - subcategory = "Percy Mode" + subcategory = "Percy Mode", ) var percyMode = false @@ -1948,7 +1997,7 @@ object OneConfigScreen : Config( name = "Current Screen", description = "Dumps the current screen.", category = "Dev", - subcategory = "Percy Mode" + subcategory = "Percy Mode", ) var debugCurrentScreenDump = false @@ -1956,7 +2005,7 @@ object OneConfigScreen : Config( name = "Entity Dump", description = "Dumps all entities.", category = "Dev", - subcategory = "Percy Mode" + subcategory = "Percy Mode", ) var debugEntityDump = false @@ -1964,7 +2013,7 @@ object OneConfigScreen : Config( name = "Inventory Dump", description = "Dumps your inventory.", category = "Dev", - subcategory = "Percy Mode" + subcategory = "Percy Mode", ) var debugInventoryDump = false @@ -1972,7 +2021,7 @@ object OneConfigScreen : Config( name = "Player Dump", description = "Dumps all players.", category = "Dev", - subcategory = "Percy Mode" + subcategory = "Percy Mode", ) var debugPlayerDump = false @@ -1983,7 +2032,7 @@ object OneConfigScreen : Config( category = "Dev", subcategory = "API", min = .1f, - max = 30f + max = 30f, ) var timeBetweenRequests = 0.5f @@ -1993,7 +2042,7 @@ object OneConfigScreen : Config( category = "Dev", subcategory = "API", min = 0f, - max = 90f + max = 90f, ) var playerDataCacheTime = 5 @@ -2001,7 +2050,7 @@ object OneConfigScreen : Config( name = "Print errors in chat", description = "Send errors on getting data in chat (Recommended, however if you get spammed or have a bad internet connection, turn it off).", category = "Dev", - subcategory = "API" + subcategory = "API", ) var printApiErrors = true @@ -2010,7 +2059,7 @@ object OneConfigScreen : Config( description = "Change the owner of the repo used for public data.", category = "Dev", subcategory = "API Source", - secure = true + secure = true, ) var repoOwner = "PartlySaneStudios" @@ -2019,7 +2068,7 @@ object OneConfigScreen : Config( description = "Change the name of the repo used for public data.", category = "Dev", subcategory = "API Source", - secure = true + secure = true, ) var repoName = "partly-sane-skies-public-data" @@ -2027,14 +2076,14 @@ object OneConfigScreen : Config( name = "API URL", category = "Dev", subcategory = "API Source", - secure = true + secure = true, ) var apiUrl = "http://partlysanecloud.su386.dev" @Switch( name = "Load API Data Directly from GitHub", category = "Dev", - subcategory = "API Source" + subcategory = "API Source", ) var useGithubForPublicData = false diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/config/PSSHud.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/config/PSSHud.kt index 8653a18b5..e7fd532bb 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/config/PSSHud.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/config/PSSHud.kt @@ -26,7 +26,7 @@ abstract class PSSHud( protected var x: Float = 0.0F, protected var y: Float = 0.0F, var positionAlignment: Int = 0, - var scale: Float = 1.0f + var scale: Float = 1.0f, ) { /** * Whether the current rendering cycle is an example (when the user is configuring the main menu) @@ -38,33 +38,37 @@ abstract class PSSHud( * * @return The OneConfig hud */ - open val oneConfigHud = object : Hud(enabled, x, y, positionAlignment, scale) { - override fun draw(matrices: UMatrixStack?, x: Float, y: Float, scale: Float, example: Boolean) { - this@PSSHud.x = x - this@PSSHud.y = y - this@PSSHud.scale = scale - this@PSSHud.example = example - } - - override fun getWidth(scale: Float, example: Boolean): Float { - return try { - this@PSSHud.getWidth(scale, example) - } catch (e: Exception) { - e.printStackTrace() - 0.0F + open val oneConfigHud = + object : Hud(enabled, x, y, positionAlignment, scale) { + override fun draw( + matrices: UMatrixStack?, + x: Float, + y: Float, + scale: Float, + example: Boolean, + ) { + this@PSSHud.x = x + this@PSSHud.y = y + this@PSSHud.scale = scale + this@PSSHud.example = example } - } - override fun getHeight(scale: Float, example: Boolean): Float { - return try { - this@PSSHud.getHeight(scale, example) - } catch (e: Exception) { - e.printStackTrace() - 0.0F - } - } - } + override fun getWidth(scale: Float, example: Boolean): Float = + try { + this@PSSHud.getWidth(scale, example) + } catch (e: Exception) { + e.printStackTrace() + 0.0F + } + override fun getHeight(scale: Float, example: Boolean): Float = + try { + this@PSSHud.getHeight(scale, example) + } catch (e: Exception) { + e.printStackTrace() + 0.0F + } + } /** * @return Height of the Hud's bounding box in pixels @@ -81,6 +85,4 @@ abstract class PSSHud( * @param example whether it is an example or not */ abstract fun getWidth(scale: Float, example: Boolean): Float - - -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/config/psconfig/Config.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/config/psconfig/Config.kt index ae80a4868..efdb3aff5 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/config/psconfig/Config.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/config/psconfig/Config.kt @@ -3,7 +3,6 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.config.psconfig import com.google.gson.JsonElement @@ -12,10 +11,10 @@ import me.partlysanestudios.partlysaneskies.utils.SystemUtils.log import org.apache.logging.log4j.Level class Config : ConfigOption() { - companion object { val ConfigOption.asConfig get() = this as Config } + // Recursively find paths for options fun find(path: String): ConfigOption? { val indexOfSplit = path.indexOf("/") @@ -34,6 +33,7 @@ class Config : ConfigOption() { } private val options = LinkedHashMap() + // Recursively create new options to get to the path fun registerOption(path: String, configOption: ConfigOption): Config { val indexOfSplit = path.indexOf("/") @@ -55,9 +55,7 @@ class Config : ConfigOption() { return this } - fun getAllOptions(): LinkedHashMap { - return options.clone() as LinkedHashMap - } + fun getAllOptions(): LinkedHashMap = options.clone() as LinkedHashMap override fun loadFromJson(element: JsonElement) { val obj = element.asJsonObject @@ -66,7 +64,7 @@ class Config : ConfigOption() { // If the parameter exists if (obj.has(option.key)) { try { - option.value.loadFromJson(obj.get(option.key)) + option.value.loadFromJson(obj[option.key]) } catch (e: Exception) { log(Level.ERROR, "Error loading option ${option.key}") @@ -86,11 +84,15 @@ class Config : ConfigOption() { } var savePath: String? = null + fun save() { if (parent == null) { - ConfigManager.saveConfig(savePath ?: throw IllegalArgumentException("Unable to Save. No save path provided. Config is not registered."), this) + ConfigManager.saveConfig( + savePath ?: throw IllegalArgumentException("Unable to Save. No save path provided. Config is not registered."), + this, + ) } else { (parent as? Config)?.save() ?: throw IllegalArgumentException("Unable to save. Parent of config is not a config.") } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/config/psconfig/ConfigManager.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/config/psconfig/ConfigManager.kt index 33ed7573d..e2a81a718 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/config/psconfig/ConfigManager.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/config/psconfig/ConfigManager.kt @@ -3,7 +3,6 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.config.psconfig import com.google.gson.GsonBuilder @@ -11,11 +10,9 @@ import com.google.gson.JsonParser import me.partlysanestudios.partlysaneskies.utils.SystemUtils.log import org.apache.logging.log4j.Level import java.io.FileWriter -import java.nio.file.Files import kotlin.io.path.Path object ConfigManager { - private val configs = HashMap() // Save path should not include the /config/partly-sane-skies/ @@ -84,6 +81,5 @@ object ConfigManager { e.printStackTrace() } } - } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/config/psconfig/ConfigOption.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/config/psconfig/ConfigOption.kt index e2c5232ff..9915582df 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/config/psconfig/ConfigOption.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/config/psconfig/ConfigOption.kt @@ -3,15 +3,14 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.config.psconfig import com.google.gson.JsonElement abstract class ConfigOption { - abstract fun loadFromJson(element: JsonElement) + abstract fun saveToJson(): JsonElement open var parent: ConfigOption? = null -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/config/psconfig/Toggle.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/config/psconfig/Toggle.kt index 4d75ea7ce..147de7331 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/config/psconfig/Toggle.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/config/psconfig/Toggle.kt @@ -3,7 +3,6 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.config.psconfig import com.google.gson.JsonElement @@ -13,8 +12,8 @@ import me.partlysanestudios.partlysaneskies.config.psconfig.Config.Companion.asC class Toggle( val name: String, val description: String = "", - defaultState: Boolean = false -): ConfigOption() { + defaultState: Boolean = false, +) : ConfigOption() { companion object { val ConfigOption.asToggle get() = this as Toggle val ConfigOption.asBoolean get() = this.asToggle.state @@ -32,9 +31,5 @@ class Toggle( state = element.asBoolean } - override fun saveToJson(): JsonElement { - return JsonParser().parse(state.toString()) - } - - -} \ No newline at end of file + override fun saveToJson(): JsonElement = JsonParser().parse(state.toString()) +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/api/GetRequest.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/api/GetRequest.kt index 46d191741..0d5689ce0 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/api/GetRequest.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/api/GetRequest.kt @@ -7,45 +7,45 @@ import org.apache.logging.log4j.Level import java.io.BufferedReader import java.io.InputStreamReader import java.net.HttpURLConnection -import javax.net.ssl.HttpsURLConnection import java.net.URL - +import java.security.cert.X509Certificate +import javax.net.ssl.HostnameVerifier +import javax.net.ssl.HttpsURLConnection import javax.net.ssl.SSLContext import javax.net.ssl.TrustManager import javax.net.ssl.X509TrustManager -import java.security.cert.X509Certificate -import javax.net.ssl.HostnameVerifier class GetRequest( url: URL, function: RequestRunnable?, inMainThread: Boolean = false, executeOnNextFrame: Boolean = false, - acceptAllCertificates: Boolean = false + acceptAllCertificates: Boolean = false, ) : Request(url, function, inMainThread, executeOnNextFrame, acceptAllCertificates) { constructor( url: String, function: RequestRunnable?, inMainThread: Boolean = false, executeOnNextFrame: Boolean = false, - acceptAllCertificates: Boolean = false - ): this(URL(url), function, inMainThread, executeOnNextFrame, acceptAllCertificates) + acceptAllCertificates: Boolean = false, + ) : this(URL(url), function, inMainThread, executeOnNextFrame, acceptAllCertificates) // Constructor without certificate option constructor( url: URL, function: RequestRunnable?, inMainThread: Boolean = false, - executeOnNextFrame: Boolean = false - ): this(url, function, inMainThread, executeOnNextFrame, false) + executeOnNextFrame: Boolean = false, + ) : this(url, function, inMainThread, executeOnNextFrame, false) // Constructor without certificates option constructor( url: String, function: RequestRunnable?, inMainThread: Boolean = false, - executeOnNextFrame: Boolean = false - ): this(URL(url), function, inMainThread, executeOnNextFrame, false) + executeOnNextFrame: Boolean = false, + ) : this(URL(url), function, inMainThread, executeOnNextFrame, false) + override fun startRequest() { // Opens a new connection with the url val connection = url.openConnection() as HttpURLConnection @@ -53,11 +53,22 @@ class GetRequest( connection.setRequestProperty("User-Agent", "Partly-Sane-Skies/" + PartlySaneSkies.VERSION) if (acceptAllCertificates && connection is HttpsURLConnection) { // Create a trust manager that does not validate certificate chains - val trustAllCerts = arrayOf(object : X509TrustManager { - override fun getAcceptedIssuers(): Array = arrayOf() - override fun checkClientTrusted(chain: Array, authType: String) {} - override fun checkServerTrusted(chain: Array, authType: String) {} - }) + val trustAllCerts = + arrayOf( + object : X509TrustManager { + override fun getAcceptedIssuers(): Array = arrayOf() + + override fun checkClientTrusted( + chain: Array, + authType: String, + ) {} + + override fun checkServerTrusted( + chain: Array, + authType: String, + ) {} + }, + ) // Install the all-trusting trust manager for a specific SSL context val sslContext = SSLContext.getInstance("SSL") @@ -87,25 +98,25 @@ class GetRequest( if (PartlySaneSkies.config.printApiErrors) { sendClientMessage( """ - Error: ${connection.getResponseMessage()}:${connection.getResponseCode()} - Contact PSS admins for more information - """.trimIndent() + Error: ${connection.getResponseMessage()}:${connection.getResponseCode()} + Contact PSS admins for more information + """.trimIndent(), ) } else { log( Level.ERROR, """ - Error: ${connection.getResponseMessage()}:${connection.getResponseCode()} - Contact PSS admins for more information - """.trimIndent() + Error: ${connection.getResponseMessage()}:${connection.getResponseCode()} + Contact PSS admins for more information + """.trimIndent(), ) } log( Level.ERROR, """ - Error: ${connection.getResponseMessage()}:${connection.getResponseCode()} - URL: ${url} - """.trimIndent() + Error: ${connection.getResponseMessage()}:${connection.getResponseCode()} + URL: $url + """.trimIndent(), ) // Disconnect the connection connection.disconnect() @@ -138,5 +149,4 @@ class GetRequest( // Runs on current thread function.run(this) } - -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/api/PostRequest.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/api/PostRequest.kt index e2027f7a9..ced937f78 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/api/PostRequest.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/api/PostRequest.kt @@ -8,8 +8,11 @@ import java.io.BufferedReader import java.io.InputStreamReader import java.net.URL import java.security.cert.X509Certificate -import javax.net.ssl.* - +import javax.net.ssl.HostnameVerifier +import javax.net.ssl.HttpsURLConnection +import javax.net.ssl.SSLContext +import javax.net.ssl.TrustManager +import javax.net.ssl.X509TrustManager class PostRequest( url: URL, @@ -26,7 +29,7 @@ class PostRequest( inMainThread: Boolean = false, executeOnNextFrame: Boolean = false, acceptAllCertificates: Boolean = false, - ): this(URL(url), function, postContent, inMainThread, executeOnNextFrame, acceptAllCertificates) + ) : this(URL(url), function, postContent, inMainThread, executeOnNextFrame, acceptAllCertificates) // Constructor without certificate option @Deprecated("Use constructor with acceptAllCertificates option") @@ -36,7 +39,7 @@ class PostRequest( postContent: String, inMainThread: Boolean = false, executeOnNextFrame: Boolean = false, - ): this(url, function, postContent, inMainThread, executeOnNextFrame, false) + ) : this(url, function, postContent, inMainThread, executeOnNextFrame, false) // Constructor without certificates option @Deprecated("Use constructor with acceptAllCertificates option") @@ -46,7 +49,7 @@ class PostRequest( postContent: String, inMainThread: Boolean = false, executeOnNextFrame: Boolean = false, - ): this(URL(url), function, postContent, inMainThread, executeOnNextFrame, false) + ) : this(URL(url), function, postContent, inMainThread, executeOnNextFrame, false) override fun startRequest() { // Opens a new connection with the url @@ -56,11 +59,22 @@ class PostRequest( connection.setRequestProperty("Content-Type", "application/json") if (acceptAllCertificates) { // Create a trust manager that does not validate certificate chains - val trustAllCerts = arrayOf(object : X509TrustManager { - override fun getAcceptedIssuers(): Array = arrayOf() - override fun checkClientTrusted(chain: Array, authType: String) {} - override fun checkServerTrusted(chain: Array, authType: String) {} - }) + val trustAllCerts = + arrayOf( + object : X509TrustManager { + override fun getAcceptedIssuers(): Array = arrayOf() + + override fun checkClientTrusted( + chain: Array, + authType: String, + ) {} + + override fun checkServerTrusted( + chain: Array, + authType: String, + ) {} + }, + ) // Install the all-trusting trust manager for a specific SSL context val sslContext = SSLContext.getInstance("SSL") @@ -96,25 +110,25 @@ class PostRequest( if (PartlySaneSkies.config.printApiErrors) { ChatUtils.sendClientMessage( """ - Error: ${connection.getResponseMessage()}:${connection.getResponseCode()} - Contact PSS admins for more information - """.trimIndent() + Error: ${connection.getResponseMessage()}:${connection.getResponseCode()} + Contact PSS admins for more information + """.trimIndent(), ) } else { SystemUtils.log( Level.ERROR, """ - Error: ${connection.getResponseMessage()}:${connection.getResponseCode()} - Contact PSS admins for more information - """.trimIndent() + Error: ${connection.getResponseMessage()}:${connection.getResponseCode()} + Contact PSS admins for more information + """.trimIndent(), ) } SystemUtils.log( Level.ERROR, """ - Error: ${connection.getResponseMessage()}:${connection.getResponseCode()} - URL: $url - """.trimIndent() + Error: ${connection.getResponseMessage()}:${connection.getResponseCode()} + URL: $url + """.trimIndent(), ) // Disconnect the connection connection.disconnect() @@ -147,4 +161,4 @@ class PostRequest( // Runs on current thread function.run(this) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/api/Request.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/api/Request.kt index 9f54563a0..922043375 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/api/Request.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/api/Request.kt @@ -3,19 +3,10 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.data.api -import me.partlysanestudios.partlysaneskies.PartlySaneSkies -import me.partlysanestudios.partlysaneskies.utils.ChatUtils.sendClientMessage -import me.partlysanestudios.partlysaneskies.utils.SystemUtils.log -import org.apache.logging.log4j.Level -import java.io.BufferedReader import java.io.IOException -import java.io.InputStreamReader -import java.net.HttpURLConnection import java.net.URL -import java.security.cert.X509Certificate import javax.net.ssl.* /** @@ -31,7 +22,7 @@ abstract class Request( internal val function: RequestRunnable?, internal val inMainThread: Boolean = false, internal val executeOnNextFrame: Boolean = false, - internal val acceptAllCertificates: Boolean = false + internal val acceptAllCertificates: Boolean = false, ) { // Constructor with string url and certificate option constructor( @@ -39,7 +30,7 @@ abstract class Request( function: RequestRunnable?, inMainThread: Boolean = false, executeOnNextFrame: Boolean = false, - acceptAllCertificates: Boolean = false + acceptAllCertificates: Boolean = false, ) : this(URL(url), function, inMainThread, executeOnNextFrame, acceptAllCertificates) // Constructor without certificate option @@ -47,7 +38,7 @@ abstract class Request( url: URL, function: RequestRunnable?, inMainThread: Boolean = false, - executeOnNextFrame: Boolean = false + executeOnNextFrame: Boolean = false, ) : this(url, function, inMainThread, executeOnNextFrame, false) // Constructor without certificates option @@ -55,7 +46,7 @@ abstract class Request( url: String, function: RequestRunnable?, inMainThread: Boolean = false, - executeOnNextFrame: Boolean = false + executeOnNextFrame: Boolean = false, ) : this(URL(url), function, inMainThread, executeOnNextFrame, false) // A string that contains the response message (not body) @@ -74,7 +65,6 @@ abstract class Request( // A list that contains all the HTTP codes where the request should rerun internal var tryAgainOnCodes = ArrayList() - /** * Flags the request as failed * @@ -82,7 +72,6 @@ abstract class Request( */ fun setFailed(reason: String = "") { if (reason != "") { - this.responseMessage = reason } this.hasFailed = true @@ -91,12 +80,12 @@ abstract class Request( /** * @return if the request has failed */ - fun hasSucceeded(): Boolean { - return if (responseCode !in 200..299) { + fun hasSucceeded(): Boolean = + if (responseCode !in 200..299) { false - } else !hasFailed - } - + } else { + !hasFailed + } /** * Sends the get request @@ -107,16 +96,12 @@ abstract class Request( /** * @return the request runnable */ - fun getWhatToRunWhenFinished(): RequestRunnable? { - return function - } + fun getWhatToRunWhenFinished(): RequestRunnable? = function /** * @return the request url */ - fun getURL(): URL { - return url - } + fun getURL(): URL = url /** * Adds codes to the try again list. Whenever the response encounters one of these codes, it will send a new request. @@ -142,21 +127,15 @@ abstract class Request( /** * @return if the request will run in the main thread */ - fun isMainThread(): Boolean { - return inMainThread - } + fun isMainThread(): Boolean = inMainThread /** * @return if the RequestManager will run the RequestRunnable in the main thread on the next frame */ - fun isRunNextFrame(): Boolean { - return executeOnNextFrame - } + fun isRunNextFrame(): Boolean = executeOnNextFrame /** * @return the error message and response code */ - fun getErrorMessage(): String { - return "Error: " + this.responseMessage + ":" + this.responseCode - } -} \ No newline at end of file + fun getErrorMessage(): String = "Error: " + this.responseMessage + ":" + this.responseCode +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/api/RequestRunnable.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/api/RequestRunnable.kt index f0610daa2..bb66dfbfc 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/api/RequestRunnable.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/api/RequestRunnable.kt @@ -3,10 +3,8 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.data.api fun interface RequestRunnable { fun run(request: Request) - -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/api/RequestsManager.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/api/RequestsManager.kt index 6a74a4667..9a6ca36af 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/api/RequestsManager.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/api/RequestsManager.kt @@ -3,7 +3,6 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.data.api import me.partlysanestudios.partlysaneskies.PartlySaneSkies @@ -13,29 +12,29 @@ import java.util.LinkedList import java.util.Queue object RequestsManager { - private val requestsQueue: Queue = LinkedList() private var lastRequestTime: Long = 0 + val thread = + Thread( + { + while (true) { + try { + run() + } catch (exception: Exception) { + exception.printStackTrace() + } finally { + } - val thread = Thread({ - while (true) { - try { - run() - - } catch (exception: Exception) { - exception.printStackTrace() - } finally { - - } - - try { - Thread.sleep(50) - } catch (e: InterruptedException) { - e.printStackTrace() - } - } - }, "Partly Sane Skies Request Manager").start() + try { + Thread.sleep(50) + } catch (e: InterruptedException) { + e.printStackTrace() + } + } + }, + "Partly Sane Skies Request Manager", + ).start() private fun run() { if (requestsQueue.isEmpty()) { @@ -65,7 +64,6 @@ object RequestsManager { e.printStackTrace() } } - } else { var loggedUrl = element.getURL().toString() @@ -74,24 +72,27 @@ object RequestsManager { } // Creates a new thread to execute request - Thread(Runnable { - try { - element.startRequest() - } catch (e: IOException) { - element.setFailed("") - // If supposed to run in the next frame, run in the next frame - if (element.isRunNextFrame()) { - PartlySaneSkies.minecraft.addScheduledTask { - element.getWhatToRunWhenFinished()!!.run(element) + Thread( + Runnable { + try { + element.startRequest() + } catch (e: IOException) { + element.setFailed("") + // If supposed to run in the next frame, run in the next frame + if (element.isRunNextFrame()) { + PartlySaneSkies.minecraft.addScheduledTask { + element.getWhatToRunWhenFinished()!!.run(element) + } + return@Runnable } - return@Runnable - } - // Runs on current thread - element.getWhatToRunWhenFinished()?.run(element) - e.printStackTrace() - } - }, "Request to $loggedUrl").start() + // Runs on current thread + element.getWhatToRunWhenFinished()?.run(element) + e.printStackTrace() + } + }, + "Request to $loggedUrl", + ).start() } } diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/cache/PetData.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/cache/PetData.kt index 8c7125f35..3e269c62a 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/cache/PetData.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/cache/PetData.kt @@ -3,7 +3,6 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.data.cache import com.google.gson.Gson @@ -12,15 +11,15 @@ import com.google.gson.annotations.Expose import me.partlysanestudios.partlysaneskies.PartlySaneSkies import me.partlysanestudios.partlysaneskies.data.skyblockdata.Rarity import me.partlysanestudios.partlysaneskies.data.skyblockdata.Rarity.Companion.getRarityFromColorCode +import me.partlysanestudios.partlysaneskies.events.SubscribePSSEvent +import me.partlysanestudios.partlysaneskies.events.minecraft.PSSChatEvent +import me.partlysanestudios.partlysaneskies.events.minecraft.TablistUpdateEvent import me.partlysanestudios.partlysaneskies.utils.MathUtils -import me.partlysanestudios.partlysaneskies.utils.MinecraftUtils import me.partlysanestudios.partlysaneskies.utils.MinecraftUtils.containerInventory import me.partlysanestudios.partlysaneskies.utils.StringUtils.nextAfter import me.partlysanestudios.partlysaneskies.utils.StringUtils.removeColorCodes import me.partlysanestudios.partlysaneskies.utils.StringUtils.removeResets import net.minecraft.client.gui.inventory.GuiChest -import net.minecraftforge.client.event.ClientChatReceivedEvent -import net.minecraftforge.fml.common.eventhandler.SubscribeEvent import java.io.FileWriter import java.io.IOException import java.io.Reader @@ -38,20 +37,19 @@ object PetData { val petNameRegex = "§.\\[Lvl (\\d+)] (§.)(\\w+(\\s\\w+)*)(?: ✦)?".toRegex() - var lastSaveTime = -1L + fun tick() { parsePetGuiForCache() - parsePetFromTablist() if (MathUtils.onCooldown(lastSaveTime, (60 * 1000L * .25).toLong())) { return } lastSaveTime = PartlySaneSkies.time - Thread({ - save() - }, "Pet Data Save").start() - + Thread( + { save() }, + "Pet Data Save", + ).start() } @Throws(IOException::class) @@ -109,23 +107,23 @@ object PetData { */ fun getCurrentPetRarity() = petDataJson?.currentPetRarity ?: Rarity.UNKNOWN - @SubscribeEvent - fun parseFromChat(event: ClientChatReceivedEvent) { + @SubscribePSSEvent + fun onChat(event: PSSChatEvent) { // Parse despawn message - if (event.message.unformattedText.startsWith("You despawned your")) { + if (event.component.unformattedText.startsWith("You despawned your")) { petDataJson?.currentPetName = "" petDataJson?.currentPetLevel = -1 petDataJson?.currentPetRarity = Rarity.UNKNOWN } - if (event.message.unformattedText.startsWith("You summoned your")) { + if (event.component.unformattedText.startsWith("You summoned your")) { // Define the regular expression pattern val regex = "§r§aYou summoned your §r(§.)(\\w+(\\s\\w+)*)( ✦)?§r§a!§r" // Create a Pattern object val pattern: Pattern = Pattern.compile(regex) // Create a Matcher object - val matcher: Matcher = pattern.matcher(event.message.formattedText) + val matcher: Matcher = pattern.matcher(event.message) if (!matcher.find()) { return } @@ -137,10 +135,10 @@ object PetData { } val petLevelUpRegex = "§r§aYour §r(§.)(\\w+(\\s\\w+)*)( ✦)? §r§aleveled up to level §r§9(\\d+)§r§a!§r".toRegex() - if (petLevelUpRegex.find(event.message.formattedText) != null) { + if (petLevelUpRegex.find(event.message) != null) { // Find the match - val matchResult = petLevelUpRegex.find(event.message.formattedText) + val matchResult = petLevelUpRegex.find(event.message) // Extract pet name and level if a match is found matchResult?.let { @@ -153,24 +151,21 @@ object PetData { } } - if (petNameRegex.find(event.message.formattedText) != null) { - val matchResult = petNameRegex.find(event.message.formattedText)!! + if (petNameRegex.find(event.message) != null) { + val matchResult = petNameRegex.find(event.message)!! // Extract the pet level and name val (petLevel, colorCode, petName) = matchResult.destructured - petDataJson?.currentPetLevel = petLevel.toInt() petDataJson?.currentPetName = petName petDataJson?.currentPetRarity = colorCode.getRarityFromColorCode() petDataJson?.petNameLevelMap?.get(petDataJson?.currentPetRarity)?.put(petName, petLevel.toInt()) - } } - private fun parsePetFromTablist() { - val tablist = MinecraftUtils.getTabList() - - val pet = tablist.nextAfter("§e§lPet:")?.removeResets()?.trim() ?: return + @SubscribePSSEvent + fun parsePetFromTablist(event: TablistUpdateEvent) { + val pet = event.list.nextAfter("§e§lPet:")?.removeResets()?.trim() ?: return petNameRegex.find(pet)?.let { val (petLevel, colorCode, petName) = it.destructured @@ -220,7 +215,6 @@ object PetData { * @property petNameLevelMap: A two-dimensional map with the rarity as the first key, and a hashmap containing the pet name as the key and the pet level as the value as the value */ private class PetDataJson { - @Expose var currentPetName: String = "" @@ -239,4 +233,4 @@ object PetData { } } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/cache/StatsData.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/cache/StatsData.kt index 22cbd57c8..7a09c406c 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/cache/StatsData.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/cache/StatsData.kt @@ -4,7 +4,7 @@ import net.minecraftforge.client.event.ClientChatReceivedEvent import net.minecraftforge.fml.common.eventhandler.SubscribeEvent object StatsData { - //Public variables + // Public variables val currentHealth: Double get() = cachedCurrentHealth val maxHealth: Double get() = cachedMaxHealth val defense: Double get() = cachedCurrentDefense @@ -18,7 +18,7 @@ object StatsData { private var cachedMaxMana = -1.0 @SubscribeEvent - fun onChatMessage(event: ClientChatReceivedEvent) { + fun onActionbar(event: ClientChatReceivedEvent) { if (event.type != 2.toByte()) { return } @@ -69,4 +69,4 @@ object StatsData { this.cachedCurrentDefense = current.replace(",", "").toDoubleOrNull() ?: cachedCurrentDefense } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/cache/VisitorLogbookData.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/cache/VisitorLogbookData.kt index e0e3b479c..2ef4b28b9 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/cache/VisitorLogbookData.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/cache/VisitorLogbookData.kt @@ -24,7 +24,6 @@ import java.nio.file.Paths import kotlin.io.path.Path object VisitorLogbookData { - private var data: VisitorLogBookJson? = null private val jsonPath = Path("./config/partly-sane-skies/visitorLogbook.json") @@ -104,17 +103,21 @@ object VisitorLogbookData { } } - val texture = - item.tagCompound?.getCompoundTag("SkullOwner")?.getCompoundTag("Properties")?.getTagList("textures", 10) - ?.getCompoundTagAt(0)?.getString("Value") ?: "" + val texture = item.tagCompound + ?.getCompoundTag("SkullOwner") + ?.getCompoundTag("Properties") + ?.getTagList("textures", 10) + ?.getCompoundTagAt(0) + ?.getString("Value") ?: "" val visitor = Visitor(displayName, rarity, texture, timesVisited, timesAccepted) data?.visitors?.set("$displayName+$texture", visitor) } - Thread({ - save() - }, "Visitor Data Save").start() + Thread( + { save() }, + "Visitor Data Save", + ).start() } fun getVisitor(name: String): Visitor? { @@ -124,18 +127,14 @@ object VisitorLogbookData { if (visitor.name == name) { return visitor } - } return null - } else { return visitor } } - fun getAllVisitors(): MutableCollection { - return data?.visitors?.values ?: ArrayList() - } + fun getAllVisitors(): MutableCollection = data?.visitors?.values ?: ArrayList() fun isVisitorLogbook(screen: GuiScreen): Boolean { if (screen !is GuiChest) { @@ -159,4 +158,4 @@ object VisitorLogbookData { @Expose val visitors = HashMap() } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/pssdata/PublicDataManager.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/pssdata/PublicDataManager.kt index 526bc8c7b..eb0877945 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/pssdata/PublicDataManager.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/pssdata/PublicDataManager.kt @@ -8,32 +8,25 @@ package me.partlysanestudios.partlysaneskies.data.pssdata import me.partlysanestudios.partlysaneskies.PartlySaneSkies.Companion.config import me.partlysanestudios.partlysaneskies.commands.PSSCommand import me.partlysanestudios.partlysaneskies.data.api.GetRequest -import me.partlysanestudios.partlysaneskies.data.api.Request import me.partlysanestudios.partlysaneskies.data.api.RequestsManager import me.partlysanestudios.partlysaneskies.events.data.LoadPublicDataEvent import me.partlysanestudios.partlysaneskies.utils.ChatUtils.sendClientMessage -import net.minecraft.command.ICommandSender import net.minecraft.util.ChatComponentText import java.net.MalformedURLException object PublicDataManager { - // Add all initializing of public data here private val fileCache = HashMap() /** * @return the current repo's owner */ - fun getRepoOwner(): String { - return config.repoOwner - } + fun getRepoOwner(): String = config.repoOwner /** * @return the current repo's name */ - fun getRepoName(): String { - return config.repoName - } + fun getRepoName(): String = config.repoName /** * Gets the file from either the cache or the GitHub repo @@ -57,14 +50,17 @@ object PublicDataManager { try { val url = getPublicDataUrl(getRepoOwner(), getRepoName(), fixedPath) RequestsManager.newRequest( - GetRequest(url, { - if (!it.hasSucceeded()) { + GetRequest( + url, + { + if (!it.hasSucceeded()) { + synchronized(lock) { lock.notifyAll() } + return@GetRequest + } + fileCache[path] = it.getResponse() synchronized(lock) { lock.notifyAll() } - return@GetRequest - } - fileCache[path] = it.getResponse() - synchronized(lock) { lock.notifyAll() } - }) + }, + ), ) } catch (e: MalformedURLException) { synchronized(lock) { lock.notifyAll() } @@ -77,16 +73,21 @@ object PublicDataManager { return if (!fileCache.containsKey(path)) { "" - } else fileCache[fixedPath] ?: "" + } else { + fileCache[fixedPath] ?: "" + } } - fun getPublicDataUrl(repoOwner: String, repoName: String, filePath: String): String { - return if (config.useGithubForPublicData) { - "https://raw.githubusercontent.com/${repoOwner}/${repoName}/main/data/${filePath}" + fun getPublicDataUrl( + repoOwner: String, + repoName: String, + filePath: String, + ): String = + if (config.useGithubForPublicData) { + "https://raw.githubusercontent.com/$repoOwner/$repoName/main/data/$filePath" } else { - "${config.apiUrl}/v1/pss/publicdata?owner=${repoOwner}&repo=${repoName}&path=/data/${filePath}" + "${config.apiUrl}/v1/pss/publicdata?owner=$repoOwner&repo=$repoName&path=/data/$filePath" } - } /** * Creates and registers the clear data command @@ -99,13 +100,14 @@ object PublicDataManager { .addAlias("pssclearcache") .setDescription("Clears your Partly Sane Studios data") .setRunnable { - val chatcomponent = ChatComponentText( - """ - §b§4-----------------------------------------------------§7 - Data Refreshed - §b§4-----------------------------------------------------§0 - """.trimIndent() - ) + val chatcomponent = + ChatComponentText( + """ + §b§4-----------------------------------------------------§7 + Data Refreshed + §b§4-----------------------------------------------------§0 + """.trimIndent(), + ) fileCache.clear() sendClientMessage(chatcomponent) LoadPublicDataEvent.onDataLoad() @@ -113,5 +115,4 @@ object PublicDataManager { } private class Lock : Object() - } diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/skyblockdata/IslandType.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/skyblockdata/IslandType.kt index 67b57a278..c52df64af 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/skyblockdata/IslandType.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/skyblockdata/IslandType.kt @@ -6,8 +6,7 @@ package me.partlysanestudios.partlysaneskies.data.skyblockdata -import me.partlysanestudios.partlysaneskies.utils.MinecraftUtils -import me.partlysanestudios.partlysaneskies.utils.StringUtils.removeColorCodes +import me.partlysanestudios.partlysaneskies.utils.HypixelUtils enum class IslandType(val islandName: String) { HUB("Hub"), @@ -22,34 +21,23 @@ enum class IslandType(val islandName: String) { DEEP_CAVERNS("Deep Caverns"), DWARVEN_MINES("Dwarven Mines"), CRYSTAL_HOLLOWS("Crystal Hollows"), + MINESHAFT("Mineshaft"), FARMING_ISLAND("The Farming Islands"), - WINTER_ISLAND("Jerry's Workshop"), // value by sh, unconfirmed + WINTER_ISLAND("Jerry's Workshop"), RIFT("The Rift"), CATACOMBS("Catacombs"), KUUDRA("Kuudra"), - NONE(""); + NONE(""), + ; - fun onIsland(): Boolean { - return this == IslandType.getCurrentIsland() - } + fun onIsland() = this == HypixelUtils.currentIsland companion object { /** - * Gets the current island type from the tablist - * @return The current island type + * @param islandTypes The island to check for + * @return True if the player is on any of the specified islands */ - fun getCurrentIsland(): IslandType { - for (line in MinecraftUtils.getTabList()) { - if (line.removeColorCodes().startsWith("Area: ") || line.removeColorCodes().startsWith("Dungeon: ")) { - val islandName = line.removeColorCodes().replace("Area: ", "").replace("Dungeon: ", "").trim() - - return IslandType.entries.firstOrNull { it.islandName.equals(islandName, ignoreCase = true) } - ?: NONE - } - } - - return NONE - } + fun onIslands(vararg islandTypes: IslandType) = islandTypes.any { it.onIsland() } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/skyblockdata/Rarity.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/skyblockdata/Rarity.kt index ad3dcba87..d9f93d32e 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/skyblockdata/Rarity.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/skyblockdata/Rarity.kt @@ -23,14 +23,15 @@ enum class Rarity(val order: Int, val colorCode: String, val displayName: String ULTIMATE_COSMETIC(7, "§4", "Ultimate Cosmetic"), SPECIAL(8, "§c", "Special"), VERY_SPECIAL(9, "§c", "Very Special"), - UNOBTAINABLE(10, "§4", "Admin"); + UNOBTAINABLE(10, "§4", "Admin"), + ; companion object { /** * @return the rarity associated with a color code */ - fun String.getRarityFromColorCode(): Rarity { - return when (this) { + fun String.getRarityFromColorCode(): Rarity = + when (this) { COMMON.colorCode -> COMMON UNCOMMON.colorCode -> UNCOMMON RARE.colorCode -> RARE @@ -45,7 +46,5 @@ enum class Rarity(val order: Int, val colorCode: String, val displayName: String else -> UNKNOWN } - - } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/skyblockdata/SkyblockDataManager.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/skyblockdata/SkyblockDataManager.kt index 80a208d17..c1f83656c 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/skyblockdata/SkyblockDataManager.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/skyblockdata/SkyblockDataManager.kt @@ -15,6 +15,7 @@ import me.partlysanestudios.partlysaneskies.data.api.RequestsManager.newRequest import me.partlysanestudios.partlysaneskies.data.pssdata.PublicDataManager.getFile import me.partlysanestudios.partlysaneskies.events.SubscribePSSEvent import me.partlysanestudios.partlysaneskies.events.data.LoadPublicDataEvent +import me.partlysanestudios.partlysaneskies.utils.StringUtils.removeColorCodes import java.io.IOException import java.net.MalformedURLException @@ -33,9 +34,8 @@ object SkyblockDataManager { private var nameToIdMap = HashMap() private var idToItemMap = HashMap() private var lastAhUpdateTime = time - private fun checkLastUpdate(): Boolean { - return time >= lastAhUpdateTime + 1000 * 60 * 5 - } + + private fun checkLastUpdate(): Boolean = time >= lastAhUpdateTime + 1000 * 60 * 5 fun updateAll() { lastAhUpdateTime = time @@ -45,7 +45,8 @@ object SkyblockDataManager { @Throws(IOException::class) private fun updateItems() { newRequest( - GetRequest("${config.apiUrl}/v1/hypixel/skyblockitem", + GetRequest( + "${config.apiUrl}/v1/hypixel/skyblockitem", RequestRunnable { s: Request -> val itemDataString = s.getResponse() if (!s.hasSucceeded()) { @@ -56,34 +57,37 @@ object SkyblockDataManager { for (product in products) { val en = product.asJsonObject - val rarity = try { - Rarity.valueOf(en.get("rarity")?.asString ?: "") - } catch (e: IllegalArgumentException) { - Rarity.UNKNOWN - } - - val skyblockItem = SkyblockItem( - en.get("itemId").asString, - rarity, - en.get("name")?.asString ?: "", - en.get("npcSell")?.asDouble ?: 0.0, - en.get("bazaarBuy")?.asDouble ?: 0.0, - en.get("bazaarSell")?.asDouble ?: 0.0, - en.get("averageBazaarBuy")?.asDouble ?: 0.0, - en.get("averageBazaarSell")?.asDouble ?: 0.0, - en.get("lowestBin")?.asDouble ?: 0.0, - en.get("averageLowestBin")?.asDouble ?: 0.0, - en.get("material")?.asString ?: "", - en.get("unstackable")?.asBoolean ?: false - ) - - idToItemMap[en.get("itemId").asString] = skyblockItem - nameToIdMap[en.get("name").asString] = en.get("itemId").asString - + val rarity = + try { + Rarity.valueOf(en.get("rarity")?.asString ?: "") + } catch (e: IllegalArgumentException) { + Rarity.UNKNOWN + } + + val skyblockItem = + SkyblockItem( + en.get("itemId").asString, + rarity, + en.get("name")?.asString ?: "", + en.get("npcSell")?.asDouble ?: 0.0, + en.get("bazaarBuy")?.asDouble ?: 0.0, + en.get("bazaarSell")?.asDouble ?: 0.0, + en.get("averageBazaarBuy")?.asDouble ?: 0.0, + en.get("averageBazaarSell")?.asDouble ?: 0.0, + en.get("lowestBin")?.asDouble ?: 0.0, + en.get("averageLowestBin")?.asDouble ?: 0.0, + en.get("material")?.asString ?: "", + en.get("unstackable")?.asBoolean ?: false, + ) + + idToItemMap[skyblockItem.id] = skyblockItem + nameToIdMap[skyblockItem.name.removeColorCodes()] = skyblockItem.id } - - }, inMainThread = false, executeOnNextFrame = false, acceptAllCertificates = false - ) + }, + inMainThread = false, + executeOnNextFrame = false, + acceptAllCertificates = false, + ), ) } @@ -92,22 +96,16 @@ object SkyblockDataManager { JsonParser().parse(getFile("constants/bits_shop.json")).getAsJsonObject().getAsJsonObject("bits_shop") for ((id, value) in bitsShopObject.entrySet()) { val bitCost = value.asInt - val item = getItem(id) - ?: continue + val item = getItem(id) ?: continue bitIds.add(item.id) item.bitCost = bitCost } } - fun getId(name: String): String { - return nameToIdMap[name] ?: "" - } + fun getId(name: String): String = nameToIdMap[name.removeColorCodes()] ?: "" + + fun getItem(id: String): SkyblockItem? = idToItemMap[id] - fun getItem(id: String): SkyblockItem? { - return if (!idToItemMap.containsKey(id)) { - null - } else idToItemMap[id] - } fun runUpdaterTick() { if (checkLastUpdate()) { @@ -123,13 +121,16 @@ object SkyblockDataManager { } } + fun getAllItems(): List = idToItemMap.keys.toList() + // --------------------------- Skills --------------------------- private var idToSkillMap = HashMap() @Throws(MalformedURLException::class) fun initSkills() { newRequest( - GetRequest("https://api.hypixel.net/resources/skyblock/skills", + GetRequest( + "https://api.hypixel.net/resources/skyblock/skills", RequestRunnable { s: Request -> val itemDataString = s.getResponse() if (!s.hasSucceeded()) { @@ -166,17 +167,18 @@ object SkyblockDataManager { // Adds the skill to the map idToSkillMap[id] = skill } - }, false, false - ) + }, + false, + false, + ), ) } - fun getSkill(skillId: String): SkyblockSkill? { - return idToSkillMap[skillId] - } + fun getSkill(skillId: String): SkyblockSkill? = idToSkillMap[skillId] // --------------------------- Players --------------------------- private val playerCache = HashMap() + fun getPlayer(username: String): SkyblockPlayer { val player: SkyblockPlayer? if (playerCache.containsKey(username)) { diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/skyblockdata/SkyblockItem.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/skyblockdata/SkyblockItem.kt index 72dd7bbaf..fc2f7ad6a 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/skyblockdata/SkyblockItem.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/skyblockdata/SkyblockItem.kt @@ -7,7 +7,7 @@ package me.partlysanestudios.partlysaneskies.data.skyblockdata import net.minecraft.item.Item import net.minecraft.util.ResourceLocation -import java.util.* +import java.util.Locale class SkyblockItem( val id: String, @@ -21,7 +21,7 @@ class SkyblockItem( var lowestBin: Double, var averageLowestBin: Double, var material: String, - var unstackable: Boolean + var unstackable: Boolean, ) { companion object { val emptyItem = SkyblockItem("", Rarity.UNKNOWN, "", 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, "", false) @@ -29,8 +29,8 @@ class SkyblockItem( var bitCost = 0 - fun getSellPrice(): Double { - return if (bazaarSellPrice != 0.0) { + fun getSellPrice(): Double = + if (bazaarSellPrice != 0.0) { bazaarSellPrice } else if (lowestBin != 0.0) { lowestBin @@ -39,20 +39,18 @@ class SkyblockItem( } else { 0.0 } - } - fun getBuyPrice(): Double { - return if (bazaarBuyPrice != 0.0) { + fun getBuyPrice(): Double = + if (bazaarBuyPrice != 0.0) { bazaarBuyPrice } else if (lowestBin != 0.0) { lowestBin } else { 0.0 } - } - fun getAverageBuyPrice(): Double { - return if (averageBazaarBuy != 0.0) { + fun getAverageBuyPrice(): Double = + if (averageBazaarBuy != 0.0) { averageBazaarBuy } else if (lowestBin != 0.0) { averageLowestBin @@ -61,10 +59,9 @@ class SkyblockItem( } else { 0.0 } - } - fun getAverageSellPrice(): Double { - return if (bazaarSellPrice != 0.0) { + fun getAverageSellPrice(): Double = + if (bazaarSellPrice != 0.0) { averageBazaarSell } else if (lowestBin != 0.0) { averageLowestBin @@ -73,7 +70,6 @@ class SkyblockItem( } else { 0.0 } - } fun getBestPrice(): Double { val list = ArrayList() @@ -84,49 +80,32 @@ class SkyblockItem( return list[list.size - 1] } - fun hasSellPrice(): Boolean { - return getSellPrice() != 0.0 - } + fun hasSellPrice(): Boolean = getSellPrice() != 0.0 - fun hasBuyPrice(): Boolean { - return getBuyPrice() != 0.0 - } + fun hasBuyPrice(): Boolean = getBuyPrice() != 0.0 - fun hasBitCost(): Boolean { - return bitCost != 0 - } + fun hasBitCost(): Boolean = bitCost != 0 - fun getStackSize(): Int { - return if (unstackable) { + fun getStackSize(): Int = + if (unstackable) { 1 } else { - Item.itemRegistry?.getObject( - ResourceLocation( - "minecraft", - material.lowercase(Locale.getDefault()) - ) - )?.itemStackLimit ?: 64 + Item.itemRegistry + ?.getObject( + ResourceLocation( + "minecraft", + material.lowercase(Locale.getDefault()), + ), + )?.itemStackLimit ?: 64 } - } - fun hasAverageLowestBin(): Boolean { - return averageLowestBin != 0.0 - } + fun hasAverageLowestBin(): Boolean = averageLowestBin != 0.0 - fun hasAverageBazaarSell(): Boolean { - return averageLowestBin != 0.0 - } + fun hasAverageBazaarSell(): Boolean = averageLowestBin != 0.0 - fun hasAverageBazaarBuy(): Boolean { - return averageLowestBin != 0.0 - } + fun hasAverageBazaarBuy(): Boolean = averageLowestBin != 0.0 - fun hasAverageSellPrice(): Boolean { - return getAverageSellPrice() != 0.0 - } - - fun hasAverageBuyPrice(): Boolean { - return getAverageBuyPrice() != 0.0 - } + fun hasAverageSellPrice(): Boolean = getAverageSellPrice() != 0.0 -} \ No newline at end of file + fun hasAverageBuyPrice(): Boolean = getAverageBuyPrice() != 0.0 +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/skyblockdata/SkyblockPlayer.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/skyblockdata/SkyblockPlayer.kt index a7c8a60b1..dbd995cf1 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/skyblockdata/SkyblockPlayer.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/skyblockdata/SkyblockPlayer.kt @@ -9,7 +9,6 @@ import com.google.gson.JsonParser import me.partlysanestudios.partlysaneskies.PartlySaneSkies.Companion.config import me.partlysanestudios.partlysaneskies.PartlySaneSkies.Companion.time import me.partlysanestudios.partlysaneskies.data.api.GetRequest -import me.partlysanestudios.partlysaneskies.data.api.Request import me.partlysanestudios.partlysaneskies.data.api.RequestsManager import me.partlysanestudios.partlysaneskies.utils.MathUtils import me.partlysanestudios.partlysaneskies.utils.StringUtils.titleCase @@ -19,13 +18,10 @@ import net.minecraft.nbt.NBTTagList import org.apache.logging.log4j.Level class SkyblockPlayer(val username: String) { - - private var selectedProfileUUID: String = "" var lastUpdateTime: Long = 0 var uuid: String = "" - var skyblockLevel = 0.0 var catacombsLevel = 0.0 var combatLevel = 0.0 @@ -54,192 +50,226 @@ class SkyblockPlayer(val username: String) { var baseIntelligence = 0.0 var baseEffectiveHealth = 0.0 - private class Lock : Object() - fun isExpired(): Boolean { - return !MathUtils.onCooldown(lastUpdateTime, config.playerDataCacheTime * 60 * 1000L) - } + fun isExpired(): Boolean = !MathUtils.onCooldown(lastUpdateTime, config.playerDataCacheTime * 60 * 1000L) fun instantiateData() { val requestURL = "https://mowojang.matdoes.dev/users/profiles/minecraft/$username" val lock = Lock() - RequestsManager.newRequest(GetRequest(requestURL, { uuidRequest -> - if (!uuidRequest.hasSucceeded()) { - synchronized(lock) { - lock.notifyAll() - } - log(Level.ERROR, "Error getting mojang api for $username") - return@GetRequest - } - - uuid = JsonParser().parse(uuidRequest.getResponse()).getAsJsonObject().get("id")?.asString ?: "" - - val pssSkyblockPlayerUrl = "${config.apiUrl}/v1/hypixel/skyblockplayer?uuid=$uuid" - RequestsManager.newRequest(GetRequest(pssSkyblockPlayerUrl, { skyblockPlayerResponse -> - if (!skyblockPlayerResponse.hasSucceeded()) { - synchronized(lock) { - lock.notifyAll() - } - log(Level.ERROR, "Error getting partly sane skies api $username") - return@GetRequest - } - lastUpdateTime = time - - val skyblockPlayerObject = - JsonParser().parse(skyblockPlayerResponse.getResponse()).asJsonObject["skyblockPlayer"].asJsonObject - - selectedProfileUUID = skyblockPlayerObject["currentProfileId"]?.asString ?: "" - val profiles = skyblockPlayerObject["profiles"].asJsonArray - for (profile in profiles) { - val profObj = profile.asJsonObject - if (profObj["selected"].asBoolean) { - skyblockLevel = profObj["skyblockExperience"].asDouble / 100 - catacombsLevel = catacombsLevelToExperience(profObj["catacombsExperience"].asFloat) - combatLevel = SkyblockDataManager.getSkill("COMBAT")?.getLevelFromExperience(profObj["combatExperience"].asFloat) ?: 0.0 - miningLevel = SkyblockDataManager.getSkill("MINING")?.getLevelFromExperience(profObj["miningExperience"].asFloat) ?: 0.0 - foragingLevel = SkyblockDataManager.getSkill("FORAGING")?.getLevelFromExperience(profObj["foragingExperience"].asFloat) ?: 0.0 - farmingLevel = SkyblockDataManager.getSkill("FARMING")?.getLevelFromExperience(profObj["farmingExperience"].asFloat) ?: 0.0 - enchantingLevel = SkyblockDataManager.getSkill("ENCHANTING")?.getLevelFromExperience(profObj["enchantingExperience"].asFloat) ?: 0.0 - fishingLevel = SkyblockDataManager.getSkill("FISHING")?.getLevelFromExperience(profObj["fishingExperience"].asFloat) ?: 0.0 - alchemyLevel = SkyblockDataManager.getSkill("ALCHEMY")?.getLevelFromExperience(profObj["alchemyExperience"].asFloat) ?: 0.0 - tamingLevel = SkyblockDataManager.getSkill("TAMING")?.getLevelFromExperience(profObj["tamingExperience"].asFloat) ?: 0.0 - averageSkillLevel = (combatLevel + miningLevel + foragingLevel + farmingLevel + enchantingLevel + fishingLevel + alchemyLevel + tamingLevel) / 8 - petName = profObj["petName"].asString.titleCase() - selectedDungeonClass = profObj["selectedDungeonClass"].asString.titleCase() - totalRuns = profObj["totalRuns"].asInt - secretsCount = profObj["secretsCount"].asInt - secretsPerRun = secretsCount / totalRuns.toDouble() - baseHealth = profObj["baseHealth"].asDouble - baseDefense = profObj["baseDefense"].asDouble - baseIntelligence = profObj["baseIntelligence"].asDouble - baseEffectiveHealth = profObj["baseEffectiveHealth"].asDouble - - - if (profObj["armorData"] == null) { - armorName = arrayOf("", "", "", "") - } else { - val armorNBT: NBTTagList = - SystemUtils.base64ToNbt(profObj["armorData"].asString).getTagList("i", 10) - armorName = arrayOf("", "", "", "") - for (i in 0 until armorNBT.tagCount()) { - armorName[i] = - armorNBT.getCompoundTagAt(i).getCompoundTag("tag").getCompoundTag("display") - .getString("Name") - } + RequestsManager.newRequest( + GetRequest( + requestURL, + { uuidRequest -> + if (!uuidRequest.hasSucceeded()) { + synchronized(lock) { + lock.notifyAll() } + log(Level.ERROR, "Error getting mojang api for $username") + return@GetRequest + } - val arrowNBT: NBTTagList = - SystemUtils.base64ToNbt(profObj["quiverData"].asString).getTagList("i", 10) - - var sum = -1 - for (i in 0 until arrowNBT.tagCount()) { - val item = arrowNBT.getCompoundTagAt(i) - val itemDisplayTag = - arrowNBT.getCompoundTagAt(i).getCompoundTag("tag").getCompoundTag("display") - if (!itemDisplayTag.hasKey("Lore")) { - continue - } - val loreList = itemDisplayTag.getTagList("Lore", 8) - for (k in 0 until loreList.tagCount()) { - val loreLine = loreList.getStringTagAt(k) - if (loreLine.contains("ARROW")) { - sum += if (item.hasKey("Count")) { - item.getInteger("Count") - } else { - 1 + uuid = JsonParser() + .parse(uuidRequest.getResponse()) + .getAsJsonObject() + .get("id") + ?.asString ?: "" + + val pssSkyblockPlayerUrl = "${config.apiUrl}/v1/hypixel/skyblockplayer?uuid=$uuid" + RequestsManager.newRequest( + GetRequest( + pssSkyblockPlayerUrl, + { skyblockPlayerResponse -> + if (!skyblockPlayerResponse.hasSucceeded()) { + synchronized(lock) { + lock.notifyAll() } - break + log(Level.ERROR, "Error getting partly sane skies api $username") + return@GetRequest } - } - } - arrowCount = sum - - - normalRunCount = arrayOf(0, 0, 0, 0, 0, 0, 0, 0) - - val normalRunArray = profObj["normalRuns"].asJsonArray - for (i in 0 until normalRunArray.size()) { - normalRunCount[i] = normalRunArray[i].asInt - } - - masterModeRunCount = arrayOf(0, 0, 0, 0, 0, 0, 0, 0) - - val masterModeRunArray = profObj["masterModeRuns"].asJsonArray - for (i in 0 until normalRunArray.size()) { - masterModeRunCount[i] = masterModeRunArray[i].asInt - } - - break - } - } - synchronized(lock) { - lock.notifyAll() - } - })) - })) + lastUpdateTime = time + + val skyblockPlayerObject = + JsonParser().parse(skyblockPlayerResponse.getResponse()).asJsonObject["skyblockPlayer"].asJsonObject + + selectedProfileUUID = skyblockPlayerObject["currentProfileId"]?.asString ?: "" + val profiles = skyblockPlayerObject["profiles"].asJsonArray + for (profile in profiles) { + val profObj = profile.asJsonObject + if (profObj["selected"].asBoolean) { + skyblockLevel = profObj["skyblockExperience"].asDouble / 100 + catacombsLevel = catacombsLevelToExperience(profObj["catacombsExperience"].asFloat) + combatLevel = SkyblockDataManager + .getSkill("COMBAT") + ?.getLevelFromExperience(profObj["combatExperience"].asFloat) ?: 0.0 + miningLevel = SkyblockDataManager + .getSkill("MINING") + ?.getLevelFromExperience(profObj["miningExperience"].asFloat) ?: 0.0 + foragingLevel = SkyblockDataManager + .getSkill("FORAGING") + ?.getLevelFromExperience(profObj["foragingExperience"].asFloat) ?: 0.0 + farmingLevel = SkyblockDataManager + .getSkill("FARMING") + ?.getLevelFromExperience(profObj["farmingExperience"].asFloat) ?: 0.0 + enchantingLevel = SkyblockDataManager + .getSkill("ENCHANTING") + ?.getLevelFromExperience(profObj["enchantingExperience"].asFloat) ?: 0.0 + fishingLevel = SkyblockDataManager + .getSkill("FISHING") + ?.getLevelFromExperience(profObj["fishingExperience"].asFloat) ?: 0.0 + alchemyLevel = SkyblockDataManager + .getSkill("ALCHEMY") + ?.getLevelFromExperience(profObj["alchemyExperience"].asFloat) ?: 0.0 + tamingLevel = SkyblockDataManager + .getSkill("TAMING") + ?.getLevelFromExperience(profObj["tamingExperience"].asFloat) ?: 0.0 + averageSkillLevel = + ( + combatLevel + miningLevel + foragingLevel + farmingLevel + enchantingLevel + fishingLevel + + alchemyLevel + + tamingLevel + ) / + 8 + petName = profObj["petName"].asString.titleCase() + selectedDungeonClass = profObj["selectedDungeonClass"].asString.titleCase() + totalRuns = profObj["totalRuns"].asInt + secretsCount = profObj["secretsCount"].asInt + secretsPerRun = secretsCount / totalRuns.toDouble() + baseHealth = profObj["baseHealth"].asDouble + baseDefense = profObj["baseDefense"].asDouble + baseIntelligence = profObj["baseIntelligence"].asDouble + baseEffectiveHealth = profObj["baseEffectiveHealth"].asDouble + + if (profObj["armorData"] == null) { + armorName = arrayOf("", "", "", "") + } else { + val armorNBT: NBTTagList = + SystemUtils.base64ToNbt(profObj["armorData"].asString).getTagList("i", 10) + armorName = arrayOf("", "", "", "") + for (i in 0 until armorNBT.tagCount()) { + armorName[i] = + armorNBT + .getCompoundTagAt(i) + .getCompoundTag("tag") + .getCompoundTag("display") + .getString("Name") + } + } + + val arrowNBT: NBTTagList = + SystemUtils.base64ToNbt(profObj["quiverData"].asString).getTagList("i", 10) + + var sum = -1 + for (i in 0 until arrowNBT.tagCount()) { + val item = arrowNBT.getCompoundTagAt(i) + val itemDisplayTag = + arrowNBT.getCompoundTagAt(i).getCompoundTag("tag").getCompoundTag("display") + if (!itemDisplayTag.hasKey("Lore")) { + continue + } + val loreList = itemDisplayTag.getTagList("Lore", 8) + for (k in 0 until loreList.tagCount()) { + val loreLine = loreList.getStringTagAt(k) + if (loreLine.contains("ARROW")) { + sum += + if (item.hasKey("Count")) { + item.getInteger("Count") + } else { + 1 + } + break + } + } + } + arrowCount = sum + + normalRunCount = arrayOf(0, 0, 0, 0, 0, 0, 0, 0) + + val normalRunArray = profObj["normalRuns"].asJsonArray + for (i in 0 until normalRunArray.size()) { + normalRunCount[i] = normalRunArray[i].asInt + } + + masterModeRunCount = arrayOf(0, 0, 0, 0, 0, 0, 0, 0) + + val masterModeRunArray = profObj["masterModeRuns"].asJsonArray + for (i in 0 until normalRunArray.size()) { + masterModeRunCount[i] = masterModeRunArray[i].asInt + } + + break + } + } + synchronized(lock) { + lock.notifyAll() + } + }, + ), + ) + }, + ), + ) synchronized(lock) { lock.wait() } - } - - private var catacombsExperiencePerLevel = intArrayOf( - 50, - 75, - 110, - 160, - 230, - 330, - 470, - 670, - 950, - 1340, - 1890, - 2665, - 3760, - 5260, - 7380, - 10300, - 14400, - 20000, - 27600, - 38000, - 52500, - 71500, - 97000, - 132000, - 180000, - 243000, - 328000, - 445000, - 600000, - 800000, - 1065000, - 1410000, - 1900000, - 2500000, - 3300000, - 4300000, - 5600000, - 7200000, - 9200000, - 12000000, - 15000000, - 19000000, - 24000000, - 30000000, - 38000000, - 48000000, - 60000000, - 75000000, - 93000000, - 116250000 - ) + private var catacombsExperiencePerLevel = + intArrayOf( + 50, + 75, + 110, + 160, + 230, + 330, + 470, + 670, + 950, + 1340, + 1890, + 2665, + 3760, + 5260, + 7380, + 10300, + 14400, + 20000, + 27600, + 38000, + 52500, + 71500, + 97000, + 132000, + 180000, + 243000, + 328000, + 445000, + 600000, + 800000, + 1065000, + 1410000, + 1900000, + 2500000, + 3300000, + 4300000, + 5600000, + 7200000, + 9200000, + 12000000, + 15000000, + 19000000, + 24000000, + 30000000, + 38000000, + 48000000, + 60000000, + 75000000, + 93000000, + 116250000, + ) private fun catacombsLevelToExperience(experience: Float): Double { var level = 0f @@ -251,9 +281,9 @@ class SkyblockPlayer(val username: String) { level = (i - 1).toFloat() } } - level += (experience - catacombsExperiencePerLevel[level.toInt()]) / (catacombsExperiencePerLevel[level.toInt() + 1] - catacombsExperiencePerLevel[level.toInt()]) + level += + (experience - catacombsExperiencePerLevel[level.toInt()]) / + (catacombsExperiencePerLevel[level.toInt() + 1] - catacombsExperiencePerLevel[level.toInt()]) return level.toDouble() } - - } diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/skyblockdata/SkyblockSkill.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/skyblockdata/SkyblockSkill.kt index f00c34a4e..46ed85e7d 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/skyblockdata/SkyblockSkill.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/data/skyblockdata/SkyblockSkill.kt @@ -8,18 +8,14 @@ package me.partlysanestudios.partlysaneskies.data.skyblockdata class SkyblockSkill( // Returns the skill id val id: String, // Gets the maximum level of the skill - val maxLevel: Int, private val totalExpRequired: HashMap, + val maxLevel: Int, + private val totalExpRequired: HashMap, ) { - // Gets the total exp required to get to the current level - fun getTotalExpRequired(level: Int): Float { - return totalExpRequired[level]!! - } + fun getTotalExpRequired(level: Int): Float = totalExpRequired[level]!! // Gets the total exp required to level up from the previous level - fun getLevelUpExpRequired(level: Int): Float { - return getTotalExpRequired(level) - getTotalExpRequired(level - 1) - } + fun getLevelUpExpRequired(level: Int): Float = getTotalExpRequired(level) - getTotalExpRequired(level - 1) fun getLevelFromExperience(experience: Float): Double { var level = 0f @@ -33,7 +29,9 @@ class SkyblockSkill( } } if (level != 0.0F) { - level += (experience - experienceAtLevel[level.toInt() - 1]) / (experienceAtLevel[level.toInt()] - experienceAtLevel[level.toInt() - 1]) + level += + (experience - experienceAtLevel[level.toInt() - 1]) / + (experienceAtLevel[level.toInt()] - experienceAtLevel[level.toInt() - 1]) } return level.toDouble() } diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/events/EventManager.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/events/EventManager.kt index fcf8b4d1d..87b374f33 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/events/EventManager.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/events/EventManager.kt @@ -3,15 +3,19 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.events +import me.partlysanestudios.partlysaneskies.events.minecraft.PSSChatEvent +import me.partlysanestudios.partlysaneskies.events.minecraft.TablistUpdateEvent import me.partlysanestudios.partlysaneskies.events.minecraft.render.RenderWaypointEvent import me.partlysanestudios.partlysaneskies.events.skyblock.dungeons.DungeonEndEvent import me.partlysanestudios.partlysaneskies.events.skyblock.dungeons.DungeonStartEvent +import me.partlysanestudios.partlysaneskies.events.skyblock.mining.MinesEvent +import me.partlysanestudios.partlysaneskies.utils.MinecraftUtils import me.partlysanestudios.partlysaneskies.utils.SystemUtils.log import net.minecraftforge.client.event.ClientChatReceivedEvent import net.minecraftforge.client.event.RenderWorldLastEvent +import net.minecraftforge.fml.common.eventhandler.EventPriority import net.minecraftforge.fml.common.eventhandler.SubscribeEvent import org.apache.logging.log4j.Level import kotlin.reflect.KClass @@ -20,6 +24,9 @@ import kotlin.reflect.full.hasAnnotation import kotlin.reflect.full.memberFunctions object EventManager { + + private var oldTablist = emptyList() + internal val registeredFunctions = HashMap, ArrayList>() fun register(obj: Any) { @@ -33,7 +40,7 @@ object EventManager { if (functionParameters.size != 2) { // if there is not only 1 parameter (param 1 is always the instance parameter log( Level.WARN, - "Unable to add ${function.name} due to incorrect number of function parameters (${functionParameters.size}" + "Unable to add ${function.name} due to incorrect number of function parameters (${functionParameters.size}", ) continue } @@ -47,20 +54,34 @@ object EventManager { } } + fun tick() { + val tablist = MinecraftUtils.getTabList() + + if (tablist != oldTablist) { + TablistUpdateEvent.onUpdate(registeredFunctions[TablistUpdateEvent::class] ?: ArrayList(), tablist) + oldTablist = tablist + } + } + @SubscribeEvent fun onScreenRender(event: RenderWorldLastEvent) { - RenderWaypointEvent.onEventCall( - event.partialTicks, - registeredFunctions[RenderWaypointEvent::class] ?: ArrayList() - ) + RenderWaypointEvent.onEventCall(event.partialTicks, registeredFunctions[RenderWaypointEvent::class] ?: ArrayList()) } - @SubscribeEvent - fun onChatRecievedEvent(event: ClientChatReceivedEvent) { - val message = event.message.formattedText - DungeonStartEvent.onMessageRecieved(registeredFunctions[DungeonStartEvent::class] ?: ArrayList(), message) - DungeonEndEvent.onMessageRecieved(registeredFunctions[DungeonEndEvent::class] ?: ArrayList(), message) + @SubscribeEvent(priority = EventPriority.HIGHEST) + fun onChatReceivedEvent(event: ClientChatReceivedEvent) { + if (event.type.toInt() != 0) return + + PSSChatEvent.onMessageReceived(registeredFunctions[PSSChatEvent::class] ?: ArrayList(), event.message) + } + + @SubscribePSSEvent + fun onChat(event: PSSChatEvent) { + val message = event.message + DungeonStartEvent.onMessageReceived(registeredFunctions[DungeonStartEvent::class] ?: ArrayList(), message) + DungeonEndEvent.onMessageReceived(registeredFunctions[DungeonEndEvent::class] ?: ArrayList(), message) + MinesEvent.onMessageReceived(registeredFunctions[MinesEvent::class] ?: ArrayList(), message) } internal class EventFunction(val obj: Any, val function: KFunction<*>) -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/events/SubscribePSSEvent.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/events/SubscribePSSEvent.kt index e878cddda..0fd52b712 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/events/SubscribePSSEvent.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/events/SubscribePSSEvent.kt @@ -3,7 +3,6 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.events @Retention(AnnotationRetention.RUNTIME) diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/events/data/LoadPublicDataEvent.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/events/data/LoadPublicDataEvent.kt index ba30318a0..0de34ffbc 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/events/data/LoadPublicDataEvent.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/events/data/LoadPublicDataEvent.kt @@ -20,8 +20,6 @@ class LoadPublicDataEvent { function.function.call(function.obj, event) } catch (e: Exception) { e.printStackTrace() - } finally { - } } }.start() diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/events/minecraft/PSSChatEvent.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/events/minecraft/PSSChatEvent.kt new file mode 100644 index 000000000..e12db855f --- /dev/null +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/events/minecraft/PSSChatEvent.kt @@ -0,0 +1,18 @@ +package me.partlysanestudios.partlysaneskies.events.minecraft + +import me.partlysanestudios.partlysaneskies.events.EventManager +import net.minecraft.util.IChatComponent + +class PSSChatEvent(val message: String, val component: IChatComponent) { + companion object { + internal fun onMessageReceived(functionList: List, component: IChatComponent) { + functionList.forEach { + try { + it.function.call(it.obj, PSSChatEvent(component.formattedText, component)) + } catch (exception: Exception) { + exception.printStackTrace() + } + } + } + } +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/events/minecraft/TablistUpdateEvent.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/events/minecraft/TablistUpdateEvent.kt new file mode 100644 index 000000000..fa4442fce --- /dev/null +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/events/minecraft/TablistUpdateEvent.kt @@ -0,0 +1,17 @@ +package me.partlysanestudios.partlysaneskies.events.minecraft + +import me.partlysanestudios.partlysaneskies.events.EventManager + +class TablistUpdateEvent(val list: List) { + companion object { + internal fun onUpdate(functionList: List, list: List) { + functionList.forEach { + try { + it.function.call(it.obj, TablistUpdateEvent(list)) + } catch (exception: Exception) { + exception.printStackTrace() + } + } + } + } +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/events/minecraft/render/RenderWaypointEvent.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/events/minecraft/render/RenderWaypointEvent.kt index 552e4f2ca..309158837 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/events/minecraft/render/RenderWaypointEvent.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/events/minecraft/render/RenderWaypointEvent.kt @@ -3,7 +3,6 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.events.minecraft.render import me.partlysanestudios.partlysaneskies.events.EventManager @@ -11,10 +10,7 @@ import me.partlysanestudios.partlysaneskies.render.waypoint.Waypoint import me.partlysanestudios.partlysaneskies.utils.geometry.vectors.Point3d.Companion.toPoint3d import net.minecraft.client.Minecraft -class RenderWaypointEvent( - val pipeline: WaypointRenderPipeline -) { - +class RenderWaypointEvent(val pipeline: WaypointRenderPipeline) { companion object { internal fun onEventCall(partialTicks: Float, functions: List) { val pipeline = WaypointRenderPipeline() @@ -45,6 +41,7 @@ class RenderWaypointEvent( } // Written partially by j10a1n15 + /** * Renders all the waypoints in the pipeline * @@ -61,4 +58,4 @@ class RenderWaypointEvent( } } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/events/skyblock/dungeons/DungeonEndEvent.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/events/skyblock/dungeons/DungeonEndEvent.kt index 9a72fbde7..cf213ccf5 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/events/skyblock/dungeons/DungeonEndEvent.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/events/skyblock/dungeons/DungeonEndEvent.kt @@ -4,7 +4,7 @@ import me.partlysanestudios.partlysaneskies.events.EventManager class DungeonEndEvent { companion object { - internal fun onMessageRecieved(functionList: List, formattedMessage: String) { + internal fun onMessageReceived(functionList: List, formattedMessage: String) { if (formattedMessage.contains("§r§c☠ §r§eDefeated §r")) { for (function in functionList) { try { @@ -16,4 +16,4 @@ class DungeonEndEvent { } } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/events/skyblock/dungeons/DungeonStartEvent.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/events/skyblock/dungeons/DungeonStartEvent.kt index bc7485002..75ffee5c8 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/events/skyblock/dungeons/DungeonStartEvent.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/events/skyblock/dungeons/DungeonStartEvent.kt @@ -3,7 +3,6 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.events.skyblock.dungeons import me.partlysanestudios.partlysaneskies.data.skyblockdata.IslandType @@ -12,7 +11,7 @@ import me.partlysanestudios.partlysaneskies.utils.StringUtils.removeColorCodes class DungeonStartEvent { companion object { - internal fun onMessageRecieved(functionList: List, formattedMessage: String) { + internal fun onMessageReceived(functionList: List, formattedMessage: String) { val message = formattedMessage.removeColorCodes() if (message.contains("Starting in 1 second.") && IslandType.CATACOMBS.onIsland()) { for (function in functionList) { @@ -25,4 +24,4 @@ class DungeonStartEvent { } } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/events/skyblock/mining/MinesEvent.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/events/skyblock/mining/MinesEvent.kt new file mode 100644 index 000000000..171902cfc --- /dev/null +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/events/skyblock/mining/MinesEvent.kt @@ -0,0 +1,31 @@ +// +// Written by J10a1n15. +// See LICENSE for copyright and license notices. +// + + +package me.partlysanestudios.partlysaneskies.events.skyblock.mining + +import me.partlysanestudios.partlysaneskies.events.EventManager +import me.partlysanestudios.partlysaneskies.features.mining.events.MiningEvent +import me.partlysanestudios.partlysaneskies.utils.HypixelUtils.inAdvancedMiningIsland + +class MinesEvent(val miningEvent: MiningEvent) { + companion object { + internal fun onMessageReceived(functionList: List, formattedMessage: String) { + if (!inAdvancedMiningIsland()) return + + MiningEvent.entries + .firstOrNull { it.triggeredEvent(formattedMessage) } + ?.let { event -> + for (function in functionList) { + try { + function.function.call(function.obj, MinesEvent(event)) + } catch (e: Exception) { + e.printStackTrace() + } + } + } + } + } +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/chat/ChatAlertsManager.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/chat/ChatAlertsManager.kt new file mode 100644 index 000000000..f81abad22 --- /dev/null +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/chat/ChatAlertsManager.kt @@ -0,0 +1,208 @@ +// +// Written by Su386 and ItsEmpa. +// See LICENSE for copyright and license notices. +// + +package me.partlysanestudios.partlysaneskies.features.chat + +import com.google.gson.Gson +import com.google.gson.GsonBuilder +import me.partlysanestudios.partlysaneskies.PartlySaneSkies +import me.partlysanestudios.partlysaneskies.commands.PSSCommand +import me.partlysanestudios.partlysaneskies.system.SystemNotification +import me.partlysanestudios.partlysaneskies.utils.ChatUtils +import me.partlysanestudios.partlysaneskies.utils.StringUtils.formatNumber +import me.partlysanestudios.partlysaneskies.utils.StringUtils.removeColorCodes +import net.minecraft.util.ChatComponentText +import net.minecraft.util.IChatComponent +import org.lwjgl.opengl.Display +import java.io.File +import java.io.FileWriter +import java.io.IOException +import java.nio.file.Files +import java.nio.file.Paths + +object ChatAlertsManager { + private const val DATA_PATH_NAME = "./config/partly-sane-skies/chatAlertsData.json" + private var chatAlertsList = mutableListOf() + @JvmField + val MESSAGE_PREFIXES = listOf("§r§7: ", "§r§f: ", "§f: ") + private val NON_COLOR_CODES = listOf("§r", "§o", "§n", "§m", "§l", "§k") + + @Throws(IOException::class) + fun load() { + val file = File(DATA_PATH_NAME) + + if (file.createNewFile()) { + file.setWritable(true) + FileWriter(file).use { writer -> + writer.write(Gson().toJson(ArrayList())) + } + } + + file.setWritable(true) + Files.newBufferedReader(Paths.get(file.path)).use { reader -> + chatAlertsList = Gson().fromJson(reader, ArrayList::class.java) as ArrayList + } + } + + fun registerCommand() { + PSSCommand("chatalerts") + .addAlias("ca", "chatAlert", "chal") + .setDescription("Operates the chat alerts feature: /chatalerts ") + .setRunnable { args -> + when { + args.isEmpty() -> ChatUtils.sendClientMessage("§cIncorrect usage. Correct usage: /chatalerts add/remove/list") + else -> when (args[0]) { + "list" -> listAlerts() + "add" -> { + if (args.size == 1) { + ChatUtils.sendClientMessage("§cIncorrect usage. Correct usage: /chatalerts add [alert]") + } else { + val alert = args.copyOfRange(1, args.size).joinToString(" ").trim() + addAlert(alert) + } + } + "remove" -> { + if (args.size == 1) { + ChatUtils.sendClientMessage("§cIncorrect usage. Correct usage: /chatalerts remove [number]") + } else { + args[1].toIntOrNull()?.let { removeAlert(it) } ?: run { + ChatUtils.sendClientMessage("§c\"${args[1]}\" could not be read as a number. Correct Usage: /chatalerts remove [number]") + } + } + } + else -> ChatUtils.sendClientMessage("§cIncorrect usage. Correct usage: /chatalerts add/remove/list") + } + } + }.register() + } + + @Throws(IOException::class) + fun save() { + val file = File(DATA_PATH_NAME) + val gson = GsonBuilder().setPrettyPrinting().serializeSpecialFloatingPointValues().create() + val json = gson.toJson(chatAlertsList) + FileWriter(file).use { writer -> + writer.write(json) + } + } + + private fun addAlert(alert: String) { + chatAlertsList += alert + try { + save() + ChatUtils.sendClientMessage("§b\"§d$alert§b\" was successfully added as alert number §d${chatAlertsList.size}§b.") + } catch (e: IOException) { + e.printStackTrace() + ChatUtils.sendClientMessage("§cChat Alerts was unable to save. Please try again.") + } + } + + fun getChatAlertCount(): Int = chatAlertsList.size + + private fun listAlerts() { + val message = StringBuilder("§d§m-----------------------------------------------------\n§bChat Alerts:\n§d§m-----------------------------------------------------\n") + chatAlertsList.forEachIndexed { index, alert -> + message.append("${(index+1).formatNumber()}: $alert\n") + } + ChatUtils.sendClientMessage(message.toString()) + } + + private fun removeAlert(id: Int) { + if (id > chatAlertsList.size || id <= 0) { + ChatUtils.sendClientMessage("§cChat alert number $id was not found. Please enter a valid number.") + return + } + val message = chatAlertsList[id - 1] + chatAlertsList.removeAt(id - 1) + try { + save() + } catch (e: IOException) { + ChatUtils.sendClientMessage("§cChat Alerts was unable to save. Please try again.") + e.printStackTrace() + } + ChatUtils.sendClientMessage("§bChat Alert number §d$id §b(\"§d$message§b\") was successfully removed.") + } + + fun checkChatAlert(message: IChatComponent): IChatComponent { + return checkChatAlert(message, false) + } + + fun checkChatAlert(message: IChatComponent, sendSystemNotification: Boolean): IChatComponent { + val formattedMessage = message.formattedText + var beginMessageIndex = -1 + for (messagePrefix in MESSAGE_PREFIXES) { + beginMessageIndex = formattedMessage.indexOf(messagePrefix) + if (beginMessageIndex != -1) { + break + } + } + + if (beginMessageIndex == -1) { + return message + } + + val unformattedMessage = formattedMessage.removeColorCodes() + var rawMessage = formattedMessage.substring(beginMessageIndex) + rawMessage = rawMessage.removeColorCodes().replaceFirst(": ", "").trim() + val lowerCaseMessage = rawMessage.lowercase() + + for (alert in chatAlertsList) { + if (!lowerCaseMessage.contains(alert.lowercase())) { + continue + } + val messageBuilder = StringBuilder(formattedMessage) + val alertIndexUnformatted = unformattedMessage.lowercase().indexOf(alert.lowercase(), unformattedMessage.indexOf(rawMessage)) + val numOfColorCodeTotal = numOfColorCodes(formattedMessage) + val numOfColorCodeBefore = numOfColorCodeTotal - 1 + val alertIndexFormatted = numOfColorCodeBefore * 2 + alertIndexUnformatted + val charsToAdd = getLastColorCode(formattedMessage.substring(0, alertIndexFormatted + 1)).toCharArray() + messageBuilder.insert(alertIndexFormatted + alert.length, charsToAdd, 0, charsToAdd.size) + messageBuilder.insert(alertIndexFormatted, "§d§l".toCharArray(), 0, 3) + + if (PartlySaneSkies.config.chatAlertSendSystemNotification && !Display.isActive() && sendSystemNotification) { + SystemNotification.showNotification(message.formattedText.removeColorCodes()) + } + return ChatComponentText(messageBuilder.toString()) + } + return message + } + + private fun numOfColorCodes(str: String): Int { + var i = 0 + val textBuilder = StringBuilder(str) + while (textBuilder.indexOf("§") != -1) { + textBuilder.deleteCharAt(textBuilder.indexOf("§") + 1) + textBuilder.deleteCharAt(textBuilder.indexOf("§")) + i++ + } + return i + } + + private fun getLastColorCode(str: String): String { + var currentCode = "" + val textBuilder = StringBuilder(str) + while (textBuilder.indexOf("§") != -1) { + var shouldContinue = false + for (code in NON_COLOR_CODES) { + if (textBuilder.indexOf("§") == -1 || textBuilder.substring(textBuilder.indexOf("§"), textBuilder.indexOf("§") + 2) != code) { + continue + } + textBuilder.deleteCharAt(textBuilder.indexOf("§") + 1) + textBuilder.deleteCharAt(textBuilder.indexOf("§")) + shouldContinue = true + break + } + + if (shouldContinue || textBuilder.indexOf("§") == -1) { + continue + } + + currentCode = textBuilder.substring(textBuilder.indexOf("§"), textBuilder.indexOf("§") + 2) + textBuilder.deleteCharAt(textBuilder.indexOf("§") + 1) + textBuilder.deleteCharAt(textBuilder.indexOf("§")) + } + return currentCode + } +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/chat/ChatColors.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/chat/ChatColors.kt new file mode 100644 index 000000000..34c52575c --- /dev/null +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/chat/ChatColors.kt @@ -0,0 +1,90 @@ +// +// Written by Su386 and ItsEmpa. +// See LICENSE for copyright and license notices. +// + +package me.partlysanestudios.partlysaneskies.features.chat + +import me.partlysanestudios.partlysaneskies.PartlySaneSkies +import me.partlysanestudios.partlysaneskies.utils.StringUtils.matchGroup +import me.partlysanestudios.partlysaneskies.utils.StringUtils.removeColorCodes +import net.minecraft.util.ChatComponentText +import net.minecraft.util.IChatComponent + +object ChatColors { + + fun detectColorMessage(message: IChatComponent): IChatComponent { + val formattedMessage = message.formattedText + val prefix = getPrefix(formattedMessage) + if (prefix.isEmpty()) return message + + val color = getChatColor(prefix) + return if (color.isEmpty()) message + else ChatComponentText(insertColor(formattedMessage, color)) + } + + fun detectNonMessage(message: IChatComponent): IChatComponent { + if (!PartlySaneSkies.config.colorNonMessages) return message + + val formattedMessage = message.formattedText + if (!formattedMessage.contains("§r§7: ")) return message + + if (formattedMessage.startsWith("§dTo ") || formattedMessage.startsWith("§dFrom ")) { + return message + } + + val unformattedMessage = message.unformattedText + val containsRankNames = PartlySaneSkies.RANK_NAMES.any { unformattedMessage.contains(it) } + + return if (containsRankNames) message + else ChatComponentText(insertColor(formattedMessage, "§r")) + } + + fun getChatColor(prefix: String): String = when (prefix.lowercase()) { + "party" -> { + if (!PartlySaneSkies.config.colorPartyChat) "" + else if (PartlySaneSkies.config.visibleColors) "§6" + else "§9" + } + "guild" -> { + if (!PartlySaneSkies.config.colorGuildChat) "" + else if (PartlySaneSkies.config.visibleColors) "§a" + else "§2" + } + "officer" -> { + if (!PartlySaneSkies.config.colorOfficerChat) "" + else "§3" + } + "to", "from" -> { + if (!PartlySaneSkies.config.colorPrivateMessages) "" + else "§d" + } + "co-op" -> { + if (!PartlySaneSkies.config.colorCoopChat) "" + else "§b" + } + else -> "" + } + + private val prefixPattern = "(?Party|Guild|Officer|To|From|Co-op) >?.*".toPattern() + + fun getPrefix(message: String): String = prefixPattern.matchGroup(message.removeColorCodes(), "chat") ?: "" + + private fun insertColor(message: String, color: String): String { + var messageStartIndex = -1 + + for (prefix in ChatAlertsManager.MESSAGE_PREFIXES) { + if (message.contains(prefix)) { + messageStartIndex = message.indexOf(prefix) + prefix.length + break + } + } + + if (messageStartIndex == -1) return message + + val preMessageString = message.substring(0, messageStartIndex) + val messageString = message.substring(messageStartIndex) + + return preMessageString + color + messageString.removeColorCodes() + } +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/chat/ChatManager.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/chat/ChatManager.kt index fef803101..922ede04a 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/chat/ChatManager.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/chat/ChatManager.kt @@ -3,7 +3,6 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.features.chat import me.partlysanestudios.partlysaneskies.PartlySaneSkies @@ -20,78 +19,55 @@ import net.minecraftforge.fml.common.eventhandler.EventPriority import net.minecraftforge.fml.common.eventhandler.SubscribeEvent import java.util.regex.Pattern - object ChatManager { @SubscribeEvent(priority = EventPriority.LOWEST) fun onChatReceived(event: ClientChatReceivedEvent) { -// If all chat modification features are disabled - if (!doModifyChatEnabled()) { - return - } + if (!doModifyChatEnabled()) return - if (event.type != 0.toByte()) { - return - } - -// If the message doesn't need to be modified - if (!event.message.doChatMessageModify()) { - return - } + if (event.type != 0.toByte()) return + if (!event.message.doChatMessageModify()) return - // ChatUtils.sendClientMessage("ChatManager.onChatReceived: ${event.message.formattedText}") + var messageToSend = event.message - event.isCanceled = true // cancels the even - - var messageToSend = event.message // Creates a new message to build on - -// If the chat colors is supposed to run if (ChatColors.getChatColor(ChatColors.getPrefix(messageToSend.formattedText)).isNotEmpty()) { messageToSend = ChatColors.detectColorMessage(messageToSend) - } else if (!ChatColors.detectNonMessage(messageToSend).formattedText.equals(messageToSend.formattedText)) { + } else if (ChatColors.detectNonMessage(messageToSend).formattedText != messageToSend.formattedText) { messageToSend = ChatColors.detectNonMessage(messageToSend) } -// If the chat alerts manager finds something - if (!ChatAlertsManager.checkChatAlert(messageToSend).formattedText.equals(messageToSend.formattedText)) { - // Plays a flute sound + if (ChatAlertsManager.checkChatAlert(messageToSend).formattedText != messageToSend.formattedText) { PartlySaneSkies.minecraft.soundHandler?.playSound( PositionedSoundRecord.create( ResourceLocation( "partlysaneskies", - "flute_scale" - ) - ) + "flute_scale", + ), + ), ) messageToSend = ChatAlertsManager.checkChatAlert(messageToSend, true) } - // If the word editor wants to edit something if (WordEditor.shouldEditMessage(messageToSend)) { messageToSend = ChatComponentText((WordEditor.handleWordEditorMessage(messageToSend.formattedText))) } - // If owo language is enabled if (config.owoLanguage) { messageToSend = ChatComponentText(OwO.owoify(messageToSend.formattedText)) } - // If the message has not changed - if (messageToSend.equals(event.message)) { - event.isCanceled = false // Reset the event - // ChatUtils.sendClientMessage("Message has not changed") - return - } - if (config.prettyMimicKilled) { - messageToSend = ChatComponentText( - messageToSend.formattedText.replace( - "\$SKYTILS-DUNGEON-SCORE-MIMIC\$", - config.prettyMimicKilledString + messageToSend = + ChatComponentText( + messageToSend.formattedText.replace( + "\$SKYTILS-DUNGEON-SCORE-MIMIC\$", + config.prettyMimicKilledString, + ), ) - ) } + if (messageToSend == event.message) return + event.isCanceled = true messageToSend.chatStyle = event.message.chatStyle.createDeepCopy() val urls = messageToSend.extractUrls() @@ -107,63 +83,11 @@ object ChatManager { PartlySaneSkies.minecraft.ingameGUI?.chatGUI?.printChatMessage(messageToSend) } - fun IChatComponent.hasClickAction(): Boolean { -// If the message is null - if (this.chatStyle == null) { - return false - } - -// If the chat style is empty - else if (this.chatStyle.isEmpty) { - return false - } - -// If the chat has no click event - else if (this.chatStyle.chatClickEvent == null) { - return false - } + fun IChatComponent.hasClickAction(): Boolean = + chatStyle?.takeIf { !it.isEmpty }?.chatClickEvent?.value?.isNotEmpty() ?: false -// If the chat has no click event value - else if (this.chatStyle.chatClickEvent.value == null) { - return false - } - -// If the chat has no value for the action - else if (this.chatStyle.chatClickEvent.value.isEmpty()) { - return false - } - - return true - } - - fun IChatComponent.hasHoverAction(): Boolean { -// If the message is null - if (this.chatStyle == null) { - return false - } - -// If the chat style is empty - else if (this.chatStyle.isEmpty) { - return false - } - -// If the chat has no click event - else if (this.chatStyle.chatHoverEvent == null) { - return false - } - -// If the chat has no click event value - else if (this.chatStyle.chatHoverEvent.value == null) { - return false - } - -// If the chat has no value for the action - else if (this.chatStyle.chatHoverEvent.value.unformattedText.isEmpty()) { - return false - } - - return true - } + fun IChatComponent.hasHoverAction(): Boolean = + chatStyle?.takeIf { !it.isEmpty }?.chatHoverEvent?.value?.unformattedText?.isNotEmpty() ?: false fun extractUrls(text: String): List { val containedUrls = ArrayList() @@ -178,61 +102,24 @@ object ChatManager { return containedUrls } - fun IChatComponent.extractUrls(): List { - return extractUrls(this.unformattedText.removeColorCodes()) - } + fun IChatComponent.extractUrls(): List = extractUrls(unformattedText.removeColorCodes()) // Returns if we interact with chat at all // ADD A CHECK FOR ANY FEATURE THAT MODIFIES AN EXISTING CHAT MESSAGE - private fun doModifyChatEnabled(): Boolean { - val config = PartlySaneSkies.config - - if (config.colorCoopChat) { - return true - } else if (config.colorGuildChat) { - return true - } else if (config.colorOfficerChat) { - return true - } else if (config.colorPartyChat) { - return true - } else if (config.colorNonMessages) { - return true - } else if (config.colorPrivateMessages) { - return true - } else if (ChatAlertsManager.getChatAlertCount() != 0) { - return true - } else if (WordEditor.wordsToEdit.isNotEmpty() && PartlySaneSkies.config.wordEditor) { - return true - } else if (config.owoLanguage) { - return true - } - - return false + private fun doModifyChatEnabled(): Boolean = with (PartlySaneSkies.config) { + colorCoopChat || colorGuildChat || colorOfficerChat || colorPartyChat || + colorNonMessages || colorPrivateMessages || ChatAlertsManager.getChatAlertCount() != 0 || + (WordEditor.wordsToEdit.isNotEmpty() && wordEditor) || owoLanguage } - //ALSO HERE, DON'T FORGET + // ALSO HERE, DON'T FORGET private fun IChatComponent.doChatMessageModify(): Boolean { - if (this.formattedText.startsWith("{\"server\":")) { - return false - } - if (this.formattedText.startsWith(PartlySaneSkies.CHAT_PREFIX)) { - return false - } - if (ChatColors.getChatColor( - ChatColors.getPrefix(this.formattedText) - ).isNotEmpty() - ) { - return true - } else if (!ChatAlertsManager.checkChatAlert(this).formattedText.equals(this.formattedText)) { - return true - } else if (!ChatColors.detectNonMessage(this).formattedText.equals(this.formattedText)) { - return true - } else if (WordEditor.shouldEditMessage(this)) { - return true - } else if (config.owoLanguage) { - return true //there is almost no way this will never not trigger - } else { - return false - } + if (formattedText.startsWith("{\"server\":")) return false + if (formattedText.startsWith(PartlySaneSkies.CHAT_PREFIX)) return false + + return ChatColors.getChatColor(ChatColors.getPrefix(formattedText)).isNotEmpty() || + ChatAlertsManager.checkChatAlert(this).formattedText != formattedText || + ChatColors.detectNonMessage(this).formattedText != formattedText || + WordEditor.shouldEditMessage(this) || config.owoLanguage } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/chat/ChatTransformer.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/chat/ChatTransformer.kt index 001ca5d98..f62247762 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/chat/ChatTransformer.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/chat/ChatTransformer.kt @@ -3,7 +3,6 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.features.chat import cc.polyfrost.oneconfig.events.event.ChatSendEvent @@ -11,7 +10,6 @@ import cc.polyfrost.oneconfig.libs.eventbus.Subscribe import me.partlysanestudios.partlysaneskies.PartlySaneSkies import me.partlysanestudios.partlysaneskies.PartlySaneSkies.Companion.config - // Currently only using to owoify send chat messages (meow) object ChatTransformer { var lastmsg = "" @@ -57,7 +55,5 @@ object ChatTransformer { }.start() } - private fun doChatTransform(): Boolean { - return config.transformOWO - } + private fun doChatTransform(): Boolean = config.transformOWO } diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/chat/OwO.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/chat/OwO.kt new file mode 100644 index 000000000..0def0e46d --- /dev/null +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/chat/OwO.kt @@ -0,0 +1,50 @@ +// +// Written by J10a1n15 and ItsEmpa. +// See LICENSE for copyright and license notices. +// + + +package me.partlysanestudios.partlysaneskies.features.chat + +object OwO { + private val replacements = listOf( + "r" to "w", + "l" to "w", + "R" to "W", + "L" to "W", + "no" to "nyo", + "No" to "Nyo", + "NO" to "NYO", + "na" to "nya", + "Na" to "Nya", + "NA" to "NYA", + "ne" to "nye", + "Ne" to "Nye", + "NE" to "NYE", + "ni" to "nyi", + "Ni" to "Nyi", + "NI" to "NYI", + "nu" to "nyu", + "Nu" to "Nyu", + "NU" to "NYU", + "n" to "ny", + "N" to "Ny", + "ove" to "uv", + "Ove" to "Uv", + "OVE" to "UV", + "o" to "owo", + "O" to "OwO", + "!" to " >w<", + "?" to " owo?", + "." to " owo.", + "," to " owo," + ) + + fun owoify(text: String): String { + var owoifiedText = text + for ((oldValue, newValue) in replacements) { + owoifiedText = owoifiedText.replace(oldValue, newValue, ignoreCase = false) + } + return owoifiedText + } +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/chat/WordEditor.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/chat/WordEditor.kt new file mode 100644 index 000000000..c5d2354f3 --- /dev/null +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/chat/WordEditor.kt @@ -0,0 +1,121 @@ +// +// Written by J10a1n15 and ItsEmpa. +// See LICENSE for copyright and license notices. +// + +package me.partlysanestudios.partlysaneskies.features.chat + +import com.google.gson.Gson +import com.google.gson.GsonBuilder +import me.partlysanestudios.partlysaneskies.PartlySaneSkies +import me.partlysanestudios.partlysaneskies.commands.PSSCommand +import me.partlysanestudios.partlysaneskies.utils.ChatUtils +import net.minecraft.util.IChatComponent +import org.apache.commons.lang3.ArrayUtils +import java.io.File +import java.io.FileWriter +import java.io.IOException +import java.io.Reader +import java.nio.file.Files +import java.nio.file.Paths + +object WordEditor { + + private const val WORD_EDITOR_PATH = "./config/partly-sane-skies/wordEditor.json" + + // TODO change to map? + var wordsToEdit: Array> = arrayOf() + private set + + fun load() { + val file = File(WORD_EDITOR_PATH) + file.setWritable(true) + if (file.createNewFile()) { + FileWriter(file).use { it.write(Gson().toJson(arrayOf>())) } + } + val reader: Reader = Files.newBufferedReader(Paths.get(file.path)) + wordsToEdit = Gson().fromJson(reader, Array>::class.java) + } + + fun save() { + val file = File(WORD_EDITOR_PATH) + file.createNewFile() + val gson: Gson = GsonBuilder() + .setPrettyPrinting() + .serializeSpecialFloatingPointValues() + .create() + val json: String = gson.toJson(wordsToEdit) + FileWriter(file).use { it.write(json) } + } + + // already checks config before calling this, so config check is not needed here + fun handleWordEditorMessage(message: String): String { + var editedMessage = message + wordsToEdit.forEach { (wordToReplace, replacementWord) -> + editedMessage = editedMessage.replace(wordToReplace, replacementWord) + } + return editedMessage + } + + fun shouldEditMessage(message: IChatComponent): Boolean { + if (!PartlySaneSkies.config.wordEditor) return false + + val formattedMessage = message.formattedText + return wordsToEdit.any { (wordToReplace, _) -> wordToReplace in formattedMessage } + } + + // List all words configured for replacement + fun listWords() { + if (wordsToEdit.isEmpty()) { + ChatUtils.sendClientMessage("§7There are no words to replace.") + return + } + ChatUtils.sendClientMessage("§7Words to replace:") + wordsToEdit.forEachIndexed { index, (wordToReplace, replacementWord) -> + ChatUtils.sendClientMessage("§b${index + 1}. §7$wordToReplace §8-> §7$replacementWord") + } + } + + // Register the word editor command + fun registerWordEditorCommand() { + PSSCommand("wordeditor") + .addAlias("wordedit", "we", "worldreplace", "wr") + .setDescription("Operates the word editor: /wordeditor add , /wordeditor list or /wordeditor remove ") + .setRunnable { args -> + when { + args.isEmpty() || args[0].equals("list", ignoreCase = true) -> { + ChatUtils.sendClientMessage("§7To add a word to replace, run §b/wordeditor add §7. To remove a word, run §b/wordeditor remove §7. To list all of the words, run §b/wordeditor list§7.") + listWords() + } + args[0].equals("remove", ignoreCase = true) -> { + if (args.size < 2) { + ChatUtils.sendClientMessage("§cError: Must provide an index to remove") + return@setRunnable + } + val i = args[1].toIntOrNull()?.takeIf { it in 1..wordsToEdit.size } ?: run { + ChatUtils.sendClientMessage("§cPlease enter a valid number index and try again.") + return@setRunnable + } + ChatUtils.sendClientMessage("§aRemoving: §b${wordsToEdit[i - 1][0]} §8-> §b${wordsToEdit[i - 1][1]}") + wordsToEdit = ArrayUtils.removeElement(wordsToEdit, wordsToEdit[i - 1]) + save() + } + args[0].equals("add", ignoreCase = true) -> { + if (args.size < 3) { + ChatUtils.sendClientMessage("§cError: Must provide a word and a replacement") + return@setRunnable + } + val word = args[1] + val replacement = args.drop(2).joinToString(" ") + ChatUtils.sendClientMessage("§aAdding: §b$word §8-> §b$replacement") + wordsToEdit = wordsToEdit.plus(arrayOf(word, replacement)) + try { + save() + } catch (e: IOException) { + e.printStackTrace() + } + } + } + }.register() + } +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/commands/Crepes.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/commands/Crepes.kt index 844d9bb35..b48c1e83d 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/commands/Crepes.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/commands/Crepes.kt @@ -7,47 +7,46 @@ package me.partlysanestudios.partlysaneskies.features.commands import me.partlysanestudios.partlysaneskies.commands.PSSCommand import me.partlysanestudios.partlysaneskies.utils.ChatUtils.sendClientMessage -import net.minecraft.command.ICommandSender import net.minecraft.event.ClickEvent import net.minecraft.util.ChatComponentText object Crepes { - fun registerCrepesCommand() { PSSCommand("crepes") .addAlias("crêpes") .setDescription("Crepes!") .setRunnable { - val chatComponent = ChatComponentText( - """ - §0§m-----------------------------------------------------§0 - §6Ingredients: - - §f- 250g of wheat flour - §f- 50g of butter - §f- 50cl of milk - §f- 10cl of water - §f- 4 (big) eggs - §f- 2 tablespoons of powdered sugar - §f- 1 pinch of salt - - §f1) In a large mixing bowl, add the wheat flour, the 2 tablespoons of powdered sugar, and 1 pinch of salt - §f2) While whisking the bowl, progressively pour in the milk and the water - §f3) After, add in the (melted) butter and the eggs - §f4) Leave the bowl in the fridge for 30-45 minutes - §f5) Look up a tutorial on how to make crêpes on a pan - §f6) Enjoy your (burnt) crêpes with something like Nutella, sugar, or marmalade - - §fSource: - §5http://www.recettes-bretonnes.fr/crepe-bretonne/recette-crepe.html - §0§m-----------------------------------------------------§0 - """.trimIndent() - ) + val chatComponent = + ChatComponentText( + """ + §0§m-----------------------------------------------------§0 + §6Ingredients: + + §f- 250g of wheat flour + §f- 50g of butter + §f- 50cl of milk + §f- 10cl of water + §f- 4 (big) eggs + §f- 2 tablespoons of powdered sugar + §f- 1 pinch of salt + + §f1) In a large mixing bowl, add the wheat flour, the 2 tablespoons of powdered sugar, and 1 pinch of salt + §f2) While whisking the bowl, progressively pour in the milk and the water + §f3) After, add in the (melted) butter and the eggs + §f4) Leave the bowl in the fridge for 30-45 minutes + §f5) Look up a tutorial on how to make crêpes on a pan + §f6) Enjoy your (burnt) crêpes with something like Nutella, sugar, or marmalade + + §fSource: + §5http://www.recettes-bretonnes.fr/crepe-bretonne/recette-crepe.html + §0§m-----------------------------------------------------§0 + """.trimIndent(), + ) chatComponent.chatStyle.setChatClickEvent( ClickEvent( ClickEvent.Action.OPEN_URL, - "http://www.recettes-bretonnes.fr/crepe-bretonne/recette-crepe.html" - ) + "http://www.recettes-bretonnes.fr/crepe-bretonne/recette-crepe.html", + ), ) sendClientMessage(chatComponent) }.register() diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/commands/HelpCommand.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/commands/HelpCommand.kt index dd771a308..b2af567c8 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/commands/HelpCommand.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/commands/HelpCommand.kt @@ -9,12 +9,10 @@ import me.partlysanestudios.partlysaneskies.PartlySaneSkies.Companion.config import me.partlysanestudios.partlysaneskies.commands.CommandManager import me.partlysanestudios.partlysaneskies.commands.PSSCommand import me.partlysanestudios.partlysaneskies.utils.ChatUtils.sendClientMessage -import net.minecraft.command.ICommandSender import org.lwjgl.input.Keyboard -import java.util.* +import java.util.Locale object HelpCommand { - fun registerConfigCommand() { PSSCommand("pssconfig") .addAlias("pssc", "pssconf") @@ -22,8 +20,7 @@ object HelpCommand { .setRunnable { sendClientMessage("§bOpening config menu...") enqueueRenderOperation(Runnable { config.openGui() }) - } - .register() + }.register() } fun registerPSSCommand() { @@ -37,6 +34,7 @@ object HelpCommand { } private var configAliases: Set = setOf("conf", "c", "config") + fun registerHelpCommand() { PSSCommand("psshelp") .addAlias("pssh", "helpss", "helppss", "pshelp", "helpihavenoideawhatpartlysaneskiesis") @@ -64,8 +62,9 @@ object HelpCommand { } fun printHelpMessage() { - val str = StringBuilder( - """§3§m-----------------------------------------------------§r + val str = + StringBuilder( + """§3§m-----------------------------------------------------§r §b§l§nWelcome to Partly Sane Skies!§r Partly Sane Skies is a mod developed by Su386 and FlagMaster. This mod aims to be a quality of life mod for Hypixel SkyBlock. @@ -82,8 +81,8 @@ Partly Sane Skies is a mod developed by Su386 and FlagMaster. This mod aims to b §5> Visit the GitHub §5> §dAll of the features wouldn't fit in this message, so check out the GitHub to see all of the features. §3§m-----------------------------------------------------§r -§dCommands:""" // Can't trim indent because it will mess with formatting - ) +§dCommands:""", // Can't trim indent because it will mess with formatting + ) for ((_, command) in CommandManager.commandList) { str.append("\n") str.append("\n §b> /").append(command.name) diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/commands/PSSDiscord.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/commands/PSSDiscord.kt index fd78287c3..080685c91 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/commands/PSSDiscord.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/commands/PSSDiscord.kt @@ -9,7 +9,6 @@ import me.partlysanestudios.partlysaneskies.PartlySaneSkies import me.partlysanestudios.partlysaneskies.PartlySaneSkies.Companion.discordCode import me.partlysanestudios.partlysaneskies.PartlySaneSkies.Companion.minecraft import me.partlysanestudios.partlysaneskies.commands.PSSCommand -import net.minecraft.command.ICommandSender import net.minecraft.event.ClickEvent import net.minecraft.util.ChatComponentText diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/commands/SanityCheck.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/commands/SanityCheck.kt index c3e8ae32f..4fbeae4d0 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/commands/SanityCheck.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/commands/SanityCheck.kt @@ -8,11 +8,9 @@ import me.partlysanestudios.partlysaneskies.data.pssdata.PublicDataManager import me.partlysanestudios.partlysaneskies.utils.ChatUtils import me.partlysanestudios.partlysaneskies.utils.SkyCryptUtils import me.partlysanestudios.partlysaneskies.utils.SystemUtils.getJsonFromPath -import net.minecraft.command.ICommandSender import java.util.regex.Pattern object SanityCheck { - private val playerName: String by lazy { PartlySaneSkies.minecraft.thePlayer.name } private const val sanityCheckPath: String = "constants/sanity_check_data.json" private const val usernameRegex: String = "^[a-zA-Z0-9_]{2,16}\$" @@ -22,7 +20,7 @@ object SanityCheck { PSSCommand("sanitycheck") .addAlias("checksanity", "psssanity", "pssinsanity", "pssinsane", "psssane") .setDescription("Checks for one's sanity. This command is purely for fun; do not take its results seriously.") - .setRunnable {args: Array -> + .setRunnable { args: Array -> ChatUtils.sendClientMessage("Attempting to begin sanity analysis...") Thread { var username = playerName @@ -33,11 +31,13 @@ object SanityCheck { username = args[0] } if (validateUsernameByRegex(username)) { - val sanityCheckDataJsonObject: JsonObject = JsonParser().parse( - PublicDataManager.getFile( - sanityCheckPath - ) - ).getAsJsonObject() + val sanityCheckDataJsonObject: JsonObject = + JsonParser() + .parse( + PublicDataManager.getFile( + sanityCheckPath, + ), + ).getAsJsonObject() val highestSkyblockNetworth = sanityCheckDataJsonObject.getJsonFromPath("highestnwlong")?.asLong?.toDouble() ?: 360567766418.0 @@ -51,9 +51,13 @@ object SanityCheck { val networthRatio = 1.0 - (currentProfileNetworth / highestSkyblockNetworth) val firstJoinRatio = 1.0 - (currentProfileFirstJoin.toDouble() / oldestSkyblockFirstJoin.toDouble()) - ChatUtils.sendClientMessage("§a${if (username != playerName) "$username is" else "You are"} ${(networthRatio * 100) + (firstJoinRatio * 100)}% insane.") + ChatUtils.sendClientMessage( + "§a${if (username != playerName) "$username is" else "You are"} ${(networthRatio * 100) + (firstJoinRatio * 100)}% insane.", + ) } else { - ChatUtils.sendClientMessage("§eIt appears that $username does not qualify for a PSS sanity check, due to current API circumstances. Try again later, or report this to us via §9/pssdiscord §eif this issue persists.") + ChatUtils.sendClientMessage( + "§eIt appears that $username does not qualify for a PSS sanity check, due to current API circumstances. Try again later, or report this to us via §9/pssdiscord §eif this issue persists.", + ) } } else { ChatUtils.sendClientMessage("§cPlease enter a valid Minecraft username to perform a §9/sanitycheck §con.") @@ -63,8 +67,5 @@ object SanityCheck { }.register() } - private fun validateUsernameByRegex(username: String): Boolean { - return usernamePattern.matcher(username).find() - } - + private fun validateUsernameByRegex(username: String): Boolean = usernamePattern.matcher(username).find() } diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/commands/Version.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/commands/Version.kt index e838badc3..c94d44a21 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/commands/Version.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/commands/Version.kt @@ -9,31 +9,30 @@ import me.partlysanestudios.partlysaneskies.PartlySaneSkies import me.partlysanestudios.partlysaneskies.PartlySaneSkies.Companion.isLatestVersion import me.partlysanestudios.partlysaneskies.commands.PSSCommand import me.partlysanestudios.partlysaneskies.utils.ChatUtils.sendClientMessage -import net.minecraft.command.ICommandSender import net.minecraft.event.ClickEvent import net.minecraft.util.ChatComponentText object Version { - fun registerVersionCommand() { PSSCommand("partlysaneskiesversion") - .addAlias("pssversion") - .addAlias("pssv") - .addAlias("partlysaneskiesv") + .addAlias("pssversion", "pssv", "partlysaneskiesv") .setDescription("Prints the version of Partly Sane Skies you are using") .setRunnable { - val chatcomponent = ChatComponentText( - """§b§m-----------------------------------------------------§0 - §b§lPartly Sane Skies Version: - §e${PartlySaneSkies.VERSION}${if (isLatestVersion) "\n§aYou are using the latest version of Partly Sane Skies!" else "\n§cYou are not using the latest version of Partly Sane Skies! Click here to download the newest version!"} - §b§m-----------------------------------------------------§0""".trimIndent() - ) + val chatcomponent = + ChatComponentText( + """ + §b§m-----------------------------------------------------§0 + §b§lPartly Sane Skies Version: + §e${PartlySaneSkies.VERSION}${if (isLatestVersion) "\n§aYou are using the latest version of Partly Sane Skies!" else "\n§cYou are not using the latest version of Partly Sane Skies! Click here to download the newest version!"} + §b§m-----------------------------------------------------§0 + """.trimIndent(), + ) if (!isLatestVersion) { chatcomponent.chatStyle.setChatClickEvent( ClickEvent( ClickEvent.Action.OPEN_URL, - "https://github.com/PartlySaneStudios/partly-sane-skies/releases" - ) + "https://github.com/PartlySaneStudios/partly-sane-skies/releases", + ), ) } sendClientMessage(chatcomponent) diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/debug/CrystalHollowsGemstoneMapper.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/debug/CrystalHollowsGemstoneMapper.kt index b93f2bdc0..9334f9d65 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/debug/CrystalHollowsGemstoneMapper.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/debug/CrystalHollowsGemstoneMapper.kt @@ -21,10 +21,9 @@ import java.time.Instant import java.time.LocalDateTime import java.time.ZoneId import java.time.format.DateTimeFormatter -import java.util.* +import java.util.LinkedList object CrystalHollowsGemstoneMapper { - private val range = Range3d(Point3d(201.0, 30.0, 201.0), Point3d(824.0, 189.0, 824.0)) private val world = minecraft.theWorld private var alreadyCheckedCoords = ArrayList() @@ -32,7 +31,8 @@ object CrystalHollowsGemstoneMapper { fun scanWorld() { alreadyCheckedCoords = ArrayList() val rangeSize = - (range.sortedPoints[1].x - range.sortedPoints[0].x) * (range.sortedPoints[1].y - range.sortedPoints[0].y) * (range.sortedPoints[1].z - range.sortedPoints[0].z) + (range.sortedPoints[1].x - range.sortedPoints[0].x) * (range.sortedPoints[1].y - range.sortedPoints[0].y) * + (range.sortedPoints[1].z - range.sortedPoints[0].z) var checkedBlocks = 0 val gemstones = LinkedList() val startTime = time @@ -49,7 +49,7 @@ object CrystalHollowsGemstoneMapper { val minutesLeft = timeLeft / 1000 / 60 sendClientMessage( "Checking block (${x.formatNumber()}, ${y.formatNumber()}, ${z.formatNumber()})\n${checkedBlocks.formatNumber()} / ${rangeSize.formatNumber()} " + - "(${(checkedBlocks / rangeSize * 100).round(1)}%, ${minutesLeft.round(2).formatNumber()} minutes left)..." + "(${(checkedBlocks / rangeSize * 100).round(1)}%, ${minutesLeft.round(2).formatNumber()} minutes left)...", ) val point = Point3d(x.toDouble(), y.toDouble(), z.toDouble()) @@ -75,7 +75,6 @@ object CrystalHollowsGemstoneMapper { sendClientMessage("Data dumped data") } - fun getPrettyData() { val filePath = File("./config/partly-sane-skies/rawgemstone.json") sendClientMessage("Loading data...") @@ -90,7 +89,7 @@ object CrystalHollowsGemstoneMapper { i++ sendClientMessage( "Converting crystal ${i.formatNumber()} of ${totalLength.formatNumber()} " + - "(${(i / totalLength * 100).round(1).formatNumber()}%)..." + "(${(i / totalLength * 100).round(1).formatNumber()}%)...", ) val obj = element.asJsonObject @@ -102,8 +101,9 @@ object CrystalHollowsGemstoneMapper { val coordObj = coordElement.asJsonObject val point = Point3d(coordObj.get("x").asDouble, coordObj.get("y").asDouble, coordObj.get("z").asDouble) try { - val color = world.getBlockState(point.toBlockPosInt()) - .getValue(PropertyEnum.create("color", EnumDyeColor::class.java)) + val color = world + .getBlockState(point.toBlockPosInt()) + .getValue(PropertyEnum.create("color", EnumDyeColor::class.java)) val type = "COLOR_$color" if (!map.contains(type)) { @@ -112,7 +112,6 @@ object CrystalHollowsGemstoneMapper { map[type]?.add(coordObj) } catch (e: Exception) { - e.printStackTrace() continue } } @@ -128,11 +127,12 @@ object CrystalHollowsGemstoneMapper { sumZ += coordObj.get("z").asDouble } - val averagePoint = Point3d( - (sumX / en.value.size).round(1), - (sumY / en.value.size).round(1), - (sumZ / en.value.size).round(1) - ) + val averagePoint = + Point3d( + (sumX / en.value.size).round(1), + (sumY / en.value.size).round(1), + (sumZ / en.value.size).round(1), + ) try { val type = en.key @@ -149,7 +149,6 @@ object CrystalHollowsGemstoneMapper { sendClientMessage("Data dumped.") } - fun removeNucleusCords() { val filePath = File("./config/partly-sane-skies/prettygemstone.json") sendClientMessage("Loading data...") @@ -164,7 +163,7 @@ object CrystalHollowsGemstoneMapper { for (element in jsonArray) { sendClientMessage( "Converting crystal ${i.formatNumber()} of ${totalLength.formatNumber()} " + - "(${(i / totalLength * 100).round(1).formatNumber()}%)..." + "(${(i / totalLength * 100).round(1).formatNumber()}%)...", ) val obj = element.asJsonObject @@ -191,7 +190,6 @@ object CrystalHollowsGemstoneMapper { val size: Int, ) - private fun dumpGemstoneData(gemstones: List) { val json = GsonBuilder().setPrettyPrinting().create().toJson(gemstones) // Format the Instant to a human-readable date and time @@ -204,7 +202,7 @@ object CrystalHollowsGemstoneMapper { File("./config/partly-sane-skies/dumps/").mkdirs() // Declares the file - val file = File("./config/partly-sane-skies/dumps/gemstone-dump-${formattedDate}.json") + val file = File("./config/partly-sane-skies/dumps/gemstone-dump-$formattedDate.json") file.createNewFile() file.setWritable(true) // Saves the data to the file @@ -225,7 +223,7 @@ object CrystalHollowsGemstoneMapper { File("./config/partly-sane-skies/dumps/").mkdirs() // Declares the file - val file = File("./config/partly-sane-skies/dumps/pretty-gemstone-dump-${formattedDate}.json") + val file = File("./config/partly-sane-skies/dumps/pretty-gemstone-dump-$formattedDate.json") file.createNewFile() file.setWritable(true) // Saves teh data to the file @@ -246,7 +244,7 @@ object CrystalHollowsGemstoneMapper { File("./config/partly-sane-skies/dumps/").mkdirs() // Declares the file - val file = File("./config/partly-sane-skies/dumps/nonucleus-gemstone-dump-${formattedDate}.json") + val file = File("./config/partly-sane-skies/dumps/nonucleus-gemstone-dump-$formattedDate.json") file.createNewFile() file.setWritable(true) // Saves the data to the file @@ -255,7 +253,7 @@ object CrystalHollowsGemstoneMapper { writer.close() } - private fun extractGemstone(point: Point3d, gemstoneCoords: ArrayList) { + private fun extractGemstone(point: Point3d, gemstoneCoords: ArrayList, ) { for (x in -1..1) { for (y in -1..1) { for (z in -1..1) { @@ -283,10 +281,7 @@ object CrystalHollowsGemstoneMapper { } } - private fun isGlass(blockState: IBlockState): Boolean { - return blockState.block.material == Material.glass - } - + private fun isGlass(blockState: IBlockState): Boolean = blockState.block.material == Material.glass private class Gemstone(val coordinates: List, val type: String) { val geographicMiddle: Point3d @@ -295,7 +290,6 @@ object CrystalHollowsGemstoneMapper { var yPoints = 0.0 var zPoints = 0.0 - for (point in coordinates) { xPoints += point.x yPoints += point.y @@ -304,6 +298,5 @@ object CrystalHollowsGemstoneMapper { return Point3d(xPoints / coordinates.size, yPoints / coordinates.size, zPoints / coordinates.size) } - } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/debug/DebugKey.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/debug/DebugKey.kt index e99697dc1..71053fed9 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/debug/DebugKey.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/debug/DebugKey.kt @@ -3,7 +3,6 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.features.debug import cc.polyfrost.oneconfig.config.core.OneColor @@ -14,14 +13,14 @@ import me.partlysanestudios.partlysaneskies.PartlySaneSkies.Companion.config import me.partlysanestudios.partlysaneskies.PartlySaneSkies.Companion.minecraft import me.partlysanestudios.partlysaneskies.PartlySaneSkies.Companion.time import me.partlysanestudios.partlysaneskies.data.cache.StatsData -import me.partlysanestudios.partlysaneskies.data.skyblockdata.IslandType import me.partlysanestudios.partlysaneskies.data.skyblockdata.Rarity import me.partlysanestudios.partlysaneskies.events.SubscribePSSEvent +import me.partlysanestudios.partlysaneskies.events.minecraft.PSSChatEvent import me.partlysanestudios.partlysaneskies.events.minecraft.render.RenderWaypointEvent import me.partlysanestudios.partlysaneskies.features.dungeons.PlayerRating import me.partlysanestudios.partlysaneskies.features.dungeons.TerminalWaypoints -import me.partlysanestudios.partlysaneskies.features.gui.hud.rngdropbanner.Drop -import me.partlysanestudios.partlysaneskies.features.gui.hud.rngdropbanner.DropBannerDisplay +import me.partlysanestudios.partlysaneskies.features.gui.hud.DropBannerDisplay +import me.partlysanestudios.partlysaneskies.features.items.rngdrop.Drop import me.partlysanestudios.partlysaneskies.features.themes.ThemeManager import me.partlysanestudios.partlysaneskies.render.RenderEuclid.drawCylinderFill import me.partlysanestudios.partlysaneskies.render.RenderEuclid.drawCylinderOutline @@ -30,6 +29,7 @@ import me.partlysanestudios.partlysaneskies.render.gui.hud.PSSBanner import me.partlysanestudios.partlysaneskies.render.waypoint.Waypoint import me.partlysanestudios.partlysaneskies.system.SystemNotification import me.partlysanestudios.partlysaneskies.utils.ChatUtils.sendClientMessage +import me.partlysanestudios.partlysaneskies.utils.HypixelUtils import me.partlysanestudios.partlysaneskies.utils.MinecraftUtils.containerInventory import me.partlysanestudios.partlysaneskies.utils.MinecraftUtils.getItemstackList import me.partlysanestudios.partlysaneskies.utils.MinecraftUtils.xSize @@ -41,7 +41,6 @@ import net.minecraft.client.gui.inventory.GuiChest import net.minecraft.client.renderer.GlStateManager import net.minecraft.client.renderer.Tessellator import net.minecraft.client.renderer.vertex.DefaultVertexFormats -import net.minecraftforge.client.event.ClientChatReceivedEvent import net.minecraftforge.client.event.RenderWorldLastEvent import net.minecraftforge.fml.common.eventhandler.SubscribeEvent import org.apache.logging.log4j.Level @@ -49,22 +48,17 @@ import org.lwjgl.opengl.GL11 import java.awt.Color object DebugKey { - fun init() { config.debugMode = false } - - fun isDebugMode(): Boolean { - return config.debugMode - } + fun isDebugMode(): Boolean = config.debugMode // Runs when debug key is pressed fun onDebugKeyPress() { config.debugMode = !config.debugMode sendClientMessage("Debug mode: " + isDebugMode()) - if (config.debugRenderTestBanner) { renderNewBanner(PSSBanner("Test", 5000L, 5f, OneColor(255, 0, 255, 1).toJavaColor())) } @@ -87,12 +81,11 @@ object DebugKey { Thread { sendClientMessage("Dumping...") PercyMode.dump() - }.start() } if (config.debugPrintCurrentLocationFromIslandType) { - sendClientMessage("Island Type: ${IslandType.getCurrentIsland()}") + sendClientMessage("Island Type: ${HypixelUtils.currentIsland}") } if (config.debugLogCachedF7Puzzles) { @@ -100,7 +93,9 @@ object DebugKey { } if (config.debugPrintCurrentCachedStats) { - sendClientMessage("Health: ${StatsData.currentHealth}/${StatsData.maxHealth}, Defense: ${StatsData.defense}, Mana: ${StatsData.currentMana}/${StatsData.maxMana}") + sendClientMessage( + "Health: ${StatsData.currentHealth}/${StatsData.maxHealth}, Defense: ${StatsData.defense}, Mana: ${StatsData.currentMana}/${StatsData.maxMana}", + ) } if (config.debugRenderRNGBanner) { @@ -150,15 +145,14 @@ object DebugKey { sendClientMessage("ySize: ${chest.ySize}") } } - } // Runs chat analyzer for debug mode - @SubscribeEvent - fun chatAnalyzer(event: ClientChatReceivedEvent) { + @SubscribePSSEvent + fun onChat(event: PSSChatEvent) { if (isDebugMode() && config.debugChatAnalyser) { - log(Level.INFO, event.message.formattedText) - copyStringToClipboard(event.message.formattedText) + log(Level.INFO, event.message) + copyStringToClipboard(event.message) } } @@ -175,7 +169,6 @@ object DebugKey { @SubscribeEvent fun onWorldRenderLast(event: RenderWorldLastEvent) { - if (!(isDebugMode() && config.debugCylinder)) { return } @@ -193,7 +186,6 @@ object DebugKey { GlStateManager.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO) GL11.glLineWidth(4.0f) - // Gets the tessellator val tessellator = Tessellator.getInstance() // from my understanding it's just a tesseract but for nerdier nerds val worldRenderer = tessellator.worldRenderer @@ -203,7 +195,7 @@ object DebugKey { ThemeManager.accentColor.toJavaColor().red / 255f, ThemeManager.accentColor.toJavaColor().green / 255f, ThemeManager.accentColor.toJavaColor().blue / 255f, - (ThemeManager.accentColor.toJavaColor().alpha / 255f) * .667f + (ThemeManager.accentColor.toJavaColor().alpha / 255f) * .667f, ) worldRenderer.drawCylinderFill(cylinderPoint, 8.0, 20.0) tessellator.draw() @@ -220,4 +212,4 @@ object DebugKey { GlStateManager.popMatrix() } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/debug/ExampleHud.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/debug/ExampleHud.kt index bf402d26e..3155643a7 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/debug/ExampleHud.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/debug/ExampleHud.kt @@ -25,14 +25,13 @@ object ExampleHud : PSSHud(false, 50.0F, 50.0F) { private val window = Window(ElementaVersion.V2) - private val box = UIBlock() - .constrain { - x = 50.pixels - y = 50.pixels - height = DEFAULT_HEIGHT.pixels - width = DEFAULT_WIDTH.pixels - color = DEFAULT_COLOR.constraint - } childOf window + private val box = UIBlock().constrain { + x = 50.pixels + y = 50.pixels + height = DEFAULT_HEIGHT.pixels + width = DEFAULT_WIDTH.pixels + color = DEFAULT_COLOR.constraint + } childOf window @SubscribeEvent fun onScreenRender(event: RenderGameOverlayEvent.Text) { @@ -44,20 +43,17 @@ object ExampleHud : PSSHud(false, 50.0F, 50.0F) { box.setY(y.pixels) box.setHeight((scale * DEFAULT_HEIGHT).pixels) box.setWidth((scale * DEFAULT_WIDTH).pixels) - val color = if (example) { - EXAMPLE_COLOR - } else { - DEFAULT_COLOR - } + val color = + if (example) { + EXAMPLE_COLOR + } else { + DEFAULT_COLOR + } box.setColor(color) window.draw(gg.essential.universal.UMatrixStack()) } - override fun getWidth(scale: Float, example: Boolean): Float { - return scale * 5 - } + override fun getWidth(scale: Float, example: Boolean): Float = scale * 5 - override fun getHeight(scale: Float, example: Boolean): Float { - return scale * 5 - } + override fun getHeight(scale: Float, example: Boolean): Float = scale * 5 } diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/debug/ExampleWebhook.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/debug/ExampleWebhook.kt index c68c9796d..27923f5bb 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/debug/ExampleWebhook.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/debug/ExampleWebhook.kt @@ -3,7 +3,6 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.features.debug import gg.essential.elementa.UIComponent @@ -13,11 +12,11 @@ import me.partlysanestudios.partlysaneskies.PartlySaneSkies import me.partlysanestudios.partlysaneskies.config.psconfig.Toggle import me.partlysanestudios.partlysaneskies.features.discord.webhooks.EmbedData import me.partlysanestudios.partlysaneskies.features.discord.webhooks.EmbedField -import me.partlysanestudios.partlysaneskies.features.discord.webhooks.WebhookData import me.partlysanestudios.partlysaneskies.features.discord.webhooks.Webhook +import me.partlysanestudios.partlysaneskies.features.discord.webhooks.WebhookData import java.awt.Color -object ExampleWebhook: Webhook() { +object ExampleWebhook : Webhook() { // Use events for this. In this case, it's debug key. // Debug key event when // TODO: Debug key event @@ -58,4 +57,4 @@ object ExampleWebhook: Webhook() { config.registerOption("testOption2", Toggle("Test option 2", "This is a test description for 2", false)) config.registerOption("testOption3", Toggle("Test option 3", "This is a test description for option 3", false)) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/debug/PercyMode.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/debug/PercyMode.kt index 987a848d1..b8df06dba 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/debug/PercyMode.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/debug/PercyMode.kt @@ -3,10 +3,14 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.features.debug -import com.google.gson.* +import com.google.gson.Gson +import com.google.gson.GsonBuilder +import com.google.gson.JsonArray +import com.google.gson.JsonElement +import com.google.gson.JsonObject +import com.google.gson.JsonPrimitive import me.partlysanestudios.partlysaneskies.PartlySaneSkies import me.partlysanestudios.partlysaneskies.PartlySaneSkies.Companion.config import me.partlysanestudios.partlysaneskies.utils.ChatUtils.sendClientMessage @@ -46,7 +50,10 @@ object PercyMode { } jsonObject.add("inventories", screenObj) - jsonObject.add("class", Gson().toJsonTree(PartlySaneSkies.minecraft.currentScreen?.javaClass?.name ?: "")) + jsonObject.add( + "class", + Gson().toJsonTree(PartlySaneSkies.minecraft.currentScreen?.javaClass?.name ?: ""), + ) return jsonObject } @@ -117,7 +124,6 @@ object PercyMode { return fullObject } - private fun dumpToFile(jsonObject: JsonObject) { // Format the Instant to a human-readable date and time // Convert epoch time to LocalDateTime @@ -129,7 +135,7 @@ object PercyMode { File("./config/partly-sane-skies/dumps/").mkdirs() // Declares the file - val file = File("./config/partly-sane-skies/dumps/percy-dump-${formattedDate}.json") + val file = File("./config/partly-sane-skies/dumps/percy-dump-$formattedDate.json") file.createNewFile() file.setWritable(true) // Creates a new Gson object to save the data @@ -144,9 +150,8 @@ object PercyMode { SystemUtils.copyStringToClipboard(Gson().toJson(jsonObject)) } - fun dump() { dumpToFile(getFullDump()) dumpToClipboard(getFullDump()) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/discord/DiscordRPC.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/discord/DiscordRPC.kt index 414caa2fc..c6894a218 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/discord/DiscordRPC.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/discord/DiscordRPC.kt @@ -3,7 +3,6 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.features.discord import com.jagrosh.discordipc.IPCClient @@ -16,17 +15,14 @@ import me.partlysanestudios.partlysaneskies.utils.SystemUtils import org.apache.logging.log4j.Level import java.time.Instant - - - object DiscordRPC { private const val NORMAL_APPLICATION_ID = 1195613263845666849 private const val SBE_BAD_APPLICATION_ID = 1195625408167686175 - private var lastName = "sbe bad" private var lastMessage = "Playing Hypixel Skyblock" private var startTimeStamp = Instant.now() + fun init() { startTimeStamp = Instant.now() @@ -71,7 +67,6 @@ object DiscordRPC { return if (config.discordRPCOnlySkyblock) { // if true, check if it's in skyblock// if not in skyblock return true // if in skyblock, return true HypixelUtils.isSkyblock() - } else { // if the rpc in enabled, but the only in skyblock is disabled, return true true } @@ -79,22 +74,24 @@ object DiscordRPC { fun run() { val sbeBadMode = config.discordPlayingMode == 1 - val applicationId = if (sbeBadMode) { - SBE_BAD_APPLICATION_ID - } else { - NORMAL_APPLICATION_ID - } + val applicationId = + if (sbeBadMode) { + SBE_BAD_APPLICATION_ID + } else { + NORMAL_APPLICATION_ID + } val client = IPCClient(applicationId) - client.setListener(object : IPCListener { - override fun onReady(client: IPCClient) { - val builder: RichPresence.Builder = buildActivity() + client.setListener( + object : IPCListener { + override fun onReady(client: IPCClient) { + val builder: RichPresence.Builder = buildActivity() - client.sendRichPresence(builder.build()) - } - }) + client.sendRichPresence(builder.build()) + } + }, + ) client.connect() - while (true) { // If it should run or if the mode has changed, return so the run function can be called again with the right application id if (!shouldRun() || (config.discordPlayingMode == 1) != sbeBadMode) { @@ -109,15 +106,11 @@ object DiscordRPC { val builder = buildActivity() client.sendRichPresence(builder.build()) - } } catch (e: Exception) { e.printStackTrace() - } finally { - } - try { // Sleep a bit to save CPU Thread.sleep(50) @@ -125,15 +118,14 @@ object DiscordRPC { e.printStackTrace() } } - } - fun buildActivity(): RichPresence.Builder { - return RichPresence.Builder().setState(config.discordRPCName) + fun buildActivity(): RichPresence.Builder = + RichPresence + .Builder() + .setState(config.discordRPCName) .setDetails(config.discordRPCDescription) .setStartTimestamp(startTimeStamp.epochSecond) .setLargeImage("large_logo", "") .setSmallImage("small_logo", "Partly Sane Skies by Partly Sane Studios") - } - -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/discord/webhooks/EmbedData.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/discord/webhooks/EmbedData.kt index f5ac5bb24..86b0d45d3 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/discord/webhooks/EmbedData.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/discord/webhooks/EmbedData.kt @@ -3,7 +3,6 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.features.discord.webhooks data class EmbedData( @@ -11,5 +10,5 @@ data class EmbedData( var description: String? = null, var url: String? = null, var color: Int? = null, - var fields: List? = null -) \ No newline at end of file + var fields: List? = null, +) diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/discord/webhooks/EmbedField.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/discord/webhooks/EmbedField.kt index 212661840..0968fae9f 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/discord/webhooks/EmbedField.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/discord/webhooks/EmbedField.kt @@ -3,11 +3,10 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.features.discord.webhooks data class EmbedField( var name: String, var value: String, - var inline: Boolean = false -) \ No newline at end of file + var inline: Boolean = false, +) diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/discord/webhooks/Webhook.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/discord/webhooks/Webhook.kt index 9ac3b6ebb..484536294 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/discord/webhooks/Webhook.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/discord/webhooks/Webhook.kt @@ -3,7 +3,6 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.features.discord.webhooks import gg.essential.elementa.UIComponent @@ -17,9 +16,12 @@ abstract class Webhook(defaultEnabledState: Boolean = false) { companion object { private const val WEBHOOK_FOLDER_PATH = "webhooks/" } + var enabled get() = config.find("enabled")?.asBoolean ?: false - set(value) { config.find("enabled")?.asToggle?.state = value } + set(value) { + config.find("enabled")?.asToggle?.state = value + } abstract val icon: UIComponent abstract val id: String @@ -28,15 +30,13 @@ abstract class Webhook(defaultEnabledState: Boolean = false) { val config: Config = Config() open val hidden = false - init { config.registerOption("enabled", Toggle("Enabled", description = "Enable the webhook", defaultState = defaultEnabledState)) } - // Registers the config and the webhook fun register() { ConfigManager.registerNewConfig(WEBHOOK_FOLDER_PATH + id, config) WebhookEventManager.registerWebhook(this) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/discord/webhooks/WebhookData.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/discord/webhooks/WebhookData.kt index 23d684bfc..14614b34a 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/discord/webhooks/WebhookData.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/discord/webhooks/WebhookData.kt @@ -3,7 +3,6 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.features.discord.webhooks import me.partlysanestudios.partlysaneskies.data.api.PostRequest @@ -12,11 +11,10 @@ import me.partlysanestudios.partlysaneskies.utils.ChatUtils import me.partlysanestudios.partlysaneskies.utils.SystemUtils import java.net.URL - data class WebhookData( var url: String, var content: String? = null, - var embedData: List? = null + var embedData: List? = null, ) { fun send() { if (content == null && embedData == null) { @@ -28,12 +26,13 @@ data class WebhookData( return } - val urlObj = try { - URL(url) - } catch (expt: Exception) { - ChatUtils.sendClientMessage("Discord Webhook URL is invalid") - return - } + val urlObj = + try { + URL(url) + } catch (expt: Exception) { + ChatUtils.sendClientMessage("Discord Webhook URL is invalid") + return + } RequestsManager.newRequest( PostRequest( @@ -47,10 +46,10 @@ data class WebhookData( ChatUtils.sendClientMessage("Discord Webhook sent") }, WebhookSerializer.serialize(this), - false, - false, - true - ) + inMainThread = false, + executeOnNextFrame = false, + acceptAllCertificates = true, + ), ) } } diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/discord/webhooks/WebhookEventManager.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/discord/webhooks/WebhookEventManager.kt index 6b81f654a..439441b01 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/discord/webhooks/WebhookEventManager.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/discord/webhooks/WebhookEventManager.kt @@ -3,7 +3,6 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.features.discord.webhooks object WebhookEventManager { @@ -12,4 +11,4 @@ object WebhookEventManager { fun registerWebhook(webhookEvent: Webhook) { webhookEvents.add(webhookEvent) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/discord/webhooks/WebhookMenu.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/discord/webhooks/WebhookMenu.kt index fb74471a5..91ced150e 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/discord/webhooks/WebhookMenu.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/discord/webhooks/WebhookMenu.kt @@ -3,7 +3,6 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.features.discord.webhooks import gg.essential.elementa.ElementaVersion @@ -12,7 +11,13 @@ import gg.essential.elementa.components.ScrollComponent import gg.essential.elementa.components.UIBlock import gg.essential.elementa.components.UIWrappedText import gg.essential.elementa.constraints.CenterConstraint -import gg.essential.elementa.dsl.* +import gg.essential.elementa.dsl.childOf +import gg.essential.elementa.dsl.constrain +import gg.essential.elementa.dsl.constraint +import gg.essential.elementa.dsl.minus +import gg.essential.elementa.dsl.percent +import gg.essential.elementa.dsl.pixels +import gg.essential.elementa.dsl.plus import gg.essential.universal.UMatrixStack import me.partlysanestudios.partlysaneskies.PartlySaneSkies.Companion.config import me.partlysanestudios.partlysaneskies.commands.PSSCommand @@ -22,12 +27,13 @@ import me.partlysanestudios.partlysaneskies.config.psconfig.Toggle.Companion.asT import me.partlysanestudios.partlysaneskies.features.themes.ThemeManager import me.partlysanestudios.partlysaneskies.render.gui.components.PSSToggle import me.partlysanestudios.partlysaneskies.render.gui.constraints.ScaledPixelConstraint.Companion.scaledPixels +import me.partlysanestudios.partlysaneskies.render.gui.constraints.TextScaledPixelConstraint.Companion.textScaledPixels import me.partlysanestudios.partlysaneskies.utils.ElementaUtils.uiImage import me.partlysanestudios.partlysaneskies.utils.MinecraftUtils import net.minecraft.util.ResourceLocation import java.awt.Color -class WebhookMenu: WindowScreen(ElementaVersion.V5) { +class WebhookMenu : WindowScreen(ElementaVersion.V5) { companion object { fun registerWebhookCommand() { PSSCommand("webhook") @@ -39,7 +45,7 @@ class WebhookMenu: WindowScreen(ElementaVersion.V5) { } private val inactiveWebhooksPanel = ThemeManager.currentBackgroundUIImage.constrain { - x = CenterConstraint() - (300 / 2).scaledPixels - (75 / 2).scaledPixels + x = CenterConstraint() - (300 / 2).scaledPixels - (75 / 2).scaledPixels y = CenterConstraint() - 20.scaledPixels - (150 / 2).scaledPixels width = 300.scaledPixels height = 350.scaledPixels @@ -49,11 +55,11 @@ class WebhookMenu: WindowScreen(ElementaVersion.V5) { x = 15.scaledPixels y = 10.scaledPixels width = (300 - (7 * 2)).scaledPixels - textScale = 1.5.scaledPixels + textScale = 1.5.textScaledPixels color = Color.red.constraint } childOf inactiveWebhooksPanel - private val activeWebhooksPanel = ThemeManager.currentBackgroundUIImage.constrain { + private val activeWebhooksPanel = ThemeManager.currentBackgroundUIImage.constrain { x = CenterConstraint() + (300 / 2).scaledPixels + (75 / 2).scaledPixels y = CenterConstraint() - 20.scaledPixels - (150 / 2).scaledPixels width = 300.scaledPixels @@ -61,12 +67,12 @@ class WebhookMenu: WindowScreen(ElementaVersion.V5) { } childOf window private val activeWebhookText = UIWrappedText("Active Webhooks:").constrain { - x = 15.scaledPixels - y = 10.scaledPixels - width = (300 - (7 * 2)).scaledPixels - textScale = 1.5.scaledPixels - color = Color.green.constraint - } childOf activeWebhooksPanel + x = 15.scaledPixels + y = 10.scaledPixels + width = (300 - (7 * 2)).scaledPixels + textScale = 1.5.textScaledPixels + color = Color.green.constraint + } childOf activeWebhooksPanel private val webhookOptionsPanel = ThemeManager.currentBackgroundUIImage.constrain { x = CenterConstraint() @@ -86,22 +92,22 @@ class WebhookMenu: WindowScreen(ElementaVersion.V5) { x = 15.scaledPixels y = 10.scaledPixels width = 100.percent - textScale = 1.5.scaledPixels + textScale = 1.5.textScaledPixels } childOf webhookOptionsList private val sideSwitchButton = ThemeManager.currentBackgroundUIImage.constrain { - x = CenterConstraint() - y = CenterConstraint() - (300 / 2).scaledPixels + 20.scaledPixels - width = 50.scaledPixels - height = 50.scaledPixels - }.onMouseClick { - if (selectedIcon == null) { - return@onMouseClick - } + x = CenterConstraint() + y = CenterConstraint() - (300 / 2).scaledPixels + 20.scaledPixels + width = 50.scaledPixels + height = 50.scaledPixels + }.onMouseClick { + if (selectedIcon == null) { + return@onMouseClick + } - selectedIcon?.enabled = !(selectedIcon?.enabled ?: false) - updateLocations() - } childOf window + selectedIcon?.enabled = !(selectedIcon?.enabled ?: false) + updateLocations() + } childOf window private val sideSwitchIcon = ResourceLocation("partlysaneskies", "textures/gui/webhookedit/sideswitch.png") .uiImage @@ -146,20 +152,21 @@ class WebhookMenu: WindowScreen(ElementaVersion.V5) { private fun updateParameters() { val selectedConfig = selectedIcon?.webhookEvent?.config - if (selectedConfig == null) { - for (param in activeParameters) { - param.parameterBlock.hide(true) - webhookOptionsHeader.setText("") - } - activeParameters.clear() - } else { + + for (param in activeParameters) { + param.parameterBlock.hide(true) + param.parameterBlock.parent.removeChild(param.parameterBlock) + webhookOptionsHeader.setText("") + } + activeParameters.clear() + + if (selectedConfig != null) { val startX = 3.0 var x = startX var y = 30 val width = 20 for (key in selectedConfig.getAllOptions().keys) { - if (x + width > 100) { y += 30 x = startX @@ -185,6 +192,7 @@ class WebhookMenu: WindowScreen(ElementaVersion.V5) { } } } + private fun updateLocations() { val enabled = ArrayList() val disabled = ArrayList() @@ -245,7 +253,6 @@ class WebhookMenu: WindowScreen(ElementaVersion.V5) { } } - override fun onDrawScreen(matrixStack: UMatrixStack, mouseX: Int, mouseY: Int, partialTicks: Float) { super.onDrawScreen(matrixStack, mouseX, mouseY, partialTicks) @@ -268,32 +275,32 @@ class WebhookMenu: WindowScreen(ElementaVersion.V5) { var hovering = false var menu: WebhookMenu? = null - val text: MutableList get() { - val list = arrayListOf() - list.add("§d${webhookEvent.name}") - for (line in (webhookEvent.description).split("\n")) { - list.add("§7$line") + val text: MutableList + get() { + val list = arrayListOf() + list.add("§d${webhookEvent.name}") + for (line in (webhookEvent.description).split("\n")) { + list.add("§7$line") + } + return list } - return list - } - var enabled: Boolean get() { - return webhookEvent.enabled - } set(value) { - webhookEvent.enabled = value - } - val iconBox = UIBlock().onMouseEnter { - hovering = true - }.onMouseLeave { - hovering = false - }.onMouseClick { - if (menu?.selectedIcon == this@WebhookIcon) { - menu?.selectedIcon = null - } else { - menu?.selectedIcon = this@WebhookIcon + var enabled: Boolean + get() = webhookEvent.enabled + set(value) { + webhookEvent.enabled = value } + val iconBox = UIBlock() + .onMouseEnter { hovering = true } + .onMouseLeave { hovering = false } + .onMouseClick { + if (menu?.selectedIcon == this@WebhookIcon) { + menu?.selectedIcon = null + } else { + menu?.selectedIcon = this@WebhookIcon + } - menu?.updateSelected() - } + menu?.updateSelected() + } val toggle = PSSToggle() .setHeight(100.percent) @@ -315,11 +322,7 @@ class WebhookMenu: WindowScreen(ElementaVersion.V5) { var hovering = false var menu: WebhookMenu? = null - val parameterBlock = UIBlock().onMouseEnter { - hovering = true - }.onMouseLeave { - hovering = false - } + val parameterBlock = UIBlock() val toggle = PSSToggle() .setX(0.percent) @@ -331,29 +334,37 @@ class WebhookMenu: WindowScreen(ElementaVersion.V5) { val textComponent = UIWrappedText(centered = false).constrain { x = 0.pixels(alignOpposite = true) y = CenterConstraint() - textScale = 1.scaledPixels + textScale = 1.textScaledPixels width = 70.percent + color = Color.lightGray.constraint } childOf parameterBlock - val text: MutableList get() { - val list = arrayListOf() + val text: MutableList + get() { + val list = arrayListOf() - for (line in (config.find(optionPath)?.asToggle?.description ?: "").split("\n")) { - list.add("§7$line") - } + for (line in (config.find(optionPath)?.asToggle?.description ?: "").split("\n")) { + list.add("§7$line") + } - return list - } + return list + } init { parameterBlock.onMouseClickConsumer { toggle.toggleState() config.find(optionPath)?.asToggle?.state = toggle.getState() menu?.updateLocations() + }.onMouseEnter { + hovering = true + textComponent.setColor(Color.gray) + }.onMouseLeave { + hovering = false + textComponent.setColor(Color.lightGray) } toggle.setState(config.find(optionPath)?.asToggle?.state ?: false) - textComponent.setText("§7${config.find(optionPath)?.asToggle?.name ?: "(Unknown)"}" ) + textComponent.setText("§7${config.find(optionPath)?.asToggle?.name ?: "(Unknown)"}") } fun syncToggle() { diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/discord/webhooks/WebhookSerializer.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/discord/webhooks/WebhookSerializer.kt index b9ba54219..fab0f812e 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/discord/webhooks/WebhookSerializer.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/discord/webhooks/WebhookSerializer.kt @@ -3,7 +3,6 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.features.discord.webhooks object WebhookSerializer { @@ -31,59 +30,59 @@ object WebhookSerializer { } object DiscordEmbedSerializer { - fun serialize(embedData: EmbedData): String { - val builder = StringBuilder() - builder.append("{") + fun serialize(embedData: EmbedData): String { + val builder = StringBuilder() + builder.append("{") + if (embedData.title != null) { + builder.append("\"title\":\"${embedData.title}\"") + } + if (embedData.description != null) { if (embedData.title != null) { - builder.append("\"title\":\"${embedData.title}\"") + builder.append(",") } - if (embedData.description != null) { - if (embedData.title != null) { - builder.append(",") - } - builder.append("\"description\":\"${embedData.description}\"") + builder.append("\"description\":\"${embedData.description}\"") + } + if (embedData.url != null) { + if (embedData.title != null || embedData.description != null) { + builder.append(",") } - if (embedData.url != null) { - if (embedData.title != null || embedData.description != null) { - builder.append(",") - } - builder.append("\"url\":\"${embedData.url}\"") + builder.append("\"url\":\"${embedData.url}\"") + } + if (embedData.color != null) { + if (embedData.title != null || embedData.description != null || embedData.url != null) { + builder.append(",") } - if (embedData.color != null) { - if (embedData.title != null || embedData.description != null || embedData.url != null) { - builder.append(",") - } - builder.append("\"color\":${embedData.color!!}") + builder.append("\"color\":${embedData.color!!}") + } + if (embedData.fields != null) { + if (embedData.title != null || embedData.description != null || embedData.url != null || embedData.color != null) { + builder.append(",") } - if (embedData.fields != null) { - if (embedData.title != null || embedData.description != null || embedData.url != null || embedData.color != null) { + builder.append("\"fields\":[") + for (i in embedData.fields!!.indices) { + builder.append(DiscordEmbedFieldSerializer.serialize(embedData.fields!![i])) + if (i != embedData.fields!!.size - 1) { builder.append(",") } - builder.append("\"fields\":[") - for (i in embedData.fields!!.indices) { - builder.append(DiscordEmbedFieldSerializer.serialize(embedData.fields!![i])) - if (i != embedData.fields!!.size - 1) { - builder.append(",") - } - } - builder.append("]") } - builder.append("}") - return builder.toString() + builder.append("]") } + builder.append("}") + return builder.toString() + } } object DiscordEmbedFieldSerializer { - fun serialize(field: EmbedField): String { - val builder = StringBuilder() - builder.append("{") - builder.append("\"name\":\"${field.name}\"") - builder.append(",") - builder.append("\"value\":\"${field.value}\"") - builder.append(",") - builder.append("\"inline\":${field.inline}") - builder.append("}") - return builder.toString() - } + fun serialize(field: EmbedField): String { + val builder = StringBuilder() + builder.append("{") + builder.append("\"name\":\"${field.name}\"") + builder.append(",") + builder.append("\"value\":\"${field.value}\"") + builder.append(",") + builder.append("\"inline\":${field.inline}") + builder.append("}") + return builder.toString() + } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/dungeons/AutoGG.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/dungeons/AutoGG.kt index 2c7b8302e..88b336b98 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/dungeons/AutoGG.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/dungeons/AutoGG.kt @@ -3,59 +3,60 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.features.dungeons import me.partlysanestudios.partlysaneskies.PartlySaneSkies -import net.minecraftforge.client.event.ClientChatReceivedEvent -import net.minecraftforge.fml.common.eventhandler.SubscribeEvent +import me.partlysanestudios.partlysaneskies.events.SubscribePSSEvent +import me.partlysanestudios.partlysaneskies.events.minecraft.PSSChatEvent import java.util.regex.Matcher import java.util.regex.Pattern object AutoGG { - @SubscribeEvent - fun handleChatEvent(event: ClientChatReceivedEvent) { + @SubscribePSSEvent + fun onChat(event: PSSChatEvent) { if (!PartlySaneSkies.config.autoGgEnabled) { return } - if (event.message.formattedText.contains("§r§fTeam Score:")) { + if (event.message.contains("§r§fTeam Score:")) { Thread({ Thread.sleep((PartlySaneSkies.config.autoGGCooldown * 1000).toLong()) - val input = event.message.unformattedText + val input = event.component.unformattedText val regex = "\\((.*?)\\)" - val pattern: Pattern = Pattern.compile(regex) - val matcher: Matcher = pattern.matcher(input) - - if (matcher.find()) { - val score: String = matcher.group(1) - if (score.equals("S+")) { - val message = if (PartlySaneSkies.config.sendAutoGGInWhatChat == 0) { - "/pc " + PartlySaneSkies.config.autoGGMessageSPlus - } else { - "/ac " + PartlySaneSkies.config.autoGGMessageSPlus - } - PartlySaneSkies.minecraft.thePlayer.sendChatMessage(message) - - } else if (score.equals("S")) { - val message = if (PartlySaneSkies.config.sendAutoGGInWhatChat == 0) { - "/pc " + PartlySaneSkies.config.autoGGMessageS + val pattern: Pattern = Pattern.compile(regex) + val matcher: Matcher = pattern.matcher(input) + + if (matcher.find()) { + val score: String = matcher.group(1) + if (score.equals("S+")) { + val message = + if (PartlySaneSkies.config.sendAutoGGInWhatChat == 0) { + "/pc " + PartlySaneSkies.config.autoGGMessageSPlus + } else { + "/ac " + PartlySaneSkies.config.autoGGMessageSPlus + } + PartlySaneSkies.minecraft.thePlayer.sendChatMessage(message) + } else if (score.equals("S")) { + val message = + if (PartlySaneSkies.config.sendAutoGGInWhatChat == 0) { + "/pc " + PartlySaneSkies.config.autoGGMessageS + } else { + "/ac " + PartlySaneSkies.config.autoGGMessageS + } + PartlySaneSkies.minecraft.thePlayer.sendChatMessage(message) } else { - "/ac " + PartlySaneSkies.config.autoGGMessageS + val message = + if (PartlySaneSkies.config.sendAutoGGInWhatChat == 0) { + "/pc " + PartlySaneSkies.config.autoGGMessageOther + } else { + "/ac " + PartlySaneSkies.config.autoGGMessageOther + } + PartlySaneSkies.minecraft.thePlayer.sendChatMessage(message) } - PartlySaneSkies.minecraft.thePlayer.sendChatMessage(message) - - } else { - val message = if (PartlySaneSkies.config.sendAutoGGInWhatChat == 0) { - "/pc " + PartlySaneSkies.config.autoGGMessageOther - } else { - "/ac " + PartlySaneSkies.config.autoGGMessageOther - } - PartlySaneSkies.minecraft.thePlayer.sendChatMessage(message) - } - } - }, "AutoGG wait").start() + }, + "AutoGG wait", + ).start() } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/dungeons/HealthAlert.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/dungeons/HealthAlert.kt index 68b4ea5e1..6697a8899 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/dungeons/HealthAlert.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/dungeons/HealthAlert.kt @@ -3,7 +3,6 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.features.dungeons import me.partlysanestudios.partlysaneskies.PartlySaneSkies @@ -19,9 +18,7 @@ import me.partlysanestudios.partlysaneskies.utils.StringUtils.removeColorCodes import net.minecraft.client.audio.PositionedSoundRecord import net.minecraft.util.ResourceLocation - object HealthAlert { - private var lastWarnTime = 0L private fun isPlayerLowOnHealth(): Boolean { @@ -29,7 +26,6 @@ object HealthAlert { return false } - val scoreBoard = MinecraftUtils.getScoreboardLines() for (line in scoreBoard) { if (line.removeColorCodes()[0] != '[') { @@ -44,7 +40,6 @@ object HealthAlert { return health.contains("§e") || health.indexOf("§c") != health.lastIndexOf("§c") } return health.indexOf("§c") != health.lastIndexOf("§c") - } return false } @@ -54,11 +49,12 @@ object HealthAlert { return false } - val healthPercent = if (config.colouredHealerAlert == 1) { - .25 - } else { - .5 - } + val healthPercent = + if (config.colouredHealerAlert == 1) { + .25 + } else { + .5 + } return if (StatsData.currentHealth / StatsData.maxHealth < healthPercent) { true @@ -71,7 +67,7 @@ object HealthAlert { if (isPlayerLowOnHealth() && OneConfigScreen.healerAlert) { if (MathUtils.onCooldown( lastWarnTime, - (config.healerAlertCooldownSlider * 1000).toLong() + (config.healerAlertCooldownSlider * 1000).toLong(), ) ) { return @@ -81,8 +77,8 @@ object HealthAlert { PSSBanner( "A player in your party is low", 3500, - color = config.partyMemberLowColor.toJavaColor() - ) + color = config.partyMemberLowColor.toJavaColor(), + ), ) PartlySaneSkies.minecraft.soundHandler .playSound(PositionedSoundRecord.create(ResourceLocation("partlysaneskies", "bell"))) @@ -91,7 +87,7 @@ object HealthAlert { if (alertWhenPlayerLowOnHealth() && config.alertWhenPlayerLow) { if (MathUtils.onCooldown( lastWarnTime, - (config.healerAlertCooldownSlider * 1000).toLong() + (config.healerAlertCooldownSlider * 1000).toLong(), ) ) { return @@ -101,8 +97,8 @@ object HealthAlert { PSSBanner( "Your health is low", 3500, - color = config.playerLowColor.toJavaColor() - ) + color = config.playerLowColor.toJavaColor(), + ), ) PartlySaneSkies.minecraft.soundHandler .playSound(PositionedSoundRecord.create(ResourceLocation("partlysaneskies", "bell"))) diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/dungeons/ItemRefill.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/dungeons/ItemRefill.kt index 77b369349..cb7010f97 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/dungeons/ItemRefill.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/dungeons/ItemRefill.kt @@ -3,7 +3,6 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.features.dungeons import me.partlysanestudios.partlysaneskies.PartlySaneSkies @@ -14,10 +13,9 @@ import me.partlysanestudios.partlysaneskies.events.SubscribePSSEvent import me.partlysanestudios.partlysaneskies.events.skyblock.dungeons.DungeonStartEvent import me.partlysanestudios.partlysaneskies.utils.ChatUtils import me.partlysanestudios.partlysaneskies.utils.MinecraftUtils.countItemInInventory -import net.minecraft.command.ICommandSender import net.minecraftforge.fml.common.eventhandler.SubscribeEvent import net.minecraftforge.fml.common.gameevent.InputEvent -import java.util.* +import java.util.Locale object ItemRefill { @SubscribePSSEvent @@ -43,7 +41,6 @@ object ItemRefill { if (config.itemRefillKeybind.isActive()) { runItemRefil() } - } private fun runItemRefil() { @@ -74,12 +71,13 @@ object ItemRefill { val itemName = SkyblockDataManager.getItem(entry.key)?.name ?: "" if (entry.value < maxStackSize) { ChatUtils.sendClientMessage("Refilling ${maxStackSize - entry.value} ${itemName}s...") - PartlySaneSkies.minecraft.thePlayer.sendChatMessage("/gfs ${entry.key.lowercase(Locale.getDefault())} ${maxStackSize - entry.value}") + PartlySaneSkies.minecraft.thePlayer.sendChatMessage( + "/gfs ${entry.key.lowercase(Locale.getDefault())} ${maxStackSize - entry.value}", + ) } Thread.sleep(2000) } }.start() - } } diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/dungeons/PlayerRating.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/dungeons/PlayerRating.kt index fd5035669..7ff9a13a9 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/dungeons/PlayerRating.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/dungeons/PlayerRating.kt @@ -14,6 +14,7 @@ import me.partlysanestudios.partlysaneskies.data.pssdata.PublicDataManager.getFi import me.partlysanestudios.partlysaneskies.data.skyblockdata.IslandType import me.partlysanestudios.partlysaneskies.events.SubscribePSSEvent import me.partlysanestudios.partlysaneskies.events.data.LoadPublicDataEvent +import me.partlysanestudios.partlysaneskies.events.minecraft.PSSChatEvent import me.partlysanestudios.partlysaneskies.events.skyblock.dungeons.DungeonEndEvent import me.partlysanestudios.partlysaneskies.events.skyblock.dungeons.DungeonStartEvent import me.partlysanestudios.partlysaneskies.utils.ChatUtils.sendClientMessage @@ -21,12 +22,8 @@ import me.partlysanestudios.partlysaneskies.utils.MathUtils.round import me.partlysanestudios.partlysaneskies.utils.StringUtils.removeColorCodes import me.partlysanestudios.partlysaneskies.utils.StringUtils.stripLeading import me.partlysanestudios.partlysaneskies.utils.StringUtils.stripTrailing -import net.minecraft.command.ICommandSender -import net.minecraftforge.client.event.ClientChatReceivedEvent -import net.minecraftforge.fml.common.eventhandler.SubscribeEvent object PlayerRating { - private var currentPlayer = "" private var positiveRegexs = HashMap() @@ -113,7 +110,8 @@ object PlayerRating { if (config.enhancedDungeonPlayerBreakdown == 2) { playerStr.append("§2 Breakdown:\n") for ((key, value1) in value) { - playerStr.append(" §d") + playerStr + .append(" §d") .append((value1.toDouble() / (categoryPointMap[key] ?: 0) * 100.0).round(0)) .append("%§7 of ") .append(key) @@ -172,12 +170,14 @@ object PlayerRating { fun registerReprintCommand() { PSSCommand( - "reprintscore", mutableListOf("rps", "rs"), "Reprints the last score in a dungeon run" + "reprintscore", + mutableListOf("rps", "rs"), + "Reprints the last score in a dungeon run", ) { reprintLastScore() }.register() } @SubscribePSSEvent - fun onDungeonStart(event: DungeonStartEvent?) { + fun onDungeonStart(event: DungeonStartEvent) { if (!(config.dungeonPlayerBreakdown || config.dungeonSnitcher)) { return } @@ -185,7 +185,7 @@ object PlayerRating { } @SubscribePSSEvent - fun onDungeonEnd(event: DungeonEndEvent?) { + fun onDungeonEnd(event: DungeonEndEvent) { if (!(config.dungeonPlayerBreakdown || config.dungeonSnitcher)) { return } @@ -225,12 +225,12 @@ object PlayerRating { reset() } - @SubscribeEvent - fun onChatEvent(event: ClientChatReceivedEvent) { + @SubscribePSSEvent + fun onChatEvent(event: PSSChatEvent) { if (!(config.dungeonPlayerBreakdown || config.dungeonSnitcher)) { return } - if (event.message.unformattedText.contains("You are playing on profile:")) { + if (event.component.unformattedText.contains("You are playing on profile:")) { reset() return } @@ -238,6 +238,6 @@ object PlayerRating { return } - handleMessage(event.message.unformattedText) + handleMessage(event.component.unformattedText) } } diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/dungeons/RequiredSecretsFound.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/dungeons/RequiredSecretsFound.kt index f38236d85..3f891ea52 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/dungeons/RequiredSecretsFound.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/dungeons/RequiredSecretsFound.kt @@ -7,68 +7,56 @@ package me.partlysanestudios.partlysaneskies.features.dungeons import me.partlysanestudios.partlysaneskies.PartlySaneSkies.Companion.config import me.partlysanestudios.partlysaneskies.PartlySaneSkies.Companion.minecraft -import me.partlysanestudios.partlysaneskies.PartlySaneSkies.Companion.time import me.partlysanestudios.partlysaneskies.data.skyblockdata.IslandType import me.partlysanestudios.partlysaneskies.events.SubscribePSSEvent +import me.partlysanestudios.partlysaneskies.events.minecraft.TablistUpdateEvent import me.partlysanestudios.partlysaneskies.events.skyblock.dungeons.DungeonStartEvent import me.partlysanestudios.partlysaneskies.render.gui.hud.BannerRenderer.renderNewBanner import me.partlysanestudios.partlysaneskies.render.gui.hud.PSSBanner import me.partlysanestudios.partlysaneskies.utils.HypixelUtils.isSkyblock -import me.partlysanestudios.partlysaneskies.utils.MinecraftUtils.getTabList import net.minecraft.client.Minecraft import net.minecraft.client.audio.PositionedSoundRecord import net.minecraft.util.ResourceLocation object RequiredSecretsFound { - private var alreadySendThisRun = false - private var lastCheckTime = time @SubscribePSSEvent fun onDungeonStart(event: DungeonStartEvent?) { alreadySendThisRun = false } - fun tick() { - if (!isSkyblock()) { - return - } - if (!IslandType.CATACOMBS.onIsland()) { - return - } - if (alreadySendThisRun) { - return + @SubscribePSSEvent + fun onTablistUpdate(event: TablistUpdateEvent) { + if (!isSkyblock()) return + if (!IslandType.CATACOMBS.onIsland()) return + + if (alreadySendThisRun) return + + if (event.list.none { it.contains("Secrets Found: §r§a") }) return + + if (config.secretsBanner) { + renderNewBanner( + PSSBanner( + "Required Secrets Found!", + (config.secretsBannerTime * 1000).toLong(), + 3.0f, + config.secretsBannerColor.toJavaColor(), + ), + ) } - if (lastCheckTime + 100 > time) { //checks every 100ms - return + if (config.secretsChatMessage) { + Minecraft.getMinecraft().thePlayer.sendChatMessage("/pc " + config.secretsChatMessageString) } - lastCheckTime = time - - for (line in getTabList()) { - if (line.contains("Secrets Found: §r§a")) { - if (config.secretsBanner) { - renderNewBanner( - PSSBanner( - "Required Secrets Found!", - (config.secretsBannerTime * 1000).toLong(), - 3.0f, - config.secretsBannerColor.toJavaColor() - ) - ) - } - if (config.secretsChatMessage) { - Minecraft.getMinecraft().thePlayer.sendChatMessage("/pc " + config.secretsChatMessageString) - } - if (config.secretsSound) { - if (config.secretsAirRaidSiren) { - minecraft.soundHandler.playSound(PositionedSoundRecord.create(ResourceLocation("partlysaneskies", "airraidsiren"))) - } else { - minecraft.soundHandler.playSound(PositionedSoundRecord.create(ResourceLocation("partlysaneskies", "bell"))) - } - } - alreadySendThisRun = true - break - } + if (config.secretsSound) { + minecraft.soundHandler.playSound( + if (config.secretsAirRaidSiren) { + PositionedSoundRecord.create(ResourceLocation("partlysaneskies", "airraidsiren")) + } else { + PositionedSoundRecord.create(ResourceLocation("partlysaneskies", "bell")) + }, + ) } + alreadySendThisRun = true } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/dungeons/TerminalWaypoints.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/dungeons/TerminalWaypoints.kt index c4fb870a2..0e983648c 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/dungeons/TerminalWaypoints.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/dungeons/TerminalWaypoints.kt @@ -24,13 +24,13 @@ import org.apache.logging.log4j.Level.INFO import java.awt.Color object TerminalWaypoints { - - private val boundingBoxes = arrayOf( - Range3d(118.0, 103.0, 27.0, 90.0, 157.0, 124.0), - Range3d(118.0, 103.0, 145.0, 19.0, 157.0, 120.0), - Range3d(-4.0, 103.0, 145.0, 19.0, 157.0, 50.0), - Range3d(-3.0, 103.0, 26.0, 92.0, 157.0, 53.0) - ) + private val boundingBoxes = + arrayOf( + Range3d(118.0, 103.0, 27.0, 90.0, 157.0, 124.0), + Range3d(118.0, 103.0, 145.0, 19.0, 157.0, 120.0), + Range3d(-4.0, 103.0, 145.0, 19.0, 157.0, 50.0), + Range3d(-3.0, 103.0, 26.0, 92.0, 157.0, 53.0), + ) private val cachedPuzzles = ArrayList() fun logCachedPuzzles() { @@ -53,39 +53,38 @@ object TerminalWaypoints { updateAllPuzzles() - for (puzzle in cachedPuzzles) { if (playerBoundingBox?.isInRange(puzzle.pos) != true) { continue } - val waypoint = if (puzzle.active) { // Active - Waypoint( - puzzle.type.displayName, - puzzle.pos.toBlockPosInt(), - fillColor = Color.green.applyOpacity(50), - outlineColor = Color.green.applyOpacity(125) - ) - } else if (puzzle.isPlayerNearby()) { // Inactive but someone nearby - Waypoint( - puzzle.type.displayName, - puzzle.pos.toBlockPosInt(), - fillColor = Color.orange.applyOpacity(50), - outlineColor = Color.orange.applyOpacity(125) - ) - } else { // Inactive - Waypoint( - puzzle.type.displayName, - puzzle.pos.toBlockPosInt(), - fillColor = Color.red.applyOpacity(50), - outlineColor = Color.red.applyOpacity(125) - ) - } + val waypoint = + if (puzzle.active) { // Active + Waypoint( + puzzle.type.displayName, + puzzle.pos.toBlockPosInt(), + fillColor = Color.green.applyOpacity(50), + outlineColor = Color.green.applyOpacity(125), + ) + } else if (puzzle.isPlayerNearby()) { // Inactive but someone nearby + Waypoint( + puzzle.type.displayName, + puzzle.pos.toBlockPosInt(), + fillColor = Color.orange.applyOpacity(50), + outlineColor = Color.orange.applyOpacity(125), + ) + } else { // Inactive + Waypoint( + puzzle.type.displayName, + puzzle.pos.toBlockPosInt(), + fillColor = Color.red.applyOpacity(50), + outlineColor = Color.red.applyOpacity(125), + ) + } event.pipeline.add(waypoint) } } - @SubscribePSSEvent fun onDungeonStart(event: DungeonStartEvent) { // Yes I wrote the entire event system just so that I wouldn't have to call a chat event here for (terminal in cachedPuzzles) { @@ -144,7 +143,6 @@ object TerminalWaypoints { return puzzles } - private fun getCurrentBoundingBox(point3d: Point3d): Range3d? { for (boundingBox in boundingBoxes) { if (boundingBox.isInRange(point3d)) { @@ -157,10 +155,14 @@ object TerminalWaypoints { class F7Puzzle(val pos: Point3d, val type: Type) { var active = false - enum class Type(val activeArmorStandName: String, val inactiveArmorStandName: String, val displayName: String) { + enum class Type( + val activeArmorStandName: String, + val inactiveArmorStandName: String, + val displayName: String, + ) { TERMINAL("Active Terminal", "Inactive Terminal", "Terminal"), LEVER("Activated", "Not Activated", "Lever"), - DEVICE("Active", "Inactive", "Device") + DEVICE("Active", "Inactive", "Device"), } fun isPlayerNearby(): Boolean { @@ -175,8 +177,6 @@ object TerminalWaypoints { return false } - override fun toString(): String { - return "F7Puzzle(pos=$pos, type=$type, active=$active)" - } + override fun toString(): String = "F7Puzzle(pos=$pos, type=$type, active=$active)" } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/dungeons/WatcherReady.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/dungeons/WatcherReady.kt index 48c3aa6c5..4f447cccd 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/dungeons/WatcherReady.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/dungeons/WatcherReady.kt @@ -7,26 +7,26 @@ package me.partlysanestudios.partlysaneskies.features.dungeons import me.partlysanestudios.partlysaneskies.PartlySaneSkies.Companion.config import me.partlysanestudios.partlysaneskies.PartlySaneSkies.Companion.minecraft +import me.partlysanestudios.partlysaneskies.events.SubscribePSSEvent +import me.partlysanestudios.partlysaneskies.events.minecraft.PSSChatEvent import me.partlysanestudios.partlysaneskies.render.gui.hud.BannerRenderer.renderNewBanner import me.partlysanestudios.partlysaneskies.render.gui.hud.PSSBanner import net.minecraft.client.audio.PositionedSoundRecord import net.minecraft.util.ResourceLocation -import net.minecraftforge.client.event.ClientChatReceivedEvent -import net.minecraftforge.fml.common.eventhandler.SubscribeEvent object WatcherReady { - @SubscribeEvent - fun watcherReadyChatEvent(event: ClientChatReceivedEvent) { - if (event.message.unformattedText.startsWith("[BOSS] The Watcher: That will be enough for now.")) { + @SubscribePSSEvent + fun onChat(event: PSSChatEvent) { + if (event.component.unformattedText.startsWith("[BOSS] The Watcher: That will be enough for now.")) { if (config.watcherReadyBanner) { renderNewBanner( PSSBanner( "Watcher Ready!", (config.watcherReadyBannerTime * 1000).toLong(), 3.0f, - config.watcherReadyBannerColor.toJavaColor() - ) + config.watcherReadyBannerColor.toJavaColor(), + ), ) } if (config.watcherReadyChatMessage) { @@ -35,15 +35,15 @@ object WatcherReady { if (config.watcherReadySound) { minecraft.soundHandler.playSound( PositionedSoundRecord.create( - ResourceLocation("partlysaneskies", "bell") - ) + ResourceLocation("partlysaneskies", "bell"), + ), ) } if (config.watcherReadyAirRaidSiren) { minecraft.soundHandler.playSound( PositionedSoundRecord.create( - ResourceLocation("partlysaneskies", "airraidsiren") - ) + ResourceLocation("partlysaneskies", "airraidsiren"), + ), ) } } diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/economy/BitsShopValue.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/economy/BitsShopValue.kt index f0eb095c8..84a627257 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/economy/BitsShopValue.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/economy/BitsShopValue.kt @@ -20,6 +20,7 @@ import me.partlysanestudios.partlysaneskies.data.skyblockdata.SkyblockDataManage import me.partlysanestudios.partlysaneskies.data.skyblockdata.SkyblockDataManager.initBitValues import me.partlysanestudios.partlysaneskies.features.gui.SidePanel import me.partlysanestudios.partlysaneskies.render.gui.constraints.ScaledPixelConstraint.Companion.scaledPixels +import me.partlysanestudios.partlysaneskies.render.gui.constraints.TextScaledPixelConstraint.Companion.textScaledPixels import me.partlysanestudios.partlysaneskies.utils.ElementaUtils.applyBackground import me.partlysanestudios.partlysaneskies.utils.HypixelUtils.getBits import me.partlysanestudios.partlysaneskies.utils.MathUtils.round @@ -33,21 +34,23 @@ import java.awt.Color import java.io.IOException object BitsShopValue : SidePanel() { - override val panelBaseComponent: UIComponent = UIBlock().applyBackground().constrain { - x = 800.scaledPixels - y = CenterConstraint() - width = 225.scaledPixels - height = 350.scaledPixels - color = Color(0, 0, 0, 0).constraint - } + override val panelBaseComponent: UIComponent = UIBlock().applyBackground() + .constrain { + x = 800.scaledPixels + y = CenterConstraint() + width = 225.scaledPixels + height = 350.scaledPixels + color = Color(0, 0, 0, 0).constraint + } - private val textComponent = UIWrappedText().constrain { - x = CenterConstraint() - y = CenterConstraint() - height = 95.percent - width = 95.percent - textScale = 1.scaledPixels - } childOf panelBaseComponent + private val textComponent = UIWrappedText() + .constrain { + x = CenterConstraint() + y = CenterConstraint() + height = 95.percent + width = 95.percent + textScale = 1.textScaledPixels + } childOf panelBaseComponent override fun onPanelRender(event: GuiScreenEvent.BackgroundDrawnEvent) { alignPanel() @@ -107,8 +110,8 @@ object BitsShopValue : SidePanel() { for ((key, value) in sortedMap) { val item = getItem(key) ?: continue str += "§6$i. §d ${item.name}§7 costs §d${item.bitCost.formatNumber()}§7 bits " + - "and sells for §d${item.getSellPrice().round(1).formatNumber()}§7 coins " + - "\n§8 (${value.round(1).formatNumber()} coins per bit)\n" + "and sells for §d${item.getSellPrice().round(1).formatNumber()}§7 coins " + + "\n§8 (${value.round(1).formatNumber()} coins per bit)\n" i++ if (i > 5) { break @@ -120,4 +123,4 @@ object BitsShopValue : SidePanel() { return str } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/economy/CoinsToBoosterCookies.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/economy/CoinsToBoosterCookies.kt index 4b9a42f0d..7a9bd05b2 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/economy/CoinsToBoosterCookies.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/economy/CoinsToBoosterCookies.kt @@ -25,12 +25,10 @@ import me.partlysanestudios.partlysaneskies.utils.MathUtils.round import me.partlysanestudios.partlysaneskies.utils.SkyCryptUtils import me.partlysanestudios.partlysaneskies.utils.StringUtils.formatNumber import me.partlysanestudios.partlysaneskies.utils.SystemUtils.getJsonFromPath -import net.minecraft.command.ICommandSender import kotlin.math.abs import kotlin.math.ceil object CoinsToBoosterCookies { - private val playerName: String by lazy { PartlySaneSkies.minecraft.thePlayer.name } private const val boosterCookieItemId: String = "BOOSTER_COOKIE" private const val boosterCookiePath: String = "constants/booster_cookie_price.json" @@ -38,7 +36,6 @@ object CoinsToBoosterCookies { private val orderOfCurrency = arrayOf("AUD", "BRL", "CAD", "DKK", "EUR", "KPW", "NOK", "NZD", "PLN", "GBP", "SEK", "USD") - private fun currencyFormatting(money: String): String { // Formats the currency to be the right preferred symbol val boosterCookieData: JsonObject = @@ -56,58 +53,79 @@ object CoinsToBoosterCookies { fun registerCommand() { PSSCommand("coins2cookies") - .addAlias("/coinstocookies") - .addAlias("/pssco2icok") - .addAlias("/coi2cok") - .addAlias("/c2c") - .addAlias("c2c") - .addAlias("coi2cok") - .addAlias("psscoi2cok") - .addAlias("coinstocookies") + .addAlias("coinstocookies", "psscoi2cok", "c2c") .setDescription("Converts a given amount of coins to the IRL cost of booster cookies in your selected currency via §9/pssc§b.") .setRunnable { args: Array -> ChatUtils.sendClientMessage("Loading...") // Creates a new thread so we don't pause the entirety of the game to perform a request that won't work because a game tick needs to pass to be able to run - Thread({ - if (args.size == 1 && args[0].toDoubleOrNull() != null) { + Thread( + { + if (args.size == 1 && args[0].toDoubleOrNull() != null) { // Gets the public data json - val boosterCookieData: JsonObject = JsonParser().parse( - PublicDataManager.getFile( - boosterCookiePath - ) - ).getAsJsonObject() + val boosterCookieData: JsonObject = + JsonParser() + .parse( + PublicDataManager.getFile( + boosterCookiePath, + ), + ).getAsJsonObject() // Preferred currency - val prefCurr: String = orderOfCurrency[configCurr] + val prefCurr: String = orderOfCurrency[configCurr] // The cost of the smallest skyblock gem package in preferred currency - val sSGPInPreferredCurrency = - boosterCookieData["storehypixelnet"].asJsonObject.get(prefCurr).asDouble + val sSGPInPreferredCurrency = + boosterCookieData["storehypixelnet"].asJsonObject.get(prefCurr).asDouble // Gets the amount of cookies - val cookieQuantity = convertCoinsToBoosterCookies(args[0].toDouble()) + val cookieQuantity = convertCoinsToBoosterCookies(args[0].toDouble()) // Gets the amount of gem packages - val gemPackages: Double = ceil(convertCoinsToGemPackages(args[0].toDouble())) + val gemPackages: Double = ceil(convertCoinsToGemPackages(args[0].toDouble())) // Cost in irl money - val dollars: Double = (gemPackages * sSGPInPreferredCurrency).floor(2) + val dollars: Double = (gemPackages * sSGPInPreferredCurrency).floor(2) // Sends message - ChatUtils.sendClientMessage("§6${abs(args[0].toDouble()).formatNumber()} coins §etoday is equivalent to §6${cookieQuantity.round(3).formatNumber()} Booster Cookies, or §2${currencyFormatting(money = (dollars.formatNumber()))} §e(excluding sales taxes and other fees).") - ChatUtils.sendClientMessage("§7(For reference, Booster Cookies today are worth ${ceil(SkyblockDataManager.getItem(boosterCookieItemId)?.getBuyPrice() ?: 0.0).round(1).formatNumber()} coins. Note that the developers of Partly Sane Skies do not support IRL trading; the /c2c command is intended for educational purposes.)", true) - if (DebugKey.isDebugMode()) { // Optional debug message - ChatUtils.sendClientMessage("§eIf the currency symbol doesn't look right, please report this to us via §9/pssdiscord §eso we can find a replacement symbol that Minecraft 1.8.9 can render.", true) - } - } else if (args.isEmpty() || args.size == 1) { - runNetworthToCoins(playerName) - } else if (args[0].contentEquals("networth", true) || args[0].contentEquals("nw", true)) { - if (args.size == 1) { - ChatUtils.sendClientMessage("Correct Usage: /coins2cookies networth {username}") + ChatUtils.sendClientMessage( + "§6${abs(args[0].toDouble()).formatNumber()} coins §etoday is equivalent to §6${ + cookieQuantity.round( + 3, + ).formatNumber() + } Booster Cookies, or §2${currencyFormatting( + money = (dollars.formatNumber()), + )} §e(excluding sales taxes and other fees).", + ) + ChatUtils.sendClientMessage( + "§7(For reference, Booster Cookies today are worth ${ + ceil( + SkyblockDataManager + .getItem( + boosterCookieItemId, + )?.getBuyPrice() ?: 0.0, + ).round(1).formatNumber() + } coins. Note that the developers of Partly Sane Skies do not support IRL trading; the /c2c command is intended for educational purposes.)", + true, + ) + if (DebugKey.isDebugMode()) { // Optional debug message + ChatUtils.sendClientMessage( + "§eIf the currency symbol doesn't look right, please report this to us via §9/pssdiscord §eso we can find a replacement symbol that Minecraft 1.8.9 can render.", + true, + ) + } + } else if (args.isEmpty() || args.size == 1) { + runNetworthToCoins(playerName) + } else if (args[0].contentEquals("networth", true) || args[0].contentEquals("nw", true)) { + if (args.size == 1) { + ChatUtils.sendClientMessage("Correct Usage: /coins2cookies networth {username}") + return@Thread + } + runNetworthToCoins(args[1]) + } else { + ChatUtils.sendClientMessage( + "§cPlease enter a valid number for your §6coins to cookies §cconversion and try again.", + ) return@Thread } - runNetworthToCoins(args[1]) - } else { - ChatUtils.sendClientMessage("§cPlease enter a valid number for your §6coins to cookies §cconversion and try again.") - return@Thread - } - }, "Coins to Cookies").start() + }, + "Coins to Cookies", + ).start() }.register() } @@ -117,7 +135,6 @@ object CoinsToBoosterCookies { return abs(coins) / boosterCookieBuyPrice } - // Returns the amount of gem packages a given number of coins is worth // Can be fractional private fun convertCoinsToGemPackages(coins: Double): Double { @@ -133,17 +150,19 @@ object CoinsToBoosterCookies { val smallestSkyblockGemsPackage = boosterCookieDataJsonObject.getJsonFromPath("storehypixelnet/smallestgembundle")?.asDouble ?: 675.0 - return ((convertCoinsToBoosterCookies(coins) * boosterCookieInGems) / smallestSkyblockGemsPackage) //math adapted from NEU: https://github.com/NotEnoughUpdates/NotEnoughUpdates/blob/master/src/main/java/io/github/moulberry/notenoughupdates/profileviewer/BasicPage.java#L342 + return ((convertCoinsToBoosterCookies(coins) * boosterCookieInGems) / smallestSkyblockGemsPackage) // math adapted from NEU: https://github.com/NotEnoughUpdates/NotEnoughUpdates/blob/master/src/main/java/io/github/moulberry/notenoughupdates/profileviewer/BasicPage.java#L342 } private fun runNetworthToCoins(username: String = playerName) { val networth: Double = SkyCryptUtils.getSkyCryptNetworth(username) if (networth >= 0.0) { - val boosterCookieData: JsonObject = JsonParser().parse( - PublicDataManager.getFile( - boosterCookiePath - ) - ).getAsJsonObject() + val boosterCookieData: JsonObject = + JsonParser() + .parse( + PublicDataManager.getFile( + boosterCookiePath, + ), + ).getAsJsonObject() val prefCurr: String = orderOfCurrency[configCurr] val sSGPInPreferredCurrency = boosterCookieData["storehypixelnet"].asJsonObject.get(prefCurr).asDouble @@ -154,32 +173,35 @@ object CoinsToBoosterCookies { ChatUtils.sendClientMessage( "§e$namePlaceholder total networth (both soulbound and unsoulbound) of §6${ networth.round( - 2 + 2, ).formatNumber() } coins §etoday is equivalent to §6${cookieValue.formatNumber()} Booster Cookies, or §2${ currencyFormatting( - money = (dollars.formatNumber()) + money = (dollars.formatNumber()), ) - } §e(excluding sales taxes and other fees)." + } §e(excluding sales taxes and other fees).", ) ChatUtils.sendClientMessage( "§7(For reference, Booster Cookies today are worth ${ ceil( - SkyblockDataManager.getItem( - boosterCookieItemId - )?.getBuyPrice() ?: 0.0 + SkyblockDataManager + .getItem( + boosterCookieItemId, + )?.getBuyPrice() ?: 0.0, ).round(2).formatNumber() } coins. Note that the developers of Partly Sane Skies do not support IRL trading; the /c2c command is intended for educational purposes.)", - true + true, ) ChatUtils.sendClientMessage( "§ePlease use NEU's §a/pv§e command for converting your unsoulbound networth.", - true - ) - if (DebugKey.isDebugMode()) ChatUtils.sendClientMessage( - "§eIf the currency symbol doesn't look right, please report this to us via §9/pssdiscord §eso we can find a replacement symbol that Minecraft 1.8.9 can render.", - true + true, ) + if (DebugKey.isDebugMode()) { + ChatUtils.sendClientMessage( + "§eIf the currency symbol doesn't look right, please report this to us via §9/pssdiscord §eso we can find a replacement symbol that Minecraft 1.8.9 can render.", + true, + ) + } } else { ChatUtils.sendClientMessage("It seems like you don't have a networth at all... (this might be a wrong username)") } diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/economy/NoCookieWarning.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/economy/NoCookieWarning.kt index 77b86edb1..6cf02b0ad 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/economy/NoCookieWarning.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/economy/NoCookieWarning.kt @@ -16,10 +16,9 @@ import me.partlysanestudios.partlysaneskies.utils.StringUtils.removeColorCodes import net.minecraft.client.audio.PositionedSoundRecord import net.minecraft.util.ResourceLocation import java.awt.Color -import java.util.* +import java.util.Locale object NoCookieWarning { - private const val TEXT_SCALE = 2.5f private var displayString = "" private var lastWarnTime = 0L @@ -28,18 +27,22 @@ object NoCookieWarning { // determined private fun hasBoosterCookie(): Int { for (chatComponent in minecraft.ingameGUI.tabList.footer.siblings) { - if (chatComponent.formattedText.removeColorCodes().lowercase(Locale.getDefault()) + if (chatComponent.formattedText + .removeColorCodes() + .lowercase(Locale.getDefault()) .contains("not active! obtain booster cookies") ) { return 0 } } - return if (minecraft.ingameGUI.tabList.footer.siblings.isEmpty()) -1 else 1 + return if (minecraft.ingameGUI.tabList.footer.siblings.isEmpty()) { + -1 + } else { + 1 + } } - private fun hasLotsOfCoins(): Boolean { - return getCoins() > config.maxWithoutCookie - } + private fun hasLotsOfCoins(): Boolean = getCoins() > config.maxWithoutCookie private fun warn() { lastWarnTime = time @@ -52,17 +55,14 @@ object NoCookieWarning { private val timeSinceLastWarn: Long get() = time - lastWarnTime - private fun checkExpire(): Boolean { - return timeSinceLastWarn > config.noCookieWarnTime * 1000 - } + private fun checkExpire(): Boolean = timeSinceLastWarn > config.noCookieWarnTime * 1000 - private fun checkWarnAgain(): Boolean { - return if (timeSinceLastWarn > config.noCookieWarnCooldown * 1000) { + private fun checkWarnAgain(): Boolean = + if (timeSinceLastWarn > config.noCookieWarnCooldown * 1000) { true } else { false } - } fun checkCoinsTick() { if (!isSkyblock()) { @@ -84,5 +84,4 @@ object NoCookieWarning { warn() lastWarnTime = time } - } diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/economy/auctionhousemenu/AuctionElement.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/economy/auctionhousemenu/AuctionElement.kt index 6909ef6bd..cea7553da 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/economy/auctionhousemenu/AuctionElement.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/economy/auctionhousemenu/AuctionElement.kt @@ -3,7 +3,6 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.features.economy.auctionhousemenu import gg.essential.elementa.UIComponent @@ -14,19 +13,27 @@ import gg.essential.elementa.constraints.CenterConstraint import gg.essential.elementa.constraints.PixelConstraint import gg.essential.elementa.constraints.XConstraint import gg.essential.elementa.constraints.YConstraint -import gg.essential.elementa.dsl.* +import gg.essential.elementa.dsl.childOf +import gg.essential.elementa.dsl.constrain +import gg.essential.elementa.dsl.constraint +import gg.essential.elementa.dsl.div +import gg.essential.elementa.dsl.percent +import gg.essential.elementa.dsl.pixels +import gg.essential.elementa.dsl.plus +import gg.essential.elementa.dsl.times import me.partlysanestudios.partlysaneskies.PartlySaneSkies import me.partlysanestudios.partlysaneskies.data.skyblockdata.SkyblockDataManager import me.partlysanestudios.partlysaneskies.features.themes.ThemeManager import me.partlysanestudios.partlysaneskies.render.gui.components.PSSButton import me.partlysanestudios.partlysaneskies.render.gui.components.PSSItemRender +import me.partlysanestudios.partlysaneskies.render.gui.constraints.TextScaledPixelConstraint.Companion.textScaledPixels import me.partlysanestudios.partlysaneskies.utils.HypixelUtils.getItemId import me.partlysanestudios.partlysaneskies.utils.MinecraftUtils import me.partlysanestudios.partlysaneskies.utils.MinecraftUtils.getLore import me.partlysanestudios.partlysaneskies.utils.StringUtils.removeColorCodes import net.minecraft.item.ItemStack import java.awt.Color -import java.util.* +import java.util.Locale class AuctionElement( private val slot: Int, @@ -34,9 +41,8 @@ class AuctionElement( private var xConstraint: XConstraint, private var yConstraint: YConstraint, private var heightConstraint: PixelConstraint, - val textScale: Float + val textScale: Float, ) { - private val skyblockItem = SkyblockDataManager.getItem(itemstack?.getItemId() ?: "") private val boundingBox = UIBlock().constrain { @@ -66,7 +72,6 @@ class AuctionElement( clickAuction() } - private val itemHeight = (heightConstraint.value * .667f) private val itemRender: PSSItemRender = PSSItemRender(itemstack, true) @@ -76,21 +81,18 @@ class AuctionElement( .setHeight(100.percent) .setChildOf(box.component) as PSSItemRender - - private val nameComponent = UIWrappedText(getName(), centered = true).constrain { - x = CenterConstraint() - y = itemHeight.pixels - width = (heightConstraint.value * 1.25).pixels - height = (heightConstraint.value * .667).pixels - }.setTextScale(textScale.pixels) childOf boundingBox + private val nameComponent = UIWrappedText(getName(), centered = true) + .constrain { + x = CenterConstraint() + y = itemHeight.pixels + width = (heightConstraint.value * 1.25).pixels + height = (heightConstraint.value * .667).pixels + }.setTextScale(textScale.textScaledPixels) childOf boundingBox init { - boundingBox.onMouseClick { clickAuction() } - - } fun highlightIfCheapBin() { @@ -120,7 +122,6 @@ class AuctionElement( boundingBox.onMouseLeave { informationBar.clearInfo() } - } private fun clickAuction() { @@ -133,7 +134,6 @@ class AuctionElement( } val loreList: List = itemstack.getLore() for (line in loreList) { - if (line.removeColorCodes().contains("Buy it now: ")) { return true } @@ -156,9 +156,9 @@ class AuctionElement( val loreList: List = itemstack.getLore() var buyItNowPrice = "" for (line in loreList) { - if (line.removeColorCodes().contains("Buy it now:") - || line.removeColorCodes().contains("Top bid:") - || line.removeColorCodes().contains("Starting bid:") + if (line.removeColorCodes().contains("Buy it now:") || + line.removeColorCodes().contains("Top bid:") || + line.removeColorCodes().contains("Starting bid:") ) { buyItNowPrice = line.removeColorCodes().replace("[^0-9]".toRegex(), "") } @@ -169,9 +169,7 @@ class AuctionElement( return buyItNowPrice.toLong() } - fun getCostPerAmount(): Double { - return getPrice() / getAmount().toDouble() - } + fun getCostPerAmount(): Double = getPrice() / getAmount().toDouble() private fun isCheapBin(): Boolean { val sellingPrice = getPrice() @@ -185,9 +183,7 @@ class AuctionElement( return sellingPrice <= averageAhPrice * (PartlySaneSkies.config.BINSniperPercent / 100.0) } - fun getName(): String { - return itemstack?.displayName ?: "" - } + fun getName(): String = itemstack?.displayName ?: "" fun getAverageLowestBin(): Double { if (SkyblockDataManager.getItem(skyblockItem?.id ?: "") == null) { @@ -195,7 +191,9 @@ class AuctionElement( } return if (SkyblockDataManager.getItem(skyblockItem?.id ?: "")?.hasAverageLowestBin() != true) { 0.0 - } else SkyblockDataManager.getItem(skyblockItem?.id ?: "")?.averageLowestBin ?: 0.0 + } else { + SkyblockDataManager.getItem(skyblockItem?.id ?: "")?.averageLowestBin ?: 0.0 + } } fun getLowestBin(): Double { @@ -210,17 +208,19 @@ class AuctionElement( return SkyblockDataManager.getItem(skyblockItem?.id ?: "")?.getSellPrice() ?: 0.0 } - fun hasLowestBin(): Boolean { - return if (SkyblockDataManager.getItem(skyblockItem?.id ?: "") == null) { + fun hasLowestBin(): Boolean = + if (SkyblockDataManager.getItem(skyblockItem?.id ?: "") == null) { false - } else SkyblockDataManager.getItem(skyblockItem?.id ?: "")?.hasSellPrice() ?: false - } + } else { + SkyblockDataManager.getItem(skyblockItem?.id ?: "")?.hasSellPrice() ?: false + } - fun hasAverageLowestBin(): Boolean { - return if (SkyblockDataManager.getItem(skyblockItem?.id ?: "") == null) { + fun hasAverageLowestBin(): Boolean = + if (SkyblockDataManager.getItem(skyblockItem?.id ?: "") == null) { false - } else SkyblockDataManager.getItem(skyblockItem?.id ?: "")?.hasAverageLowestBin() ?: false - } + } else { + SkyblockDataManager.getItem(skyblockItem?.id ?: "")?.hasAverageLowestBin() ?: false + } fun getFormattedEndingTime(): String { if (itemstack == null) { @@ -250,16 +250,17 @@ class AuctionElement( if (itemstack == null) { return "" } - val lastLineOfLore = try { - val loreList = itemstack.getLore() - if (loreList.size - 7 - 1 < 0) { + val lastLineOfLore = + try { + val loreList = itemstack.getLore() + if (loreList.size - 7 - 1 < 0) { + return "" + } + loreList[loreList.size - 7 - 1].removeColorCodes() + } catch (exception: NullPointerException) { + exception.printStackTrace() return "" } - loreList[loreList.size - 7 - 1].removeColorCodes() - } catch (exception: NullPointerException) { - exception.printStackTrace() - return "" - } if (lastLineOfLore.uppercase(Locale.getDefault()).contains("UNCOMMON")) { str = "UNCOMMON" @@ -321,18 +322,18 @@ class AuctionElement( box.setWidth(boxHeight).setHeight(boxHeight) box.setY(boxY.pixels) - // val itemX = boxHeight / 2 itemRender.setWidth(100.percent).setHeight(100.percent) - nameComponent.setY((boxHeight + heightConstraint * 0.05)) + nameComponent + .setY((boxHeight + heightConstraint * 0.05)) .setHeight((heightConstraint.value * .667).pixels) .setWidth((heightConstraint.value * 1.25).pixels) - highlightBox.setHeight((heightConstraint.value * 1.25).pixels) + highlightBox + .setHeight((heightConstraint.value * 1.25).pixels) .setWidth((heightConstraint.value * 1.25).pixels) - this.heightConstraint = heightConstraint return this @@ -342,5 +343,4 @@ class AuctionElement( boundingBox.setChildOf(parent) return this } - } diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/economy/auctionhousemenu/AuctionHouseGui.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/economy/auctionhousemenu/AuctionHouseGui.kt index 656d0df7f..aabae47a4 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/economy/auctionhousemenu/AuctionHouseGui.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/economy/auctionhousemenu/AuctionHouseGui.kt @@ -3,7 +3,6 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.features.economy.auctionhousemenu import gg.essential.elementa.ElementaVersion @@ -17,7 +16,6 @@ import gg.essential.elementa.dsl.constraint import gg.essential.elementa.dsl.pixels import gg.essential.universal.UMatrixStack import me.partlysanestudios.partlysaneskies.PartlySaneSkies -import me.partlysanestudios.partlysaneskies.features.debug.DebugKey import me.partlysanestudios.partlysaneskies.features.themes.ThemeManager import me.partlysanestudios.partlysaneskies.utils.MinecraftUtils.containerInventory import me.partlysanestudios.partlysaneskies.utils.StringUtils.removeColorCodes @@ -26,7 +24,7 @@ import net.minecraft.inventory.IInventory import net.minecraft.item.Item import java.awt.Color -class AuctionHouseGui(defaultAuctionInventory: IInventory) : WindowScreen(ElementaVersion.V2) { +class AuctionHouseGui(defaultAuctionInventory: IInventory) : WindowScreen(ElementaVersion.V5) { private val heightPercent = PartlySaneSkies.config.masterAuctionHouseScale private val sideBarHeightPercent = PartlySaneSkies.config.auctionHouseSideBarHeight private val sideBarWidthPercent = PartlySaneSkies.config.auctionHouseSideBarWidth @@ -58,7 +56,6 @@ class AuctionHouseGui(defaultAuctionInventory: IInventory) : WindowScreen(Elemen width = sizeWidth.pixels } childOf baseBlock - private val sideBarHeight = sideBarHeightPercent * sizeHeight private val sideBarWidth = sizeWidth * sideBarWidthPercent private val itemInformationBarX = -(sideBarWidth * sideBarPadding) @@ -69,16 +66,15 @@ class AuctionHouseGui(defaultAuctionInventory: IInventory) : WindowScreen(Elemen CenterConstraint(), sideBarHeight.pixels, sideBarWidth.pixels, - textScale + textScale, ) - private val marketInformationBar = MarketInformationBar( auctionInformationBarX.pixels, CenterConstraint(), sideBarHeight.pixels, sideBarWidth.pixels, - textScale + textScale, ) private val categoriesBarHeight = 0.1665 * sizeHeight @@ -88,17 +84,16 @@ class AuctionHouseGui(defaultAuctionInventory: IInventory) : WindowScreen(Elemen categoriesBarY.pixels, categoriesBarHeight.pixels, sizeWidth.pixels, - defaultAuctionInventory + defaultAuctionInventory, ) - private val settingsBarY = backgroundImage.getBottom() + pad private val settingsBar = SettingsBar( CenterConstraint(), settingsBarY.pixels, categoriesBarHeight.pixels, sizeWidth.pixels, - defaultAuctionInventory + defaultAuctionInventory, ) private val auctions = getAuctions(defaultAuctionInventory) @@ -113,8 +108,8 @@ class AuctionHouseGui(defaultAuctionInventory: IInventory) : WindowScreen(Elemen for (row in 0 until 4) { for (column in 0 until 6) { - val x = ((boxSide + pad) * column + pad).toFloat() - val y = ((boxSide + pad) * row + pad).toFloat() + val x = (boxSide + pad) * column + pad + val y = (boxSide + pad) * row + pad try { auctions[row][column] @@ -130,21 +125,19 @@ class AuctionHouseGui(defaultAuctionInventory: IInventory) : WindowScreen(Elemen } } } - - } - private fun getAuctions(inventory: IInventory): Array> { val items = getAuctionContents(inventory) var indexOfItems = 0 - val auctions: Array> = Array(totalRows) { - Array(totalColumns) { - indexOfItems++ - items[indexOfItems - 1] + val auctions: Array> = + Array(totalRows) { + Array(totalColumns) { + indexOfItems++ + items[indexOfItems - 1] + } } - } return auctions } @@ -152,9 +145,12 @@ class AuctionHouseGui(defaultAuctionInventory: IInventory) : WindowScreen(Elemen private fun getAuctionContents(inventory: IInventory): List { val list: MutableList = ArrayList() for (i in 0..53) { - if (convertSlotToChestCoordinate(i)[0] <= 2 || convertSlotToChestCoordinate(i)[0] == 9 || convertSlotToChestCoordinate( - i - )[1] == 1 || convertSlotToChestCoordinate(i)[1] == 6 + if (convertSlotToChestCoordinate(i)[0] <= 2 || + convertSlotToChestCoordinate(i)[0] == 9 || + convertSlotToChestCoordinate( + i, + )[1] == 1 || + convertSlotToChestCoordinate(i)[1] == 6 ) { continue } @@ -164,7 +160,6 @@ class AuctionHouseGui(defaultAuctionInventory: IInventory) : WindowScreen(Elemen return list } - override fun onDrawScreen(matrixStack: UMatrixStack, mouseX: Int, mouseY: Int, partialTicks: Float) { super.onDrawScreen(matrixStack, mouseX, mouseY, partialTicks) @@ -181,40 +176,20 @@ class AuctionHouseGui(defaultAuctionInventory: IInventory) : WindowScreen(Elemen window.draw(matrixStack) } - companion object { fun tick() { - if (!PartlySaneSkies.config.customAhGui) { - return - } + if (!PartlySaneSkies.config.customAhGui) return val gui = PartlySaneSkies.minecraft.currentScreen ?: return -// ChatUtils.sendClientMessage("A gui has been opened") - - - if (gui !is GuiChest) { - return - } + if (gui !is GuiChest) return - if (!isAhGui(gui.containerInventory)) { -// ChatUtils.sendClientMessage("Not AH Gui") - return - } + if (!isAhGui(gui.containerInventory)) return val guiAlreadyOpen = PartlySaneSkies.minecraft.currentScreen is AuctionHouseGui - if (guiAlreadyOpen) { - return - } - - if (DebugKey.isDebugMode()) { - return - } -// val inventory = MinecraftUtils.getSeparateUpperLowerInventories(event.gui)[0] + if (guiAlreadyOpen) return -// ChatUtils.sendClientMessage("Opening menu") val inventory = gui.containerInventory -// event.isCanceled = true if (isAuctionHouseFullyLoaded(inventory)) { val ahGui = AuctionHouseGui(inventory) PartlySaneSkies.minecraft.displayGuiScreen(ahGui) @@ -223,32 +198,25 @@ class AuctionHouseGui(defaultAuctionInventory: IInventory) : WindowScreen(Elemen openMenu() } - fun isAhGui(inventory: IInventory?): Boolean { - if (inventory == null) { - return true - } - - if (PartlySaneSkies.minecraft.currentScreen !is GuiChest) { - return false - } - return inventory.displayName.formattedText.removeColorCodes() - .contains("Auctions Browser") || inventory.displayName.formattedText.removeColorCodes() + fun isAhGui(inventory: IInventory): Boolean = inventory.displayName.formattedText + .removeColorCodes() + .contains("Auctions Browser") || + inventory.displayName.formattedText + .removeColorCodes() .contains("Auctions: \"") - } - private fun openMenu(): AuctionHouseGui { - var inventory = (PartlySaneSkies.minecraft.currentScreen as GuiChest).containerInventory - - return if (isAuctionHouseFullyLoaded(inventory)) { - inventory = (PartlySaneSkies.minecraft.currentScreen as GuiChest).containerInventory - AuctionHouseGui(inventory) - } else { - openMenu() + private fun openMenu() { + val gui = PartlySaneSkies.minecraft.currentScreen + if (gui is GuiChest) { + val inventory = gui.containerInventory + if (isAuctionHouseFullyLoaded(inventory)) { + AuctionHouseGui(inventory) + } } } + private fun isAuctionHouseFullyLoaded(inventory: IInventory): Boolean { -// ChatUtils.sendClientMessage("Checking if is loaded") for (i in 0..53) { if (convertSlotToChestCoordinate(i)[0] <= 2 || convertSlotToChestCoordinate(i)[0] == 9 || @@ -262,15 +230,12 @@ class AuctionHouseGui(defaultAuctionInventory: IInventory) : WindowScreen(Elemen // Then Return false if (inventory.getStackInSlot(i) == null) { if (inventory.getStackInSlot(53) == null) { -// ChatUtils.sendClientMessage("Slot $i is broken") return false } else if (Item.getIdFromItem(inventory.getStackInSlot(53).item) != 264) { continue } -// ChatUtils.sendClientMessage("Slot $i is broken") return false - } } @@ -284,4 +249,4 @@ class AuctionHouseGui(defaultAuctionInventory: IInventory) : WindowScreen(Elemen return intArrayOf(x, y) } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/economy/auctionhousemenu/CategoriesBar.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/economy/auctionhousemenu/CategoriesBar.kt index bfda3727f..2d8cccf6f 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/economy/auctionhousemenu/CategoriesBar.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/economy/auctionhousemenu/CategoriesBar.kt @@ -3,12 +3,15 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.features.economy.auctionhousemenu import gg.essential.elementa.UIComponent import gg.essential.elementa.components.UIBlock -import gg.essential.elementa.constraints.* +import gg.essential.elementa.constraints.CenterConstraint +import gg.essential.elementa.constraints.HeightConstraint +import gg.essential.elementa.constraints.WidthConstraint +import gg.essential.elementa.constraints.XConstraint +import gg.essential.elementa.constraints.YConstraint import gg.essential.elementa.dsl.childOf import gg.essential.elementa.dsl.constrain import gg.essential.elementa.dsl.pixels @@ -16,7 +19,6 @@ import me.partlysanestudios.partlysaneskies.PartlySaneSkies import me.partlysanestudios.partlysaneskies.features.themes.ThemeManager import me.partlysanestudios.partlysaneskies.utils.ElementaUtils.uiImage import me.partlysanestudios.partlysaneskies.utils.MinecraftUtils - import net.minecraft.inventory.IInventory import net.minecraft.util.ResourceLocation import java.awt.Color @@ -26,7 +28,7 @@ class CategoriesBar( val yConstraint: YConstraint, val heightConstraint: HeightConstraint, val widthConstraint: WidthConstraint, - val inventory: IInventory + val inventory: IInventory, ) { val topBarImagePaths = arrayOf( "textures/gui/custom_ah/weapons_icon.png", @@ -34,7 +36,7 @@ class CategoriesBar( "textures/gui/custom_ah/accessories_icon.png", "textures/gui/custom_ah/consumables_icon.png", "textures/gui/custom_ah/block_icon.png", - "textures/gui/custom_ah/misc_icon.png" + "textures/gui/custom_ah/misc_icon.png", ) val topBarFurfSkyImagePaths = arrayOf( @@ -43,7 +45,7 @@ class CategoriesBar( "textures/gui/custom_ah/furfsky/accessories_icon.png", "textures/gui/custom_ah/furfsky/consumables_icon.png", "textures/gui/custom_ah/furfsky/block_icon.png", - "textures/gui/custom_ah/furfsky/misc_icon.png" + "textures/gui/custom_ah/furfsky/misc_icon.png", ) private val topBar = UIBlock() @@ -60,7 +62,6 @@ class CategoriesBar( .setHeight(heightConstraint) .setChildOf(topBar) - var selectedItem = -1 private val categoryWidth = (topBarImage.getWidth()) / 6 @@ -84,12 +85,13 @@ class CategoriesBar( for (i in 0..5) { val slot = i * 9 - val icon = UIBlock().constrain { - x = (categoryWidth * i + categoryWidth * .1).pixels - y = CenterConstraint() - width = (categoryWidth * .8).pixels - height = categoryHeight.pixels - }.setColor(Color(0, 0, 0, 0)) childOf topBarImage + val icon = UIBlock() + .constrain { + x = (categoryWidth * i + categoryWidth * .1).pixels + y = CenterConstraint() + width = (categoryWidth * .8).pixels + height = categoryHeight.pixels + }.setColor(Color(0, 0, 0, 0)) childOf topBarImage var imagePath = if (PartlySaneSkies.config.customAhGuiTextures == 1) { @@ -142,7 +144,6 @@ class CategoriesBar( topBar.setChildOf(component) } - fun update() { if (categoryList.size > selectedItem && selectedItem != -1) { for (element in categoryList) { @@ -151,4 +152,4 @@ class CategoriesBar( categoryList[selectedItem].setColor(ThemeManager.accentColor.toJavaColor()) } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/economy/auctionhousemenu/ItemInformationBar.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/economy/auctionhousemenu/ItemInformationBar.kt index b0745abbd..76bc22be7 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/economy/auctionhousemenu/ItemInformationBar.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/economy/auctionhousemenu/ItemInformationBar.kt @@ -3,14 +3,17 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.features.economy.auctionhousemenu import gg.essential.elementa.UIComponent import gg.essential.elementa.components.UIBlock import gg.essential.elementa.components.UIImage import gg.essential.elementa.components.UIWrappedText -import gg.essential.elementa.constraints.* +import gg.essential.elementa.constraints.CenterConstraint +import gg.essential.elementa.constraints.HeightConstraint +import gg.essential.elementa.constraints.WidthConstraint +import gg.essential.elementa.constraints.XConstraint +import gg.essential.elementa.constraints.YConstraint import gg.essential.elementa.dsl.childOf import gg.essential.elementa.dsl.constrain import gg.essential.elementa.dsl.constraint @@ -23,7 +26,7 @@ class ItemInformationBar( yConstraint: YConstraint, heightConstraint: HeightConstraint, widthConstraint: WidthConstraint, - textScaleFactor: Float + textScaleFactor: Float, ) { private val baseBlock: UIBlock = UIBlock().constrain { color = Color(0, 0, 0, 0).constraint @@ -60,7 +63,6 @@ class ItemInformationBar( textScale = (1.0f * textScaleFactor).pixels } childOf backgroundImage - init { description.setText(descriptionString) header.setText(headerString) @@ -89,5 +91,4 @@ class ItemInformationBar( header.setText(headerString) } } - -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/economy/auctionhousemenu/MarketInformationBar.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/economy/auctionhousemenu/MarketInformationBar.kt index 36ccc42e5..73f634302 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/economy/auctionhousemenu/MarketInformationBar.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/economy/auctionhousemenu/MarketInformationBar.kt @@ -3,22 +3,25 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.features.economy.auctionhousemenu import gg.essential.elementa.UIComponent import gg.essential.elementa.components.UIBlock import gg.essential.elementa.components.UIImage import gg.essential.elementa.components.UIWrappedText -import gg.essential.elementa.constraints.* +import gg.essential.elementa.constraints.CenterConstraint +import gg.essential.elementa.constraints.HeightConstraint +import gg.essential.elementa.constraints.WidthConstraint +import gg.essential.elementa.constraints.XConstraint +import gg.essential.elementa.constraints.YConstraint import gg.essential.elementa.dsl.childOf import gg.essential.elementa.dsl.constrain import gg.essential.elementa.dsl.constraint import gg.essential.elementa.dsl.pixels import me.partlysanestudios.partlysaneskies.features.themes.ThemeManager +import me.partlysanestudios.partlysaneskies.render.gui.constraints.TextScaledPixelConstraint.Companion.textScaledPixels import me.partlysanestudios.partlysaneskies.utils.MathUtils.round import me.partlysanestudios.partlysaneskies.utils.StringUtils.formatNumber - import java.awt.Color class MarketInformationBar( @@ -26,7 +29,7 @@ class MarketInformationBar( yConstraint: YConstraint, heightConstraint: HeightConstraint, widthConstraint: WidthConstraint, - textScaleFactor: Float + textScaleFactor: Float, ) { private val baseBlock: UIBlock = UIBlock().constrain { color = Color(0, 0, 0, 0).constraint @@ -52,7 +55,7 @@ class MarketInformationBar( y = 10.pixels height = heightConstraint width = widthConstraint - textScale = (1.5f * textScaleFactor).pixels + textScale = (1.5f * textScaleFactor).textScaledPixels } childOf backgroundImage private val description: UIWrappedText = UIWrappedText(centered = true) constrain { @@ -60,7 +63,7 @@ class MarketInformationBar( y = 40.pixels height = heightConstraint width = widthConstraint - textScale = (1.0f * textScaleFactor).pixels + textScale = (1.0f * textScaleFactor).textScaledPixels } childOf backgroundImage init { @@ -72,25 +75,28 @@ class MarketInformationBar( } fun loadAuction(auction: AuctionElement) { - headerString = if (auction.isBin()) { - "Buy It Now Details:" - } else { - "Auction Details:\n" - } + headerString = + if (auction.isBin()) { + "Buy It Now Details:" + } else { + "Auction Details:\n" + } var info = "" info += "&6Offer Information:\n\n\n" - info += if (auction.getPrice() != -1L) { - "&eSelling Price: &6${auction.getPrice().toDouble().formatNumber()}" - } else { - "\n&eSelling Price: \n&8&o(Unknown)\n\n" - } - - info += if (auction.getFormattedEndingTime().isNotEmpty()) { - "\n&eEnding In: &6${auction.getFormattedEndingTime()}" - } else { - "\n&eEnding In: \n&8&o(Unknown)\n\n" - } + info += + if (auction.getPrice() != -1L) { + "&eSelling Price: &6${auction.getPrice().toDouble().formatNumber()}" + } else { + "\n&eSelling Price: \n&8&o(Unknown)\n\n" + } + + info += + if (auction.getFormattedEndingTime().isNotEmpty()) { + "\n&eEnding In: &6${auction.getFormattedEndingTime()}" + } else { + "\n&eEnding In: \n&8&o(Unknown)\n\n" + } if (auction.getAmount() > 1) { info += "\n\n\n" @@ -100,33 +106,41 @@ class MarketInformationBar( info += "\n\n\n\n\n\n" info += "&eMarket Stats:\n\n\n" - info += if (auction.hasLowestBin()) { - "\n&bCurrent Lowest Bin: &e${auction.getLowestBin().round(2).formatNumber()}" - } else { - "\n&bCurrent Lowest Bin: \n&8&o(Unknown)\n\n" - } - - info += if (auction.hasAverageLowestBin()) { - "\n&bAverage Lowest Bin (Last Day): &e${auction.getAverageLowestBin().round(2).formatNumber()}" - } else { - "\n&bAverage Lowest Bin (Last Day): \n&8&o(Unknown)\n\n" - } - - info += if (auction.hasLowestBin() && auction.hasAverageLowestBin()) { - "\n&bItem Inflation: \n&e${((auction.getLowestBin() / auction.getAverageLowestBin() * 100.0).round(2) - 100).formatNumber()}%\n\n" - } else { - "\n&bInflation: \n&8&o(Unknown)\n\n" - } - - info += if (auction.hasLowestBin()) { - "\n&bItem Mark up: \n&e${ - (auction.getPrice() / auction.getLowestBin() / auction.getAmount() * 100 - 100).round( - 2 - ).formatNumber() - }%\n" - } else { - "\n&bItem Mark up: \n&8&o(Unknown)\n" - } + info += + if (auction.hasLowestBin()) { + "\n&bCurrent Lowest Bin: &e${auction.getLowestBin().round(2).formatNumber()}" + } else { + "\n&bCurrent Lowest Bin: \n&8&o(Unknown)\n\n" + } + + info += + if (auction.hasAverageLowestBin()) { + "\n&bAverage Lowest Bin (Last Day): &e${auction.getAverageLowestBin().round(2).formatNumber()}" + } else { + "\n&bAverage Lowest Bin (Last Day): \n&8&o(Unknown)\n\n" + } + + info += + if (auction.hasLowestBin() && auction.hasAverageLowestBin()) { + "\n&bItem Inflation: \n&e${( + (auction.getLowestBin() / auction.getAverageLowestBin() * 100.0).round( + 2, + ) - 100 + ).formatNumber()}%\n\n" + } else { + "\n&bInflation: \n&8&o(Unknown)\n\n" + } + + info += + if (auction.hasLowestBin()) { + "\n&bItem Mark up: \n&e${ + (auction.getPrice() / auction.getLowestBin() / auction.getAmount() * 100 - 100).round( + 2, + ).formatNumber() + }%\n" + } else { + "\n&bItem Mark up: \n&8&o(Unknown)\n" + } descriptionString = info } @@ -145,5 +159,4 @@ class MarketInformationBar( header.setText(headerString) } } - -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/economy/auctionhousemenu/SettingsBar.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/economy/auctionhousemenu/SettingsBar.kt index 1115cc051..815cbce49 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/economy/auctionhousemenu/SettingsBar.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/economy/auctionhousemenu/SettingsBar.kt @@ -3,12 +3,15 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.features.economy.auctionhousemenu import gg.essential.elementa.UIComponent import gg.essential.elementa.components.UIBlock -import gg.essential.elementa.constraints.* +import gg.essential.elementa.constraints.CenterConstraint +import gg.essential.elementa.constraints.HeightConstraint +import gg.essential.elementa.constraints.WidthConstraint +import gg.essential.elementa.constraints.XConstraint +import gg.essential.elementa.constraints.YConstraint import gg.essential.elementa.dsl.childOf import gg.essential.elementa.dsl.constrain import gg.essential.elementa.dsl.pixels @@ -18,18 +21,17 @@ import me.partlysanestudios.partlysaneskies.utils.ElementaUtils.uiImage import me.partlysanestudios.partlysaneskies.utils.MinecraftUtils import me.partlysanestudios.partlysaneskies.utils.MinecraftUtils.getLore import me.partlysanestudios.partlysaneskies.utils.StringUtils.removeColorCodes - import net.minecraft.inventory.IInventory import net.minecraft.util.ResourceLocation import java.awt.Color -import java.util.* +import java.util.Locale class SettingsBar( val xConstraint: XConstraint, val yConstraint: YConstraint, val heightConstraint: HeightConstraint, val widthConstraint: WidthConstraint, - val inventory: IInventory + val inventory: IInventory, ) { private var bottomBarImagePaths = arrayOf( "textures/gui/custom_ah/left_arrow_icon.png", @@ -39,7 +41,7 @@ class SettingsBar( "textures/gui/custom_ah/sort_filter/unknown.png", "textures/gui/custom_ah/rarity_filter/no_filter.png", "textures/gui/custom_ah/type/all.png", - "textures/gui/custom_ah/right_arrow_icon.png" + "textures/gui/custom_ah/right_arrow_icon.png", ) private var bottomBarFurfSkyImagePaths = arrayOf( @@ -50,10 +52,9 @@ class SettingsBar( "textures/gui/custom_ah/furfsky/sort_filter/unknown.png", "textures/gui/custom_ah/furfsky/rarity_filter/no_filter.png", "textures/gui/custom_ah/furfsky/type/all.png", - "textures/gui/custom_ah/furfsky/right_arrow_icon.png" + "textures/gui/custom_ah/furfsky/right_arrow_icon.png", ) - private val bottomBar = UIBlock() .setX(xConstraint) .setY(yConstraint) @@ -68,7 +69,6 @@ class SettingsBar( .setHeight(heightConstraint) .setChildOf(bottomBar) - var selectedItem = -1 private val settingWidth = (bottomBarImage.getWidth()) / 8 @@ -93,12 +93,13 @@ class SettingsBar( for (i in 0..7) { val slot = i + 46 - val icon = UIBlock().constrain { - x = (settingWidth * i + settingWidth * .1).pixels - y = CenterConstraint() - width = (settingWidth * .8).pixels - height = settingHeight.pixels - }.setColor(Color(0, 0, 0, 0)) childOf bottomBarImage + val icon = UIBlock() + .constrain { + x = (settingWidth * i + settingWidth * .1).pixels + y = CenterConstraint() + width = (settingWidth * .8).pixels + height = settingHeight.pixels + }.setColor(Color(0, 0, 0, 0)) childOf bottomBarImage var imagePath: String = bottomBarImagePaths[i] if (PartlySaneSkies.config.customAhGuiTextures == 1) { @@ -196,8 +197,6 @@ class SettingsBar( imagePath = imagePath.replace("all", binImageName) } - - ResourceLocation("partlysaneskies", imagePath).uiImage.constrain { x = CenterConstraint() y = CenterConstraint() @@ -243,7 +242,6 @@ class SettingsBar( bottomBar.setChildOf(component) } - fun update() { if (settingList.size > selectedItem && selectedItem != -1) { for (element in settingList) { @@ -252,5 +250,4 @@ class SettingsBar( settingList[selectedItem].setColor(ThemeManager.accentColor.toJavaColor()) } } - -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/farming/MathematicalHoeRightClicks.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/farming/MathematicalHoeRightClicks.kt index 43457ab7b..7f8c1bee9 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/farming/MathematicalHoeRightClicks.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/farming/MathematicalHoeRightClicks.kt @@ -15,7 +15,6 @@ import me.partlysanestudios.partlysaneskies.events.SubscribePSSEvent import me.partlysanestudios.partlysaneskies.events.data.LoadPublicDataEvent import me.partlysanestudios.partlysaneskies.utils.HypixelUtils.getItemId import me.partlysanestudios.partlysaneskies.utils.MathUtils.onCooldown -import net.minecraft.command.ICommandSender import net.minecraft.event.ClickEvent import net.minecraft.util.ChatComponentText import net.minecraft.util.IChatComponent @@ -23,7 +22,6 @@ import net.minecraftforge.event.entity.player.PlayerInteractEvent import net.minecraftforge.fml.common.eventhandler.SubscribeEvent object MathematicalHoeRightClicks { - private var lastMessageSendTime: Long = 0 var lastAllowHoeRightClickTime: Long = 0 private val hoes = ArrayList() @@ -52,10 +50,11 @@ object MathematicalHoeRightClicks { return } if (!onCooldown(lastMessageSendTime, 3000)) { - val message: IChatComponent = ChatComponentText( - """${PartlySaneSkies.CHAT_PREFIX}§8Right Clicks are disabled while holding a Mathematical Hoe -§7Click this message or run /allowhoerightclick to allow right clicks for ${config.allowRightClickTime} minutes.""" - ) + val message: IChatComponent = + ChatComponentText( + """${PartlySaneSkies.CHAT_PREFIX}§8Right Clicks are disabled while holding a Mathematical Hoe +§7Click this message or run /allowhoerightclick to allow right clicks for ${config.allowRightClickTime} minutes.""", + ) message.chatStyle.setChatClickEvent(ClickEvent(ClickEvent.Action.RUN_COMMAND, "/allowhoerightclick")) minecraft.ingameGUI.chatGUI.printChatMessage(message) lastMessageSendTime = time @@ -64,7 +63,6 @@ object MathematicalHoeRightClicks { } } - private val isHoldingHoe: Boolean get() { if (hoes == null) { @@ -79,42 +77,44 @@ object MathematicalHoeRightClicks { fun registerCommand() { PSSCommand("allowhoerightclick") - .addAlias("allowhoerightclicks") - .addAlias("ahrc") + .addAlias("allowhoerightclicks", "ahrc") .setDescription("Allows hoe right clicks for a few minutes") .setRunnable { val canRightClickHoe = onCooldown(lastAllowHoeRightClickTime, (config.allowRightClickTime * 60L * 1000L).toLong()) - lastAllowHoeRightClickTime = if (canRightClickHoe) { - val message: IChatComponent = - ChatComponentText("${PartlySaneSkies.CHAT_PREFIX}§bThe ability to right-click with a hoe has been §cdisabled§b again.\n§dClick this message or run /allowhoerightclick to allow right-clicks for ${config.allowRightClickTime} again.") - message.chatStyle.setChatClickEvent( - ClickEvent( - ClickEvent.Action.RUN_COMMAND, - "/allowhoerightclick" + lastAllowHoeRightClickTime = + if (canRightClickHoe) { + val message: IChatComponent = + ChatComponentText( + "${PartlySaneSkies.CHAT_PREFIX}§bThe ability to right-click with a hoe has been §cdisabled§b again.\n§dClick this message or run /allowhoerightclick to allow right-clicks for ${config.allowRightClickTime} again.", + ) + message.chatStyle.setChatClickEvent( + ClickEvent( + ClickEvent.Action.RUN_COMMAND, + "/allowhoerightclick", + ), ) - ) - minecraft.ingameGUI.chatGUI.printChatMessage(message) + minecraft.ingameGUI.chatGUI.printChatMessage(message) - 0 - } else { - val message: IChatComponent = - ChatComponentText("${PartlySaneSkies.CHAT_PREFIX}§bThe ability to right-click with a hoe has been §aenabled§b for ${config.allowRightClickTime} minutes.\n§dClick this message or run /allowhoerightclick to disable right-clicks again.") - message.chatStyle.setChatClickEvent( - ClickEvent( - ClickEvent.Action.RUN_COMMAND, - "/allowhoerightclick" + 0 + } else { + val message: IChatComponent = + ChatComponentText( + "${PartlySaneSkies.CHAT_PREFIX}§bThe ability to right-click with a hoe has been §aenabled§b for ${config.allowRightClickTime} minutes.\n§dClick this message or run /allowhoerightclick to disable right-clicks again.", + ) + message.chatStyle.setChatClickEvent( + ClickEvent( + ClickEvent.Action.RUN_COMMAND, + "/allowhoerightclick", + ), ) - ) - minecraft.ingameGUI.chatGUI.printChatMessage(message) + minecraft.ingameGUI.chatGUI.printChatMessage(message) - time - } - } - .register() + time + } + }.register() } - } diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/farming/WrongToolCropWarning.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/farming/WrongToolCropWarning.kt index dc804cd22..e42b5daab 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/farming/WrongToolCropWarning.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/farming/WrongToolCropWarning.kt @@ -11,6 +11,7 @@ import me.partlysanestudios.partlysaneskies.PartlySaneSkies.Companion.config import me.partlysanestudios.partlysaneskies.PartlySaneSkies.Companion.minecraft import me.partlysanestudios.partlysaneskies.PartlySaneSkies.Companion.time import me.partlysanestudios.partlysaneskies.data.pssdata.PublicDataManager +import me.partlysanestudios.partlysaneskies.data.skyblockdata.IslandType import me.partlysanestudios.partlysaneskies.events.SubscribePSSEvent import me.partlysanestudios.partlysaneskies.events.data.LoadPublicDataEvent import me.partlysanestudios.partlysaneskies.events.minecraft.player.PlayerBreakBlockEvent @@ -29,14 +30,12 @@ object WrongToolCropWarning { @SubscribePSSEvent fun onBlockBreak(event: PlayerBreakBlockEvent) { - if (!config.wrongToolForCropEnabled) { - return - } - if (onCooldown(lastWarnTime, (config.wrongToolForCropCooldown * 1000).toLong())) { - return - } + if (!config.wrongToolForCropEnabled) return + if (onCooldown(lastWarnTime, (config.wrongToolForCropCooldown * 1000).toLong())) return + if (!IslandType.onIslands(IslandType.GARDEN, IslandType.FARMING_ISLAND, IslandType.HUB, IslandType.CRIMSON_ISLE)) return + val block = minecraft.theWorld.getBlockState(event.point.toBlockPos())?.block - val unlocalizedName = block?.unlocalizedName ?: "" + val unlocalizedName = block?.unlocalizedName ?: return val crop = getCrop(unlocalizedName) ?: return @@ -76,16 +75,15 @@ object WrongToolCropWarning { } } - private fun getCrop(unlocalizedName: String): CropToolData.Crop? { - return if (!CropToolData.jsonObject.has(unlocalizedName)) { + private fun getCrop(unlocalizedName: String): CropToolData.Crop? = + if (!CropToolData.jsonObject.has(unlocalizedName)) { null } else { CropToolData.serializeCrop( unlocalizedName, - CropToolData.jsonObject[unlocalizedName]?.asJsonObject ?: JsonObject() + CropToolData.jsonObject[unlocalizedName]?.asJsonObject ?: JsonObject(), ) } - } private fun getAllCrops(): List { val list = ArrayList() @@ -107,23 +105,21 @@ object WrongToolCropWarning { JsonParser().parse(PublicDataManager.getFile("constants/crop_tools.json")).asJsonObject ?: JsonObject() } - fun serializeCrop(cropUnlocalizedName: String, cropObject: JsonObject): Crop { - return Crop( + fun serializeCrop(cropUnlocalizedName: String, cropObject: JsonObject): Crop = + Crop( unlocalizedName = cropUnlocalizedName, mathematicalHoeIds = cropObject["math"]?.asJsonArray?.map { it.asString } ?: ArrayList(), otherSkyblockHoes = cropObject["other_skyblock"]?.asJsonArray?.map { it.asString } ?: ArrayList(), otherMinecraftHoes = cropObject["other_minecraft"]?.asJsonArray?.map { it.asString } ?: ArrayList(), - requireReplenish = cropObject["require_replenish"]?.asBoolean ?: false + requireReplenish = cropObject["require_replenish"]?.asBoolean ?: false, ) - } internal class Crop( val unlocalizedName: String, val mathematicalHoeIds: List, val otherSkyblockHoes: List, val otherMinecraftHoes: List, - val requireReplenish: Boolean - + val requireReplenish: Boolean, ) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/farming/endoffarmnotifer/EndOfFarmNotifier.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/farming/endoffarmnotifer/EndOfFarmNotifier.kt index 721a8c9e6..a914da3cb 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/farming/endoffarmnotifer/EndOfFarmNotifier.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/farming/endoffarmnotifer/EndOfFarmNotifier.kt @@ -10,14 +10,12 @@ import com.google.gson.GsonBuilder import com.google.gson.JsonParser import me.partlysanestudios.partlysaneskies.PartlySaneSkies import me.partlysanestudios.partlysaneskies.commands.PSSCommand -import me.partlysanestudios.partlysaneskies.commands.PSSCommandRunnable import me.partlysanestudios.partlysaneskies.data.skyblockdata.IslandType import me.partlysanestudios.partlysaneskies.render.gui.hud.BannerRenderer.renderNewBanner import me.partlysanestudios.partlysaneskies.render.gui.hud.PSSBanner import me.partlysanestudios.partlysaneskies.utils.* import me.partlysanestudios.partlysaneskies.utils.geometry.vectors.Range3d import net.minecraft.client.audio.PositionedSoundRecord -import net.minecraft.command.ICommandSender import net.minecraft.util.ResourceLocation import net.minecraftforge.event.entity.player.PlayerInteractEvent import net.minecraftforge.fml.common.eventhandler.SubscribeEvent @@ -31,9 +29,7 @@ import java.nio.file.Paths import kotlin.math.max import kotlin.math.min - object EndOfFarmNotifier { - internal var ranges = ArrayList() private lateinit var selectedPos1: IntArray private lateinit var selectedPos2: IntArray @@ -50,7 +46,7 @@ object EndOfFarmNotifier { fun checkAllRangesTick() { if (!MathUtils.onCooldown( rangeToHighlightSetTime, - (PartlySaneSkies.config.farmHightlightTime * 1000).toLong() // damn we can english (it's called highlight) + (PartlySaneSkies.config.farmHightlightTime * 1000).toLong(), // damn we can english (it's called highlight) ) ) { rangeToHighlight = null @@ -61,7 +57,7 @@ object EndOfFarmNotifier { } if (MathUtils.onCooldown( lastChimeTime, - (PartlySaneSkies.config.farmnotifierChimeTime * 1000).toLong() + (PartlySaneSkies.config.farmnotifierChimeTime * 1000).toLong(), ) ) { return @@ -75,8 +71,8 @@ object EndOfFarmNotifier { displayString, 1000, TEXT_SCALE.toFloat(), - Color.red - ) + Color.red, + ), ) } @@ -88,14 +84,15 @@ object EndOfFarmNotifier { min(selectedPos1[1].toDouble(), selectedPos2[1].toDouble()) val bigY: Double = max(selectedPos1[1].toDouble(), selectedPos2[1].toDouble()) - val range = Range3d( - selectedPos1[0].toDouble(), - smallY, - selectedPos1[2].toDouble(), - selectedPos2[0].toDouble(), - bigY, - selectedPos2[2].toDouble() - ) + val range = + Range3d( + selectedPos1[0].toDouble(), + smallY, + selectedPos1[2].toDouble(), + selectedPos2[0].toDouble(), + bigY, + selectedPos2[2].toDouble(), + ) range.rangeName = name selectedPos1 = IntArray(0) selectedPos2 = IntArray(0) @@ -122,9 +119,9 @@ object EndOfFarmNotifier { if (range.isInRange( PartlySaneSkies.minecraft.thePlayer.posX, PartlySaneSkies.minecraft.thePlayer.posY, - PartlySaneSkies.minecraft.thePlayer.posZ + PartlySaneSkies.minecraft.thePlayer.posZ, ) - ) { //Pos with decimals + ) { // Pos with decimals return true } } @@ -159,7 +156,7 @@ object EndOfFarmNotifier { val x = event.pos.x val y = event.pos.y val z = event.pos.z - ChatUtils.sendClientMessage("§7Set §bpositon ${pos}§7 to §b($x, $y, $z)§7") + ChatUtils.sendClientMessage("§7Set §bpositon $pos§7 to §b($x, $y, $z)§7") if (pos == 1) { selectedPos1 = intArrayOf(x, y, z) pos = 2 @@ -180,10 +177,11 @@ object EndOfFarmNotifier { val file = File("./config/partly-sane-skies/endOfFarmRanges.json") file.createNewFile() // Creates a new Gson object to save the data - val gson = GsonBuilder() - .setPrettyPrinting() - .serializeSpecialFloatingPointValues() - .create() + val gson = + GsonBuilder() + .setPrettyPrinting() + .serializeSpecialFloatingPointValues() + .create() // Saves teh data to the file val json = gson.toJson(ranges) val writer = FileWriter(file) @@ -221,14 +219,15 @@ object EndOfFarmNotifier { largeCoordinate[i] = element.asInt i++ } - val loadRange = Range3d( - smallCoordinate[0].toDouble(), - smallCoordinate[1].toDouble(), - smallCoordinate[2].toDouble(), - largeCoordinate[0].toDouble(), - largeCoordinate[1].toDouble(), - largeCoordinate[2].toDouble() - ) + val loadRange = + Range3d( + smallCoordinate[0].toDouble(), + smallCoordinate[1].toDouble(), + smallCoordinate[2].toDouble(), + largeCoordinate[0].toDouble(), + largeCoordinate[1].toDouble(), + largeCoordinate[2].toDouble(), + ) loadRange.rangeName = range["rangeName"].asString list.add(loadRange) } @@ -245,18 +244,21 @@ object EndOfFarmNotifier { if (args.size >= 3 && args[0].isNotEmpty() && args[1].isNotEmpty() && args[2].isNotEmpty()) { try { selectedPos1 = intArrayOf(args[0].toInt(), args[1].toInt(), args[2].toInt()) - ChatUtils.sendClientMessage("§7Set §bpositon 1§7 to §b(" + selectedPos1[0] + ", " + selectedPos1[1] + ", " + selectedPos1[2] + ")§7") + ChatUtils.sendClientMessage( + "§7Set §bpositon 1§7 to §b(" + selectedPos1[0] + ", " + selectedPos1[1] + ", " + selectedPos1[2] + ")§7", + ) } catch (e: NumberFormatException) { ChatUtils.sendClientMessage("§cPlease enter a valid number and try again.") } } else { - with (PartlySaneSkies.minecraft.thePlayer) { + with(PartlySaneSkies.minecraft.thePlayer) { selectedPos2 = intArrayOf(position.x - 1, position.y, position.z - 1) - ChatUtils.sendClientMessage("§7Set §bpositon 1§7 to §b(" + selectedPos1[0] + ", " + selectedPos1[1] + ", " + selectedPos1[2] + ")§7") + ChatUtils.sendClientMessage( + "§7Set §bpositon 1§7 to §b(" + selectedPos1[0] + ", " + selectedPos1[1] + ", " + selectedPos1[2] + ")§7", + ) } } - } - .register() + }.register() } fun registerPos2Command() { @@ -266,18 +268,21 @@ object EndOfFarmNotifier { if (args.size >= 3 && args[0].isNotEmpty() && args[1].isNotEmpty() && args[2].isNotEmpty()) { try { selectedPos2 = intArrayOf(args[0].toInt(), args[1].toInt(), args[2].toInt()) - ChatUtils.sendClientMessage("§7Set §bpositon 2§7 to §b(" + selectedPos2[0] + ", " + selectedPos2[1] + ", " + selectedPos2[2] + ")§7") + ChatUtils.sendClientMessage( + "§7Set §bpositon 2§7 to §b(" + selectedPos2[0] + ", " + selectedPos2[1] + ", " + selectedPos2[2] + ")§7", + ) } catch (e: java.lang.NumberFormatException) { ChatUtils.sendClientMessage("§cPlease enter a valid number and try again.") } } else { - with (PartlySaneSkies.minecraft.thePlayer) { + with(PartlySaneSkies.minecraft.thePlayer) { selectedPos2 = intArrayOf(position.x - 1, position.y, position.z - 1) - ChatUtils.sendClientMessage("§7Set §bpositon 2§7 to §b(" + selectedPos2[0] + ", " + selectedPos2[1] + ", " + selectedPos2[2] + ")§7") + ChatUtils.sendClientMessage( + "§7Set §bpositon 2§7 to §b(" + selectedPos2[0] + ", " + selectedPos2[1] + ", " + selectedPos2[2] + ")§7", + ) } } - } - .register() + }.register() } fun registerCreateRangeCommand() { @@ -289,14 +294,15 @@ object EndOfFarmNotifier { name = args[0] } if (name?.let { createNewRange(it) } == null) { - ChatUtils.sendClientMessage("§cUnable to create a new farm notifier. Make sure both §b//pos1§c and §b//pos2§c have been selected.") + ChatUtils.sendClientMessage( + "§cUnable to create a new farm notifier. Make sure both §b//pos1§c and §b//pos2§c have been selected.", + ) return@setRunnable } ChatUtils.sendClientMessage("§aCreated new Farm Notifier.") selectedPos1 = IntArray(0) selectedPos2 = IntArray(0) - } - .register() + }.register() } fun registerFarmNotifierCommand() { @@ -309,7 +315,9 @@ object EndOfFarmNotifier { .setDescription("Operates the Farm Notifier feature: //fn [list/remove/highlight/show]") .setRunnable { a: Array -> if (a.isEmpty() || a[0].equals("list", ignoreCase = true)) { - ChatUtils.sendClientMessage("§7To create a new farm notifier, run §b//pos1§7 at one end of your selection, then run §b//pos2§7 at the other end of your farm. Once the area has been selected, run §b//create§7.\n\n§b//farmnotifier§7 command:\n§b//fn remove :§7 remove a given index from the list.\n§b//fn list:§7 lists all of the farm notifiers and their indexes") + ChatUtils.sendClientMessage( + "§7To create a new farm notifier, run §b//pos1§7 at one end of your selection, then run §b//pos2§7 at the other end of your farm. Once the area has been selected, run §b//create§7.\n\n§b//farmnotifier§7 command:\n§b//fn remove :§7 remove a given index from the list.\n§b//fn list:§7 lists all of the farm notifiers and their indexes", + ) listRanges() return@setRunnable } @@ -318,12 +326,13 @@ object EndOfFarmNotifier { ChatUtils.sendClientMessage("§cError: Must provide an index to remove") return@setRunnable } - val i: Int = try { - a[1].toInt() - } catch (e: java.lang.NumberFormatException) { - ChatUtils.sendClientMessage("§cPlease enter a valid index and try again.") - return@setRunnable - } + val i: Int = + try { + a[1].toInt() + } catch (e: java.lang.NumberFormatException) { + ChatUtils.sendClientMessage("§cPlease enter a valid index and try again.") + return@setRunnable + } if (i > ranges.size || i < 1) { ChatUtils.sendClientMessage("§cPlease select a valid index and try again.") return@setRunnable @@ -343,12 +352,13 @@ object EndOfFarmNotifier { return@setRunnable } - val i: Int = try { - a[1].toInt() - } catch (e: java.lang.NumberFormatException) { - ChatUtils.sendClientMessage("§cPlease enter a valid number index and try again.") - return@setRunnable - } + val i: Int = + try { + a[1].toInt() + } catch (e: java.lang.NumberFormatException) { + ChatUtils.sendClientMessage("§cPlease enter a valid number index and try again.") + return@setRunnable + } if (i > ranges.size || i < 1) { ChatUtils.sendClientMessage("§cPlease select a valid index and try again.") return@setRunnable @@ -356,8 +366,7 @@ object EndOfFarmNotifier { rangeToHighlight = ranges[i - 1] rangeToHighlightSetTime = PartlySaneSkies.time } - } - .register() + }.register() } fun registerWandCommand() { @@ -372,33 +381,36 @@ object EndOfFarmNotifier { wandActive = !wandActive ChatUtils.sendClientMessage( "§7The wand is now " + - if (wandActive) "§aactive§7. Use your §aSkyBlock menu §7to select a range using §bright click§7 as §3pos1§7 and then §3pos2§7. This is a §crepeating cycle§7. To disable the wand, run §b/wand§7 again." - else "§cinactive§7." + if (wandActive) { + "§aactive§7. Use your §aSkyBlock menu §7to select a range using §bright click§7 as §3pos1§7 and then §3pos2§7. This is a §crepeating cycle§7. To disable the wand, run §b/wand§7 again." + } else { + "§cinactive§7." + }, ) - } - .register() + }.register() } - /* EndOfFarmNotifier Utils */ // Lists all the ranges to the chat private fun listRanges() { - val message = StringBuilder( - """ - §d§m----------------------------------------------------- - §bEnd of Farms: - §d§m----------------------------------------------------- - - """.trimIndent() - ) + val message = + StringBuilder( + """ + §d§m----------------------------------------------------- + §bEnd of Farms: + §d§m----------------------------------------------------- + + """.trimIndent(), + ) var i = 1 // For each alert, format it so its ##. [range] for (range in ranges) { - message.append("§6") + message + .append("§6") .append(i) .append("§7: ") .append(range.toString()) diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/farming/endoffarmnotifer/RangeHighlight.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/farming/endoffarmnotifer/RangeHighlight.kt index 308d093b7..c20932a5f 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/farming/endoffarmnotifer/RangeHighlight.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/farming/endoffarmnotifer/RangeHighlight.kt @@ -3,7 +3,6 @@ // See LICENSE for copyright and license notices. // - // // Time spent pulling hair out in this file: // Su386: 14.5 hours and 13 cups of tea @@ -14,7 +13,6 @@ // The thoughts and prayers of the ancients are with you (Stargate Reference) // - // // Lets goooo it finally works (half of the issues were my own stupidity) // @@ -23,7 +21,6 @@ // Still better than java tho // - package me.partlysanestudios.partlysaneskies.features.farming.endoffarmnotifer import me.partlysanestudios.partlysaneskies.PartlySaneSkies @@ -42,7 +39,6 @@ import org.lwjgl.opengl.GL11 import java.awt.Color object RangeHighlight { - @SubscribeEvent fun onRenderWorldLast(event: RenderWorldLastEvent) { if (!PartlySaneSkies.config.showFarmRegions && EndOfFarmNotifier.rangeToHighlight == null) { @@ -62,14 +58,15 @@ object RangeHighlight { color = color.applyOpacity((.4 * 255).toInt()) } - val effectiveRange = Range3d( - range.sortedPoints[0].x, - range.sortedPoints[0].y, - range.sortedPoints[0].z, - range.sortedPoints[1].x + 1, - range.sortedPoints[1].y + 1, - range.sortedPoints[1].z + 1 - ) + val effectiveRange = + Range3d( + range.sortedPoints[0].x, + range.sortedPoints[0].y, + range.sortedPoints[0].z, + range.sortedPoints[1].x + 1, + range.sortedPoints[1].y + 1, + range.sortedPoints[1].z + 1, + ) renderBox(effectiveRange, event.partialTicks, color) } } @@ -79,32 +76,33 @@ object RangeHighlight { renderBoxFaces(range, color, false, partialTicks) renderBoxEdges(range, false, partialTicks) - val pos1Block = Range3d( - range.sortedPoints[0].x, - range.sortedPoints[0].y, - range.sortedPoints[0].z, - range.sortedPoints[0].x + 1, - range.sortedPoints[0].y + 1, - range.sortedPoints[0].z + 1 - ) + val pos1Block = + Range3d( + range.sortedPoints[0].x, + range.sortedPoints[0].y, + range.sortedPoints[0].z, + range.sortedPoints[0].x + 1, + range.sortedPoints[0].y + 1, + range.sortedPoints[0].z + 1, + ) renderBoxFaces(pos1Block, Color(255, 100, 100, (.75 * 255).toInt()), false, partialTicks) renderBoxEdges(pos1Block, false, partialTicks) - val pos2Block = Range3d( - range.sortedPoints[1].x, - range.sortedPoints[1].y, - range.sortedPoints[1].z, - range.sortedPoints[1].x - 1, - range.sortedPoints[1].y - 1, - range.sortedPoints[1].z - 1 - ) + val pos2Block = + Range3d( + range.sortedPoints[1].x, + range.sortedPoints[1].y, + range.sortedPoints[1].z, + range.sortedPoints[1].x - 1, + range.sortedPoints[1].y - 1, + range.sortedPoints[1].z - 1, + ) renderBoxFaces(pos2Block, Color(100, 100, 255, (.75 * 255).toInt()), false, partialTicks) renderBoxEdges(pos2Block, false, partialTicks) } catch (e: NullPointerException) { ChatUtils.sendClientMessage("Failed rendering of $range") throw RuntimeException(e) } - } // Renders the faces of a box given a range @@ -112,7 +110,7 @@ object RangeHighlight { range: Range3d, color: Color, renderRelativeToPlayer: Boolean = false, - partialTicks: Float + partialTicks: Float, ) { // Sets the correct state GlStateManager.enableBlend() @@ -127,7 +125,6 @@ object RangeHighlight { GlStateManager.color(color.red / 255f, color.blue / 255f, color.green / 255f, color.alpha / 255f) - // Gets the x y z adn z where 1 is the smaller coordinate and 2 is the bigger one var x1 = range.sortedPoints[0].x var x2 = range.sortedPoints[1].x @@ -151,7 +148,6 @@ object RangeHighlight { z2 = range.sortedPoints[1].z - playerPos.z } - // ChatUtils.sendClientMessage("x1: $x1, x2: $x2, y1: $y1, y2: $y2, z1: $z1, z2: $z2") // Draws each face @@ -209,7 +205,6 @@ object RangeHighlight { GlStateManager.disableBlend() } - fun renderBoxEdges(range: Range3d, renderRelativeToPlayer: Boolean = false, partialTicks: Float) { // Sets the correct state GlStateManager.enableBlend() @@ -244,7 +239,6 @@ object RangeHighlight { z2 = range.sortedPoints[1].z - playerPos.z } - // Front face worldRenderer.begin(GL11.GL_LINES, DefaultVertexFormats.POSITION) GlStateManager.color(1f, 0f, 0f, 1f) @@ -334,5 +328,4 @@ object RangeHighlight { return Point3d(xPos, yPos, zPos) } - } diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/farming/garden/CompostValue.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/farming/garden/CompostValue.kt index f0471985e..966e0f9e5 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/farming/garden/CompostValue.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/farming/garden/CompostValue.kt @@ -22,6 +22,7 @@ import me.partlysanestudios.partlysaneskies.events.SubscribePSSEvent import me.partlysanestudios.partlysaneskies.events.data.LoadPublicDataEvent import me.partlysanestudios.partlysaneskies.features.gui.SidePanel import me.partlysanestudios.partlysaneskies.render.gui.constraints.ScaledPixelConstraint.Companion.scaledPixels +import me.partlysanestudios.partlysaneskies.render.gui.constraints.TextScaledPixelConstraint.Companion.textScaledPixels import me.partlysanestudios.partlysaneskies.utils.ElementaUtils.applyBackground import me.partlysanestudios.partlysaneskies.utils.MathUtils.round import me.partlysanestudios.partlysaneskies.utils.MathUtils.sortMap @@ -44,21 +45,23 @@ import kotlin.collections.set import kotlin.math.ceil object CompostValue : SidePanel() { - override val panelBaseComponent: UIComponent = UIBlock().applyBackground().constrain { - x = 800.scaledPixels - y = CenterConstraint() - width = 225.scaledPixels - height = 350.scaledPixels - color = Color(0, 0, 0, 0).constraint - } + override val panelBaseComponent: UIComponent = UIBlock().applyBackground() + .constrain { + x = 800.scaledPixels + y = CenterConstraint() + width = 225.scaledPixels + height = 350.scaledPixels + color = Color(0, 0, 0, 0).constraint + } - private val textComponent = UIWrappedText().constrain { - x = CenterConstraint() - y = CenterConstraint() - height = 95.percent - width = 95.percent - textScale = 1.scaledPixels - } childOf panelBaseComponent + private val textComponent = UIWrappedText() + .constrain { + x = CenterConstraint() + y = CenterConstraint() + height = 95.percent + width = 95.percent + textScale = 1.textScaledPixels + } childOf panelBaseComponent private var maxCompost = 0.0 private var fillLevel = 0.0 @@ -154,9 +157,9 @@ object CompostValue : SidePanel() { if (maxCompost == fillLevel) { compostAmount = getMaxCompostAbleToMake() } - str += "§6${i}. §7x§d${ceil(cropPerCompost * compostAmount).formatNumber()} ${cropName}§7 costing §d${ + str += "§6$i. §7x§d${ceil(cropPerCompost * compostAmount).formatNumber()} $cropName§7 costing §d${ (costPerCompost * compostAmount).round( - 1 + 1, ).formatNumber() }§7 coins to fill. \n§8(x${ceil(cropPerCompost).formatNumber()}/Compost)\n" i++ @@ -180,10 +183,7 @@ object CompostValue : SidePanel() { } } - - private fun getCompostCost(inventory: IInventory): Double { - return getCompostCostString(inventory).parseAbbreviatedNumber() - } + private fun getCompostCost(inventory: IInventory): Double = getCompostCostString(inventory).parseAbbreviatedNumber() private fun getCompostCostString(composterInventory: IInventory): String { val infoItem = composterInventory.getStackInSlot(46) @@ -241,17 +241,11 @@ object CompostValue : SidePanel() { } } - private fun getOrganicMatterLimit(inventory: IInventory): Double { - return getOrganicMatterLimitString(inventory).parseAbbreviatedNumber() - } + private fun getOrganicMatterLimit(inventory: IInventory): Double = getOrganicMatterLimitString(inventory).parseAbbreviatedNumber() - private fun getMaxCompostAbleToMake(): Double { - return maxCompost / compostCost - } + private fun getMaxCompostAbleToMake(): Double = maxCompost / compostCost - private fun getCurrentCompostAbleToMake(): Double { - return (maxCompost - fillLevel) / compostCost - } + private fun getCurrentCompostAbleToMake(): Double = (maxCompost - fillLevel) / compostCost private fun getOrganicMatterLimitString(composterInventory: IInventory): String { val infoItem = composterInventory.getStackInSlot(46) @@ -274,4 +268,4 @@ object CompostValue : SidePanel() { amountLine = amountLine.substring(indexOfStart + 1) return amountLine } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/farming/garden/CropMilestoneWebhook.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/farming/garden/CropMilestoneWebhook.kt index d7fada98b..3445dec3f 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/farming/garden/CropMilestoneWebhook.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/farming/garden/CropMilestoneWebhook.kt @@ -3,7 +3,6 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.features.farming.garden import gg.essential.elementa.constraints.CenterConstraint @@ -11,6 +10,8 @@ import gg.essential.elementa.dsl.percent import me.partlysanestudios.partlysaneskies.PartlySaneSkies import me.partlysanestudios.partlysaneskies.config.psconfig.Toggle import me.partlysanestudios.partlysaneskies.config.psconfig.Toggle.Companion.asBoolean +import me.partlysanestudios.partlysaneskies.events.SubscribePSSEvent +import me.partlysanestudios.partlysaneskies.events.minecraft.PSSChatEvent import me.partlysanestudios.partlysaneskies.features.discord.webhooks.EmbedData import me.partlysanestudios.partlysaneskies.features.discord.webhooks.EmbedField import me.partlysanestudios.partlysaneskies.features.discord.webhooks.Webhook @@ -21,8 +22,6 @@ import me.partlysanestudios.partlysaneskies.utils.StringUtils.romanNumeralToInt import me.partlysanestudios.partlysaneskies.utils.StringUtils.toRoman import net.minecraft.init.Items import net.minecraft.item.ItemStack -import net.minecraftforge.client.event.ClientChatReceivedEvent -import net.minecraftforge.fml.common.eventhandler.SubscribeEvent import java.awt.Color object CropMilestoneWebhook : Webhook() { @@ -37,30 +36,38 @@ object CropMilestoneWebhook : Webhook() { init { config.registerOption("multipleOf5", Toggle("Send only multiples of 5", "Only send multiples of 5 (Lvl 5, 10, 15, etc.)", false)) - config.registerOption("multipleOf10", Toggle("Send only multiples of 10", "Only send multiples of 10 (Lvl 10, 20, 30, etc.)", false)) - config.registerOption("useRomanNumerals", Toggle("Use Roman Numerals", "Use Roman Numerals instead of Arabic Numerals in the message", false)) + config.registerOption( + "multipleOf10", + Toggle("Send only multiples of 10", "Only send multiples of 10 (Lvl 10, 20, 30, etc.)", false), + ) + config.registerOption( + "useRomanNumerals", + Toggle("Use Roman Numerals", "Use Roman Numerals instead of Arabic Numerals in the message", false), + ) } val regex = "§lGARDEN MILESTONE §3(\\w+[\\s\\w+]*) §8(\\w+)➜§3(\\w+)".toRegex() - @SubscribeEvent - fun onChatMessage(event: ClientChatReceivedEvent) { + @SubscribePSSEvent + fun onChatMessage(event: PSSChatEvent) { if (!enabled) return - val message = event.message.formattedText + val message = event.message val (crop, oldLevel, newLevel) = regex.find(message)?.destructured ?: return - val oldLevelInt = if ("\\d+".toRegex().containsMatchIn(oldLevel)) { - oldLevel.toIntOrNull() ?: 0 - } else { - oldLevel.romanNumeralToInt() - } - - val newLevelInt = if ("\\d+".toRegex().containsMatchIn(newLevel)) { - newLevel.toIntOrNull() ?: 0 - } else { - newLevel.romanNumeralToInt() - } + val oldLevelInt = + if ("\\d+".toRegex().containsMatchIn(oldLevel)) { + oldLevel.toIntOrNull() ?: 0 + } else { + oldLevel.romanNumeralToInt() + } + + val newLevelInt = + if ("\\d+".toRegex().containsMatchIn(newLevel)) { + newLevel.toIntOrNull() ?: 0 + } else { + newLevel.romanNumeralToInt() + } if (config.find("multipleOf5")?.asBoolean == true && newLevelInt % 5 == 0) { trigger(crop, oldLevelInt, newLevelInt) @@ -72,34 +79,37 @@ object CropMilestoneWebhook : Webhook() { } private fun trigger(crop: String, oldLevel: Int, newLevel: Int) { - - val oldLevelString = if (config.find("useRomanNumerals")?.asBoolean == true) { - oldLevel.toRoman() - } else { - oldLevel.toString() - } - - val newLevelString = if (config.find("useRomanNumerals")?.asBoolean == true) { - newLevel.toRoman() - } else { - newLevel.toString() - } + val oldLevelString = + if (config.find("useRomanNumerals")?.asBoolean == true) { + oldLevel.toRoman() + } else { + oldLevel.toString() + } + + val newLevelString = + if (config.find("useRomanNumerals")?.asBoolean == true) { + newLevel.toRoman() + } else { + newLevel.toString() + } WebhookData( url = PartlySaneSkies.config.discordWebhookURL, content = " ", - embedData = listOf( - EmbedData( - title = "Garden Milestone!", - color = Color(125, 255, 125).asHex, - fields = listOf( - EmbedField( - name = crop, - value = ":tada: $oldLevelString ➜ $newLevelString :tada:", - ), + embedData = + listOf( + EmbedData( + title = "Garden Milestone!", + color = Color(125, 255, 125).asHex, + fields = + listOf( + EmbedField( + name = crop, + value = ":tada: $oldLevelString ➜ $newLevelString :tada:", + ), + ), ), ), - ), ).send() } } diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/farming/garden/SkymartValue.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/farming/garden/SkymartValue.kt index 00ed9bc87..b03031a17 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/farming/garden/SkymartValue.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/farming/garden/SkymartValue.kt @@ -23,6 +23,7 @@ import me.partlysanestudios.partlysaneskies.events.SubscribePSSEvent import me.partlysanestudios.partlysaneskies.events.data.LoadPublicDataEvent import me.partlysanestudios.partlysaneskies.features.gui.SidePanel import me.partlysanestudios.partlysaneskies.render.gui.constraints.ScaledPixelConstraint.Companion.scaledPixels +import me.partlysanestudios.partlysaneskies.render.gui.constraints.TextScaledPixelConstraint.Companion.textScaledPixels import me.partlysanestudios.partlysaneskies.utils.ElementaUtils.applyBackground import me.partlysanestudios.partlysaneskies.utils.MathUtils.round import me.partlysanestudios.partlysaneskies.utils.MathUtils.sortMap @@ -34,21 +35,23 @@ import net.minecraftforge.client.event.GuiScreenEvent import java.awt.Color object SkymartValue : SidePanel() { - override val panelBaseComponent: UIComponent = UIBlock().applyBackground().constrain { - x = 800.scaledPixels - y = CenterConstraint() - width = 225.scaledPixels - height = 350.scaledPixels - color = Color(0, 0, 0, 0).constraint - } + override val panelBaseComponent: UIComponent = UIBlock().applyBackground() + .constrain { + x = 800.scaledPixels + y = CenterConstraint() + width = 225.scaledPixels + height = 350.scaledPixels + color = Color(0, 0, 0, 0).constraint + } - private val textComponent = UIWrappedText().constrain { - x = CenterConstraint() - y = CenterConstraint() - height = 95.percent - width = 95.percent - textScale = 1.scaledPixels - } childOf panelBaseComponent + private val textComponent = UIWrappedText() + .constrain { + x = CenterConstraint() + y = CenterConstraint() + height = 95.percent + width = 95.percent + textScale = 1.textScaledPixels + } childOf panelBaseComponent override fun shouldDisplayPanel(): Boolean { if (!config.skymartValue) { @@ -68,7 +71,6 @@ object SkymartValue : SidePanel() { return skymart.displayName.formattedText.removeColorCodes().contains("SkyMart") } - private val copperCost = HashMap() override fun onPanelRender(event: GuiScreenEvent.BackgroundDrawnEvent) { @@ -81,7 +83,6 @@ object SkymartValue : SidePanel() { textComponent.setText(textString) } - @SubscribePSSEvent fun initCopperValues(event: LoadPublicDataEvent) { val str = getFile("constants/skymart_copper.json") @@ -91,7 +92,6 @@ object SkymartValue : SidePanel() { } } - private fun getString(): String { var str = "" val map = HashMap() @@ -102,9 +102,10 @@ object SkymartValue : SidePanel() { val sortedMap = map.sortMap() var i = 1 for ((key, value) in sortedMap) { - val item = getItem(key) ?: SkyblockItem.emptyItem - str += "§6$i. §d${item.name}§7 costs §d${copperCost[key]?.formatNumber() ?: 0}§7 copper and sells for §d${item.getSellPrice().round(1).formatNumber()}§7 coins \n§8 (${value.round(1).formatNumber()} coins per copper)\n" + str += "§6$i. §d${item.name}§7 costs §d${copperCost[key]?.formatNumber() ?: 0}§7 copper and sells for §d${ + item.getSellPrice().round(1).formatNumber() + }§7 coins \n§8 (${value.round(1).formatNumber()} coins per copper)\n" i++ if (i > 5) { @@ -114,4 +115,4 @@ object SkymartValue : SidePanel() { return str } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/farming/garden/VisitorLogbookStats.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/farming/garden/VisitorLogbookStats.kt index 026882041..be823c9ea 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/farming/garden/VisitorLogbookStats.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/farming/garden/VisitorLogbookStats.kt @@ -16,7 +16,6 @@ * (presumably seen across all rarities) */ - package me.partlysanestudios.partlysaneskies.features.farming.garden import gg.essential.elementa.UIComponent @@ -34,39 +33,39 @@ import me.partlysanestudios.partlysaneskies.data.cache.VisitorLogbookData.isVisi import me.partlysanestudios.partlysaneskies.data.skyblockdata.Rarity import me.partlysanestudios.partlysaneskies.features.gui.SidePanel import me.partlysanestudios.partlysaneskies.render.gui.constraints.ScaledPixelConstraint.Companion.scaledPixels +import me.partlysanestudios.partlysaneskies.render.gui.constraints.TextScaledPixelConstraint.Companion.textScaledPixels import me.partlysanestudios.partlysaneskies.utils.ElementaUtils.applyBackground import me.partlysanestudios.partlysaneskies.utils.StringUtils.formatNumber import net.minecraftforge.client.event.GuiScreenEvent import java.awt.Color object VisitorLogbookStats : SidePanel() { + override val panelBaseComponent: UIComponent = UIBlock().applyBackground() + .constrain { + x = 800.scaledPixels + y = CenterConstraint() + width = 225.scaledPixels + height = 350.scaledPixels + color = Color(0, 0, 0, 0).constraint + } - override val panelBaseComponent: UIComponent = UIBlock().applyBackground().constrain { - x = 800.scaledPixels - y = CenterConstraint() - width = 225.scaledPixels - height = 350.scaledPixels - color = Color(0, 0, 0, 0).constraint - } - - private val textComponent = UIWrappedText().constrain { - x = CenterConstraint() - y = CenterConstraint() - height = 95.percent - width = 95.percent - textScale = 1.scaledPixels - } childOf panelBaseComponent + private val textComponent = UIWrappedText() + .constrain { + x = CenterConstraint() + y = CenterConstraint() + height = 95.percent + width = 95.percent + textScale = 1.textScaledPixels + } childOf panelBaseComponent - override fun shouldDisplayPanel(): Boolean { - return if (!isVisitorLogbook(minecraft.currentScreen)) { + override fun shouldDisplayPanel(): Boolean = + if (!isVisitorLogbook(minecraft.currentScreen)) { false } else if (!PartlySaneSkies.config.visitorLogbookStats) { false } else { true } - } - override fun onPanelRender(event: GuiScreenEvent.BackgroundDrawnEvent) { alignPanel() @@ -92,7 +91,7 @@ object VisitorLogbookStats : SidePanel() { visited: HashMap, accepted: HashMap, uniqueVisits: HashMap, - uniqueAccepts: HashMap + uniqueAccepts: HashMap, ): String { var str = "" val rarities = Rarity.entries.toTypedArray().sortedBy { it.order } @@ -108,8 +107,8 @@ object VisitorLogbookStats : SidePanel() { §7Denied/Pending: §d${((visited[rarity] ?: 0) - (accepted[rarity] ?: 0)).formatNumber()}§7 (Unique: §d${((uniqueVisits[rarity] ?: 0) - (uniqueAccepts[rarity] ?: 0)).formatNumber()}§7) - """.trimIndent() + """.trimIndent() } return str } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/farming/garden/VisitorTradeValue.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/farming/garden/VisitorTradeValue.kt index 0e06ded76..1339dafde 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/farming/garden/VisitorTradeValue.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/farming/garden/VisitorTradeValue.kt @@ -3,7 +3,6 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.features.farming.garden import gg.essential.elementa.UIComponent @@ -20,6 +19,7 @@ import me.partlysanestudios.partlysaneskies.data.skyblockdata.SkyblockDataManage import me.partlysanestudios.partlysaneskies.data.skyblockdata.SkyblockDataManager.getItem import me.partlysanestudios.partlysaneskies.features.gui.SidePanel import me.partlysanestudios.partlysaneskies.render.gui.constraints.ScaledPixelConstraint.Companion.scaledPixels +import me.partlysanestudios.partlysaneskies.render.gui.constraints.TextScaledPixelConstraint.Companion.textScaledPixels import me.partlysanestudios.partlysaneskies.utils.ElementaUtils.applyBackground import me.partlysanestudios.partlysaneskies.utils.MathUtils.round import me.partlysanestudios.partlysaneskies.utils.MinecraftUtils.containerInventory @@ -33,21 +33,23 @@ import net.minecraftforge.client.event.GuiScreenEvent import java.awt.Color object VisitorTradeValue : SidePanel() { - override val panelBaseComponent: UIComponent = UIBlock().applyBackground().constrain { - x = 800.scaledPixels - y = CenterConstraint() - width = 225.scaledPixels - height = 350.scaledPixels - color = Color(0, 0, 0, 0).constraint - } + override val panelBaseComponent: UIComponent = UIBlock().applyBackground() + .constrain { + x = 800.scaledPixels + y = CenterConstraint() + width = 225.scaledPixels + height = 350.scaledPixels + color = Color(0, 0, 0, 0).constraint + } - private val textComponent = UIWrappedText().constrain { - x = CenterConstraint() - y = CenterConstraint() - height = 95.percent - width = 95.percent - textScale = 1.scaledPixels - } childOf panelBaseComponent + private val textComponent = UIWrappedText() + .constrain { + x = CenterConstraint() + y = CenterConstraint() + height = 95.percent + width = 95.percent + textScale = 1.textScaledPixels + } childOf panelBaseComponent override fun shouldDisplayPanel(): Boolean { if (!config.gardenShopTradeInfo) { @@ -93,32 +95,34 @@ object VisitorTradeValue : SidePanel() { val totalCost = getTotalCost() - textString += if (totalCost > 0) { - "§e§lTotal Cost: §r§d${totalCost.round(2).formatNumber()}\n\n" - } else { - "§e§lTotal Cost: §o§8(Unknown)§r\n\n" - } + textString += + if (totalCost > 0) { + "§e§lTotal Cost: §r§d${totalCost.round(2).formatNumber()}\n\n" + } else { + "§e§lTotal Cost: §o§8(Unknown)§r\n\n" + } textString += "§e§lCopper Received: §r§d${getCopperReturn().round(2).formatNumber()}\n\n" - val pricePerCopper: Double = getTotalCost() / getCopperReturn() - textString += if (pricePerCopper > 0) { - "§e§lCoins/Copper: §r§d${pricePerCopper.round(2).formatNumber()}\n\n" - } else { - "§e§lCoins/Copper: §o§8(Unknown)§r\n\n" - } + textString += + if (pricePerCopper > 0) { + "§e§lCoins/Copper: §r§d${pricePerCopper.round(2).formatNumber()}\n\n" + } else { + "§e§lCoins/Copper: §o§8(Unknown)§r\n\n" + } var priceBreakdown = "" val coinCostMap: HashMap = getCoinCostMap() for ((key, value) in getQuantityCostMap().entries) { val cost = coinCostMap[key] ?: continue - priceBreakdown += if (cost >= 0) { - "§7x§d${value}§7 $key for a total of §d${cost.round(2).formatNumber()}§7 coins.\n" - } else { - "§7x§d$value §7$key for a total of §o§8(Unknown)§r§7 coins.\n" - } + priceBreakdown += + if (cost >= 0) { + "§7x§d$value§7 $key for a total of §d${cost.round(2).formatNumber()}§7 coins.\n" + } else { + "§7x§d$value §7$key for a total of §o§8(Unknown)§r§7 coins.\n" + } } textString += "§e§lPrice Breakdown:§r\n" @@ -250,5 +254,4 @@ object VisitorTradeValue : SidePanel() { return totalCost } - -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/foraging/TreecapitatorCooldown.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/foraging/TreecapitatorCooldown.kt index d1ac5ff34..e7ab6536a 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/foraging/TreecapitatorCooldown.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/foraging/TreecapitatorCooldown.kt @@ -22,7 +22,6 @@ import net.minecraft.nbt.NBTTagCompound import net.minecraft.nbt.NBTTagList import net.minecraft.nbt.NBTTagString - object TreecapitatorCooldown : Cooldown() { init { CooldownManager.registerCooldown(this) @@ -31,17 +30,20 @@ object TreecapitatorCooldown : Cooldown() { override fun getTotalTime(): Long { var cooldown = 2000L - if (PetData.getCurrentPetName() == "Monkey" && PetData.getCurrentPetRarity().order >= Rarity.LEGENDARY.order && PetData.getCurrentPetLevel() != -1 && PartlySaneSkies.config.treecapCooldownMonkeyPet) { + if (PetData.getCurrentPetName() == "Monkey" && + PetData.getCurrentPetRarity().order >= Rarity.LEGENDARY.order && + PetData.getCurrentPetLevel() != -1 && + PartlySaneSkies.config.treecapCooldownMonkeyPet + ) { cooldown -= (cooldown * PetData.getCurrentPetLevel() / 200.0).toLong() } return cooldown } - override fun getDisplayName(): String { - return "Treecapitator" - } + override fun getDisplayName(): String = "Treecapitator" private var treecapitatorAxe: ItemStack? = null + override fun getItemToDisplay(): ItemStack { if (treecapitatorAxe == null) { val itemStack = ItemStack(Items.golden_axe) @@ -51,18 +53,19 @@ object TreecapitatorCooldown : Cooldown() { val displayCompound = compound.getCompoundTag("display") ?: NBTTagCompound() val loreList = NBTTagList() - val lore = arrayOf( - "§9Efficiency V", - "§7Increases how quickly your tool", - "§7breaks blocks.", - "", - "§7A forceful Gold Axe which can break", - "§7a large amount of logs in a single hit!", - "§8Cooldown: §a2s", - "", - "§7§8This item can be reforged!", - "§5§lEPIC AXE" - ) + val lore = + arrayOf( + "§9Efficiency V", + "§7Increases how quickly your tool", + "§7breaks blocks.", + "", + "§7A forceful Gold Axe which can break", + "§7a large amount of logs in a single hit!", + "§8Cooldown: §a2s", + "", + "§7§8This item can be reforged!", + "§5§lEPIC AXE", + ) // Convert lore strings to NBTTagString and add them to the list for (line in lore) { @@ -99,7 +102,6 @@ object TreecapitatorCooldown : Cooldown() { return } - if (!isWood(event.point)) { // Checks if the block is wood return } @@ -134,4 +136,4 @@ object TreecapitatorCooldown : Cooldown() { } return false } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/gui/RefreshKeybinds.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/gui/RefreshKeybinds.kt index 17aa90d81..f32dfdd68 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/gui/RefreshKeybinds.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/gui/RefreshKeybinds.kt @@ -12,7 +12,6 @@ * */ - package me.partlysanestudios.partlysaneskies.features.gui import me.partlysanestudios.partlysaneskies.PartlySaneSkies @@ -30,7 +29,7 @@ object RefreshKeybinds { @SubscribeEvent fun onGuiKeyboardInput(event: GuiScreenEvent.KeyboardInputEvent.Pre) { - if (!PartlySaneSkies.config.refreshKeybind) return + if (!PartlySaneSkies.config.refreshKeybind || !Keyboard.isCreated()) return checkKeybinds(event) } @@ -44,8 +43,10 @@ object RefreshKeybinds { val refreshKeyDownMacOS: Boolean = ((Keyboard.isKeyDown(Keyboard.KEY_LMETA) xor Keyboard.isKeyDown(Keyboard.KEY_RMETA)) && keyRDown) if ( - (keyFnFiveDown) xor ((refreshKeyDownWindowsLinux && !operatingSystem.contains("mac")) - || (refreshKeyDownMacOS && operatingSystem.contains("mac"))) + (keyFnFiveDown) xor ( + (refreshKeyDownWindowsLinux && !operatingSystem.contains("mac")) || + (refreshKeyDownMacOS && operatingSystem.contains("mac")) + ) ) { val container: ContainerChest = (gui).inventorySlots as ContainerChest for (i: Int in 0..53) { @@ -59,4 +60,4 @@ object RefreshKeybinds { } } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/gui/SidePanel.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/gui/SidePanel.kt index f0ec72c5c..07e818f6c 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/gui/SidePanel.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/gui/SidePanel.kt @@ -14,6 +14,7 @@ import gg.essential.elementa.dsl.pixels import gg.essential.elementa.dsl.plus import gg.essential.universal.UMatrixStack import me.partlysanestudios.partlysaneskies.PartlySaneSkies +import me.partlysanestudios.partlysaneskies.PartlySaneSkies.Companion.config import me.partlysanestudios.partlysaneskies.render.gui.constraints.ScaledPixelConstraint.Companion.scaledPixels import me.partlysanestudios.partlysaneskies.utils.ElementaUtils import me.partlysanestudios.partlysaneskies.utils.MinecraftUtils.xSize @@ -34,7 +35,7 @@ abstract class SidePanel { * The distance between the edge of the chest Gui and the edge of the panel. * Used by the [alignPanel] function. */ - open val pad: XConstraint = 10.scaledPixels + open val pad: XConstraint get() = config.sidePanelPadding.scaledPixels private var parented = false internal val window = Window(ElementaVersion.V5) @@ -88,4 +89,4 @@ abstract class SidePanel { * @return Whether the panel should be is rendered */ abstract fun shouldDisplayPanel(): Boolean -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/gui/hud/CooldownHud.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/gui/hud/CooldownHud.kt index 6a2e6f485..b70960a2e 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/gui/hud/CooldownHud.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/gui/hud/CooldownHud.kt @@ -28,7 +28,6 @@ private const val defaultHeight = 7 private const val defaultPadding = 120f object CooldownHud : PSSHud(true, 960F - defaultWidth / 2, 561.6F, 0, 1.0F) { - private val exampleCooldowns = ArrayList() private val cooldownElements = ArrayList() private val window = Window(ElementaVersion.V2) @@ -40,13 +39,13 @@ object CooldownHud : PSSHud(true, 960F - defaultWidth / 2, 561.6F, 0, 1.0F) { cooldownElements.add(previousCooldownElement) for (i in 2..cooldownsDisplayableAtOnce) { - val newCooldownElement = PSSHorizontalCooldown( - CenterConstraint(), - defaultPadding.percent, - defaultWidth.pixels, - defaultHeight.pixels - ) - .setChildOf(previousCooldownElement.boundingBox) + val newCooldownElement = + PSSHorizontalCooldown( + CenterConstraint(), + defaultPadding.percent, + defaultWidth.pixels, + defaultHeight.pixels, + ).setChildOf(previousCooldownElement.boundingBox) previousCooldownElement = newCooldownElement cooldownElements.add(newCooldownElement) } @@ -77,7 +76,6 @@ object CooldownHud : PSSHud(true, 960F - defaultWidth / 2, 561.6F, 0, 1.0F) { } for (i in 0.. cooldownsDisplayableAtOnce) { - cooldownsDisplayableAtOnce - } else { - sortedActiveCooldownsList.size - } + val cooldownsToDisplay = + if (sortedActiveCooldownsList.size > cooldownsDisplayableAtOnce) { + cooldownsDisplayableAtOnce + } else { + sortedActiveCooldownsList.size + } for (cooldownElement in cooldownElements) { cooldownElement.setCooldownToDisplay(null) @@ -110,9 +110,7 @@ object CooldownHud : PSSHud(true, 960F - defaultWidth / 2, 561.6F, 0, 1.0F) { window.draw(gg.essential.universal.UMatrixStack()) } - override fun getWidth(scale: Float, example: Boolean): Float { - return defaultWidth * scale - } + override fun getWidth(scale: Float, example: Boolean): Float = defaultWidth * scale override fun getHeight(scale: Float, example: Boolean): Float { val totalBarHeights = cooldownsDisplayableAtOnce * defaultHeight * scale @@ -136,4 +134,4 @@ object CooldownHud : PSSHud(true, 960F - defaultWidth / 2, 561.6F, 0, 1.0F) { override fun getItemToDisplay(): ItemStack = ItemStack(item) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/gui/hud/rngdropbanner/DropBannerDisplay.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/gui/hud/DropBannerDisplay.kt similarity index 66% rename from src/main/kotlin/me/partlysanestudios/partlysaneskies/features/gui/hud/rngdropbanner/DropBannerDisplay.kt rename to src/main/kotlin/me/partlysanestudios/partlysaneskies/features/gui/hud/DropBannerDisplay.kt index c0d64f602..1d02e44c7 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/gui/hud/rngdropbanner/DropBannerDisplay.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/gui/hud/DropBannerDisplay.kt @@ -3,7 +3,7 @@ // See LICENSE for copyright and license notices. // -package me.partlysanestudios.partlysaneskies.features.gui.hud.rngdropbanner +package me.partlysanestudios.partlysaneskies.features.gui.hud import gg.essential.elementa.ElementaVersion import gg.essential.elementa.components.UIWrappedText @@ -19,10 +19,14 @@ import me.partlysanestudios.partlysaneskies.PartlySaneSkies.Companion.minecraft import me.partlysanestudios.partlysaneskies.PartlySaneSkies.Companion.time import me.partlysanestudios.partlysaneskies.data.skyblockdata.Rarity import me.partlysanestudios.partlysaneskies.data.skyblockdata.Rarity.Companion.getRarityFromColorCode -import me.partlysanestudios.partlysaneskies.render.gui.constraints.ScaledPixelConstraint.Companion.scaledPixels +import me.partlysanestudios.partlysaneskies.features.items.rngdrop.RareDropGUIManager.isAllowedDrop +import me.partlysanestudios.partlysaneskies.events.SubscribePSSEvent +import me.partlysanestudios.partlysaneskies.events.minecraft.PSSChatEvent +import me.partlysanestudios.partlysaneskies.features.items.rngdrop.Drop +import me.partlysanestudios.partlysaneskies.features.items.rngdrop.DropWebhook +import me.partlysanestudios.partlysaneskies.render.gui.constraints.TextScaledPixelConstraint.Companion.textScaledPixels import me.partlysanestudios.partlysaneskies.utils.MathUtils.onCooldown import me.partlysanestudios.partlysaneskies.utils.StringUtils.colorCodeToColor -import net.minecraftforge.client.event.ClientChatReceivedEvent import net.minecraftforge.client.event.RenderGameOverlayEvent import net.minecraftforge.fml.common.eventhandler.SubscribeEvent import java.awt.Color @@ -32,8 +36,9 @@ object DropBannerDisplay { // Whenever someone updates the regex, please replace the regex in the following link: // Regex: https://regex101.com/r/lPUJeH/8 - private val RARE_DROP_REGEX = "(?:§r)*(?§.)(?:§.)+(?[\\w\\s]*[CD]ROP!) (?:§.)+\\(?(?:§.)*(?:\\d+x )?(?:§.)*(?§.)(?◆?[\\s\\w]+)(?:§.)+\\)? ?(?:(?:§.)+)?(?:\\((?:\\+(?:§.)*(?\\d+)% (?:§.)+✯ Magic Find(?:§.)*|[\\w\\s]+)\\))?".toRegex() - + private val RARE_DROP_REGEX = + "(?:§r)*(?§.)(?:§.)+(?[\\w\\s]*[CD]ROP!) (?:§.)+\\(?(?:§.)*(?:\\d+x )?(?:§.)*(?§.)(?◆?[\\s\\w]+)(?:§.)+\\)? ?(?:(?:§.)+)?(?:\\((?:\\+(?:§.)*(?\\d+)% (?:§.)+✯ Magic Find(?:§.)*|[\\w\\s]+)\\))?" + .toRegex() private const val SMALL_TEXT_SCALE = 2.5f private const val BIG_TEXT_SCALE = 5f @@ -47,33 +52,38 @@ object DropBannerDisplay { private var topString = "" private var dropNameString = "" - private var topText = UIWrappedText(centered = true).constrain { - textScale = (BIG_TEXT_SCALE * config.bannerSize).scaledPixels - width = 100.percent - x = CenterConstraint() - y = BANNER_HEIGHT_FACTOR.percent - } childOf window - - private var dropNameText = UIWrappedText(centered = true).constrain { - textScale = (SMALL_TEXT_SCALE * config.bannerSize).scaledPixels - width = 100.percent - x = CenterConstraint() - y = PixelConstraint(topText.getBottom() + window.getHeight() * TEXT_SPACING_FACTOR) - } childOf window - - @SubscribeEvent - fun onChatMessage(event: ClientChatReceivedEvent) { - val formattedMessage = event.message.formattedText + private var topText = + UIWrappedText(centered = true).constrain { + textScale = (BIG_TEXT_SCALE * config.bannerSize).textScaledPixels + width = 100.percent + x = CenterConstraint() + y = BANNER_HEIGHT_FACTOR.percent + } childOf window + + private var dropNameText = + UIWrappedText(centered = true).constrain { + textScale = (SMALL_TEXT_SCALE * config.bannerSize).textScaledPixels + width = 100.percent + x = CenterConstraint() + y = PixelConstraint(topText.getBottom() + window.getHeight() * TEXT_SPACING_FACTOR) + } childOf window + + @SubscribePSSEvent + fun onChatMessage(event: PSSChatEvent) { + val formattedMessage = event.message val match = RARE_DROP_REGEX.find(formattedMessage) ?: return val (dropCategoryColor, dropCategory, dropColor, name, magicFind) = match.destructured val rarity = dropColor.getRarityFromColorCode() - // TODO: add check for blocked drop if (checkRarity(rarity)) { return } + if (!isAllowedDrop(name.trim())) { + return + } + if (config.rareDropBannerSound) { minecraft.thePlayer.playSound("partlysaneskies:rngdropjingle", 100f, 1f) } @@ -101,19 +111,20 @@ object DropBannerDisplay { } var categoryColor = item.dropCategoryColor - dropNameString = "${item.dropRarity.colorCode}${item.name} ${if (item.magicFind > 0) "§b(+${item.magicFind}% ✯ Magic Find)" else ""}" + dropNameString = + "${item.dropRarity.colorCode}${item.name} ${if (item.magicFind > 0) "§b(+${item.magicFind}% ✯ Magic Find)" else ""}" topString = item.dropCategory if ( - (time - item.timeDropped > TEXT_BLINK_START_FACTOR * config.rareDropBannerTime * 1000) - && + (time - item.timeDropped > TEXT_BLINK_START_FACTOR * config.rareDropBannerTime * 1000) && (time - item.timeDropped < TEXT_BLINK_END_FACTOR * config.rareDropBannerTime * 1000) ) { - categoryColor = if (Math.round((item.timeDropped - time) / 1000f * 4) % 2 == 0) { - Color.white - } else { - item.dropCategoryColor - } + categoryColor = + if (Math.round((item.timeDropped - time) / 1000f * 4) % 2 == 0) { + Color.white + } else { + item.dropCategoryColor + } } if (!onCooldown(item.timeDropped, (config.rareDropBannerTime * 1000).toLong())) { @@ -137,8 +148,8 @@ object DropBannerDisplay { window.draw(UMatrixStack()) } - private fun checkRarity(rarity: Rarity): Boolean { - return when { + private fun checkRarity(rarity: Rarity): Boolean = + when { rarity == Rarity.COMMON && config.blockCommonDrops -> true rarity == Rarity.UNCOMMON && config.blockUncommonDrops -> true rarity == Rarity.RARE && config.blockRareDrops -> true @@ -146,5 +157,4 @@ object DropBannerDisplay { rarity == Rarity.LEGENDARY && config.blockLegendaryDrops -> true else -> false } - } } diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/gui/hud/LocationBannerDisplay.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/gui/hud/LocationBannerDisplay.kt index f9309ca93..3ca82744e 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/gui/hud/LocationBannerDisplay.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/gui/hud/LocationBannerDisplay.kt @@ -15,10 +15,9 @@ import me.partlysanestudios.partlysaneskies.utils.StringUtils.removeColorCodes import me.partlysanestudios.partlysaneskies.utils.StringUtils.stripLeading import me.partlysanestudios.partlysaneskies.utils.StringUtils.stripTrailing import java.awt.Color -import java.util.* +import java.util.Locale object LocationBannerDisplay { - private var TEXT_SCALE = 5f private var lastLocation = "" private var lastLocationTime = time @@ -68,9 +67,7 @@ object LocationBannerDisplay { renderNewBanner(PSSBanner(displayString, (config.locationBannerTime * 1000).toLong(), TEXT_SCALE, color)) } - private fun checkExpire(): Boolean { - return timeSinceLastChange > config.locationBannerTime * 1000 - } + private fun checkExpire(): Boolean = timeSinceLastChange > config.locationBannerTime * 1000 private val timeSinceLastChange: Long get() = time - lastLocationTime diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/gui/mainmenu/MainMenuOptionMenu.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/gui/mainmenu/MainMenuOptionMenu.kt index 3af82f413..811b43cb7 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/gui/mainmenu/MainMenuOptionMenu.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/gui/mainmenu/MainMenuOptionMenu.kt @@ -3,7 +3,6 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.features.gui.mainmenu import gg.essential.elementa.ElementaVersion @@ -21,8 +20,11 @@ import gg.essential.elementa.dsl.plus import gg.essential.universal.UMatrixStack import me.partlysanestudios.partlysaneskies.PartlySaneSkies import me.partlysanestudios.partlysaneskies.PartlySaneSkies.Companion.config +import me.partlysanestudios.partlysaneskies.PartlySaneSkies.Companion.coreConfig +import me.partlysanestudios.partlysaneskies.config.psconfig.Toggle.Companion.asToggle import me.partlysanestudios.partlysaneskies.features.themes.ThemeManager import me.partlysanestudios.partlysaneskies.render.gui.constraints.ScaledPixelConstraint.Companion.scaledPixels +import me.partlysanestudios.partlysaneskies.render.gui.constraints.TextScaledPixelConstraint.Companion.textScaledPixels import me.partlysanestudios.partlysaneskies.utils.ElementaUtils.uiImage import me.partlysanestudios.partlysaneskies.utils.SystemUtils import net.minecraft.util.ResourceLocation @@ -32,155 +34,174 @@ import java.time.ZoneId import java.time.format.DateTimeFormatter import java.util.Locale -class MainMenuOptionMenu(nextRunnable: Runnable): WindowScreen(ElementaVersion.V5) { - - private val backgroundBox = UIBlock().constrain { - x = CenterConstraint() - y = CenterConstraint() - width = 100.percent - height = 100.percent - color = Color(0, 0, 0).constraint - } childOf window - - private val backgroundImage = ResourceLocation("partlysaneskies", "textures/gui/main_menu/image_3_blurred.png").uiImage.constrain { - x = CenterConstraint() - y = CenterConstraint() - width = 100.percent - height = 100.percent - } childOf backgroundBox - - private val transparentBlock = UIBlock().constrain { - x = CenterConstraint() - y = CenterConstraint() - width = 100.percent - height = 100.percent - color = Color(0, 0, 0, 0).constraint - } childOf backgroundImage - - private val darkerRectangle = UIRoundedRectangle(7.5f).constrain { - x = CenterConstraint() - y = CenterConstraint() - 7.25.percent - width = 60.percent - height = 54.percent - color = Color(15, 15, 15, 115).constraint - } childOf transparentBlock - - private val headingText = UIWrappedText("Keep the new main menu?", centered = true).constrain { - x = CenterConstraint() - y = 30.percent - width = 40.percent - textScale = 2.scaledPixels - color = Color(100, 196, 255).constraint - } childOf transparentBlock - - private val subheadingText = UIWrappedText("You can always disable it later, or find other backgrounds later on in the Partly Sane Skies config. (/pssc)", centered = true).constrain { - x = CenterConstraint() - y = 35.percent - width = 50.percent - textScale = 1.scaledPixels - color = Color.white.constraint - } childOf transparentBlock - - private val yesButton = UIRoundedRectangle(5.0f).constrain { - x = CenterConstraint() - 12.percent - y = 40.percent - width = 20.percent - height = 25.percent - color = Color(90, 150, 100, 90).constraint - }.onMouseClickConsumer { - config.customMainMenu = true - nextRunnable.run() - }.onMouseEnter { - for (child in this.children) { - child.setColor(Color(200, 200, 200)) - } - }.onMouseLeave { - for (child in this.children) { - child.setColor(Color.white) - } - } childOf transparentBlock - - private val yesText = UIWrappedText("Yes, keep the new main menu", centered = true).constrain { - width = 90.percent - x = CenterConstraint() - y = 10.percent - textScale = 1.scaledPixels - color = Color.white.constraint - } childOf yesButton - - private val pssExample = ResourceLocation("partlysaneskies", "textures/gui/main_menu/selection/pssexample.png").uiImage.constrain { - x = CenterConstraint() - y = 25.percent - width = 90.percent - height = 70.percent - } childOf yesButton - - private val noButton = UIRoundedRectangle(5.0f).constrain { - x = CenterConstraint() + 12.percent - y = 40.percent - width = 20.percent - height = 25.percent - color = Color(75, 37, 45, 90).constraint - }.onMouseClickConsumer { - config.customMainMenu = false - nextRunnable.run() - }.onMouseEnter { - for (child in this.children) { - child.setColor(Color(200, 200, 200)) - } - }.onMouseLeave { - for (child in this.children) { - child.setColor(Color.white) - } - } childOf transparentBlock - - private val sccExample = ResourceLocation("partlysaneskies", "textures/gui/main_menu/selection/sccexample.png").uiImage.constrain { - x = CenterConstraint() - y = 25.percent - width = 90.percent - height = 70.percent - } childOf noButton - - private val sccTint = UIBlock().constrain { - x = CenterConstraint() - y = CenterConstraint() - width = 100.percent - height = 100.percent - color = Color(0, 0, 0, 100).constraint - } childOf sccExample - - private val noText = UIWrappedText("No, return to the default menu", centered = true).constrain { - width = 90.percent - x = CenterConstraint() - y = 10.percent - textScale = 1.scaledPixels - color = Color.white.constraint - } childOf noButton - - private val timeText = UIWrappedText(centered = true).constrain { - x = CenterConstraint() - y = 10.scaledPixels(alignOpposite = true) - color = Color.white.constraint - textScale = 1.scaledPixels - } childOf transparentBlock - - private val discordText = UIWrappedText("Discord: discord.gg/${PartlySaneSkies.discordCode}").constrain { - x = 10.scaledPixels - y = 10.scaledPixels(alignOpposite = true) - textScale = 1.scaledPixels - color = Color(69, 79, 191).constraint - }.onMouseClick { - SystemUtils.openLink("https://discord.gg/${PartlySaneSkies.discordCode}") - } childOf transparentBlock - - private val partlySaneSkiesText = UIWrappedText("Made by: Partly Sane Skies").constrain { - x = 10.scaledPixels(alignOpposite = true) - y = 10.scaledPixels(alignOpposite = true) - textScale = 1.scaledPixels - color = ThemeManager.accentColor.toJavaColor().constraint - }.onMouseClick { - SystemUtils.openLink("https://github.com/PartlySaneStudios/partly-sane-skies") - } childOf transparentBlock +class MainMenuOptionMenu(nextRunnable: Runnable) : WindowScreen(ElementaVersion.V5) { + private val backgroundBox = UIBlock() + .constrain { + x = CenterConstraint() + y = CenterConstraint() + width = 100.percent + height = 100.percent + color = Color(0, 0, 0).constraint + } childOf window + + private val backgroundImage = ResourceLocation("partlysaneskies", "textures/gui/main_menu/image_3_blurred.png").uiImage + .constrain { + x = CenterConstraint() + y = CenterConstraint() + width = 100.percent + height = 100.percent + } childOf backgroundBox + + private val transparentBlock = UIBlock() + .constrain { + x = CenterConstraint() + y = CenterConstraint() + width = 100.percent + height = 100.percent + color = Color(0, 0, 0, 0).constraint + } childOf backgroundImage + + private val darkerRectangle = UIRoundedRectangle(7.5f) + .constrain { + x = CenterConstraint() + y = CenterConstraint() - 7.25.percent + width = 60.percent + height = 54.percent + color = Color(15, 15, 15, 115).constraint + } childOf transparentBlock + + private val headingText = UIWrappedText("Keep the new main menu?", centered = true) + .constrain { + x = CenterConstraint() + y = 30.percent + width = 40.percent + textScale = 2.textScaledPixels + color = Color(100, 196, 255).constraint + } childOf transparentBlock + + private val subheadingText = UIWrappedText( + "You can always disable it later, or find other backgrounds later on in the Partly Sane Skies config. (/pssc)", + centered = true, + ).constrain { + x = CenterConstraint() + y = 35.percent + width = 50.percent + textScale = 1.textScaledPixels + color = Color.white.constraint + } childOf transparentBlock + + private val yesButton = UIRoundedRectangle(5.0f) + .constrain { + x = CenterConstraint() - 12.percent + y = 40.percent + width = 20.percent + height = 25.percent + color = Color(90, 150, 100, 90).constraint + }.onMouseClickConsumer { + config.customMainMenu = true + coreConfig.find("promptedMainMenu")?.asToggle?.state = true + nextRunnable.run() + }.onMouseEnter { + for (child in this.children) { + child.setColor(Color(200, 200, 200)) + } + }.onMouseLeave { + for (child in this.children) { + child.setColor(Color.white) + } + } childOf transparentBlock + + private val yesText = UIWrappedText("Yes, keep the new main menu", centered = true) + .constrain { + width = 90.percent + x = CenterConstraint() + y = 10.percent + textScale = 1.textScaledPixels + color = Color.white.constraint + } childOf yesButton + + private val pssExample = ResourceLocation("partlysaneskies", "textures/gui/main_menu/selection/pssexample.png").uiImage + .constrain { + x = CenterConstraint() + y = 25.percent + width = 90.percent + height = 70.percent + } childOf yesButton + + private val noButton = UIRoundedRectangle(5.0f) + .constrain { + x = CenterConstraint() + 12.percent + y = 40.percent + width = 20.percent + height = 25.percent + color = Color(75, 37, 45, 90).constraint + }.onMouseClickConsumer { + config.customMainMenu = false + coreConfig.find("promptedMainMenu")?.asToggle?.state = true + nextRunnable.run() + }.onMouseEnter { + for (child in this.children) { + child.setColor(Color(200, 200, 200)) + } + }.onMouseLeave { + for (child in this.children) { + child.setColor(Color.white) + } + } childOf transparentBlock + + private val sccExample = ResourceLocation("partlysaneskies", "textures/gui/main_menu/selection/sccexample.png").uiImage + .constrain { + x = CenterConstraint() + y = 25.percent + width = 90.percent + height = 70.percent + } childOf noButton + + private val sccTint = UIBlock() + .constrain { + x = CenterConstraint() + y = CenterConstraint() + width = 100.percent + height = 100.percent + color = Color(0, 0, 0, 100).constraint + } childOf sccExample + + private val noText = UIWrappedText("No, return to the default menu", centered = true) + .constrain { + width = 90.percent + x = CenterConstraint() + y = 10.percent + textScale = 1.textScaledPixels + color = Color.white.constraint + } childOf noButton + + private val timeText = UIWrappedText(centered = true) + .constrain { + x = CenterConstraint() + y = 10.scaledPixels(alignOpposite = true) + color = Color.white.constraint + textScale = 1.textScaledPixels + } childOf transparentBlock + + private val discordText = UIWrappedText("Discord: discord.gg/${PartlySaneSkies.discordCode}") + .constrain { + x = 10.scaledPixels + y = 10.scaledPixels(alignOpposite = true) + textScale = 1.textScaledPixels + color = Color(69, 79, 191).constraint + }.onMouseClick { + SystemUtils.openLink("https://discord.gg/${PartlySaneSkies.discordCode}") + } childOf transparentBlock + + private val partlySaneSkiesText = UIWrappedText("Made by: Partly Sane Skies") + .constrain { + x = 10.scaledPixels(alignOpposite = true) + y = 10.scaledPixels(alignOpposite = true) + textScale = 1.textScaledPixels + color = ThemeManager.accentColor.toJavaColor().constraint + }.onMouseClick { + SystemUtils.openLink("https://github.com/PartlySaneStudios/partly-sane-skies") + } childOf transparentBlock override fun onDrawScreen(matrixStack: UMatrixStack, mouseX: Int, mouseY: Int, partialTicks: Float) { super.onDrawScreen(matrixStack, mouseX, mouseY, partialTicks) diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/gui/mainmenu/PSSMainMenu.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/gui/mainmenu/PSSMainMenu.kt index c74d31f91..0f4c3f56e 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/gui/mainmenu/PSSMainMenu.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/gui/mainmenu/PSSMainMenu.kt @@ -38,8 +38,10 @@ import me.partlysanestudios.partlysaneskies.data.pssdata.PublicDataManager import me.partlysanestudios.partlysaneskies.features.security.PrivacyMode.enablePrivacyMode import me.partlysanestudios.partlysaneskies.features.themes.ThemeManager.accentColor import me.partlysanestudios.partlysaneskies.render.gui.constraints.ScaledPixelConstraint.Companion.scaledPixels +import me.partlysanestudios.partlysaneskies.render.gui.constraints.TextScaledPixelConstraint.Companion.textScaledPixels import me.partlysanestudios.partlysaneskies.utils.ElementaUtils.uiImage import me.partlysanestudios.partlysaneskies.utils.MathUtils.randInt +import me.partlysanestudios.partlysaneskies.utils.StringUtils.lastUsedColorCode import me.partlysanestudios.partlysaneskies.utils.SystemUtils import me.partlysanestudios.partlysaneskies.utils.SystemUtils.log import net.minecraft.client.audio.PositionedSoundRecord @@ -72,13 +74,11 @@ class PSSMainMenu : WindowScreen(ElementaVersion.V5) { enablePrivacyMode() } - if (config.privacyMode == 1) { enablePrivacyMode() } if (Loader.isModLoaded("skyclientcosmetics") && coreConfig.find("promptedMainMenu")?.asBoolean != true) { event.setCanceled(true) - coreConfig.find("promptedMainMenu")?.asToggle?.state = true minecraft.displayGuiScreen(MainMenuOptionMenu { minecraft.displayGuiScreen(GuiMainMenu()) }) minecraft.soundHandler.playSound(PositionedSoundRecord.create(ResourceLocation("partlysaneskies", "bell"))) } else if (config.customMainMenu) { @@ -89,30 +89,35 @@ class PSSMainMenu : WindowScreen(ElementaVersion.V5) { } private var cachedFunFact: FunFact? = null + private fun getFunFact(): FunFact { if (cachedFunFact != null) { return cachedFunFact ?: FunFact("", "") } val url = config.apiUrl + "/v1/pss/funfact" val lock = Lock() - newRequest(GetRequest(url, { request: Request -> - try { - val factInfo = JsonParser().parse(request.getResponse()).getAsJsonObject() - val fact = factInfo["funFact"].asString - log("Response: $factInfo") - log("Fun Fact: $fact") - - cachedFunFact = FunFact("Fact of the Day", fact) - synchronized(lock) { - lock.notifyAll() - } - } catch (e: Exception) { - e.printStackTrace() - synchronized(lock) { - lock.notifyAll() - } - } - })) + newRequest( + GetRequest( + url, + { request: Request -> + try { + val factInfo = JsonParser().parse(request.getResponse()).getAsJsonObject() + val fact = factInfo["funFact"].asString + log("Fun Fact: $fact") + + cachedFunFact = FunFact("Fact of the Day", fact) + synchronized(lock) { + lock.notifyAll() + } + } catch (e: Exception) { + e.printStackTrace() + synchronized(lock) { + lock.notifyAll() + } + } + }, + ), + ) synchronized(lock) { lock.wait() } @@ -125,63 +130,70 @@ class PSSMainMenu : WindowScreen(ElementaVersion.V5) { } } - val backgroundBox = UIBlock().constrain { - width = 100.percent - height = 100.percent - x = CenterConstraint() - y = CenterConstraint() - color = Color(0, 0, 0, 0).constraint - } childOf window - - private val backgroundImage = getBackgroundImage().constrain { - width = 100.percent - height = 100.percent - x = CenterConstraint() - y = CenterConstraint() - } childOf backgroundBox - - private val middleMenuBackground = UIBlock().constrain { - x = 350.scaledPixels - y = CenterConstraint() - height = 100.percent - width = 125.scaledPixels - color = Color(0, 0, 0, 75).constraint - } childOf backgroundImage - - private val topLeftMiddleMenuSide = UIRoundedRectangle(5.0f).constrain { - x = (-2).scaledPixels - y = (-5).scaledPixels - height = 50.scaledPixels - width = 2.scaledPixels - color = accentColor.toJavaColor().constraint - } childOf middleMenuBackground - - private val leftMiddleMenuSide = UIRoundedRectangle(5.0f).constrain { - x = (-2).scaledPixels - y = 50.scaledPixels + 75.scaledPixels + 5.scaledPixels - height = 100.percent - width = 2.scaledPixels - color = accentColor.toJavaColor().constraint - } childOf middleMenuBackground - - private val topRightMiddleMenuSide = UIRoundedRectangle(5.0f).constrain { - x = 100.percent - y = (-5).scaledPixels - height = 50.scaledPixels - width = 2.scaledPixels - color = accentColor.toJavaColor().constraint - } childOf middleMenuBackground - - private val rightMiddleMenuSide = UIRoundedRectangle(5.0f).constrain { - x = 100.percent - y = 50.scaledPixels + 75.scaledPixels + 5.scaledPixels - height = 100.percent - width = 2.scaledPixels - color = accentColor.toJavaColor().constraint - } childOf middleMenuBackground - - private val titleImage = - ResourceLocation("partlysaneskies", "textures/gui/main_menu/title_text.png").uiImage + val backgroundBox = UIBlock() + .constrain { + width = 100.percent + height = 100.percent + x = CenterConstraint() + y = CenterConstraint() + color = Color(0, 0, 0, 0).constraint + } childOf window + + private val backgroundImage = getBackgroundImage() + .constrain { + width = 100.percent + height = 100.percent + x = CenterConstraint() + y = CenterConstraint() + } childOf backgroundBox + + private val middleMenuBackground = UIBlock() + .constrain { + x = 350.scaledPixels + y = CenterConstraint() + height = 100.percent + width = 125.scaledPixels + color = Color(0, 0, 0, 75).constraint + } childOf backgroundImage + + private val topLeftMiddleMenuSide = UIRoundedRectangle(5.0f) + .constrain { + x = (-2).scaledPixels + y = (-5).scaledPixels + height = 50.scaledPixels + width = 2.scaledPixels + color = accentColor.toJavaColor().constraint + } childOf middleMenuBackground + + private val leftMiddleMenuSide = UIRoundedRectangle(5.0f) + .constrain { + x = (-2).scaledPixels + y = 50.scaledPixels + 75.scaledPixels + 5.scaledPixels + height = 100.percent + width = 2.scaledPixels + color = accentColor.toJavaColor().constraint + } childOf middleMenuBackground + + private val topRightMiddleMenuSide = UIRoundedRectangle(5.0f) + .constrain { + x = 100.percent + y = (-5).scaledPixels + height = 50.scaledPixels + width = 2.scaledPixels + color = accentColor.toJavaColor().constraint + } childOf middleMenuBackground + + private val rightMiddleMenuSide = UIRoundedRectangle(5.0f) + .constrain { + x = 100.percent + y = 50.scaledPixels + 75.scaledPixels + 5.scaledPixels + height = 100.percent + width = 2.scaledPixels + color = accentColor.toJavaColor().constraint + } childOf middleMenuBackground + + private val titleImage = ResourceLocation("partlysaneskies", "textures/gui/main_menu/title_text.png") + .uiImage .constrain { x = CenterConstraint() y = 50.scaledPixels @@ -191,9 +203,9 @@ class PSSMainMenu : WindowScreen(ElementaVersion.V5) { private val updateWarning = UIWrappedText( text = "Your version of Partly Sane Skies is out of date.\nPlease update to the latest version", - centered = true + centered = true, ).constrain { - textScale = 2.25.scaledPixels + textScale = 2.25.textScaledPixels x = CenterConstraint() y = 133.scaledPixels width = 700.scaledPixels @@ -202,225 +214,241 @@ class PSSMainMenu : WindowScreen(ElementaVersion.V5) { SystemUtils.openLink("https://github.com/PartlySaneStudios/partly-sane-skies/releases") } childOf middleMenuBackground - private val singlePlayerButton = UIBlock().constrain { - x = CenterConstraint() - y = 200.scaledPixels - height = 40.scaledPixels - width = middleMenuBackground.getWidth().pixels - color = Color(0, 0, 0, 0).constraint - }.onMouseClick { - mc.displayGuiScreen(GuiSelectWorld(this@PSSMainMenu)) - }.onMouseEnter { - for (child in this.children) { - child.setColor(Color(200, 200, 200)) - } - }.onMouseLeave { - for (child in this.children) { - child.setColor(Color.white) - } - } childOf middleMenuBackground - - private val singlePlayerText = UIWrappedText("Singleplayer", centered = true).constrain { - x = CenterConstraint() - y = CenterConstraint() - textScale = 1.scaledPixels - color = Color.white.constraint - }.onMouseEnter { - for (child in this.children) { - child.setColor(Color(200, 200, 200)) - } - }.onMouseLeave { - for (child in this.children) { - child.setColor(Color.white) - } - } childOf singlePlayerButton - - private val multiPlayerButton = UIBlock().constrain { - x = CenterConstraint() - y = 240.scaledPixels - height = 40.scaledPixels - width = middleMenuBackground.getWidth().pixels - color = Color(0, 0, 0, 0).constraint - }.onMouseClick { - mc.displayGuiScreen(GuiMultiplayer(this@PSSMainMenu)) - }.onMouseEnter { - for (child in this.children) { - child.setColor(Color(200, 200, 200)) - } - }.onMouseLeave { - for (child in this.children) { - child.setColor(Color.white) - } - } childOf middleMenuBackground - - private val multiPlayerText = UIWrappedText("Multiplayer", centered = true).constrain { - x = CenterConstraint() - y = CenterConstraint() - textScale = 1.scaledPixels - color = Color.white.constraint - } childOf multiPlayerButton - - private val joinHypixelButton = UIBlock().constrain { - x = CenterConstraint() - y = 280.scaledPixels - height = 40.scaledPixels - width = middleMenuBackground.getWidth().pixels - color = Color(0, 0, 0, 0).constraint - }.onMouseClick { - FMLClientHandler.instance() - .connectToServer(GuiMultiplayer(minecraft.currentScreen), ServerData("tomato", "hypixel.net", false)) - - - }.onMouseEnter { - for (child in this.children) { - child.setColor(Color(200, 200, 200)) - } - }.onMouseLeave { - for (child in this.children) { - child.setColor(Color.white) - } - } childOf middleMenuBackground - - private val joinHypixelText = UIWrappedText("Join Hypixel", centered = true).constrain { - x = CenterConstraint() - y = CenterConstraint() - textScale = 1.scaledPixels - color = Color.white.constraint - } childOf joinHypixelButton - - private val modsButton = UIBlock().constrain { - x = CenterConstraint() - y = 320.scaledPixels - height = 40.scaledPixels - width = middleMenuBackground.getWidth().pixels - color = Color(0, 0, 0, 0).constraint - }.onMouseClick { - mc.displayGuiScreen(GuiModList(this@PSSMainMenu)) - }.onMouseEnter { - for (child in this.children) { - child.setColor(Color(200, 200, 200)) - } - }.onMouseLeave { - for (child in this.children) { - child.setColor(Color.white) - } - } childOf middleMenuBackground - - private val modsText = UIWrappedText("Mods", centered = true).constrain { - x = CenterConstraint() - y = CenterConstraint() - textScale = 1.scaledPixels - color = Color.white.constraint - } childOf modsButton - - private val optionsButton = UIBlock().constrain { - x = CenterConstraint() - y = 380.scaledPixels - height = 20.scaledPixels - width = 100.percent - color = Color(0, 0, 0, 0).constraint - }.onMouseClick { - mc.displayGuiScreen(GuiOptions(this@PSSMainMenu, mc.gameSettings)) - }.onMouseEnter { - for (child in this.children) { - child.setColor(Color(200, 200, 200)) - } - }.onMouseLeave { - for (child in this.children) { - child.setColor(Color.white) - } - } childOf middleMenuBackground - - private val optionsText = UIWrappedText("Options", centered = true).constrain { - x = CenterConstraint() - y = CenterConstraint() - textScale = 1.scaledPixels - color = Color.white.constraint - } childOf optionsButton - - private val optionsDivide = UIRoundedRectangle(5.0f).constrain { - x = CenterConstraint() - y = 400.scaledPixels - height = 1.scaledPixels - width = 90.percent - color = accentColor.toJavaColor().constraint - } childOf middleMenuBackground - - private val pssOptionsButton = UIBlock().constrain { - x = CenterConstraint() - y = 400.scaledPixels - height = 20.scaledPixels - width = 100.percent - color = Color(0, 0, 0, 0).constraint - }.onMouseClick { - config.openGui() - }.onMouseEnter { - for (child in this.children) { - child.setColor(Color(200, 200, 200)) - } - }.onMouseLeave { - for (child in this.children) { - child.setColor(Color.white) - } - } childOf middleMenuBackground - - private val pssOptionsText = UIWrappedText("Partly Sane Skies Config", centered = true).constrain { - x = CenterConstraint() - y = CenterConstraint() - textScale = 0.735.scaledPixels - color = Color.white.constraint - } childOf pssOptionsButton - - private val quitButton = UIBlock().constrain { - x = CenterConstraint() - y = 440.scaledPixels - height = 40.scaledPixels - width = 100.percent - color = Color(0, 0, 0, 0).constraint - }.onMouseClick { - mc.shutdown() - }.onMouseEnter { - for (child in this.children) { - child.setColor(Color(200, 200, 200)) - } - }.onMouseLeave { - for (child in this.children) { - child.setColor(Color.white) - } - } childOf middleMenuBackground - - private val quitText = UIWrappedText("Quit", centered = true).constrain { - x = CenterConstraint() - y = CenterConstraint() - textScale = 1.scaledPixels - color = Color.white.constraint - } childOf quitButton - - private val timeText = UIWrappedText(centered = true).constrain { - x = CenterConstraint() - y = (100.percent - 10.scaledPixels) - color = Color.white.constraint - textScale = 0.5.scaledPixels - } childOf middleMenuBackground - - private val discordText = UIWrappedText("Discord: discord.gg/$discordCode").constrain { - x = 10.scaledPixels - y = 10.scaledPixels(alignOpposite = true) - textScale = 1.scaledPixels - color = Color(69, 79, 191).constraint - }.onMouseClick { - SystemUtils.openLink("https://discord.gg/$discordCode") - } childOf backgroundImage - - private val partlySaneSkiesText = UIWrappedText("Made by: Partly Sane Skies").constrain { - x = 10.scaledPixels(alignOpposite = true) - y = 10.scaledPixels(alignOpposite = true) - textScale = 1.scaledPixels - color = accentColor.toJavaColor().constraint - }.onMouseClick { - SystemUtils.openLink("https://github.com/PartlySaneStudios/partly-sane-skies") - } childOf backgroundImage - + private val singlePlayerButton = UIBlock() + .constrain { + x = CenterConstraint() + y = 200.scaledPixels + height = 40.scaledPixels + width = middleMenuBackground.getWidth().pixels + color = Color(0, 0, 0, 0).constraint + }.onMouseClick { + mc.displayGuiScreen(GuiSelectWorld(this@PSSMainMenu)) + }.onMouseEnter { + for (child in this.children) { + child.setColor(Color(200, 200, 200)) + } + }.onMouseLeave { + for (child in this.children) { + child.setColor(Color.white) + } + } childOf middleMenuBackground + + private val singlePlayerText = UIWrappedText("Singleplayer", centered = true) + .constrain { + x = CenterConstraint() + y = CenterConstraint() + textScale = 1.textScaledPixels + color = Color.white.constraint + }.onMouseEnter { + for (child in this.children) { + child.setColor(Color(200, 200, 200)) + } + }.onMouseLeave { + for (child in this.children) { + child.setColor(Color.white) + } + } childOf singlePlayerButton + + private val multiPlayerButton = UIBlock() + .constrain { + x = CenterConstraint() + y = 240.scaledPixels + height = 40.scaledPixels + width = middleMenuBackground.getWidth().pixels + color = Color(0, 0, 0, 0).constraint + }.onMouseClick { + mc.displayGuiScreen(GuiMultiplayer(this@PSSMainMenu)) + }.onMouseEnter { + for (child in this.children) { + child.setColor(Color(200, 200, 200)) + } + }.onMouseLeave { + for (child in this.children) { + child.setColor(Color.white) + } + } childOf middleMenuBackground + + private val multiPlayerText = UIWrappedText("Multiplayer", centered = true) + .constrain { + x = CenterConstraint() + y = CenterConstraint() + textScale = 1.textScaledPixels + color = Color.white.constraint + } childOf multiPlayerButton + + private val joinHypixelButton = UIBlock() + .constrain { + x = CenterConstraint() + y = 280.scaledPixels + height = 40.scaledPixels + width = middleMenuBackground.getWidth().pixels + color = Color(0, 0, 0, 0).constraint + }.onMouseClick { + FMLClientHandler + .instance() + .connectToServer(GuiMultiplayer(minecraft.currentScreen), ServerData("tomato", "hypixel.net", false)) + }.onMouseEnter { + for (child in this.children) { + child.setColor(Color(200, 200, 200)) + } + }.onMouseLeave { + for (child in this.children) { + child.setColor(Color.white) + } + } childOf middleMenuBackground + + private val joinHypixelText = UIWrappedText("Join Hypixel", centered = true) + .constrain { + x = CenterConstraint() + y = CenterConstraint() + textScale = 1.textScaledPixels + color = Color.white.constraint + } childOf joinHypixelButton + + private val modsButton = UIBlock() + .constrain { + x = CenterConstraint() + y = 320.scaledPixels + height = 40.scaledPixels + width = middleMenuBackground.getWidth().pixels + color = Color(0, 0, 0, 0).constraint + }.onMouseClick { + mc.displayGuiScreen(GuiModList(this@PSSMainMenu)) + }.onMouseEnter { + for (child in this.children) { + child.setColor(Color(200, 200, 200)) + } + }.onMouseLeave { + for (child in this.children) { + child.setColor(Color.white) + } + } childOf middleMenuBackground + + private val modsText = UIWrappedText("Mods", centered = true) + .constrain { + x = CenterConstraint() + y = CenterConstraint() + textScale = 1.textScaledPixels + color = Color.white.constraint + } childOf modsButton + + private val optionsButton = UIBlock() + .constrain { + x = CenterConstraint() + y = 380.scaledPixels + height = 20.scaledPixels + width = 100.percent + color = Color(0, 0, 0, 0).constraint + }.onMouseClick { + mc.displayGuiScreen(GuiOptions(this@PSSMainMenu, mc.gameSettings)) + }.onMouseEnter { + for (child in this.children) { + child.setColor(Color(200, 200, 200)) + } + }.onMouseLeave { + for (child in this.children) { + child.setColor(Color.white) + } + } childOf middleMenuBackground + + private val optionsText = UIWrappedText("Options", centered = true) + .constrain { + x = CenterConstraint() + y = CenterConstraint() + textScale = 1.textScaledPixels + color = Color.white.constraint + } childOf optionsButton + + private val optionsDivide = UIRoundedRectangle(5.0f) + .constrain { + x = CenterConstraint() + y = 400.scaledPixels + height = 1.scaledPixels + width = 90.percent + color = accentColor.toJavaColor().constraint + } childOf middleMenuBackground + + private val pssOptionsButton = UIBlock() + .constrain { + x = CenterConstraint() + y = 400.scaledPixels + height = 20.scaledPixels + width = 100.percent + color = Color(0, 0, 0, 0).constraint + }.onMouseClick { + config.openGui() + }.onMouseEnter { + for (child in this.children) { + child.setColor(Color(200, 200, 200)) + } + }.onMouseLeave { + for (child in this.children) { + child.setColor(Color.white) + } + } childOf middleMenuBackground + + private val pssOptionsText = UIWrappedText("Partly Sane Skies Config", centered = true) + .constrain { + x = CenterConstraint() + y = CenterConstraint() + textScale = 0.735.textScaledPixels + color = Color.white.constraint + } childOf pssOptionsButton + + private val quitButton = UIBlock() + .constrain { + x = CenterConstraint() + y = 440.scaledPixels + height = 40.scaledPixels + width = 100.percent + color = Color(0, 0, 0, 0).constraint + }.onMouseClick { + mc.shutdown() + }.onMouseEnter { + for (child in this.children) { + child.setColor(Color(200, 200, 200)) + } + }.onMouseLeave { + for (child in this.children) { + child.setColor(Color.white) + } + } childOf middleMenuBackground + + private val quitText = UIWrappedText("Quit", centered = true) + .constrain { + x = CenterConstraint() + y = CenterConstraint() + textScale = 1.textScaledPixels + color = Color.white.constraint + } childOf quitButton + + private val timeText = UIWrappedText(centered = true) + .constrain { + x = CenterConstraint() + y = (100.percent - 10.scaledPixels) + color = Color.white.constraint + textScale = 0.5.scaledPixels + } childOf middleMenuBackground + + private val discordText = UIWrappedText("Discord: discord.gg/$discordCode") + .constrain { + x = 10.scaledPixels + y = 10.scaledPixels(alignOpposite = true) + textScale = 1.textScaledPixels + color = Color(69, 79, 191).constraint + }.onMouseClick { + SystemUtils.openLink("https://discord.gg/$discordCode") + } childOf backgroundImage + + private val partlySaneSkiesText = UIWrappedText("Made by: Partly Sane Skies") + .constrain { + x = 10.scaledPixels(alignOpposite = true) + y = 10.scaledPixels(alignOpposite = true) + textScale = 1.textScaledPixels + color = accentColor.toJavaColor().constraint + }.onMouseClick { + SystemUtils.openLink("https://github.com/PartlySaneStudios/partly-sane-skies") + } childOf backgroundImage private fun getBackgroundImage(): UIImage { val images = arrayOf( @@ -430,16 +458,17 @@ class PSSMainMenu : WindowScreen(ElementaVersion.V5) { "image_3.png", "image_4.png", "image_5.png", - "image_6.png" + "image_6.png", ) - val image: String = if (config.customMainMenuImage == 0) { - "textures/gui/main_menu/" + images[randInt(1, images.size - 1)] - } else if (config.customMainMenuImage < 7) { - "textures/gui/main_menu/" + images[config.customMainMenuImage] - } else { - "" - } + val image: String = + if (config.customMainMenuImage == 0) { + "textures/gui/main_menu/" + images[randInt(1, images.size - 1)] + } else if (config.customMainMenuImage < 7) { + "textures/gui/main_menu/" + images[config.customMainMenuImage] + } else { + "" + } return if (config.customMainMenuImage == 7) { UIImage.ofFile(File("./config/partly-sane-skies/background.png")) @@ -484,27 +513,28 @@ class PSSMainMenu : WindowScreen(ElementaVersion.V5) { displayAnnouncements(0.percent, 100.percent + 32.scaledPixels, funFact.descriptionComponent ?: parent) } - } } private class Lock : Object() private fun createFunFact(funFact: FunFact, startX: XConstraint, startY: YConstraint, parent: UIComponent) { - val funFactHeading = UIWrappedText().constrain { - x = startX - y = startY - width = 300.scaledPixels - textScale = 1.5.scaledPixels - } childOf parent + val funFactHeading = + UIWrappedText().constrain { + x = startX + y = startY + width = 300.scaledPixels + textScale = 1.5.textScaledPixels + } childOf parent funFactHeading.setText("§e${funFact.title}") - val funFactText = UIWrappedText().constrain { - x = 0.percent - y = 100.percent + 5.scaledPixels - width = 100.percent - textScale = 1.33.scaledPixels - } childOf funFactHeading + val funFactText = + UIWrappedText().constrain { + x = 0.percent + y = 100.percent + 5.scaledPixels + width = 100.percent + textScale = 1.33.textScaledPixels + } childOf funFactHeading funFactText.setText("§7${funFact.description}") funFact.titleComponent = funFactHeading @@ -538,12 +568,11 @@ class PSSMainMenu : WindowScreen(ElementaVersion.V5) { }.start() } - private fun createAnnouncements( announcements: ArrayList, startX: XConstraint, startY: YConstraint, - startParent: UIComponent + startParent: UIComponent, ) { val padY = 25.scaledPixels var parent = startParent @@ -555,20 +584,22 @@ class PSSMainMenu : WindowScreen(ElementaVersion.V5) { x = xConstraint y = yConstraint width = 300.scaledPixels - textScale = 1.5.scaledPixels + textScale = 1.5.textScaledPixels }.setText( - "§e${announcement.title}" + "§e${announcement.title}", ).onMouseClick { SystemUtils.openLink(announcement.link) } childOf parent + val lastColor = announcement.description.lastUsedColorCode() ?: "§7" + val description = UIWrappedText().constrain { x = 0.percent y = 100.percent + 5.scaledPixels width = 100.percent - textScale = 1.33.scaledPixels + textScale = 1.33.textScaledPixels }.setText( - "§8${announcement.date}§r\n§7${announcement.description}" + "§8${announcement.date}§r\n§7${announcement.description.replace("\n", "\n$lastColor")}", ).onMouseClick { SystemUtils.openLink(announcement.link) } childOf title diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/information/WikiArticleOpener.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/information/WikiArticleOpener.kt index f579a6449..ae266ac1a 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/information/WikiArticleOpener.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/information/WikiArticleOpener.kt @@ -7,6 +7,8 @@ package me.partlysanestudios.partlysaneskies.features.information import me.partlysanestudios.partlysaneskies.PartlySaneSkies.Companion.config import me.partlysanestudios.partlysaneskies.PartlySaneSkies.Companion.minecraft +import me.partlysanestudios.partlysaneskies.events.SubscribePSSEvent +import me.partlysanestudios.partlysaneskies.events.minecraft.PSSChatEvent import me.partlysanestudios.partlysaneskies.features.economy.auctionhousemenu.AuctionHouseGui import me.partlysanestudios.partlysaneskies.utils.HypixelUtils.getItemId import me.partlysanestudios.partlysaneskies.utils.HypixelUtils.isSkyblock @@ -14,27 +16,24 @@ import me.partlysanestudios.partlysaneskies.utils.StringUtils.removeColorCodes import me.partlysanestudios.partlysaneskies.utils.SystemUtils.openLink import net.minecraft.client.gui.inventory.GuiContainer import net.minecraft.item.ItemStack -import net.minecraftforge.client.event.ClientChatReceivedEvent -import net.minecraftforge.fml.common.eventhandler.SubscribeEvent object WikiArticleOpener { - private var isWaitingForArticle = false - @SubscribeEvent - fun openArticle(e: ClientChatReceivedEvent) { + @SubscribePSSEvent + fun onChat(e: PSSChatEvent) { if (!isWaitingForArticle) { return } - if (e.message.formattedText.removeColorCodes().contains("Invalid")) { + if (e.component.unformattedText.contains("Invalid")) { isWaitingForArticle = false return } - if (!e.message.formattedText.removeColorCodes().contains("Click HERE")) { + if (!e.component.unformattedText.removeColorCodes().contains("Click HERE")) { return } isWaitingForArticle = false - val wikiLink = e.message.chatStyle.chatClickEvent.value + val wikiLink = e.component.chatStyle.chatClickEvent.value if (config.openWikiAutomatically) { openLink(wikiLink) } @@ -77,3 +76,4 @@ object WikiArticleOpener { // Nearly forgot camo. Camo is now in kt (even better than full hd) - Su386 +// hi ca_mo!!! - empa diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/gui/hud/rngdropbanner/Drop.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/items/rngdrop/Drop.kt similarity index 67% rename from src/main/kotlin/me/partlysanestudios/partlysaneskies/features/gui/hud/rngdropbanner/Drop.kt rename to src/main/kotlin/me/partlysanestudios/partlysaneskies/features/items/rngdrop/Drop.kt index 78c8fa276..8f32f2e93 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/gui/hud/rngdropbanner/Drop.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/items/rngdrop/Drop.kt @@ -3,9 +3,10 @@ // See LICENSE for copyright and license notices. // -package me.partlysanestudios.partlysaneskies.features.gui.hud.rngdropbanner -import me.partlysanestudios.partlysaneskies.PartlySaneSkies.Companion.time +package me.partlysanestudios.partlysaneskies.features.items.rngdrop + +import me.partlysanestudios.partlysaneskies.PartlySaneSkies import me.partlysanestudios.partlysaneskies.data.skyblockdata.Rarity import java.awt.Color @@ -20,5 +21,5 @@ class Drop( var displayTime = 0 val isStillDisplay: Boolean - get() = timeDropped + displayTime < time + get() = timeDropped + displayTime < PartlySaneSkies.time } diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/gui/hud/rngdropbanner/DropWebhook.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/items/rngdrop/DropWebhook.kt similarity index 77% rename from src/main/kotlin/me/partlysanestudios/partlysaneskies/features/gui/hud/rngdropbanner/DropWebhook.kt rename to src/main/kotlin/me/partlysanestudios/partlysaneskies/features/items/rngdrop/DropWebhook.kt index 0caed4d03..847814b28 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/gui/hud/rngdropbanner/DropWebhook.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/items/rngdrop/DropWebhook.kt @@ -4,7 +4,7 @@ // -package me.partlysanestudios.partlysaneskies.features.gui.hud.rngdropbanner +package me.partlysanestudios.partlysaneskies.features.items.rngdrop import gg.essential.elementa.constraints.CenterConstraint import gg.essential.elementa.dsl.constrain @@ -38,10 +38,25 @@ object DropWebhook : Webhook() { override val description: String = "Automatically send a Discord message\nwhenever a rare item has dropped" init { - val rarities = arrayOf(Rarity.COMMON, Rarity.UNCOMMON, Rarity.RARE, Rarity.EPIC, Rarity.LEGENDARY, Rarity.MYTHIC, Rarity.DIVINE) + val rarities = arrayOf( + Rarity.COMMON, + Rarity.UNCOMMON, + Rarity.RARE, + Rarity.EPIC, + Rarity.LEGENDARY, + Rarity.MYTHIC, + Rarity.DIVINE + ) for (rarity in rarities) { val displayName = rarity.displayName - config.registerOption("send$displayName", Toggle("Send $displayName Drops", "Allow the webhook to send drops of ${displayName.lowercase()} rarity.", true)) + config.registerOption( + "send$displayName", + Toggle( + "Send $displayName Drops", + "Allow the webhook to send drops of ${displayName.lowercase()} rarity.", + true + ), + ) } } @@ -56,11 +71,7 @@ object DropWebhook : Webhook() { val name = drop.name val description = "${drop.magicFind}% ✯ Magic Find!" - val color = if (drop.dropRarity == Rarity.UNKNOWN) { - Color.white.asHex - } else { - drop.dropRarity.colorCode.colorCodeToColor().asHex - } + val color = if (drop.dropRarity == Rarity.UNKNOWN) Color.white.asHex else drop.dropRarity.colorCode.colorCodeToColor().asHex WebhookData( url = PartlySaneSkies.config.discordWebhookURL, @@ -69,7 +80,8 @@ object DropWebhook : Webhook() { EmbedData( title = title, color = color, - fields = listOf( + fields = + listOf( EmbedField( name = name, value = description, diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/items/rngdrop/RareDropGUI.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/items/rngdrop/RareDropGUI.kt new file mode 100644 index 000000000..53bc5c0a7 --- /dev/null +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/items/rngdrop/RareDropGUI.kt @@ -0,0 +1,369 @@ +// +// Written by J10a1n15 and Su386. +// See LICENSE for copyright and license notices. +// + + +package me.partlysanestudios.partlysaneskies.features.items.rngdrop + +import gg.essential.elementa.ElementaVersion +import gg.essential.elementa.WindowScreen +import gg.essential.elementa.components.ScrollComponent +import gg.essential.elementa.components.UIBlock +import gg.essential.elementa.components.UIWrappedText +import gg.essential.elementa.components.input.UITextInput +import gg.essential.elementa.constraints.CenterConstraint +import gg.essential.elementa.constraints.CramSiblingConstraint +import gg.essential.elementa.constraints.SiblingConstraint +import gg.essential.elementa.dsl.childOf +import gg.essential.elementa.dsl.constrain +import gg.essential.elementa.dsl.constraint +import gg.essential.elementa.dsl.percent +import gg.essential.elementa.dsl.pixels +import gg.essential.elementa.dsl.plus +import me.partlysanestudios.partlysaneskies.data.skyblockdata.Rarity +import me.partlysanestudios.partlysaneskies.data.skyblockdata.SkyblockDataManager +import me.partlysanestudios.partlysaneskies.features.items.rngdrop.RareDropGUIManager.currentFilter +import me.partlysanestudios.partlysaneskies.features.items.rngdrop.RareDropGUIManager.currentFilterType +import me.partlysanestudios.partlysaneskies.features.themes.ThemeManager +import me.partlysanestudios.partlysaneskies.render.gui.components.PSSButton +import me.partlysanestudios.partlysaneskies.render.gui.constraints.ScaledPixelConstraint.Companion.scaledPixels +import me.partlysanestudios.partlysaneskies.render.gui.constraints.TextScaledPixelConstraint.Companion.textScaledPixels +import me.partlysanestudios.partlysaneskies.utils.ImageUtils.minus +import me.partlysanestudios.partlysaneskies.utils.StringUtils.colorCodeToColor +import org.lwjgl.input.Keyboard +import java.awt.Color + +class RareDropGUI : WindowScreen(ElementaVersion.V5) { + private val backgroundBox = UIBlock().constrain { + width = 75.percent + height = 75.percent + x = CenterConstraint() + y = CenterConstraint() + color = Color(0, 0, 0, 0).constraint + } childOf window + + /** + * Create Filter Container + */ + private val createFilterContainer = ThemeManager.currentBackgroundUIImage.constrain { + width = 60.percent + height = 75.percent + x = 40.percent + y = 0.percent + } childOf backgroundBox + + private val createFiltersHeading = UIWrappedText("Create Filters:").constrain { + width = 90.percent + x = 5.percent + y = 2.percent + textScale = 2.5.textScaledPixels + color = Color.lightGray.constraint + } childOf createFilterContainer + + private val createFiltersSearchBar = UITextInput("Search Items...").constrain { + width = 90.percent + height = 3.percent + x = 5.percent + y = SiblingConstraint() + 2.percent + textScale = 1.5.textScaledPixels + color = Color.gray.constraint + }.onMouseClick { + grabWindowFocus() + }.onKeyType {_, key -> + if (key == Keyboard.KEY_NUMPADENTER || key == Keyboard.KEY_RETURN){ + val text = (this as UITextInput).getText() + if (text.isBlank()) return@onKeyType + RareDropGUIManager.addFilter(text) + this.setText("") + updateFilterList() + } + + this.setColor(Color.lightGray) + + updateCreateFilterAutocomplete() + }.onMouseEnter { + this.setColor(Color.lightGray) + }.onMouseLeave { + if ((this as UITextInput).getText().isEmpty()) { + this.setColor(Color.gray) + } + } as UITextInput childOf createFilterContainer + + private val createFilterButton = PSSButton() + .setText("Add to ${currentFilterType.displayName} Filter") + .setX(CramSiblingConstraint() + 5.percent) + .setY(CramSiblingConstraint() + 2.percent) + .setHeight(50.scaledPixels) + .setWidth(60.scaledPixels) + .setChildOf(createFilterContainer) + .onMouseClickConsumer { + val text = createFiltersSearchBar.getText() + if (text.isBlank()) return@onMouseClickConsumer + RareDropGUIManager.addFilter(text) + createFiltersSearchBar.setText("") + updateFilterList() + } + + private var opposite = RareDropGUIManager.FilterType.entries.first { it != currentFilterType } + private val switchTypeButton = PSSButton() + .setText("Switch to ${opposite.displayName}") + .setX(CramSiblingConstraint() + 2.percent) + .setY(CramSiblingConstraint()) + .setHeight(50.scaledPixels) + .setWidth(90.scaledPixels) + .setChildOf(createFilterContainer) + .onMouseClickConsumer { + currentFilterType = opposite + opposite = RareDropGUIManager.FilterType.entries.first { it != currentFilterType } + RareDropGUIManager.saveData() + update() + } + + private val autoCompleteScrollComponent = ScrollComponent().constrain { + x = CenterConstraint() + y = SiblingConstraint() + 2.percent + width = 90.percent + height = 70.percent + color = Color.red.constraint + } childOf createFilterContainer + + /** + * Active Filter Container + */ + private val activeFiltersContainer = ThemeManager.currentBackgroundUIImage.constrain { + width = 35.percent + height = 100.percent + x = 0.percent + y = 0.percent + } childOf backgroundBox + + private val activeFiltersHeading = UIWrappedText("Active ${currentFilterType.displayName} Filters:").constrain { + width = 90.percent + x = 5.percent + y = 2.percent + textScale = 2.5.textScaledPixels + color = Color.green.constraint + } childOf activeFiltersContainer + + private val activeFiltersSearchBar: UITextInput = UITextInput("Search Filters...").constrain { + width = 90.percent + height = 3.percent + x = 5.percent + y = SiblingConstraint() + 2.percent + textScale = 1.5.textScaledPixels + color = Color.gray.constraint + }.onMouseClick { + grabWindowFocus() + }.onKeyType { _, _ -> + updateFilterList() + }.onMouseEnter { + this.setColor(Color.lightGray) + }.onMouseLeave { + if ((this as UITextInput).getText().isEmpty()) { + this.setColor(Color.gray) + } + } as UITextInput childOf activeFiltersContainer + + private val activeFiltersScrollComponent = ScrollComponent( + scrollIconColor = ThemeManager.primaryColor.toJavaColor(), + innerPadding = 10f, + ).constrain { + width = 100.percent + height = 90.percent + x = 0.percent + y = SiblingConstraint() + 1.percent + } childOf activeFiltersContainer + + + /** + * Presets Container + */ + private val presetsContainer = ThemeManager.currentBackgroundUIImage.constrain { + width = 60.percent + height = 20.percent + x = 40.percent + y = 80.percent + } childOf backgroundBox + + private val presetsHeading = UIWrappedText("Add Bulk Items:").constrain { + x = 4.percent + y = 10.percent + width = 92.percent + textScale = 1.5.textScaledPixels + color = Color.green.constraint + } childOf presetsContainer + + private val presetButtons = RareDropGUIManager.presets.forEachIndexed { columnIndex, (presetName, items) -> + PSSButton() + .setText(presetName) + .setX((15 * columnIndex + 5).percent) + .setY(CenterConstraint() + 10.percent) + .setHeight(50.scaledPixels) + .setWidth(60.scaledPixels) + .setChildOf(presetsContainer) + .onMouseClickConsumer { + RareDropGUIManager.addFilter(*items.toTypedArray()) + updateFilterList() + } + } + + init { + update() + } + + private fun createAutoCompletedItem(itemName: String, itemColor: Color) { + val boundingBox = UIBlock().constrain { + x = CramSiblingConstraint(10f) + y = CramSiblingConstraint(10f) + width = 48.percent + height = 8.5.percent + color = Color(0, 0, 0, 0).constraint + } childOf autoCompleteScrollComponent + + + val text = UIWrappedText(itemName).constrain { + x = 0.pixels + y = CenterConstraint() + width = 100.percent + textScale = 1.5.textScaledPixels + color = itemColor.constraint + } + + val textHitbox = UIBlock().constrain { + x = 0.pixels + y = CenterConstraint() + width = 90.percent + height = 100.percent + color = Color(0, 0, 0, 0).constraint + }.onMouseClick { + if (it.mouseButton != 0) { + return@onMouseClick + } + + RareDropGUIManager.addFilter(itemName) + updateFilterList() + }.onMouseEnter { + text.setColor(itemColor - Color(66, 66, 66)) + }.onMouseLeave { + text.setColor(itemColor) + } childOf boundingBox + + text childOf textHitbox + + val fillArrow = UIWrappedText("↖", centered = true).constrain { + x = 0.pixels(alignOpposite = true) + y = CenterConstraint() + width = 10.percent + height = 100.percent + textScale = 3.textScaledPixels + color = Color.lightGray.constraint + }.onMouseClick { + if (it.mouseButton != 0) { + return@onMouseClick + } + createFiltersSearchBar.setText(itemName) + updateCreateFilterAutocomplete() + }.onMouseEnter { + this.setColor(Color.gray) + }.onMouseLeave { + this.setColor(Color.lightGray) + } childOf boundingBox + } + + private fun updateCreateFilterAutocomplete() { + autoCompleteScrollComponent.clearChildren() + val searchText = createFiltersSearchBar.getText() + + createFiltersSearchBar.setColor(if (searchText.isBlank()) Color.gray else Color.lightGray) + + val addedNames = mutableSetOf() + + SkyblockDataManager.getAllItems() + .asSequence() + .mapNotNull { id -> + SkyblockDataManager.getItem(id)?.takeIf { + id.contains(searchText, ignoreCase = true) || it.name.contains(searchText, ignoreCase = true) + }?.let { item -> + item.name to if (item.rarity == Rarity.UNKNOWN) { + Color.white + } else { + item.rarity.colorCode.colorCodeToColor() + } + } + } + .sortedBy { it.first } + .filter { (name, _) -> + addedNames.add(name) + } + .take(100) + .forEach { (name, color) -> + createAutoCompletedItem(name, color) + } + } + + private fun update() { + updateFilterList() + updateTitles() + updateCreateFilterAutocomplete() + } + + private fun updateTitles() { + activeFiltersHeading.setText("Active ${currentFilterType.displayName} Filters:") + createFilterButton.setText("Add to ${currentFilterType.displayName}") + switchTypeButton.setText("Switch to ${opposite.displayName} Mode") + } + + private fun updateFilterList() { + activeFiltersScrollComponent.clearChildren() + + if (activeFiltersSearchBar.getText().isBlank()) { + activeFiltersSearchBar.setColor(Color.gray) + } else { + activeFiltersSearchBar.setColor(Color.lightGray) + } + + currentFilter + .filter { it.contains(activeFiltersSearchBar.getText(), ignoreCase = true) } + .forEach { filter -> + val box = UIBlock() childOf activeFiltersScrollComponent + val xText = UIWrappedText("§cx", centered = true).constrain { + x = 0.pixels + y = CenterConstraint() + width = 10.percent + textScale = 1.5.textScaledPixels + } childOf box + + val filterText = UIWrappedText(filter).constrain { + x = SiblingConstraint(4f) + y = CenterConstraint() + textScale = 1.5.textScaledPixels + width = 90.percent + } childOf box + + box.constrain { + x = 0.percent + y = SiblingConstraint(4f) + height = 4.percent + width = 90.percent + color = Color(0, 0, 0, 0).constraint + }.onMouseClick { + currentFilter -= filter + RareDropGUIManager.saveData() + updateFilterList() + }.onMouseEnter { + filterText.setText("§m$filter") + }.onMouseLeave { + filterText.setText(filter) + } + + val id = SkyblockDataManager.getId(filter) + val color = if (id.isNotBlank()) { + SkyblockDataManager.getItem(id)?.rarity?.colorCode?.colorCodeToColor() ?: Color.lightGray + } else { + Color.lightGray + } + filterText.setColor(color) + } + } +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/items/rngdrop/RareDropGUIManager.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/items/rngdrop/RareDropGUIManager.kt new file mode 100644 index 000000000..55aa2054f --- /dev/null +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/items/rngdrop/RareDropGUIManager.kt @@ -0,0 +1,154 @@ +// +// Written by J10a1n15. +// See LICENSE for copyright and license notices. +// + + +package me.partlysanestudios.partlysaneskies.features.items.rngdrop + +import cc.polyfrost.oneconfig.utils.gui.GuiUtils +import com.google.gson.Gson +import com.google.gson.GsonBuilder +import com.google.gson.JsonParser +import me.partlysanestudios.partlysaneskies.commands.PSSCommand +import me.partlysanestudios.partlysaneskies.utils.ChatUtils +import me.partlysanestudios.partlysaneskies.utils.StringUtils.pluralize +import java.io.File +import java.io.FileWriter +import java.io.IOException +import java.io.Reader +import java.nio.file.Files +import java.nio.file.Paths + +object RareDropGUIManager { + + private var filters: MutableMap> = mutableMapOf() + private const val CONFIG_PATH = "./config/partly-sane-skies/rareDropFilters.json" + + var currentFilterType: FilterType = FilterType.BLACKLIST + set(value) { + field = value + saveData() + } + + var currentFilter: Set + get() = filters[currentFilterType] ?: emptySet() + set(value) { + filters[currentFilterType] = value + } + + fun isAllowedDrop(drop: String) = (FilterType.WHITELIST.isEnabled() && currentFilter.contains(drop)) || + (FilterType.BLACKLIST.isEnabled() && !currentFilter.contains(drop)) + + fun registerCommand() { + PSSCommand("raredrop") + .addAlias("rd") + .setDescription("Opens the Rare Drop GUI") + .setRunnable { _ -> + openGui() + } + .register() + } + + fun addFilter(vararg filters: String) { + ChatUtils.sendClientMessage("Added ${"filter".pluralize(filters.size)}") + currentFilter += filters + saveData() + } + + private fun openGui() { + GuiUtils.displayScreen(RareDropGUI()) + } + + val presets = listOf( + RareDropPreset( + "Dungeons", + listOf( + "Conjuring", "Silent Death", "Dreadlord Sword", "Zombie Soldier Cutlass", "Earth Shard", + "Zombie Commander Whip", "Zombie Knight Sword", "Soulstealer Bow", "Sniper Bow", "Machine Gun Shortbow", + "Bouncy Helmet", "Bouncy Chestplate", "Bouncy Leggings", "Bouncy Boots", "Heavy Helmet", "Heavy Chestplate", + "Heavy Leggings", "Heavy Boots", "Rotten Helmet", "Rotten Chestplate", "Rotten Leggings", "Rotten Boots", + "Sniper Helmet", "Skeleton Grunt Helmet", "Skeleton Grunt Chestplate", "Skeleton Grunt Leggings", + "Skeleton Grunt Boots", "Skeleton Lord Helmet", "Skeleton Lord Chestplate", "Skeleton Lord Leggings", + "Skeleton Lord Boots", "Skeleton Master Helmet", "Skeleton Master Chestplate", "Skeleton Master Leggings", + "Skeleton Master Boots", "Skeleton Soldier Helmet", "Skeleton Soldier Chestplate", "Skeleton Soldier Leggings", + "Skeleton Soldier Boots", "Skeletor Helmet", "Skeletor Chestplate", "Skeletor Leggings", "Skeletor Boots", + "Super Heavy Helmet", "Super Heavy Chestplate", "Super Heavy Leggings", "Super Heavy Boots", + "Zombie Commander Helmet", "Zombie Commander Chestplate", "Zombie Commander Leggings", "Zombie Commander Boots", + "Zombie Knight Helmet", "Zombie Knight Chestplate", "Zombie Knight Leggings", "Zombie Knight Boots", + "Zombie Lord Helmet", "Zombie Lord Chestplate", "Zombie Lord Leggings", "Zombie Lord Boots", + "Zombie Soldier Helmet", "Zombie Soldier Chestplate", "Zombie Soldier Leggings", "Zombie Soldier Boots" + ), + ), + RareDropPreset( + "Useless End Drops", + listOf( + "Ender Helmet", "Ender Chestplate", "Ender Leggings", "Ender Boots", "Ender Belt", "Ender Cloak", + "Ender Gauntlet", "Ender Necklace", "Enchanted Ender Pearl", "End Stone Bow", "Ender Monocle", + "Enchanted Eye of Ender", "Enchanted End Stone", "Enchanted Obsidian", + ), + ), + RareDropPreset( + "Useless Garden Drops", + listOf( + "Beady Eyes", "Buzzin' Beats Vinyl", "Cicada Symphony Vinyl", "Clipped Wings", "DynaMITES Vinyl", + "Earthworm Ensemble Vinyl", "Not Just A Pest Vinyl", "Pretty Fly Vinyl", + ), + ), + ) + + enum class FilterType(val displayName: String) { + BLACKLIST("Blacklist"), + WHITELIST("Whitelist"), + ; + + fun isEnabled() = this == currentFilterType + } + + @Throws(IOException::class) + fun saveData() { + val file = File(CONFIG_PATH) + file.createNewFile() + val gson = GsonBuilder() + .setPrettyPrinting() + .serializeSpecialFloatingPointValues() + .create() + + val data = mutableMapOf( + "currentFilterType" to currentFilterType.name, + "filters" to filters, + ) + + val writer = FileWriter(file) + writer.write(gson.toJson(data)) + writer.close() + } + + @Throws(IOException::class) + fun loadData() { + val file = File(CONFIG_PATH) + file.setWritable(true) + + if (file.createNewFile()) { + val writer = FileWriter(file) + writer.write(Gson().toJson(emptyMap())) + writer.close() + } + + val reader: Reader = Files.newBufferedReader(Paths.get(file.path)) + val jsonElement = JsonParser().parse(reader) + reader.close() + + val jsonObject = jsonElement.asJsonObject + + filters = mutableMapOf>().apply { + jsonObject.getAsJsonObject("filters").entrySet().forEach { (key, value) -> + val filterType = FilterType.valueOf(key) + val filterSet = value.asJsonArray.map { it.asString }.toSet() + this[filterType] = filterSet + } + } + + currentFilterType = FilterType.valueOf(jsonObject["currentFilterType"].asString) + } +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/items/rngdrop/RareDropPreset.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/items/rngdrop/RareDropPreset.kt new file mode 100644 index 000000000..a6578e6fb --- /dev/null +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/items/rngdrop/RareDropPreset.kt @@ -0,0 +1,9 @@ +// +// Written by J10a1n15. +// See LICENSE for copyright and license notices. +// + + +package me.partlysanestudios.partlysaneskies.features.items.rngdrop + +data class RareDropPreset(val name: String, val items: List) diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/mining/PickaxeWarning.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/mining/PickaxeWarning.kt index 323683491..49fabcea2 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/mining/PickaxeWarning.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/mining/PickaxeWarning.kt @@ -18,11 +18,10 @@ import net.minecraftforge.client.event.ClientChatReceivedEvent import net.minecraftforge.event.entity.player.PlayerInteractEvent import net.minecraftforge.fml.common.eventhandler.EventPriority import net.minecraftforge.fml.common.eventhandler.SubscribeEvent -import java.util.regex.Pattern object PickaxeWarning { - private val pattern = Pattern.compile("(Mining Speed Boost|Pickobulus|Maniac Miner|Vein Seeker) is now available!") + private val pattern = "(Mining Speed Boost|Pickobulus|Maniac Miner|Vein Seeker|Hazardous Miner|Gemstone Infusion) is now available!".toPattern() private val pickaxeAbilities = arrayOf( "Mining Speed Boost", "Pickobulus", @@ -48,8 +47,8 @@ object PickaxeWarning { config.pickaxeAbilityReadyBannerText, (config.pickaxeBannerTime * 1000).toLong(), 4.0f, - config.pickaxeBannerColor.toJavaColor() - ) + config.pickaxeBannerColor.toJavaColor(), + ), ) } if (config.pickaxeAbilityReadySound) { @@ -81,4 +80,4 @@ object PickaxeWarning { } } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/mining/crystalhollows/WormWarning.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/mining/crystalhollows/WormWarning.kt index a33d24b62..9546b5b1d 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/mining/crystalhollows/WormWarning.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/mining/crystalhollows/WormWarning.kt @@ -8,19 +8,18 @@ package me.partlysanestudios.partlysaneskies.features.mining.crystalhollows import me.partlysanestudios.partlysaneskies.PartlySaneSkies.Companion.config import me.partlysanestudios.partlysaneskies.PartlySaneSkies.Companion.minecraft import me.partlysanestudios.partlysaneskies.PartlySaneSkies.Companion.time +import me.partlysanestudios.partlysaneskies.events.SubscribePSSEvent +import me.partlysanestudios.partlysaneskies.events.minecraft.PSSChatEvent import me.partlysanestudios.partlysaneskies.render.gui.hud.BannerRenderer.renderNewBanner import me.partlysanestudios.partlysaneskies.render.gui.hud.PSSBanner -import net.minecraftforge.client.event.ClientChatReceivedEvent -import net.minecraftforge.fml.common.eventhandler.SubscribeEvent object WormWarning { - private var wormWarningString = "" private var wormWarningBannerTime: Long = 0 - @SubscribeEvent - fun wormWarningChatEvent(event: ClientChatReceivedEvent) { - if (event.message.unformattedText.startsWith("You hear the sound of something approaching...")) { + @SubscribePSSEvent + fun onChat(event: PSSChatEvent) { + if (event.component.unformattedText.startsWith("You hear the sound of something approaching...")) { if (config.wormWarningBanner) { wormWarningBannerTime = time wormWarningString = "A Worm Has Spawned!" @@ -29,8 +28,8 @@ object WormWarning { wormWarningString, (config.wormWarningBannerTime * 1000).toLong(), 3f, - config.wormWarningBannerColor.toJavaColor() - ) + config.wormWarningBannerColor.toJavaColor(), + ), ) } if (config.wormWarningBannerSound) { diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/mining/crystalhollows/gemstonewaypoints/GemstoneData.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/mining/crystalhollows/gemstonewaypoints/GemstoneData.kt index 20a9930cd..f44bfc059 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/mining/crystalhollows/gemstonewaypoints/GemstoneData.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/mining/crystalhollows/gemstonewaypoints/GemstoneData.kt @@ -3,7 +3,6 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.features.mining.crystalhollows.gemstonewaypoints import com.google.gson.JsonObject @@ -19,8 +18,8 @@ import org.apache.logging.log4j.Level import java.awt.Color object GemstoneData { - val map = HashMap>>() + private fun registerLocation(gemstone: Gemstone) { val chunk = gemstone.chunk if (!map.containsKey(chunk)) { @@ -37,21 +36,23 @@ object GemstoneData { @SubscribePSSEvent fun loadJsonData(event: LoadPublicDataEvent) { - Thread({ - val startTime = time - val publicDataResponse = PublicDataManager.getFile("constants/gemstone_locations.json") + Thread( + { + val startTime = time + val publicDataResponse = PublicDataManager.getFile("constants/gemstone_locations.json") // log(Level.INFO, publicDataResponse) - val publicDataArray = JsonParser().parse(publicDataResponse).asJsonArray - - for (element in publicDataArray) { - val gemstone = serializeGemstone(element.asJsonObject) - registerLocation(gemstone) - } + val publicDataArray = JsonParser().parse(publicDataResponse).asJsonArray - val timeElasped = time - startTime - log(Level.INFO, "Loaded all gemstone data in ${timeElasped / 1000.0} seconds") - }, "GemstoneLoadData").start() + for (element in publicDataArray) { + val gemstone = serializeGemstone(element.asJsonObject) + registerLocation(gemstone) + } + val timeElasped = time - startTime + log(Level.INFO, "Loaded all gemstone data in ${timeElasped / 1000.0} seconds") + }, + "GemstoneLoadData", + ).start() } private fun serializeGemstone(gemstoneJson: JsonObject): Gemstone { @@ -68,10 +69,10 @@ object GemstoneData { AMETHYST("Amethyst", Color(0xFF55FF)), AMBER("Amber", Color(0xFFAA00)), JADE("Jade", Color(0x55FF55)), - SAPPHIRE("Sapphire", Color(0x5555FF)) + SAPPHIRE("Sapphire", Color(0x5555FF)), } class Gemstone(val type: GemstoneType, val block: Point3d, val size: Int) { val chunk: Point2d get() = block.toChunk() } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/mining/crystalhollows/gemstonewaypoints/GemstoneWaypointRender.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/mining/crystalhollows/gemstonewaypoints/GemstoneWaypointRender.kt index 0f6028d3e..9dafa9dc6 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/mining/crystalhollows/gemstonewaypoints/GemstoneWaypointRender.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/mining/crystalhollows/gemstonewaypoints/GemstoneWaypointRender.kt @@ -3,7 +3,6 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.features.mining.crystalhollows.gemstonewaypoints import me.partlysanestudios.partlysaneskies.PartlySaneSkies.Companion.config @@ -17,7 +16,6 @@ import me.partlysanestudios.partlysaneskies.utils.geometry.vectors.Point3d import java.awt.Color object GemstoneWaypointRender { - @SubscribePSSEvent fun onWaypointRenderEvent(event: RenderWaypointEvent) { if (!config.renderGemstoneWaypoints) { @@ -70,24 +68,25 @@ object GemstoneWaypointRender { val brightness = config.gemstoneBrightness val originalColor = gemstone.type.color - val darkerColor = Color( - (originalColor.red * brightness).toInt(), - (originalColor.green * brightness).toInt(), - (originalColor.blue * brightness).toInt() - ) - - val waypoint = Waypoint( - "${gemstone.type.displayName} Gemstone | Size: ${gemstone.size}", - gemstone.block.toBlockPos(), - outlineColor = darkerColor.applyOpacity(255), - fillColor = darkerColor.applyOpacity(100), - showBeam = config.showGemstoneBeam - ) + val darkerColor = + Color( + (originalColor.red * brightness).toInt(), + (originalColor.green * brightness).toInt(), + (originalColor.blue * brightness).toInt(), + ) + + val waypoint = + Waypoint( + "${gemstone.type.displayName} Gemstone | Size: ${gemstone.size}", + gemstone.block.toBlockPos(), + outlineColor = darkerColor.applyOpacity(255), + fillColor = darkerColor.applyOpacity(100), + showBeam = config.showGemstoneBeam, + ) event.pipeline.add(waypoint) } } } } - } } diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/mining/events/MiningEvent.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/mining/events/MiningEvent.kt new file mode 100644 index 000000000..82fb3c75b --- /dev/null +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/mining/events/MiningEvent.kt @@ -0,0 +1,160 @@ +// +// Written by J10a1n15. +// See LICENSE for copyright and license notices. +// + + +package me.partlysanestudios.partlysaneskies.features.mining.events + +import me.partlysanestudios.partlysaneskies.PartlySaneSkies.Companion.config + +enum class MiningEvent( + val event: String, + val color: String, + val triggeredEvent: (String) -> Boolean, + val config: () -> Boolean, +) { + POWDER( + "2x Powder", + "§b⚑", + { it.contains("§l2X POWDER STARTED!") }, + { config.mining2xPowderSound }, + ), + POWDER20( + "2x Powder Event in 20s!", + "§b⚑", + { it.contains("The §b2x Powder §eevent starts in §a20 §eseconds!") }, + { config.mining2xPowderSound && config.miningWarn20sBeforeEvent }, + ), + WIND( + "Gone with the Wind", + "§9⚑", + { it.contains("§r§9§lGONE WITH THE WIND STARTED!") }, + { config.miningGoneWithTheWindSound }, + ), + WIND20( + "Gone with the Wind Event in 20s!", + "§9⚑", + { it.contains("The §9Gone with the Wind §eevent starts in §a20 §eseconds!") }, + { config.miningGoneWithTheWindSound && config.miningWarn20sBeforeEvent }, + ), + BETTER_TOGETHER( + "Better Together", + "§d⚑", + { it.contains("§r§d§lBETTER TOGETHER STARTED!") }, + { config.miningBetterTogetherSound }, + ), + BETTER_TOGETHER20( + "Better Together Event in 20s!", + "§d⚑", + { it.contains("The §dBetter Together §eevent starts in §a20 §eseconds!") }, + { config.miningBetterTogetherSound && config.miningWarn20sBeforeEvent }, + ), + RAID( + "Goblin Raid", + "§c⚑", + { it.contains("§r§c§lGOBLIN RAID STARTED!") }, + { config.miningGoblinRaidSound }, + ), + RAID20( + "Goblin Raid Event in 20s!", + "§c⚑", + { it.contains("The §cGoblin Raid §eevent starts in §a20 §eseconds!") }, + { config.miningGoblinRaidSound && config.miningWarn20sBeforeEvent }, + ), + RAFFLE( + "Raffle", + "§6⚑", + { it.contains("§r§6§lRAFFLE STARTED!") }, + { config.miningRaffleSound }, + ), + RAFFLE20( + "Raffle Event in 20s!", + "§6⚑", + { it.contains("The §6Raffle §eevent starts in §a20 §eseconds!") }, + { config.miningRaffleSound && config.miningWarn20sBeforeEvent }, + ), + GOURMAND( + "Mithril Gourmand", + "§b⚑", + { it.contains("§r§b§lMITHRIL GOURMAND STARTED!") }, + { config.miningMithrilGourmandSound }, + ), + GOURMAND20( + "Mithril Gourmand Event in 20s!", + "§b⚑", + { it.contains("The §bMithril Gourmand §eevent starts in §a20 §eseconds!") }, + { config.miningMithrilGourmandSound && config.miningWarn20sBeforeEvent }, + ), + + POWDER_GHAST( + "Powder Ghast", + "§r§6", + { it.contains("§r§6§lPOWDER GHAST!") }, + { config.miningPowderGhastSound }, + ), + FALLEN_STAR( + "Fallen Star", + "§r§5", + { it.contains("§r§5§l✯ §r§eA §r§5Fallen Star §r§ehas crashed at ") }, + { config.miningFallenStarSound }, + ), +} + +/* ALL THE MINING EVENTS RELATED MESSAGES + + **MAJOR EVENTS** + + 2x POWDER + §b⚑ §eThe §b2x Powder §eevent starts in §a20 §eseconds! + §eThis is a passive event! §bIt's happening everywhere in the §bCrystal Hollows!§r + + §r§r§r §r§b§l2X POWDER STARTED!§r + + + WIND + §9⚑ §eThe §9Gone with the Wind §eevent starts in §a20 §eseconds! + §eThis is a passive event! §bIt's happening everywhere in the §bCrystal Hollows!§r + + §r§r§r §r§9§lGONE WITH THE WIND STARTED!§r + + + BETTER TOGETHER + §d⚑ §eThe §dBetter Together §eevent starts in §a20 §eseconds! + §eThis is a passive event! §bIt's happening everywhere in the §bCrystal Hollows!§r + + §r§r§r §r§d§lBETTER TOGETHER STARTED!§r + + + RAID + §c⚑ §eThe §cGoblin Raid §eevent starts in §a20 §eseconds! + §aClick here §eto teleport to §bGarry §eand prepare!§r + + §r§r§r §r§c§lGOBLIN RAID STARTED!§r + + + RAFFLE + §6⚑ §eThe §6Raffle §eevent starts in §a20 §eseconds! + §aClick here §eto teleport to §bGarry §eand prepare!§r + + §r§r§r §r§6§lRAFFLE STARTED!§r + + + GOURMAND + §b⚑ §eThe §bMithril Gourmand §eevent starts in §a20 §eseconds! + §aClick here §eto teleport to §bGarry §eand prepare!§r + + §r§r§r §r§b§lMITHRIL GOURMAND STARTED!§r + + + **MINOR EVENTS** + + POWDER GHAST + §r§6The sound of pickaxes clashing against the rock has attracted the attention of the §r§6§lPOWDER GHAST!§r + §r§eFind the §r§6Powder Ghast§r§e near the §r§bCliffside Veins§r§e!§r + + + FALLEN STAR + §r§5§l✯ §r§eA §r§5Fallen Star §r§ehas crashed at §r§bRoyal Mines§r§e! Nearby ore and Powder drops are amplified!§r + + */ diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/mining/events/MiningEventNotifier.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/mining/events/MiningEventNotifier.kt new file mode 100644 index 000000000..9392105a8 --- /dev/null +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/mining/events/MiningEventNotifier.kt @@ -0,0 +1,35 @@ +// +// Written by J10a1n15. +// See LICENSE for copyright and license notices. +// + +package me.partlysanestudios.partlysaneskies.features.mining.events + +import me.partlysanestudios.partlysaneskies.PartlySaneSkies.Companion.config +import me.partlysanestudios.partlysaneskies.PartlySaneSkies.Companion.minecraft +import me.partlysanestudios.partlysaneskies.events.SubscribePSSEvent +import me.partlysanestudios.partlysaneskies.events.skyblock.mining.MinesEvent +import me.partlysanestudios.partlysaneskies.render.gui.hud.BannerRenderer.renderNewBanner +import me.partlysanestudios.partlysaneskies.render.gui.hud.PSSBanner +import me.partlysanestudios.partlysaneskies.system.SystemNotification.showNotification +import me.partlysanestudios.partlysaneskies.utils.StringUtils.removeColorCodes +import org.lwjgl.opengl.Display + +object MiningEventNotifier { + + @SubscribePSSEvent + fun onMiningEvent(event: MinesEvent) { + if (!config.miningEventsToggle) return + + if (event.miningEvent.config().not()) return + + minecraft.thePlayer.playSound("partlysaneskies:bell", 100F, 1F) + val text = event.miningEvent.color + event.miningEvent.event + if (config.miningSendSystemNotifications && !Display.isActive()) { + showNotification(text.removeColorCodes()) + } + if (config.miningShowEventBanner) { + renderNewBanner(PSSBanner(text, (config.miningEventBannerTime * 1000).toLong(), 4f)) + } + } +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/security/PrivacyMode.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/security/PrivacyMode.kt index f718960c5..be36e4529 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/security/PrivacyMode.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/security/PrivacyMode.kt @@ -5,18 +5,15 @@ import me.partlysanestudios.partlysaneskies.utils.SystemUtils import org.apache.logging.log4j.Level object PrivacyMode { - private var enablePrivacyMode = false - fun shouldBlockTelemetry(): Boolean { - return PartlySaneSkies.config.privacyMode == 3 || (PartlySaneSkies.config.privacyMode != 0 && enablePrivacyMode) - } + fun shouldBlockTelemetry(): Boolean = + PartlySaneSkies.config.privacyMode == 3 || (PartlySaneSkies.config.privacyMode != 0 && enablePrivacyMode) fun enablePrivacyMode() { SystemUtils.log( Level.INFO, - "Privacy mode has been enabled. Privacy Mode Option: ${PartlySaneSkies.config.privacyMode}" + "Privacy mode has been enabled. Privacy Mode Option: ${PartlySaneSkies.config.privacyMode}", ) } - -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/security/modschecker/ModChecker.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/security/modschecker/ModChecker.kt index 11c6ee51e..e4ea242d9 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/security/modschecker/ModChecker.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/security/modschecker/ModChecker.kt @@ -19,7 +19,6 @@ import me.partlysanestudios.partlysaneskies.utils.ChatUtils.sendClientMessage import me.partlysanestudios.partlysaneskies.utils.SystemUtils import me.partlysanestudios.partlysaneskies.utils.SystemUtils.copyStringToClipboard import me.partlysanestudios.partlysaneskies.utils.SystemUtils.isValidURL -import net.minecraft.command.ICommandSender import net.minecraft.event.ClickEvent import net.minecraft.event.HoverEvent import net.minecraft.util.ChatComponentText @@ -34,14 +33,16 @@ import java.security.MessageDigest object ModChecker { fun registerModCheckCommand() { PSSCommand( - "modcheck", ArrayList(), "Checks the mods in your mod folder if they are updated" + "modcheck", + ArrayList(), + "Checks the mods in your mod folder if they are updated", ) { args: Array -> Thread { if (args.isNotEmpty()) { sendClientMessage("Loading... (using data from custom repository)") loadModDataFromRepo( getRepoOwner(), - getRepoName() + getRepoName(), ) } else { sendClientMessage("Loading...") @@ -54,22 +55,25 @@ object ModChecker { private var knownMods: List = ArrayList() private var hasRunOnStartup = false + fun runOnStartup() { - Thread(Runnable { - if (!config.checkModsOnStartup) { - return@Runnable - } - try { - Thread.sleep(5000) - } catch (e: InterruptedException) { - throw RuntimeException(e) - } - if (!hasRunOnStartup) { - hasRunOnStartup = true - sendClientMessage("Loading...") - loadModDataFromRepo() - } - }).start() + Thread( + Runnable { + if (!config.checkModsOnStartup) { + return@Runnable + } + try { + Thread.sleep(5000) + } catch (e: InterruptedException) { + throw RuntimeException(e) + } + if (!hasRunOnStartup) { + hasRunOnStartup = true + sendClientMessage("Loading...") + loadModDataFromRepo() + } + }, + ).start() } fun run() { @@ -126,7 +130,11 @@ object ModChecker { debugBuilder.append("\n ") } } - chatMessage.appendSibling(ChatComponentText("\n§7Disclaimer: You should always exercise caution when downloading things from the internet. The PSS Mod Checker is not foolproof. Use at your own risk.")) + chatMessage.appendSibling( + ChatComponentText( + "\n§7Disclaimer: You should always exercise caution when downloading things from the internet. The PSS Mod Checker is not foolproof. Use at your own risk.", + ), + ) if (config.showUpToDateMods) { if (knownMods.isNotEmpty()) { chatMessage.appendSibling( @@ -135,8 +143,8 @@ object ModChecker { §6Up to date Mods: (${knownMods.size}) - """.trimIndent() - ) + """.trimIndent(), + ), ) } for (container in knownMods) { @@ -147,16 +155,17 @@ object ModChecker { } catch (e: IOException) { e.printStackTrace() } - val mod = findModFromHash(hash) - ?: continue + val mod = + findModFromHash(hash) + ?: continue val message: IChatComponent = ChatComponentText("\n§a${mod.name} §7is up to date") if (isValidURL(mod.downloadLink)) { message.chatStyle.setChatClickEvent(ClickEvent(ClickEvent.Action.OPEN_URL, mod.downloadLink)) message.chatStyle.setChatHoverEvent( HoverEvent( HoverEvent.Action.SHOW_TEXT, - ChatComponentText("Click for the official website for " + mod.name + "!") - ) + ChatComponentText("Click for the official website for " + mod.name + "!"), + ), ) } chatMessage.appendSibling(message) @@ -182,8 +191,8 @@ object ModChecker { message.chatStyle.setChatHoverEvent( HoverEvent( HoverEvent.Action.SHOW_TEXT, - ChatComponentText("Click for the official website for " + mod.name + "!") - ) + ChatComponentText("Click for the official website for " + mod.name + "!"), + ), ) } chatMessage.appendSibling(message) @@ -195,8 +204,8 @@ object ModChecker { §cUnknown Mods: (${unknownMods.size}) - """.trimIndent() - ) + """.trimIndent(), + ), ) chatMessage.appendSibling(ChatComponentText("\n§7These mods have not been verified by PSS admins!")) } @@ -223,8 +232,8 @@ object ModChecker { message.chatStyle.setChatHoverEvent( HoverEvent( HoverEvent.Action.SHOW_TEXT, - ChatComponentText("Click for the official website for " + mod.name + "!") - ) + ChatComponentText("Click for the official website for " + mod.name + "!"), + ), ) } } catch (e: IllegalStateException) { @@ -233,30 +242,32 @@ object ModChecker { chatMessage.appendSibling(message) debugBuilder.append( """ - - "${container.modId}": { - """.trimIndent() + + "${container.modId}": { + """.trimIndent(), ) debugBuilder.append("\n \"name\": \"$modName\",") debugBuilder.append( """ - "download": "${container.metadata.url}",""" + "download": "${container.metadata.url}",""", ) debugBuilder.append("\n \"versions\": {") debugBuilder.append( """ - "${container.version}": "$hash"""" + "${container.version}": "$hash"""", ) debugBuilder.append("\n },") debugBuilder.append("\n \"betaVersions\": {") debugBuilder.append( """ - "${container.version}": "$hash"""" + "${container.version}": "$hash"""", ) debugBuilder.append("\n }") debugBuilder.append("\n},") } - chatMessage.appendSibling(ChatComponentText("\n\n§9If you believe any of these mods may be a mistake, report it in the PSS discord! §7(/pssdiscord)")) + chatMessage.appendSibling( + ChatComponentText("\n\n§9If you believe any of these mods may be a mistake, report it in the PSS discord! §7(/pssdiscord)"), + ) if (isDebugMode()) { sendClientMessage( """ @@ -264,12 +275,12 @@ object ModChecker { ${ insertCharacterAfterNewLine( debugBuilder.toString(), - "§8" + "§8", ) } - """.trimIndent() + """.trimIndent(), ) copyStringToClipboard("```json\n$debugBuilder\n```") } @@ -294,21 +305,27 @@ object ModChecker { userName: String = "PartlySaneStudios", repoName: String = "partly-sane-skies-public-data", ) { - val url: String = if (config.useGithubForPublicData) { - "https://raw.githubusercontent.com/$userName/$repoName/main/data/mods.json" - } else { - config.apiUrl + "/v1/pss/publicdata?owner=" + userName + "&repo=" + repoName + "&path=/data/mods.json" - } - newRequest(GetRequest(url, { request: Request -> - knownMods = ArrayList() - try { - knownMods = read(Gson().fromJson(request.getResponse(), ModDataJson::class.java)) - run() - } catch (e: Exception) { - sendClientMessage("§cError reading the mod data from repo!") - e.printStackTrace() + val url: String = + if (config.useGithubForPublicData) { + "https://raw.githubusercontent.com/$userName/$repoName/main/data/mods.json" + } else { + config.apiUrl + "/v1/pss/publicdata?owner=" + userName + "&repo=" + repoName + "&path=/data/mods.json" } - })) + newRequest( + GetRequest( + url, + { request: Request -> + knownMods = ArrayList() + try { + knownMods = read(Gson().fromJson(request.getResponse(), ModDataJson::class.java)) + run() + } catch (e: Exception) { + sendClientMessage("§cError reading the mod data from repo!") + e.printStackTrace() + } + }, + ), + ) } private fun read(modData: ModDataJson): List { diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/skills/BestiaryLevelUpWebhook.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/skills/BestiaryLevelUpWebhook.kt index 7f0bc99fc..e3e7562b6 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/skills/BestiaryLevelUpWebhook.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/skills/BestiaryLevelUpWebhook.kt @@ -3,7 +3,6 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.features.skills import gg.essential.elementa.constraints.CenterConstraint @@ -11,6 +10,8 @@ import gg.essential.elementa.dsl.percent import me.partlysanestudios.partlysaneskies.PartlySaneSkies import me.partlysanestudios.partlysaneskies.config.psconfig.Toggle import me.partlysanestudios.partlysaneskies.config.psconfig.Toggle.Companion.asBoolean +import me.partlysanestudios.partlysaneskies.events.SubscribePSSEvent +import me.partlysanestudios.partlysaneskies.events.minecraft.PSSChatEvent import me.partlysanestudios.partlysaneskies.features.discord.webhooks.EmbedData import me.partlysanestudios.partlysaneskies.features.discord.webhooks.EmbedField import me.partlysanestudios.partlysaneskies.features.discord.webhooks.Webhook @@ -21,11 +22,9 @@ import me.partlysanestudios.partlysaneskies.utils.StringUtils.romanNumeralToInt import me.partlysanestudios.partlysaneskies.utils.StringUtils.toRoman import net.minecraft.init.Items import net.minecraft.item.ItemStack -import net.minecraftforge.client.event.ClientChatReceivedEvent -import net.minecraftforge.fml.common.eventhandler.SubscribeEvent import java.awt.Color -object BestiaryLevelUpWebhook: Webhook() { +object BestiaryLevelUpWebhook : Webhook() { override val icon = PSSItemRender(ItemStack(Items.rotten_flesh), true) .setX(CenterConstraint()) .setY(CenterConstraint()) @@ -37,28 +36,37 @@ object BestiaryLevelUpWebhook: Webhook() { init { config.registerOption("multipleOf5", Toggle("Send only multiples of 5", "Only send multiples of 5 (Lvl 5, 10, 15, etc.)", false)) - config.registerOption("multipleOf10", Toggle("Send only multiples of 10", "Only send multiples of 10 (Lvl 10, 20, 30, etc.)", false)) - config.registerOption("useRomanNumerals", Toggle("Use Roman Numerals", "Use Roman Numerals instead of Arabic Numerals in the message", false)) + config.registerOption( + "multipleOf10", + Toggle("Send only multiples of 10", "Only send multiples of 10 (Lvl 10, 20, 30, etc.)", false), + ) + config.registerOption( + "useRomanNumerals", + Toggle("Use Roman Numerals", "Use Roman Numerals instead of Arabic Numerals in the message", false), + ) } private val regex = "§b(§.)(\\w+[\\s\\w+]*) §7§8(\\w+) §8➡§b §b(\\w+)".toRegex() - @SubscribeEvent - fun onChatMessage(event: ClientChatReceivedEvent) { - val message = event.message.formattedText + @SubscribePSSEvent + fun onChatMessage(event: PSSChatEvent) { + if (!enabled) return + val message = event.message val (_, mob, oldLevel, newLevel) = regex.find(message)?.destructured ?: return - val oldLevelInt = if ("\\d+".toRegex().containsMatchIn(oldLevel)) { - oldLevel.toIntOrNull() ?: 0 - } else { - oldLevel.romanNumeralToInt() - } + val oldLevelInt = + if ("\\d+".toRegex().containsMatchIn(oldLevel)) { + oldLevel.toIntOrNull() ?: 0 + } else { + oldLevel.romanNumeralToInt() + } - val newLevelInt = if ("\\d+".toRegex().containsMatchIn(newLevel)) { - newLevel.toIntOrNull() ?: 0 - } else { - newLevel.romanNumeralToInt() - } + val newLevelInt = + if ("\\d+".toRegex().containsMatchIn(newLevel)) { + newLevel.toIntOrNull() ?: 0 + } else { + newLevel.romanNumeralToInt() + } if (config.find("multipleOf5")?.asBoolean == true && newLevelInt % 5 == 0) { trigger(mob, oldLevelInt, newLevelInt) @@ -70,34 +78,37 @@ object BestiaryLevelUpWebhook: Webhook() { } private fun trigger(mob: String, oldLevel: Int, newLevel: Int) { + val oldLevelString = + if (config.find("useRomanNumerals")?.asBoolean == true) { + oldLevel.toRoman() + } else { + oldLevel.toString() + } - val oldLevelString = if (config.find("useRomanNumerals")?.asBoolean == true) { - oldLevel.toRoman() - } else { - oldLevel.toString() - } - - val newLevelString = if (config.find("useRomanNumerals")?.asBoolean == true) { - newLevel.toRoman() - } else { - newLevel.toString() - } + val newLevelString = + if (config.find("useRomanNumerals")?.asBoolean == true) { + newLevel.toRoman() + } else { + newLevel.toString() + } WebhookData( url = PartlySaneSkies.config.discordWebhookURL, content = " ", - embedData = listOf( - EmbedData( - title = "Bestiary Level Up!", - color = Color(125, 255, 125).asHex, - fields = listOf( - EmbedField( - name = mob, - value = ":tada: $oldLevelString ➜ $newLevelString :tada:", - ) - ) - ) - ) + embedData = + listOf( + EmbedData( + title = "Bestiary Level Up!", + color = Color(125, 255, 125).asHex, + fields = + listOf( + EmbedField( + name = mob, + value = ":tada: $oldLevelString ➜ $newLevelString :tada:", + ), + ), + ), + ), ).send() } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/skills/BestiaryMilestoneWebhook.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/skills/BestiaryMilestoneWebhook.kt index 3faf963cb..e7e8a8646 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/skills/BestiaryMilestoneWebhook.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/skills/BestiaryMilestoneWebhook.kt @@ -3,7 +3,6 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.features.skills import gg.essential.elementa.constraints.CenterConstraint @@ -11,6 +10,8 @@ import gg.essential.elementa.dsl.percent import me.partlysanestudios.partlysaneskies.PartlySaneSkies import me.partlysanestudios.partlysaneskies.config.psconfig.Toggle import me.partlysanestudios.partlysaneskies.config.psconfig.Toggle.Companion.asBoolean +import me.partlysanestudios.partlysaneskies.events.SubscribePSSEvent +import me.partlysanestudios.partlysaneskies.events.minecraft.PSSChatEvent import me.partlysanestudios.partlysaneskies.features.discord.webhooks.EmbedData import me.partlysanestudios.partlysaneskies.features.discord.webhooks.EmbedField import me.partlysanestudios.partlysaneskies.features.discord.webhooks.Webhook @@ -21,8 +22,6 @@ import me.partlysanestudios.partlysaneskies.utils.StringUtils.romanNumeralToInt import me.partlysanestudios.partlysaneskies.utils.StringUtils.toRoman import net.minecraft.init.Items import net.minecraft.item.ItemStack -import net.minecraftforge.client.event.ClientChatReceivedEvent -import net.minecraftforge.fml.common.eventhandler.SubscribeEvent import java.awt.Color object BestiaryMilestoneWebhook : Webhook() { @@ -37,20 +36,25 @@ object BestiaryMilestoneWebhook : Webhook() { init { config.registerOption("multipleOf5", Toggle("Send only multiples of 5", "Only send multiples of 5 (Lvl 5, 10, 15, etc.)", false)) - config.registerOption("multipleOf10", Toggle("Send only multiples of 10", "Only send multiples of 10 (Lvl 10, 20, 30, etc.)", false)) - config.registerOption("useRomanNumerals", Toggle("Use Roman Numerals", "Use Roman Numerals instead of Arabic Numerals in the message", false)) + config.registerOption( + "multipleOf10", + Toggle("Send only multiples of 10", "Only send multiples of 10 (Lvl 10, 20, 30, etc.)", false), + ) + config.registerOption( + "useRomanNumerals", + Toggle("Use Roman Numerals", "Use Roman Numerals instead of Arabic Numerals in the message", false), + ) } - private var headingMessageSent = false private val regex = "§8(\\w+)➡§e(\\w+)".toRegex() - @SubscribeEvent - fun onChatMessage(event: ClientChatReceivedEvent) { + @SubscribePSSEvent + fun onChatMessage(event: PSSChatEvent) { if (!enabled) return - val message = event.message.formattedText + val message = event.message if (message.contains("§lBESTIARY MILESTONE")) { headingMessageSent = true return @@ -59,17 +63,19 @@ object BestiaryMilestoneWebhook : Webhook() { headingMessageSent = false val (oldLevel, newLevel) = regex.find(message)?.destructured ?: return - val oldLevelInt = if ("\\d+".toRegex().containsMatchIn(oldLevel)) { - oldLevel.toIntOrNull() ?: 0 - } else { - oldLevel.romanNumeralToInt() - } - - val newLevelInt = if ("\\d+".toRegex().containsMatchIn(newLevel)) { - newLevel.toIntOrNull() ?: 0 - } else { - newLevel.romanNumeralToInt() - } + val oldLevelInt = + if ("\\d+".toRegex().containsMatchIn(oldLevel)) { + oldLevel.toIntOrNull() ?: 0 + } else { + oldLevel.romanNumeralToInt() + } + + val newLevelInt = + if ("\\d+".toRegex().containsMatchIn(newLevel)) { + newLevel.toIntOrNull() ?: 0 + } else { + newLevel.romanNumeralToInt() + } if (config.find("multipleOf5")?.asBoolean == true && newLevelInt % 5 == 0) { trigger(oldLevelInt, newLevelInt) @@ -81,34 +87,37 @@ object BestiaryMilestoneWebhook : Webhook() { } private fun trigger(oldLevel: Int, newLevel: Int) { - - val oldLevelString = if (config.find("useRomanNumerals")?.asBoolean == true) { - oldLevel.toRoman() - } else { - oldLevel.toString() - } - - val newLevelString = if (config.find("useRomanNumerals")?.asBoolean == true) { - newLevel.toRoman() - } else { - newLevel.toString() - } + val oldLevelString = + if (config.find("useRomanNumerals")?.asBoolean == true) { + oldLevel.toRoman() + } else { + oldLevel.toString() + } + + val newLevelString = + if (config.find("useRomanNumerals")?.asBoolean == true) { + newLevel.toRoman() + } else { + newLevel.toString() + } WebhookData( url = PartlySaneSkies.config.discordWebhookURL, content = " ", - embedData = listOf( - EmbedData( - title = "Bestiary Level Up!", - color = Color(255, 195, 0).asHex, - fields = listOf( - EmbedField( - name = "Milestone", - value = ":tada: $oldLevelString ➜ $newLevelString :tada:", - ), + embedData = + listOf( + EmbedData( + title = "Bestiary Level Up!", + color = Color(255, 195, 0).asHex, + fields = + listOf( + EmbedField( + name = "Milestone", + value = ":tada: $oldLevelString ➜ $newLevelString :tada:", + ), + ), ), ), - ), ).send() } } diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/skills/PetAlert.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/skills/PetAlert.kt index 7fb11cc1f..ac6d8729d 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/skills/PetAlert.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/skills/PetAlert.kt @@ -24,6 +24,7 @@ import me.partlysanestudios.partlysaneskies.data.cache.PetData.getCurrentPetRari import me.partlysanestudios.partlysaneskies.data.skyblockdata.Rarity import me.partlysanestudios.partlysaneskies.features.gui.SidePanel import me.partlysanestudios.partlysaneskies.render.gui.constraints.ScaledPixelConstraint.Companion.scaledPixels +import me.partlysanestudios.partlysaneskies.render.gui.constraints.TextScaledPixelConstraint.Companion.textScaledPixels import me.partlysanestudios.partlysaneskies.utils.ChatUtils.sendClientMessage import me.partlysanestudios.partlysaneskies.utils.ElementaUtils.applyBackground import me.partlysanestudios.partlysaneskies.utils.HypixelUtils.getItemId @@ -35,7 +36,6 @@ import me.partlysanestudios.partlysaneskies.utils.StringUtils.removeColorCodes import net.minecraft.client.audio.PositionedSoundRecord import net.minecraft.client.gui.inventory.GuiChest import net.minecraft.client.gui.inventory.GuiContainer -import net.minecraft.command.ICommandSender import net.minecraft.event.ClickEvent import net.minecraft.util.ChatComponentText import net.minecraft.util.ResourceLocation @@ -43,21 +43,22 @@ import net.minecraftforge.client.event.GuiScreenEvent import java.awt.Color object PetAlert : SidePanel() { - - override val panelBaseComponent: UIComponent = UIBlock().applyBackground().constrain { - x = 800.scaledPixels - y = CenterConstraint() - width = 175.scaledPixels - height = 100.scaledPixels - color = Color(0, 0, 0, 0).constraint - } - - private val textComponent = UIWrappedText(centered = true).constrain { - x = CenterConstraint() - y = CenterConstraint() - width = 95.percent - textScale = 1.scaledPixels - } childOf panelBaseComponent + override val panelBaseComponent: UIComponent = UIBlock().applyBackground() + .constrain { + x = 800.scaledPixels + y = CenterConstraint() + width = 175.scaledPixels + height = 100.scaledPixels + color = Color(0, 0, 0, 0).constraint + } + + private val textComponent = UIWrappedText(centered = true) + .constrain { + x = CenterConstraint() + y = CenterConstraint() + width = 95.percent + textScale = 1.textScaledPixels + } childOf panelBaseComponent override fun onPanelRender(event: GuiScreenEvent.BackgroundDrawnEvent) { alignPanel() @@ -66,13 +67,14 @@ object PetAlert : SidePanel() { currentlySelectedPetName = "§8(Unknown)" } - val petColorCode = if (config.selectedPet.isEmpty()) { - "§d" - } else if (currentlySelectedPetName.equals(config.selectedPet, ignoreCase = true)) { - "§a" - } else { - "§c" - } + val petColorCode = + if (config.selectedPet.isEmpty()) { + "§d" + } else if (currentlySelectedPetName.equals(config.selectedPet, ignoreCase = true)) { + "§a" + } else { + "§c" + } var petLevel = "" if (getCurrentPetLevel() != -1) { @@ -84,7 +86,8 @@ object PetAlert : SidePanel() { petRarity = getCurrentPetRarity().displayName + " " } - val textString = """ + val textString = + """ §eCurrently Selected Pet: $petColorCode$petLevel$petRarity$currentlySelectedPetName @@ -97,6 +100,7 @@ object PetAlert : SidePanel() { private var lastMessageSendTime: Long = 0 private var lastSoundTime: Long = 0 private var lastMuteTime: Long = 0 + fun runPetAlertTick() { if (!config.incorrectPetForMinionAlert) { return @@ -129,9 +133,9 @@ object PetAlert : SidePanel() { PositionedSoundRecord.create( ResourceLocation( "partlysaneskies", - "airraidsiren" - ) - ) + "airraidsiren", + ), + ), ) } @@ -139,11 +143,12 @@ object PetAlert : SidePanel() { } if (!onCooldown(lastMessageSendTime, 3000)) { - val message = ChatComponentText( - "${PartlySaneSkies.CHAT_PREFIX}§cYOU CURRENTLY HAVE $petName§c SELECTED AS YOUR PET. YOU WANTED TO UPGRADE $selectedPetName.\n§dClick this message or run /mutepetalert to mute the alert for ${config.petAlertMuteTime} ${ - "minutes".pluralize(config.petAlertMuteTime) - }." - ) + val message = + ChatComponentText( + "${PartlySaneSkies.CHAT_PREFIX}§cYOU CURRENTLY HAVE $petName§c SELECTED AS YOUR PET. YOU WANTED TO UPGRADE $selectedPetName.\n§dClick this message or run /mutepetalert to mute the alert for ${config.petAlertMuteTime} ${ + "minutes".pluralize(config.petAlertMuteTime) + }.", + ) message.chatStyle.setChatClickEvent(ClickEvent(ClickEvent.Action.RUN_COMMAND, "/mutepetalert")) minecraft.ingameGUI.chatGUI.printChatMessage(message) lastMessageSendTime = time @@ -156,7 +161,10 @@ object PetAlert : SidePanel() { } val upper = (minecraft.currentScreen as GuiChest).containerInventory - val inventoryNameMatches = upper.displayName.formattedText.removeColorCodes().contains("Minion") + val inventoryNameMatches = + upper.displayName.formattedText + .removeColorCodes() + .contains("Minion") if (!inventoryNameMatches) { return false } @@ -167,13 +175,11 @@ object PetAlert : SidePanel() { return displayName.contains("Minion") } - fun favouritePet() { if (!isSkyblock()) { return } - if (!isPetGui()) { return } @@ -196,7 +202,9 @@ object PetAlert : SidePanel() { PSSCommand("mutepetalert") .setDescription("Mutes the pet alert for a set amount of minutes.") .setRunnable { - sendClientMessage("§bPet alert has been muted for ${config.petAlertMuteTime} ${"minute".pluralize(config.petAlertMuteTime)}.") + sendClientMessage( + "§bPet alert has been muted for ${config.petAlertMuteTime} ${"minute".pluralize(config.petAlertMuteTime)}.", + ) lastMuteTime = time }.register() } diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/skills/PetLevelUpWebhook.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/skills/PetLevelUpWebhook.kt index 6392cbbc9..8aa830915 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/skills/PetLevelUpWebhook.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/skills/PetLevelUpWebhook.kt @@ -3,7 +3,6 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.features.skills import gg.essential.elementa.constraints.CenterConstraint @@ -13,6 +12,8 @@ import me.partlysanestudios.partlysaneskies.config.psconfig.Toggle import me.partlysanestudios.partlysaneskies.config.psconfig.Toggle.Companion.asBoolean import me.partlysanestudios.partlysaneskies.data.skyblockdata.Rarity import me.partlysanestudios.partlysaneskies.data.skyblockdata.Rarity.Companion.getRarityFromColorCode +import me.partlysanestudios.partlysaneskies.events.SubscribePSSEvent +import me.partlysanestudios.partlysaneskies.events.minecraft.PSSChatEvent import me.partlysanestudios.partlysaneskies.features.discord.webhooks.EmbedData import me.partlysanestudios.partlysaneskies.features.discord.webhooks.EmbedField import me.partlysanestudios.partlysaneskies.features.discord.webhooks.Webhook @@ -23,8 +24,6 @@ import me.partlysanestudios.partlysaneskies.utils.StringUtils.colorCodeToColor import me.partlysanestudios.partlysaneskies.utils.StringUtils.toRoman import net.minecraft.init.Items import net.minecraft.item.ItemStack -import net.minecraftforge.client.event.ClientChatReceivedEvent -import net.minecraftforge.fml.common.eventhandler.SubscribeEvent object PetLevelUpWebhook : Webhook() { override val icon = PSSItemRender(ItemStack(Items.bone), true) @@ -37,24 +36,40 @@ object PetLevelUpWebhook : Webhook() { override val description = "Send a webhook whenever you level up a pet" init { - config.registerOption("multipleOf10", Toggle("Send only multiples of 10", "Only send multiples of 10 (Lvl 10, 20, 30, etc.)", false)) - config.registerOption("level100", Toggle("Send only when pet reaches level 100", "Only send a webhook when the pet reaches level 100", false)) - config.registerOption("useRomanNumerals", Toggle("Use Roman Numerals", "Use Roman Numerals instead of Arabic Numerals in the message", false)) + config.registerOption( + "multipleOf10", + Toggle("Send only multiples of 10", "Only send multiples of 10 (Lvl 10, 20, 30, etc.)", false), + ) + config.registerOption( + "level100", + Toggle("Send only when pet reaches level 100", "Only send a webhook when the pet reaches level 100", false), + ) + config.registerOption( + "useRomanNumerals", + Toggle("Use Roman Numerals", "Use Roman Numerals instead of Arabic Numerals in the message", false), + ) val rarities = arrayOf(Rarity.COMMON, Rarity.UNCOMMON, Rarity.RARE, Rarity.EPIC, Rarity.LEGENDARY, Rarity.MYTHIC) for (rarity in rarities) { val displayName = rarity.displayName - config.registerOption("send$displayName", Toggle("Send $displayName Pets", "Allow the webhook to send level ups for pets of ${displayName.lowercase()} rarity.", true)) + config.registerOption( + "send$displayName", + Toggle( + "Send $displayName Pets", + "Allow the webhook to send level ups for pets of ${displayName.lowercase()} rarity.", + true, + ), + ) } } private val regex = "§r§aYour §r(§.)((\\w+(\\s\\w+)*)( ✦)?) §r§aleveled up to level §r§9(\\d+)§r§a!§r".toRegex() - @SubscribeEvent - fun onChatMessage(event: ClientChatReceivedEvent) { + @SubscribePSSEvent + fun onChatMessage(event: PSSChatEvent) { if (!enabled) return - val message = event.message.formattedText + val message = event.message regex.find(message)?.let { val colorCode = it.groupValues[1] @@ -78,27 +93,30 @@ object PetLevelUpWebhook : Webhook() { } private fun trigger(name: String, level: Int, rarity: Rarity) { - val levelString = if (config.find("useRomanNumerals")?.asBoolean == true) { - level.toRoman() - } else { - level.toString() - } + val levelString = + if (config.find("useRomanNumerals")?.asBoolean == true) { + level.toRoman() + } else { + level.toString() + } WebhookData( url = PartlySaneSkies.config.discordWebhookURL, content = " ", - embedData = listOf( - EmbedData( - title = "Pet Level Up!", - color = rarity.colorCode.colorCodeToColor().asHex, - fields = listOf( - EmbedField( - name = "${rarity.displayName} $name", - value = ":tada: $levelString :tada:", - ), + embedData = + listOf( + EmbedData( + title = "Pet Level Up!", + color = rarity.colorCode.colorCodeToColor().asHex, + fields = + listOf( + EmbedField( + name = "${rarity.displayName} $name", + value = ":tada: $levelString :tada:", + ), + ), ), ), - ), ).send() } } diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/skills/SkillUpgradeRecommendation.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/skills/SkillUpgradeRecommendation.kt new file mode 100644 index 000000000..5142d33c3 --- /dev/null +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/skills/SkillUpgradeRecommendation.kt @@ -0,0 +1,142 @@ +/* + * Written by Su386 and J10a1n15. + * See LICENSE for copyright and license notices. + */ + +package me.partlysanestudios.partlysaneskies.features.skills + +import me.partlysanestudios.partlysaneskies.PartlySaneSkies.Companion.minecraft +import me.partlysanestudios.partlysaneskies.commands.PSSCommand +import me.partlysanestudios.partlysaneskies.data.skyblockdata.SkyblockDataManager.getPlayer +import me.partlysanestudios.partlysaneskies.data.skyblockdata.SkyblockDataManager.getSkill +import me.partlysanestudios.partlysaneskies.data.skyblockdata.SkyblockPlayer +import me.partlysanestudios.partlysaneskies.utils.ChatUtils.sendClientMessage +import me.partlysanestudios.partlysaneskies.utils.MathUtils.round +import me.partlysanestudios.partlysaneskies.utils.StringUtils.titleCase +import java.io.IOException +import java.util.Locale +import kotlin.math.ceil +import kotlin.math.pow + + +object SkillUpgradeRecommendation { + + private val weightConstants = mapOf( + "mining" to 1.68207448, + "foraging" to 1.732826, + "enchanting" to 1.46976583, + "combat" to 1.65797687265, + "fishing" to 1.906418, + "alchemy" to 1.5, + "farming" to 1.717848139, + ) + + private fun getRecommendedSkills(username: String?): LinkedHashMap { + val skillScoreMap = hashMapOf() + val player = getPlayer(username!!) + + weightConstants.keys.forEach { skill -> + val skillLevel = getSkillLevel(skill, player) + val maxSkillLevel = getSkill(skill.uppercase(Locale.getDefault()))?.maxLevel?.toDouble() ?: 0.0 + + if (skillLevel < maxSkillLevel) { + skillScoreMap[skill] = if (skillLevel < 5) 100000.0 else calculateScore(skill, player) + } + } + + val catacombsLevel = player.catacombsLevel + val maxCatacombsLevel = 50.0 + + if (catacombsLevel < maxCatacombsLevel) { + skillScoreMap["catacombs"] = if (catacombsLevel < 5) { + 100000.0 + } else { + val weightDiff = calculateCatacombsWeight(catacombsLevel) - calculateCatacombsWeight(ceil(catacombsLevel)) + (maxCatacombsLevel - catacombsLevel) / weightDiff * 1.10 + 10 + } + } + + return skillScoreMap.entries + .sortedBy { it.value } + .associateTo(LinkedHashMap()) { it.key to it.value } + } + + + private fun getSkillLevel(skill: String, player: SkyblockPlayer) = when (skill) { + "mining" -> player.miningLevel + "foraging" -> player.foragingLevel + "enchanting" -> player.enchantingLevel + "combat" -> player.combatLevel + "fishing" -> player.fishingLevel + "alchemy" -> player.alchemyLevel + "farming" -> player.farmingLevel + else -> -1.0 + } + + private fun printMessage(map: HashMap) { + val message = StringBuilder( + """ + §3§m-----------------------------------------------------§r + §b§l§nRecommended skills to level up (In Order):§r + + §7This calculation is based off of the amount of weight each skill will add when you level it up. Lower level skills will be prioritized.§r + §7§oNote: Sometimes, low level skills such as alchemy will show up first. These skills are less important but due to the mathematical approach, they will appear first. + + + §8(Skill) : (Upgrade Importance Score) + + """.trimIndent(), + ) + + for (entry in map.entries.reversed()) { + message.append("\n${entry.key.titleCase()} : ${entry.value.round(2)}") + } + + message.append("\n§3§m-----------------------------------------------------§r") + + sendClientMessage((message.toString())) + } + + fun registerCommand() { + PSSCommand("skillup") + .addAlias("skillu", "su") + .setDescription("Recommends which skill to upgrade: /skillup [username]") + .setRunnable { args: Array -> + sendClientMessage("Loading...") + + val task = Runnable { + val username = if (args.isNotEmpty()) args[0] else minecraft.thePlayer.name + val skillMap: HashMap = try { + getRecommendedSkills(username) + } catch (e: IOException) { + sendClientMessage("Error getting data for $username. Maybe the player is nicked or there is an invalid API key.") + return@Runnable + } + + minecraft.addScheduledTask { + printMessage(skillMap) + } + } + + Thread(task).start() + }.register() + } + + private fun calculateSkillWeight(level: Double, constant: Double) = (level * 10).pow(constant + level / 100) / 1250 + + private fun calculateCatacombsWeight(level: Double) = level.pow(4.5) * 0.0002149604615 + + private fun calculateScore(skill: String, player: SkyblockPlayer): Double { + val currentSkillLevel = getSkillLevel(skill, player) + + val weightConstant: Double = weightConstants[skill] ?: 1.0 + + val awayFromMaxComponent = getSkillLevel(skill, player) - getSkill(skill.uppercase(Locale.getDefault()))!!.maxLevel + val currentSenitherWeight = calculateSkillWeight(currentSkillLevel - 5, weightConstant) + val nextLevelSenitherWeight = calculateSkillWeight(ceil(currentSkillLevel - 5), weightConstant) + val levelUpSenitherWeightComponent = currentSenitherWeight - nextLevelSenitherWeight + + return awayFromMaxComponent / levelUpSenitherWeightComponent + 10 + } + +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/skills/SkillUpgradeWebhook.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/skills/SkillUpgradeWebhook.kt index 53c83ae02..7e730a3fe 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/skills/SkillUpgradeWebhook.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/skills/SkillUpgradeWebhook.kt @@ -3,7 +3,6 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.features.skills import gg.essential.elementa.constraints.CenterConstraint @@ -11,6 +10,8 @@ import gg.essential.elementa.dsl.percent import me.partlysanestudios.partlysaneskies.PartlySaneSkies import me.partlysanestudios.partlysaneskies.config.psconfig.Toggle import me.partlysanestudios.partlysaneskies.config.psconfig.Toggle.Companion.asBoolean +import me.partlysanestudios.partlysaneskies.events.SubscribePSSEvent +import me.partlysanestudios.partlysaneskies.events.minecraft.PSSChatEvent import me.partlysanestudios.partlysaneskies.features.discord.webhooks.EmbedData import me.partlysanestudios.partlysaneskies.features.discord.webhooks.EmbedField import me.partlysanestudios.partlysaneskies.features.discord.webhooks.Webhook @@ -22,8 +23,6 @@ import me.partlysanestudios.partlysaneskies.utils.StringUtils.romanNumeralToInt import me.partlysanestudios.partlysaneskies.utils.StringUtils.toRoman import net.minecraft.init.Items import net.minecraft.item.ItemStack -import net.minecraftforge.client.event.ClientChatReceivedEvent -import net.minecraftforge.fml.common.eventhandler.SubscribeEvent import java.awt.Color object SkillUpgradeWebhook : Webhook() { @@ -38,31 +37,39 @@ object SkillUpgradeWebhook : Webhook() { init { config.registerOption("multipleOf5", Toggle("Send only multiples of 5", "Only send multiples of 5 (Lvl 5, 10, 15, etc.)", false)) - config.registerOption("multipleOf10", Toggle("Send only multiples of 10", "Only send multiples of 10 (Lvl 10, 20, 30, etc.)", false)) - config.registerOption("useRomanNumerals", Toggle("Use Roman Numerals", "Use Roman Numerals instead of Arabic Numerals in the message", false)) + config.registerOption( + "multipleOf10", + Toggle("Send only multiples of 10", "Only send multiples of 10 (Lvl 10, 20, 30, etc.)", false), + ) + config.registerOption( + "useRomanNumerals", + Toggle("Use Roman Numerals", "Use Roman Numerals instead of Arabic Numerals in the message", false), + ) } val regex = "SKILL LEVEL UP (\\w+) (\\w+)➜(\\w+)".toRegex() - @SubscribeEvent - fun onChatMessage(event: ClientChatReceivedEvent) { + @SubscribePSSEvent + fun onChatMessage(event: PSSChatEvent ) { if (!enabled) return val message = event.trueUnformattedMessage val (skill, oldLevel, newLevel) = regex.find(message)?.destructured ?: return - val oldLevelInt = if ("\\d+".toRegex().containsMatchIn(oldLevel)) { - oldLevel.toIntOrNull() ?: 0 - } else { - oldLevel.romanNumeralToInt() - } + val oldLevelInt = + if ("\\d+".toRegex().containsMatchIn(oldLevel)) { + oldLevel.toIntOrNull() ?: 0 + } else { + oldLevel.romanNumeralToInt() + } - val newLevelInt = if ("\\d+".toRegex().containsMatchIn(newLevel)) { - newLevel.toIntOrNull() ?: 0 - } else { - newLevel.romanNumeralToInt() - } + val newLevelInt = + if ("\\d+".toRegex().containsMatchIn(newLevel)) { + newLevel.toIntOrNull() ?: 0 + } else { + newLevel.romanNumeralToInt() + } if (config.find("multipleOf5")?.asBoolean == true && newLevelInt % 5 == 0) { trigger(skill, oldLevelInt, newLevelInt) @@ -74,35 +81,38 @@ object SkillUpgradeWebhook : Webhook() { } private fun trigger(skill: String, oldLevel: Int, newLevel: Int) { - - val oldLevelString = if (config.find("useRomanNumerals")?.asBoolean == true) { - oldLevel.toRoman() - } else { - oldLevel.toString() - } - - val newLevelString = if (config.find("useRomanNumerals")?.asBoolean == true) { - newLevel.toRoman() - } else { - newLevel.toString() - } + val oldLevelString = + if (config.find("useRomanNumerals")?.asBoolean == true) { + oldLevel.toRoman() + } else { + oldLevel.toString() + } + + val newLevelString = + if (config.find("useRomanNumerals")?.asBoolean == true) { + newLevel.toRoman() + } else { + newLevel.toString() + } WebhookData( url = PartlySaneSkies.config.discordWebhookURL, content = " ", - embedData = listOf( - EmbedData( - title = "Skill Level Up!", - color = Color(125, 255, 125).asHex, - fields = listOf( - EmbedField( - name = skill, - value = ":tada: $oldLevelString ➜ $newLevelString :tada:", - inline = true, - ), + embedData = + listOf( + EmbedData( + title = "Skill Level Up!", + color = Color(125, 255, 125).asHex, + fields = + listOf( + EmbedField( + name = skill, + value = ":tada: $oldLevelString ➜ $newLevelString :tada:", + inline = true, + ), + ), ), ), - ), ).send() } } diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/sound/EnhancedSound.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/sound/EnhancedSound.kt index 9555e3791..05b1b4eb6 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/sound/EnhancedSound.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/sound/EnhancedSound.kt @@ -13,62 +13,52 @@ import net.minecraftforge.client.event.sound.PlaySoundEvent import net.minecraftforge.fml.common.eventhandler.SubscribeEvent object EnhancedSound { + private val instruments = + arrayOf( + "live_clarinet", + "clarinet", + "electric_piano", + "flute", + "organ", + "piano", + "string_ensemble", + "trombone", + "trumpet", + "violin", + "wind_ensemble", + "discord_sound", + "kazoo", + ) - private val instruments = arrayOf( - "live_clarinet", - "clarinet", - "electric_piano", - "flute", - "organ", - "piano", - "string_ensemble", - "trombone", - "trumpet", - "violin", - "wind_ensemble", - "discord_sound", - "kazoo" - ) + private fun buildReplacementSound( + event: PlaySoundEvent, + resourceLocation: ResourceLocation, + ): ISound = + object : ISound { + override fun getSoundLocation(): ResourceLocation = resourceLocation - private fun buildReplacementSound(event: PlaySoundEvent, resourceLocation: ResourceLocation): ISound { - return object : ISound { - override fun getSoundLocation(): ResourceLocation { - return resourceLocation - } + override fun canRepeat(): Boolean = false - override fun canRepeat(): Boolean { - return false - } + override fun getRepeatDelay(): Int = 0 - override fun getRepeatDelay(): Int { - return 0 - } + override fun getVolume(): Float = event.sound.volume - override fun getVolume(): Float { - return event.sound.volume - } + override fun getPitch(): Float = event.sound.pitch - override fun getPitch(): Float { - return event.sound.pitch - } + override fun getXPosF(): Float = + minecraft.thePlayer.position.y + .toFloat() - override fun getXPosF(): Float { - return minecraft.thePlayer.position.y.toFloat() - } + override fun getYPosF(): Float = + minecraft.thePlayer.position.y + .toFloat() - override fun getYPosF(): Float { - return minecraft.thePlayer.position.y.toFloat() - } - - override fun getZPosF(): Float { - return minecraft.thePlayer.position.z.toFloat() - } + override fun getZPosF(): Float = + minecraft.thePlayer.position.z + .toFloat() - override fun getAttenuationType(): AttenuationType { - return AttenuationType.NONE - } + override fun getAttenuationType(): AttenuationType = AttenuationType.NONE } - } @SubscribeEvent fun onSoundEvent(event: PlaySoundEvent) { @@ -76,10 +66,11 @@ object EnhancedSound { if (config.customSoundOption == 0) { return } - val sound = buildReplacementSound( - event, - ResourceLocation("partlysaneskies", "tenor_" + instruments[config.customSoundOption - 1]) - ) + val sound = + buildReplacementSound( + event, + ResourceLocation("partlysaneskies", "tenor_" + instruments[config.customSoundOption - 1]), + ) event.result = sound minecraft.soundHandler .playSound(sound) @@ -88,20 +79,22 @@ object EnhancedSound { if (config.customSoundOption == 0) { return } - val sound = buildReplacementSound( - event, - ResourceLocation("partlysaneskies", "bass_" + instruments[config.customSoundOption - 1]) - ) + val sound = + buildReplacementSound( + event, + ResourceLocation("partlysaneskies", "bass_" + instruments[config.customSoundOption - 1]), + ) event.result = sound minecraft.soundHandler.playSound(sound) } else if (event.name.equals("note.harp", ignoreCase = true)) { if (config.customSoundOption == 0) { return } - val sound = buildReplacementSound( - event, - ResourceLocation("partlysaneskies", "alto_" + instruments[config.customSoundOption - 1]) - ) + val sound = + buildReplacementSound( + event, + ResourceLocation("partlysaneskies", "alto_" + instruments[config.customSoundOption - 1]), + ) event.result = sound minecraft.soundHandler.playSound(sound) diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/sound/Prank.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/sound/Prank.kt index 8c663a07b..41442a354 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/sound/Prank.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/sound/Prank.kt @@ -5,7 +5,6 @@ package me.partlysanestudios.partlysaneskies.features.sound - import me.partlysanestudios.partlysaneskies.PartlySaneSkies import me.partlysanestudios.partlysaneskies.utils.MathUtils import net.minecraft.client.audio.PositionedSoundRecord @@ -13,7 +12,6 @@ import net.minecraft.util.ResourceLocation import java.time.LocalDate import java.time.Month - private const val numOfSounds = 7 private var lastPrankTime = PartlySaneSkies.time @@ -29,10 +27,8 @@ private var lastPrankTime = PartlySaneSkies.time */ object Prank { - var shouldPrankREPO = false - fun setPrankKillSwitch(value: Boolean) { shouldPrankREPO = value } @@ -74,4 +70,3 @@ object Prank { } } } - diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/themes/ThemeManager.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/themes/ThemeManager.kt index e508f69e0..d568f93c5 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/themes/ThemeManager.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/features/themes/ThemeManager.kt @@ -32,20 +32,21 @@ object ThemeManager { private val backgroundUIImages: ArrayList = ArrayList() private val buttonDataList: ArrayList = ArrayList() private val toggleDataList: ArrayList = ArrayList() - private val defaultThemes: Array = arrayOf( - Theme("Classic (Dark)", Color(46, 47, 50), Color(37, 38, 41), Color(1, 255, 255)), - Theme("Royal Dark (Dark)", Color(46, 47, 50), Color(39, 31, 43), Color(91, 192, 235)), - Theme("Midnight Forest (Dark)", Color(46, 47, 50), Color(40, 50, 38), Color(35, 206, 107)), - Theme("Moonless Night (Very Dark)", Color(24, 24, 27), Color(15, 17, 20), Color(8, 124, 167)), - Theme("Stormy Night (Very Dark)", Color(23, 23, 34), Color(5, 5, 27), Color(94, 74, 227)), - Theme("The Void (Very Dark)", Color(14, 17, 21), Color(5, 5, 12), Color(113, 179, 64)), - Theme("Classic (Light)", Color(245, 245, 245), Color(213, 210, 195), Color(42, 84, 209)), - Theme("Royal Light (Light)", Color(245, 245, 245), Color(127, 106, 147), Color(242, 97, 87)), - Theme("Partly Cloudy (Light)", Color(245, 245, 245), Color(84, 95, 117), Color(217, 114, 255)), - Theme("Waterfall (Colorful)", Color(214, 237, 246), Color(172, 215, 236), Color(108, 197, 81)), - Theme("Jungle (Colorful)", Color(201, 227, 172), Color(144, 190, 109), Color(254, 100, 163)), - Theme("Dunes (Colorful)", Color(229, 177, 129), Color(222, 107, 72), Color(131, 34, 50)) - ) + private val defaultThemes: Array = + arrayOf( + Theme("Classic (Dark)", Color(46, 47, 50), Color(37, 38, 41), Color(1, 255, 255)), + Theme("Royal Dark (Dark)", Color(46, 47, 50), Color(39, 31, 43), Color(91, 192, 235)), + Theme("Midnight Forest (Dark)", Color(46, 47, 50), Color(40, 50, 38), Color(35, 206, 107)), + Theme("Moonless Night (Very Dark)", Color(24, 24, 27), Color(15, 17, 20), Color(8, 124, 167)), + Theme("Stormy Night (Very Dark)", Color(23, 23, 34), Color(5, 5, 27), Color(94, 74, 227)), + Theme("The Void (Very Dark)", Color(14, 17, 21), Color(5, 5, 12), Color(113, 179, 64)), + Theme("Classic (Light)", Color(245, 245, 245), Color(213, 210, 195), Color(42, 84, 209)), + Theme("Royal Light (Light)", Color(245, 245, 245), Color(127, 106, 147), Color(242, 97, 87)), + Theme("Partly Cloudy (Light)", Color(245, 245, 245), Color(84, 95, 117), Color(217, 114, 255)), + Theme("Waterfall (Colorful)", Color(214, 237, 246), Color(172, 215, 236), Color(108, 197, 81)), + Theme("Jungle (Colorful)", Color(201, 227, 172), Color(144, 190, 109), Color(254, 100, 163)), + Theme("Dunes (Colorful)", Color(229, 177, 129), Color(222, 107, 72), Color(131, 34, 50)), + ) fun tick() { if (!config.useCustomAccentColor) { @@ -87,13 +88,16 @@ object ThemeManager { val currentBackgroundUIImage: UIImage get() { - val image: UIImage = if (config.disableThemes) { ResourceLocation("partlysaneskies", "textures/gui/base_color_background.png").uiImage - } else { - try { - UIImage.ofFile(currentBackgroundFile) - } catch (e: IOException) { ResourceLocation("partlysaneskies", "textures/gui/base_color_background.png").uiImage + val image: UIImage = + if (config.disableThemes) { + ResourceLocation("partlysaneskies", "textures/gui/base_color_background.png").uiImage + } else { + try { + UIImage.ofFile(currentBackgroundFile) + } catch (e: IOException) { + ResourceLocation("partlysaneskies", "textures/gui/base_color_background.png").uiImage + } } - } backgroundUIImages.add(image) return image } @@ -103,47 +107,54 @@ object ThemeManager { fun getCurrentButtonUIImage(accentColor: OneColor): UIImage { val image: UIImage if (config.disableThemes) { - image = if ((accentColor == ThemeManager.accentColor)) { - ResourceLocation("partlysaneskies", "textures/gui/base_color_button.png").uiImage - } else { - ResourceLocation("partlysaneskies", "textures/gui/base_color_button_transparent.png").uiImage - } + image = + if ((accentColor == ThemeManager.accentColor)) { + ResourceLocation("partlysaneskies", "textures/gui/base_color_button.png").uiImage + } else { + ResourceLocation("partlysaneskies", "textures/gui/base_color_button_transparent.png").uiImage + } } else { - image = try { - UIImage.ofFile(getCurrentButtonFile(accentColor)) - } catch (e: IOException) { - if ((accentColor == ThemeManager.accentColor)) { ResourceLocation("partlysaneskies", "textures/gui/base_color_button.png").uiImage - } else { ResourceLocation("partlysaneskies", "textures/gui/base_color_button_transparent.png").uiImage + image = + try { + UIImage.ofFile(getCurrentButtonFile(accentColor)) + } catch (e: IOException) { + if ((accentColor == ThemeManager.accentColor)) { + ResourceLocation("partlysaneskies", "textures/gui/base_color_button.png").uiImage + } else { + ResourceLocation("partlysaneskies", "textures/gui/base_color_button_transparent.png").uiImage + } } - } } buttonDataList.add(ButtonData(image, accentColor)) return image } - fun getCurrentToggleUIImage(selected: Boolean): UIImage { - return getCurrentToggleUIImage(selected, accentColor) - } + fun getCurrentToggleUIImage(selected: Boolean): UIImage = getCurrentToggleUIImage(selected, accentColor) - fun getCurrentToggleUIImage(selected: Boolean, accentColor: OneColor): UIImage { + fun getCurrentToggleUIImage( + selected: Boolean, + accentColor: OneColor, + ): UIImage { var image: UIImage if (config.disableThemes) { - image = if (selected) { - ResourceLocation("partlysaneskies", "textures/gui/selected_toggle.png").uiImage - } else { - ResourceLocation("partlysaneskies", "textures/gui/unselected_toggle.png").uiImage - } + image = + if (selected) { + ResourceLocation("partlysaneskies", "textures/gui/selected_toggle.png").uiImage + } else { + ResourceLocation("partlysaneskies", "textures/gui/unselected_toggle.png").uiImage + } } - image = try { - UIImage.ofFile(getCurrentToggleFile(selected, accentColor)) - } catch (e: IOException) { - if (selected) { - ResourceLocation("partlysaneskies", "textures/gui/selected_toggle.png").uiImage - } else { - ResourceLocation("partlysaneskies", "textures/gui/unselected_toggle.png").uiImage + image = + try { + UIImage.ofFile(getCurrentToggleFile(selected, accentColor)) + } catch (e: IOException) { + if (selected) { + ResourceLocation("partlysaneskies", "textures/gui/selected_toggle.png").uiImage + } else { + ResourceLocation("partlysaneskies", "textures/gui/unselected_toggle.png").uiImage + } } - } toggleDataList.add(ToggleData(image, selected, accentColor)) return image @@ -153,92 +164,59 @@ object ThemeManager { get() = getBackgroundWithColor(primaryColor, secondaryColor, accentColor) val currentButtonFile: File - get() { - return getCurrentButtonFile(accentColor) - } + get()= getCurrentButtonFile(accentColor) - fun getCurrentButtonFile(accentColor: OneColor): File { - return getButtonWithColor(primaryColor, secondaryColor, accentColor) - } + fun getCurrentButtonFile(accentColor: OneColor): File = getButtonWithColor(primaryColor, secondaryColor, accentColor) - fun getCurrentToggleFile(selected: Boolean): File { - return getCurrentToggleFile(selected, accentColor) - } + fun getCurrentToggleFile(selected: Boolean): File = getCurrentToggleFile(selected, accentColor) - fun getCurrentToggleFile(selected: Boolean, accentColor: OneColor): File { - return if (selected) { + fun getCurrentToggleFile( + selected: Boolean, + accentColor: OneColor, + ): File = + if (selected) { getToggleWithColor(primaryColor, secondaryColor, accentColor) } else { getToggleWithColor(primaryColor, secondaryColor, secondaryColor) } - } val primaryColor: OneColor - get() { - return if (!config.customTheme) { - val themeIndex: Int = config.themeIndex - OneColor(defaultThemes[themeIndex].primaryColor) - } else { - config.primaryColor - } - } + get() = if (!config.customTheme) OneColor(defaultThemes[config.themeIndex].primaryColor) else config.primaryColor + val darkPrimaryColor: OneColor - get() { - return OneColor(darkenColor(primaryColor)) - } + get() = OneColor(darkenColor(primaryColor)) + val lightPrimaryColor: OneColor - get() { - return OneColor(lightenColor(primaryColor)) - } + get() = OneColor(lightenColor(primaryColor)) + val secondaryColor: OneColor - get() { - return if (!config.customTheme) { - val themeIndex: Int = config.themeIndex - OneColor(defaultThemes[themeIndex].secondaryColor) - } else { - config.secondaryColor - } - } + get() = if (!config.customTheme) OneColor(defaultThemes[config.themeIndex].secondaryColor) else config.secondaryColor + val darkSecondaryColor: OneColor - get() { - return OneColor(darkenColor(secondaryColor)) - } + get() = OneColor(darkenColor(secondaryColor)) + val lightSecondaryColor: OneColor - get() { - return OneColor(lightenColor(secondaryColor)) - } + get() = OneColor(lightenColor(secondaryColor)) + val accentColor: OneColor - get() { - return if (!config.useCustomAccentColor) { - val themeIndex: Int = config.themeIndex - OneColor(defaultThemes[themeIndex].defaultAccentColor) - } else { - config.accentColor - } - } + get() = if (!config.useCustomAccentColor) OneColor(defaultThemes[config.themeIndex].defaultAccentColor) else config.accentColor + val darkAccentColor: Color - get() { - return darkenColor(accentColor) - } + get() = darkenColor(accentColor) + val lightAccentColor: Color - get() { - return lightenColor(accentColor) - } + get() = lightenColor(accentColor) - private fun darkenColor(color: OneColor): Color { - return darkenColor(color.toJavaColor()) - } + private fun darkenColor(color: OneColor): Color = darkenColor(color.toJavaColor()) private fun darkenColor(color: Color): Color { val averageR: Int = (color.red * .761).toInt() val averageG: Int = (color.green * .761).toInt() val averageB: Int = (color.blue * .761).toInt() - return Color(averageR, averageG, averageB, color.getTransparency()) + return Color(averageR, averageG, averageB, color.alpha) } - private fun lightenColor(color: OneColor): Color { - return lightenColor(color.toJavaColor()) - } + private fun lightenColor(color: OneColor): Color = lightenColor(color.toJavaColor()) private fun lightenColor(color: Color): Color { val averageR: Int = (color.red * .798 + 255 * .202).toInt() @@ -293,10 +271,7 @@ object ThemeManager { filePath.toFile().createNewFile() replaceColor(debugImage, PRIMARY_DEBUG_COLOR, primaryColor) replaceColor(debugImage, SECONDARY_DEBUG_COLOR, secondaryColor) - replaceColor( - debugImage, ACCENT_DEBUG_COLOR, - (accentColor) - ) + replaceColor(debugImage, ACCENT_DEBUG_COLOR, accentColor) saveImage(debugImage, filePath) return filePath.toFile() } @@ -320,10 +295,7 @@ object ThemeManager { filePath.toFile().createNewFile() replaceColor(debugImage, PRIMARY_DEBUG_COLOR, primaryColor) replaceColor(debugImage, SECONDARY_DEBUG_COLOR, secondaryColor) - replaceColor( - debugImage, ACCENT_DEBUG_COLOR, - (accentColor) - ) + replaceColor(debugImage, ACCENT_DEBUG_COLOR, accentColor) saveImage(debugImage, filePath) return filePath.toFile() } @@ -332,8 +304,12 @@ object ThemeManager { class ToggleData(val image: UIImage, selected: Boolean, val color: OneColor) { val isSelected: Boolean = selected - } - class Theme(val name: String, val primaryColor: Color, val secondaryColor: Color, val defaultAccentColor: Color) + class Theme( + val name: String, + val primaryColor: Color, + val secondaryColor: Color, + val defaultAccentColor: Color, + ) } diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/RenderEuclid.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/RenderEuclid.kt index f8c897b5c..78d82b109 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/RenderEuclid.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/RenderEuclid.kt @@ -16,27 +16,32 @@ import me.partlysanestudios.partlysaneskies.utils.geometry.vectors.Range3d import net.minecraft.client.renderer.WorldRenderer object RenderEuclid { - /** * @param baseCenter The center of the base of the cylinder * @param height The height of the cylinder * @param radius The radius of the cylinder * @param numOfSides Because this is minecraft, the cylinder is an approximation using a regular polygons. Because of this, the function should really be called "drawRegularPolygonalPrism" */ - fun WorldRenderer.drawCylinderFill(baseCenter: Point3d, radius: Double, height: Double, numOfSides: Int = 48) { + fun WorldRenderer.drawCylinderFill( + baseCenter: Point3d, + radius: Double, + height: Double, + numOfSides: Int = 48, + ) { val pointPairs: ArrayList = ArrayList() - - var lastX = calculatePoint( - radius, - numOfSides, - 0 - ).x + baseCenter.x // Set the first x = (cos(angle) * r = 0) + the center of the circle - var lastZ = calculatePoint( - radius, - numOfSides, - 0 - ).y + baseCenter.z // Set the first z = (sin(angle) * r = r) + the center of the circle + var lastX = + calculatePoint( + radius, + numOfSides, + 0, + ).x + baseCenter.x // Set the first x = (cos(angle) * r = 0) + the center of the circle + var lastZ = + calculatePoint( + radius, + numOfSides, + 0, + ).y + baseCenter.z // Set the first z = (sin(angle) * r = r) + the center of the circle val firstX = lastX val firstZ = lastZ // Go around the circle, connecting the previous side to the next side @@ -66,21 +71,27 @@ object RenderEuclid { * @param radius The radius of the cylinder * @param numOfSides Because this is minecraft, the cylinder is an approximation using a regular polygons. Because of this, the function should really be called "drawRegularPolygonalPrism" */ - fun WorldRenderer.drawCylinderOutline(baseCenter: Point3d, radius: Double, height: Double, numOfSides: Int = 48) { + fun WorldRenderer.drawCylinderOutline( + baseCenter: Point3d, + radius: Double, + height: Double, + numOfSides: Int = 48, + ) { val bottomPointPairs: ArrayList = ArrayList() val topPointPairs: ArrayList = ArrayList() - - var lastX = calculatePoint( - radius, - numOfSides, - 0 - ).x + baseCenter.x // Set the first x = (cos(angle) * r = 0) + the center of the circle - var lastZ = calculatePoint( - radius, - numOfSides, - 0 - ).y + baseCenter.z // Set the first z = (sin(angle) * r = r) + the center of the circle + var lastX = + calculatePoint( + radius, + numOfSides, + 0, + ).x + baseCenter.x // Set the first x = (cos(angle) * r = 0) + the center of the circle + var lastZ = + calculatePoint( + radius, + numOfSides, + 0, + ).y + baseCenter.z // Set the first z = (sin(angle) * r = r) + the center of the circle val firstX = lastX val firstZ = lastZ // Go around the circle, connecting the previous side to the next side @@ -105,8 +116,8 @@ object RenderEuclid { topPointPairs.add( Range3d( Point3d(lastX, baseCenter.y + height, lastZ), - Point3d(firstX, baseCenter.y + height, firstZ) - ) + Point3d(firstX, baseCenter.y + height, firstZ), + ), ) // Draw the sides @@ -122,11 +133,14 @@ object RenderEuclid { } } - private fun calculatePoint(radius: Double, numOfSides: Int, currentSide: Int): Point2d { + private fun calculatePoint( + radius: Double, + numOfSides: Int, + currentSide: Int, + ): Point2d { val angle = ((360 / numOfSides) * currentSide).toAngleFromDegrees() val x = cos(angle) * radius val y = sin(angle) * radius return Point2d(x, y) } - -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/RenderPrimitives.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/RenderPrimitives.kt index d169964d9..8dd9822cb 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/RenderPrimitives.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/RenderPrimitives.kt @@ -3,7 +3,6 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.render import me.partlysanestudios.partlysaneskies.utils.geometry.orientation.Axis @@ -13,8 +12,10 @@ import me.partlysanestudios.partlysaneskies.utils.geometry.vectors.Range3d import net.minecraft.client.renderer.WorldRenderer object RenderPrimitives { - - fun WorldRenderer.drawDiagonalFaceFill(range: Range3d, axisOfRotation: Axis) { + fun WorldRenderer.drawDiagonalFaceFill( + range: Range3d, + axisOfRotation: Axis, + ) { val p1 = range.points[0] val p2 = range.points[1] val p3: Point3d @@ -42,7 +43,6 @@ object RenderPrimitives { this.pos(p4.x, p4.y, p4.z).endVertex() // bottom right } - /** * Renders a flat face on the plane of the given axis * @param p1 a two-dimensional point where x will be the first point in the order (x, y, z) @@ -50,7 +50,12 @@ object RenderPrimitives { * @param axis the plane that the face will be parallel to * @param constantDimension the non changing dimension (for the x plane, z stays constant; for the y plane, y stays constant; for the z plane, x stays constant) */ - fun WorldRenderer.drawPerpendicularFaceFill(p1: Point2d, p2: Point2d, axis: Axis, constantDimension: Double) { + fun WorldRenderer.drawPerpendicularFaceFill( + p1: Point2d, + p2: Point2d, + axis: Axis, + constantDimension: Double, + ) { // If the plane is on the x plane, then the z stays constant when (axis) { Axis.X_AXIS -> { @@ -94,7 +99,12 @@ object RenderPrimitives { * @param axis the plane that the face will be parallel to * @param constantDimension the non changing dimension (for the x plane, z stays constant; for the y plane, y stays constant; for the z plane, x stays constant) */ - fun WorldRenderer.drawPerpendicularFaceOutline(p1: Point2d, p2: Point2d, axis: Axis, constantDimension: Double) { + fun WorldRenderer.drawPerpendicularFaceOutline( + p1: Point2d, + p2: Point2d, + axis: Axis, + constantDimension: Double, + ) { // If the plane is on the x plane, then the z stays constant when (axis) { Axis.X_AXIS -> { @@ -137,7 +147,6 @@ object RenderPrimitives { val (x1, x2) = listOf(p1.x, p2.x).sorted() val (y1, y2) = listOf(p1.y, p2.y).sorted() - this.pos(constantDimension, x1, y1).endVertex() this.pos(constantDimension, x2, y1).endVertex() @@ -159,7 +168,10 @@ object RenderPrimitives { * @param p1 One corner of the box to draw * @param p2 Opposite corner of the box to draw */ - fun WorldRenderer.drawBoxOutline(p1: Point3d, p2: Point3d) { + fun WorldRenderer.drawBoxOutline( + p1: Point3d, + p2: Point3d, + ) { val (x1, x2) = listOf(p1.x, p2.x).sorted() val (y1, y2) = listOf(p1.y, p2.y).sorted() val (z1, z2) = listOf(p1.z, p2.z).sorted() @@ -178,14 +190,16 @@ object RenderPrimitives { this.drawPerpendicularFaceOutline(Point2d(y1, z1), Point2d(y2, z2), Axis.Z_AXIS, x2) } - /** * Draws a cube's faces * * @param p1 One corner of the box to draw * @param p2 Opposite corner of the box to draw */ - fun WorldRenderer.drawBoxFill(p1: Point3d, p2: Point3d) { + fun WorldRenderer.drawBoxFill( + p1: Point3d, + p2: Point3d, + ) { val (x1, x2) = listOf(p1.x, p2.x).sorted() val (y1, y2) = listOf(p1.y, p2.y).sorted() val (z1, z2) = listOf(p1.z, p2.z).sorted() @@ -203,6 +217,4 @@ object RenderPrimitives { // x face back (x is constant) this.drawPerpendicularFaceFill(Point2d(y1, z1), Point2d(y2, z2), Axis.Z_AXIS, x2) } - - -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/TextRenderer.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/TextRenderer.kt index 8df369bbc..717940c14 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/TextRenderer.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/TextRenderer.kt @@ -3,7 +3,6 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.render import me.partlysanestudios.partlysaneskies.PartlySaneSkies @@ -12,7 +11,10 @@ import net.minecraft.util.BlockPos import org.lwjgl.opengl.GL11 object TextRenderer { - fun renderText3d(pos: BlockPos, text: String) { + fun renderText3d( + pos: BlockPos, + text: String, + ) { val x = pos.x.toDouble() + 0.5 val y = pos.y.toDouble() + 1.0 val z = pos.z.toDouble() + 0.5 @@ -24,7 +26,7 @@ object TextRenderer { GlStateManager.translate( x - renderManager.viewerPosX, y - renderManager.viewerPosY, - z - renderManager.viewerPosZ + z - renderManager.viewerPosZ, ) GlStateManager.rotate(-renderManager.playerViewY, 0.0f, 1.0f, 0.0f) GlStateManager.rotate(renderManager.playerViewX, 1.0f, 0.0f, 0.0f) @@ -35,13 +37,12 @@ object TextRenderer { GlStateManager.disableLighting() GlStateManager.disableDepth() - GlStateManager.enableBlend() GlStateManager.tryBlendFuncSeparate( GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_SRC_ALPHA, - GL11.GL_ONE + GL11.GL_ONE, ) fontRenderer.drawString(text, -fontRenderer.getStringWidth(text) / 2, 0, 0xFFFFFF) @@ -52,4 +53,4 @@ object TextRenderer { GlStateManager.popMatrix() } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/gui/components/PSSButton.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/gui/components/PSSButton.kt index 472e330b2..12bf851db 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/gui/components/PSSButton.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/gui/components/PSSButton.kt @@ -7,9 +7,12 @@ package me.partlysanestudios.partlysaneskies.render.gui.components import cc.polyfrost.oneconfig.config.core.OneColor import gg.essential.elementa.UIComponent import gg.essential.elementa.components.UIBlock -import gg.essential.elementa.components.UIImage import gg.essential.elementa.components.UIWrappedText -import gg.essential.elementa.constraints.* +import gg.essential.elementa.constraints.CenterConstraint +import gg.essential.elementa.constraints.HeightConstraint +import gg.essential.elementa.constraints.WidthConstraint +import gg.essential.elementa.constraints.XConstraint +import gg.essential.elementa.constraints.YConstraint import gg.essential.elementa.dsl.childOf import gg.essential.elementa.dsl.constrain import gg.essential.elementa.dsl.constraint @@ -17,35 +20,41 @@ import gg.essential.elementa.dsl.percent import gg.essential.elementa.events.UIClickEvent import me.partlysanestudios.partlysaneskies.features.themes.ThemeManager.currentButtonUIImage import me.partlysanestudios.partlysaneskies.features.themes.ThemeManager.getCurrentButtonUIImage +import me.partlysanestudios.partlysaneskies.render.gui.constraints.ScaledPixelConstraint.Companion.scaledPixels +import me.partlysanestudios.partlysaneskies.render.gui.constraints.TextScaledPixelConstraint.Companion.textScaledPixels +import me.partlysanestudios.partlysaneskies.utils.ImageUtils.minus +import me.partlysanestudios.partlysaneskies.utils.ImageUtils.plus import java.awt.Color import java.util.function.Consumer class PSSButton { - private var color: OneColor private var text: String = "" private val onMouseClick = ArrayList>() - private val backgroundBlock = UIBlock().constrain { - color = Color(0, 0, 0, 0).constraint - }.onMouseClick { - for (method in onMouseClick) { - method.accept(it) + private val backgroundBlock = UIBlock() + .constrain { + color = Color(0, 0, 0, 0).constraint + }.onMouseClick { + for (method in onMouseClick) { + method.accept(it) + } } - } - private var buttonTexture = currentButtonUIImage.constrain { - x = CenterConstraint() - y = CenterConstraint() - width = 100.percent - height = 100.percent - } childOf backgroundBlock + private var buttonTexture = currentButtonUIImage + .constrain { + x = CenterConstraint() + y = CenterConstraint() + width = 100.percent + height = 100.percent + } childOf backgroundBlock private val textComponent = UIWrappedText(text, false, Color(0, 0, 0, 0), true).constrain { x = CenterConstraint() y = CenterConstraint() width = 100.percent - color = Color.white.constraint + color = Color.lightGray.constraint + textScale = 1.textScaledPixels } childOf backgroundBlock constructor() { @@ -61,6 +70,18 @@ class PSSButton { this.color = color } + init { + backgroundBlock.onMouseEnter { + buttonTexture.setWidth(105.percent) + buttonTexture.setHeight(105.percent) + textComponent.setColor(textComponent.getColor() - Color(68, 68, 68)) + }.onMouseLeave { + buttonTexture.setWidth(100.percent) + buttonTexture.setHeight(100.percent) + textComponent.setColor(textComponent.getColor() + Color(68, 68, 68)) + } + } + fun setHeight(height: HeightConstraint): PSSButton { backgroundBlock.setHeight(height) return this @@ -86,9 +107,7 @@ class PSSButton { return this } - fun setColor(color: Color): PSSButton { - return setColor(OneColor(color)) - } + fun setColor(color: Color): PSSButton = setColor(OneColor(color)) fun setColor(color: OneColor): PSSButton { backgroundBlock.removeChild(buttonTexture) diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/gui/components/PSSHorizontalCooldown.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/gui/components/PSSHorizontalCooldown.kt index b10490c5b..e4f0ed2dd 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/gui/components/PSSHorizontalCooldown.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/gui/components/PSSHorizontalCooldown.kt @@ -3,13 +3,20 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.render.gui.components import gg.essential.elementa.UIComponent import gg.essential.elementa.components.UIRoundedRectangle -import gg.essential.elementa.constraints.* -import gg.essential.elementa.dsl.* +import gg.essential.elementa.constraints.CenterConstraint +import gg.essential.elementa.constraints.HeightConstraint +import gg.essential.elementa.constraints.WidthConstraint +import gg.essential.elementa.constraints.XConstraint +import gg.essential.elementa.constraints.YConstraint +import gg.essential.elementa.dsl.childOf +import gg.essential.elementa.dsl.constrain +import gg.essential.elementa.dsl.constraint +import gg.essential.elementa.dsl.percent +import gg.essential.elementa.dsl.pixels import me.partlysanestudios.partlysaneskies.render.gui.constraints.ScaledPixelConstraint.Companion.scaledPixels import me.partlysanestudios.partlysaneskies.render.gui.hud.cooldown.Cooldown import me.partlysanestudios.partlysaneskies.utils.ElementaUtils.weightedAverage @@ -19,33 +26,36 @@ class PSSHorizontalCooldown( private val xConstraint: XConstraint, private val yConstraint: YConstraint, private val widthConstraint: WidthConstraint, - private val heightConstraint: HeightConstraint + private val heightConstraint: HeightConstraint, ) { private var cooldown: Cooldown? = null - val boundingBox = UIRoundedRectangle(2f).constrain { - radius = 4f.scaledPixels - x = xConstraint - y = yConstraint - height = heightConstraint - width = widthConstraint - color = Color(0, 0, 0, 0).constraint - } + val boundingBox = UIRoundedRectangle(2f) + .constrain { + radius = 4f.scaledPixels + x = xConstraint + y = yConstraint + height = heightConstraint + width = widthConstraint + color = Color(0, 0, 0, 0).constraint + } - private val displayBox = UIRoundedRectangle(2f).constrain { - radius = 4f.scaledPixels - x = 0f.pixels - y = 0f.pixels - height = 100f.percent - width = 0f.pixels - color = Color(255, 0, 0).constraint - } childOf boundingBox - - private val itemRender = PSSItemRender(null, autoScaleWidth = true).constrain { - width = 1.75.percent - x = (-35).percent - y = CenterConstraint() - } childOf boundingBox + private val displayBox = UIRoundedRectangle(2f) + .constrain { + radius = 4f.scaledPixels + x = 0f.pixels + y = 0f.pixels + height = 100f.percent + width = 0f.pixels + color = Color(255, 0, 0).constraint + } childOf boundingBox + + private val itemRender = PSSItemRender(null, autoScaleWidth = true) + .constrain { + width = 1.75.percent + x = (-35).percent + y = CenterConstraint() + } childOf boundingBox fun setChildOf(parent: UIComponent): PSSHorizontalCooldown { boundingBox.setChildOf(parent) diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/gui/components/PSSItemRender.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/gui/components/PSSItemRender.kt index 26b57a5cd..6e9858297 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/gui/components/PSSItemRender.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/gui/components/PSSItemRender.kt @@ -16,7 +16,6 @@ import net.minecraft.client.renderer.GlStateManager import net.minecraft.item.ItemStack class PSSItemRender(var item: ItemStack?, private val autoScaleWidth: Boolean = false) : UIComponent() { - private var itemScale = 1f override fun draw(matrixStack: UMatrixStack) { diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/gui/components/PSSToggle.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/gui/components/PSSToggle.kt index 74f6e9316..fd34e53f7 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/gui/components/PSSToggle.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/gui/components/PSSToggle.kt @@ -7,7 +7,11 @@ package me.partlysanestudios.partlysaneskies.render.gui.components import gg.essential.elementa.UIComponent import gg.essential.elementa.components.UIBlock import gg.essential.elementa.components.UIImage -import gg.essential.elementa.constraints.* +import gg.essential.elementa.constraints.CenterConstraint +import gg.essential.elementa.constraints.HeightConstraint +import gg.essential.elementa.constraints.WidthConstraint +import gg.essential.elementa.constraints.XConstraint +import gg.essential.elementa.constraints.YConstraint import gg.essential.elementa.dsl.childOf import gg.essential.elementa.dsl.constrain import gg.essential.elementa.dsl.percent @@ -21,40 +25,48 @@ class PSSToggle { private var backgroundBlock: UIBlock = UIBlock() .setColor(Color(0, 0, 0, 0)) as UIBlock - private var buttonTexture: UIImage = getCurrentToggleUIImage(false).constrain { - x = CenterConstraint() - y = CenterConstraint() - width = 100.percent - height = 100.percent - } childOf backgroundBlock - - fun toggleState(): PSSToggle { - return setState(!state) + private var buttonTexture: UIImage = getCurrentToggleUIImage(false) + .constrain { + x = CenterConstraint() + y = CenterConstraint() + width = 100.percent + height = 100.percent + } childOf backgroundBlock + + init { + backgroundBlock.onMouseEnter { + buttonTexture.setWidth(105.percent) + buttonTexture.setHeight(105.percent) + }.onMouseLeave { + buttonTexture.setWidth(100.percent) + buttonTexture.setHeight(100.percent) + } } + fun toggleState(): PSSToggle = setState(!state) + fun setState(state: Boolean): PSSToggle { this.state = state return updateState() } - fun getState(): Boolean { - return this.state - } + fun getState(): Boolean = this.state private fun updateState(): PSSToggle { val children = buttonTexture.children backgroundBlock.removeChild(buttonTexture) - buttonTexture = if (state) { - getCurrentToggleUIImage(true) - } else { - getCurrentToggleUIImage(false) - }.constrain { - width = 100.percent - height = 100.percent - x = CenterConstraint() - y = CenterConstraint() - } + buttonTexture = + if (state) { + getCurrentToggleUIImage(true) + } else { + getCurrentToggleUIImage(false) + }.constrain { + width = 100.percent + height = 100.percent + x = CenterConstraint() + y = CenterConstraint() + } backgroundBlock.insertChildAt(buttonTexture, 0) diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/gui/constraints/ScaledPixelConstraint.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/gui/constraints/ScaledPixelConstraint.kt index 04f40892b..239126752 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/gui/constraints/ScaledPixelConstraint.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/gui/constraints/ScaledPixelConstraint.kt @@ -7,45 +7,38 @@ import gg.essential.elementa.constraints.resolution.ConstraintVisitor import gg.essential.elementa.dsl.pixels import me.partlysanestudios.partlysaneskies.utils.ElementaUtils -class ScaledPixelConstraint(var value: Float, val alignOpposite: Boolean = false, val alignOutside: Boolean = false) : - MasterConstraint { +open class ScaledPixelConstraint( + var value: Float, + val alignOpposite: Boolean = false, + val alignOutside: Boolean = false, +) : MasterConstraint { companion object { val Number.scaledPixels: ScaledPixelConstraint - get() { - return ScaledPixelConstraint((this.toDouble()).toFloat(), alignOpposite = false, alignOutside = false) - } + get() = ScaledPixelConstraint(this.toFloat(), alignOpposite = false, alignOutside = false) - fun Number.scaledPixels(alignOpposite: Boolean = false, alignOutside: Boolean = false): ScaledPixelConstraint { - return ScaledPixelConstraint((this.toDouble()).toFloat(), alignOpposite, alignOutside) - } + fun Number.scaledPixels(alignOpposite: Boolean = false, alignOutside: Boolean = false): ScaledPixelConstraint = + ScaledPixelConstraint(this.toFloat(), alignOpposite, alignOutside) } override var cachedValue = 0f override var constrainTo: UIComponent? = null override var recalculate = true - override fun getHeightImpl(component: UIComponent): Float { - return (value * ElementaUtils.scaleFactor).pixels(alignOpposite, alignOutside).getHeightImpl(component) - } + override fun getHeightImpl(component: UIComponent): Float = + (value * ElementaUtils.scaleFactor).pixels(alignOpposite, alignOutside).getHeightImpl(component) - override fun getRadiusImpl(component: UIComponent): Float { - return (value * ElementaUtils.scaleFactor).pixels(alignOpposite, alignOutside).getRadiusImpl(component) - } + override fun getRadiusImpl(component: UIComponent): Float = + (value * ElementaUtils.scaleFactor).pixels(alignOpposite, alignOutside).getRadiusImpl(component) - override fun getWidthImpl(component: UIComponent): Float { - return (value * ElementaUtils.scaleFactor).pixels(alignOpposite, alignOutside).getWidthImpl(component) - } + override fun getWidthImpl(component: UIComponent): Float = + (value * ElementaUtils.scaleFactor).pixels(alignOpposite, alignOutside).getWidthImpl(component) - override fun getXPositionImpl(component: UIComponent): Float { - return (value * ElementaUtils.scaleFactor).pixels(alignOpposite, alignOutside).getXPositionImpl(component) - } + override fun getXPositionImpl(component: UIComponent): Float = + (value * ElementaUtils.scaleFactor).pixels(alignOpposite, alignOutside).getXPositionImpl(component) - override fun getYPositionImpl(component: UIComponent): Float { - return (value * ElementaUtils.scaleFactor).pixels(alignOpposite, alignOutside).getYPositionImpl(component) - } - - override fun visitImpl(visitor: ConstraintVisitor, type: ConstraintType) { - return (value * ElementaUtils.scaleFactor).pixels(alignOpposite, alignOutside).visitImpl(visitor, type) - } + override fun getYPositionImpl(component: UIComponent): Float = + (value * ElementaUtils.scaleFactor).pixels(alignOpposite, alignOutside).getYPositionImpl(component) -} \ No newline at end of file + override fun visitImpl(visitor: ConstraintVisitor, type: ConstraintType) = + (value * ElementaUtils.scaleFactor).pixels(alignOpposite, alignOutside).visitImpl(visitor, type) +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/gui/constraints/TextScaledPixelConstraint.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/gui/constraints/TextScaledPixelConstraint.kt new file mode 100644 index 000000000..367985462 --- /dev/null +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/gui/constraints/TextScaledPixelConstraint.kt @@ -0,0 +1,52 @@ +// +// Written by Su386. +// See LICENSE for copyright and license notices. +// + + +package me.partlysanestudios.partlysaneskies.render.gui.constraints + +import gg.essential.elementa.UIComponent +import gg.essential.elementa.constraints.ConstraintType +import gg.essential.elementa.constraints.MasterConstraint +import gg.essential.elementa.constraints.resolution.ConstraintVisitor +import gg.essential.elementa.dsl.pixels +import me.partlysanestudios.partlysaneskies.utils.ElementaUtils + +class TextScaledPixelConstraint( + var value: Float, + val alignOpposite: Boolean = false, + val alignOutside: Boolean = false, +) : MasterConstraint { + constructor(value: Float): this(value, false, false) + + companion object { + val Number.textScaledPixels: TextScaledPixelConstraint + get() = TextScaledPixelConstraint(this.toFloat(), alignOpposite = false, alignOutside = false) + + fun Number.textScaledPixels(alignOpposite: Boolean = false, alignOutside: Boolean = false): TextScaledPixelConstraint = + TextScaledPixelConstraint(this.toFloat(), alignOpposite, alignOutside) + } + + override var cachedValue = 0f + override var constrainTo: UIComponent? = null + override var recalculate = true + + override fun getHeightImpl(component: UIComponent): Float = + (value * ElementaUtils.scaleFactor * ElementaUtils.textScale).pixels(alignOpposite, alignOutside).getHeightImpl(component) + + override fun getRadiusImpl(component: UIComponent): Float = + (value * ElementaUtils.scaleFactor * ElementaUtils.textScale).pixels(alignOpposite, alignOutside).getRadiusImpl(component) + + override fun getWidthImpl(component: UIComponent): Float = + (value * ElementaUtils.scaleFactor * ElementaUtils.textScale).pixels(alignOpposite, alignOutside).getWidthImpl(component) + + override fun getXPositionImpl(component: UIComponent): Float = + (value * ElementaUtils.scaleFactor * ElementaUtils.textScale).pixels(alignOpposite, alignOutside).getXPositionImpl(component) + + override fun getYPositionImpl(component: UIComponent): Float = + (value * ElementaUtils.scaleFactor * ElementaUtils.textScale).pixels(alignOpposite, alignOutside).getYPositionImpl(component) + + override fun visitImpl(visitor: ConstraintVisitor, type: ConstraintType) = + (value * ElementaUtils.scaleFactor * ElementaUtils.textScale).pixels(alignOpposite, alignOutside).visitImpl(visitor, type) +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/gui/hud/BannerRenderer.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/gui/hud/BannerRenderer.kt index 4be147a09..c937db529 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/gui/hud/BannerRenderer.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/gui/hud/BannerRenderer.kt @@ -15,9 +15,10 @@ import gg.essential.elementa.dsl.constraint import gg.essential.elementa.dsl.pixels import gg.essential.universal.UMatrixStack import me.partlysanestudios.partlysaneskies.PartlySaneSkies +import me.partlysanestudios.partlysaneskies.render.gui.constraints.ScaledPixelConstraint.Companion.scaledPixels +import me.partlysanestudios.partlysaneskies.render.gui.constraints.TextScaledPixelConstraint.Companion.textScaledPixels import me.partlysanestudios.partlysaneskies.utils.ImageUtils.applyOpacity import me.partlysanestudios.partlysaneskies.utils.MathUtils - import net.minecraft.client.gui.Gui import net.minecraftforge.client.event.RenderGameOverlayEvent import net.minecraftforge.fml.common.eventhandler.SubscribeEvent @@ -28,15 +29,13 @@ object BannerRenderer : Gui() { private val window = Window(ElementaVersion.V2) - private var displayText: UIText = UIText("{EMPTY BANNER}") .constrain { - textScale = 5F.pixels + textScale = 5F.scaledPixels x = CenterConstraint() y = CenterConstraint() color = Color(255, 255, 255, 0).constraint - - }.setColor(Color(255, 255, 255, 0)) as UIText childOf window + } childOf window @SubscribeEvent fun onScreenRender(event: RenderGameOverlayEvent.Text) { @@ -58,15 +57,16 @@ object BannerRenderer : Gui() { val calculatedTextScale = (bannerToRender.textScale * PartlySaneSkies.config.bannerSize) if (displayText.getText() != bannerToRender.text) { - displayText.setText(bannerToRender.text) + displayText + .setText(bannerToRender.text) .constrain { - textScale = calculatedTextScale.pixels + textScale = calculatedTextScale.textScaledPixels x = CenterConstraint() y = (window.getHeight() * .125f).pixels color = bannerToRender.getFadedColor().constraint } childOf window } else if (displayText.getTextScale() != calculatedTextScale.pixels.value) { - displayText.setTextScale(calculatedTextScale.pixels) + displayText.setTextScale(calculatedTextScale.textScaledPixels) } // ChatUtils.sendClientMessage(bannerToRender.getFadedColor().alpha.toString()) @@ -83,7 +83,6 @@ object BannerRenderer : Gui() { // ChatUtils.sendClientMessage("Banner: ${banner.text} is out of date ${banner.renderStartTime}, ${banner.lengthOfTimeToRender}") bannerList.removeAt(i) } - } } @@ -113,7 +112,7 @@ class PSSBanner( val text: String, val lengthOfTimeToRender: Long, val textScale: Float = 5f, - private val color: Color = Color.red + private val color: Color = Color.red, ) { val creationTime = PartlySaneSkies.time @@ -123,13 +122,9 @@ class PSSBanner( this.renderStartTime = PartlySaneSkies.time } - fun isOutOfDate(): Boolean { - return !MathUtils.onCooldown(renderStartTime, lengthOfTimeToRender) - } + fun isOutOfDate(): Boolean = !MathUtils.onCooldown(renderStartTime, lengthOfTimeToRender) - fun hasStartedRendering(): Boolean { - return renderStartTime == -1L - } + fun hasStartedRendering(): Boolean = renderStartTime == -1L fun getFadedColor(): Color { val alpha = getAlpha(renderStartTime, lengthOfTimeToRender / 1000.0).toInt() @@ -140,7 +135,6 @@ class PSSBanner( private fun getAlpha(timeStarted: Long, displayLengthSeconds: Double): Short { val displayLength = displayLengthSeconds * 1000 - val fadeLength = displayLength * (1 / 6.0) val timeSinceStarted = PartlySaneSkies.time - timeStarted @@ -156,7 +150,4 @@ class PSSBanner( 0 } } - } - - diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/gui/hud/cooldown/Cooldown.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/gui/hud/cooldown/Cooldown.kt index 90d760804..8656e690b 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/gui/hud/cooldown/Cooldown.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/gui/hud/cooldown/Cooldown.kt @@ -10,22 +10,17 @@ import me.partlysanestudios.partlysaneskies.utils.MathUtils import net.minecraft.item.ItemStack abstract class Cooldown { - private var startingTime = -1L /** * @return Starting time of cooldown in milliseconds */ - fun getStartingTime(): Long { - return startingTime - } + fun getStartingTime(): Long = startingTime /** * @return Ending time of the cooldown in milliseconds */ - fun getEndingTime(): Long { - return getStartingTime() + getTotalTime() - } + fun getEndingTime(): Long = getStartingTime() + getTotalTime() /** * @return Total time of the cooldown in milliseconds @@ -35,9 +30,7 @@ abstract class Cooldown { /** * @return Time remaining of the cooldown in milliseconds */ - fun getTimeRemaining(): Long { - return getEndingTime() - PartlySaneSkies.time - } + fun getTimeRemaining(): Long = getEndingTime() - PartlySaneSkies.time /** * Starts the cooldown by setting the starting time to now @@ -49,9 +42,7 @@ abstract class Cooldown { /* * Returns true if the cooldown is active, false if it is not */ - fun isCooldownActive(): Boolean { - return MathUtils.onCooldown(startingTime, getTotalTime()) - } + fun isCooldownActive(): Boolean = MathUtils.onCooldown(startingTime, getTotalTime()) /* * Returns the name of the cooldown @@ -59,4 +50,4 @@ abstract class Cooldown { abstract fun getDisplayName(): String abstract fun getItemToDisplay(): ItemStack -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/gui/hud/cooldown/CooldownManager.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/gui/hud/cooldown/CooldownManager.kt index c0d401b0d..fbb9be0ad 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/gui/hud/cooldown/CooldownManager.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/gui/hud/cooldown/CooldownManager.kt @@ -3,13 +3,11 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.render.gui.hud.cooldown -import java.util.* +import java.util.LinkedList object CooldownManager { - private val cooldowns = ArrayList() fun getActiveCooldowns(): List { @@ -27,4 +25,4 @@ object CooldownManager { fun registerCooldown(cooldown: Cooldown) { cooldowns.add(cooldown) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/waypoint/BeamRenderer.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/waypoint/BeamRenderer.kt index d3c1579d1..a3fda7434 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/waypoint/BeamRenderer.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/waypoint/BeamRenderer.kt @@ -3,7 +3,6 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.render.waypoint import me.partlysanestudios.partlysaneskies.render.RenderPrimitives.drawBoxFill @@ -17,7 +16,11 @@ import org.lwjgl.opengl.GL11 import java.awt.Color object BeamRenderer { - fun renderBeam(pos: BlockPos, outlineColor: Color, fillColor: Color) { + fun renderBeam( + pos: BlockPos, + outlineColor: Color, + fillColor: Color, + ) { val minecraft = Minecraft.getMinecraft() val renderManager = minecraft.renderManager val tessellator = Tessellator.getInstance() @@ -39,13 +42,12 @@ object BeamRenderer { val y = pos.y.toDouble() + 1 val z = pos.z.toDouble() + .333 - worldRenderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION) GlStateManager.color( fillColor.red / 255f, fillColor.green / 255f, fillColor.blue / 255f, - fillColor.alpha / 255f + fillColor.alpha / 255f, ) worldRenderer.drawBoxFill(Point3d(x, y, z), Point3d(x + .333, 256.0, z + .333)) @@ -58,4 +60,4 @@ object BeamRenderer { GlStateManager.popMatrix() } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/waypoint/BlockHighlightRenderer.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/waypoint/BlockHighlightRenderer.kt index 4f8f593d8..d216ae979 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/waypoint/BlockHighlightRenderer.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/waypoint/BlockHighlightRenderer.kt @@ -3,7 +3,6 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.render.waypoint import me.partlysanestudios.partlysaneskies.render.RenderPrimitives.drawBoxFill @@ -17,9 +16,12 @@ import net.minecraft.util.BlockPos import org.lwjgl.opengl.GL11 import java.awt.Color - object BlockHighlightRenderer { - fun renderColoredBlockHighlight(pos: BlockPos, outlineColor: Color, fillColor: Color) { + fun renderColoredBlockHighlight( + pos: BlockPos, + outlineColor: Color, + fillColor: Color, + ) { val minecraft = Minecraft.getMinecraft() val renderManager = minecraft.renderManager val tessellator = Tessellator.getInstance() @@ -46,18 +48,17 @@ object BlockHighlightRenderer { outlineColor.red / 255f, outlineColor.green / 255f, outlineColor.blue / 255f, - outlineColor.alpha / 255f + outlineColor.alpha / 255f, ) worldRenderer.drawBoxOutline(Point3d(x, y, z), Point3d(x + 1, y + 1, z + 1)) tessellator.draw() - worldRenderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION) GlStateManager.color( fillColor.red / 255f, fillColor.green / 255f, fillColor.blue / 255f, - fillColor.alpha / 255f + fillColor.alpha / 255f, ) worldRenderer.drawBoxFill(Point3d(x, y, z), Point3d(x + 1, y + 1, z + 1)) tessellator.draw() @@ -67,7 +68,6 @@ object BlockHighlightRenderer { GlStateManager.disableBlend() GlStateManager.enableDepth() - GlStateManager.popMatrix() } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/waypoint/Waypoint.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/waypoint/Waypoint.kt index 73c344036..8d5fb3bfe 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/waypoint/Waypoint.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/render/waypoint/Waypoint.kt @@ -3,7 +3,6 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.render.waypoint import me.partlysanestudios.partlysaneskies.render.TextRenderer @@ -19,9 +18,8 @@ class Waypoint( val showBeam: Boolean = true, val showBlockHighlight: Boolean = true, val showLabel: Boolean = true, - val showDistance: Boolean = true + val showDistance: Boolean = true, ) { - /** * Render the waypoint * @@ -49,4 +47,4 @@ class Waypoint( TextRenderer.renderText3d(this.position.up(), distanceText) } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/system/SystemNotification.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/system/SystemNotification.kt index e822e75b9..851af47f1 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/system/SystemNotification.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/system/SystemNotification.kt @@ -3,7 +3,6 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.system import java.awt.SystemTray @@ -30,8 +29,10 @@ object SystemNotification { val tray = SystemTray.getSystemTray() // Custom Icon doesnt seem to be possible anyway sooo idk - val image = Toolkit.getDefaultToolkit() - .createImage(URL("https://cdn.modrinth.com/data/jlWHBQtc/8be3d6a35e683c41f9ddf086fd6d56146a494d75.jpeg")) + val image = + Toolkit + .getDefaultToolkit() + .createImage(URL("https://cdn.modrinth.com/data/jlWHBQtc/8be3d6a35e683c41f9ddf086fd6d56146a494d75.jpeg")) val trayIcon = TrayIcon(image, "PartlySaneSkies") trayIcon.setImageAutoSize(true) @@ -49,4 +50,4 @@ object SystemNotification { private fun showJOptionPaneBackup(text: String) { JOptionPane.showMessageDialog(null, text, NOTIFICATION_TITLE, JOptionPane.INFORMATION_MESSAGE) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/ChatUtils.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/ChatUtils.kt index 660b6b314..12d25e3a7 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/ChatUtils.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/ChatUtils.kt @@ -3,14 +3,13 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.utils import me.partlysanestudios.partlysaneskies.PartlySaneSkies +import me.partlysanestudios.partlysaneskies.events.minecraft.PSSChatEvent import me.partlysanestudios.partlysaneskies.utils.StringUtils.removeColorCodes import net.minecraft.util.ChatComponentText import net.minecraft.util.IChatComponent -import net.minecraftforge.client.event.ClientChatReceivedEvent import org.apache.logging.log4j.Level import java.awt.Toolkit import java.awt.datatransfer.StringSelection @@ -23,7 +22,8 @@ object ChatUtils { fun visPrint(print: Any) { SystemUtils.log(Level.INFO, "\n\n\n$print\n\n\n".trimIndent()) try { - PartlySaneSkies.minecraft.ingameGUI.chatGUI.printChatMessage(ChatComponentText("\n $print")) + PartlySaneSkies.minecraft.ingameGUI.chatGUI + .printChatMessage(ChatComponentText("\n $print")) val stringSelection = StringSelection(print.toString()) try { val clipboard = Toolkit.getDefaultToolkit().systemClipboard @@ -35,7 +35,8 @@ object ChatUtils { } fun sendClientMessage(chatComponent: IChatComponent?) { - PartlySaneSkies.minecraft.ingameGUI.chatGUI.printChatMessage(chatComponent) + PartlySaneSkies.minecraft.ingameGUI.chatGUI + .printChatMessage(chatComponent) } fun sendClientMessage(text: String) { @@ -44,7 +45,7 @@ object ChatUtils { - val ClientChatReceivedEvent.trueUnformattedMessage get() = this.message.unformattedText.removeColorCodes() + val PSSChatEvent.trueUnformattedMessage get() = this.component.unformattedText.removeColorCodes() /** * Sends a message to the client. @@ -64,4 +65,4 @@ object ChatUtils { } } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/ElementaUtils.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/ElementaUtils.kt index e3802cb05..59bfc573d 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/ElementaUtils.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/ElementaUtils.kt @@ -3,7 +3,6 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.utils import gg.essential.elementa.UIComponent @@ -11,6 +10,7 @@ import gg.essential.elementa.components.UIImage import gg.essential.elementa.constraints.CenterConstraint import gg.essential.elementa.dsl.percent import gg.essential.universal.UResolution +import me.partlysanestudios.partlysaneskies.config.OneConfigScreen import me.partlysanestudios.partlysaneskies.features.themes.ThemeManager import net.minecraft.client.Minecraft import net.minecraft.util.ResourceLocation @@ -20,7 +20,6 @@ import java.util.concurrent.CompletableFuture import javax.imageio.ImageIO object ElementaUtils { - val windowHeight: Int get() = UResolution.scaledHeight val windowWidth: Int get() = UResolution.scaledWidth val scaleFactor: Double @@ -28,11 +27,9 @@ object ElementaUtils { val constantWidth = 1280.0 val constantHeight = 800.0 - val width = windowWidth val height = windowHeight - return if (width < height) { width / constantWidth } else { @@ -40,45 +37,51 @@ object ElementaUtils { } } + val textScale: Double get() = OneConfigScreen.textScale.toDouble() val ResourceLocation.uiImage: UIImage - get() { - return try { + get() = try { val resource = Minecraft.getMinecraft().resourceManager.getResource(this) - UIImage(CompletableFuture.supplyAsync { - try { - return@supplyAsync ImageIO.read(resource.inputStream) - } catch (e: IOException) { - e.printStackTrace() - } finally { + UIImage( + CompletableFuture.supplyAsync { try { - resource.inputStream.close() + return@supplyAsync ImageIO.read(resource.inputStream) } catch (e: IOException) { e.printStackTrace() + } finally { + try { + resource.inputStream.close() + } catch (e: IOException) { + e.printStackTrace() + } } - } - null - }) + null + }, + ) } catch (exception: NullPointerException) { UIImage.ofResource("/assets/partlysaneskies/" + this.resourcePath) // return UIImage.ofResource("/assets/partlysaneskies/textures/null_texture.png"); } catch (exception: IOException) { UIImage.ofResource("/assets/partlysaneskies/" + this.resourcePath) } - } fun UIComponent.applyBackground(): UIComponent { - val image = ThemeManager.currentBackgroundUIImage - .setX(CenterConstraint()) - .setY(CenterConstraint()) - .setWidth(100.percent) - .setHeight(100.percent) as UIImage + val image = + ThemeManager.currentBackgroundUIImage + .setX(CenterConstraint()) + .setY(CenterConstraint()) + .setWidth(100.percent) + .setHeight(100.percent) as UIImage this.insertChildAt(image, 0) return this } - fun Color.weightedAverage(thisColorWeight: Float, otherColor: Color, otherColorWeight: Float): Color { + fun Color.weightedAverage( + thisColorWeight: Float, + otherColor: Color, + otherColorWeight: Float, + ): Color { val totalWeight = thisColorWeight + otherColorWeight val thisColorPercent = thisColorWeight / totalWeight val otherColorPercent = otherColorWeight / totalWeight @@ -88,7 +91,6 @@ object ElementaUtils { var finalB = this.blue * thisColorPercent + otherColor.blue * otherColorPercent var finalA = this.alpha * thisColorPercent + otherColor.alpha * otherColorPercent - if (finalR > 255) { finalR = 255f } @@ -102,7 +104,6 @@ object ElementaUtils { finalA = 255f } - if (finalR < 0) { finalR = 0f } @@ -116,9 +117,6 @@ object ElementaUtils { finalA = 0f } - - return Color(finalR / 255f, finalG / 255f, finalB / 255f, finalA / 255f) - } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/HypixelUtils.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/HypixelUtils.kt index fb7dfb1ea..a118aab65 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/HypixelUtils.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/HypixelUtils.kt @@ -3,27 +3,31 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.utils import me.partlysanestudios.partlysaneskies.PartlySaneSkies +import me.partlysanestudios.partlysaneskies.data.skyblockdata.IslandType +import me.partlysanestudios.partlysaneskies.events.SubscribePSSEvent +import me.partlysanestudios.partlysaneskies.events.minecraft.TablistUpdateEvent import me.partlysanestudios.partlysaneskies.utils.StringUtils.removeColorCodes import me.partlysanestudios.partlysaneskies.utils.StringUtils.stripLeading import me.partlysanestudios.partlysaneskies.utils.StringUtils.stripTrailing import net.minecraft.item.ItemStack import net.minecraft.nbt.NBTTagCompound -import java.util.* +import java.util.Locale object HypixelUtils { + + var currentIsland: IslandType? = null + // Returns if the current gamemode is skyblock - fun isSkyblock(): Boolean { - return MinecraftUtils.getScoreboardName().lowercase(Locale.getDefault()).contains("skyblock") - } + fun isSkyblock(): Boolean = MinecraftUtils.getScoreboardName().lowercase(Locale.getDefault()).contains("skyblock") // Returns if the current server is hypixel fun isHypixel(): Boolean { try { - return PartlySaneSkies.minecraft.currentServerData.serverIP.contains(".hypixel.net") + return PartlySaneSkies.minecraft.currentServerData.serverIP + .contains(".hypixel.net") } catch (ignored: NullPointerException) { } return false @@ -83,10 +87,12 @@ object HypixelUtils { } return if (money == "") { 0L - } else try { - money.toLong() - } catch (event: java.lang.NumberFormatException) { - 0 + } else { + try { + money.toLong() + } catch (event: java.lang.NumberFormatException) { + 0 + } } } @@ -98,8 +104,8 @@ object HypixelUtils { val scoreboard = MinecraftUtils.getScoreboardLines() for (line in scoreboard) { if ( - stripLeading(line).contains("⏣") - || stripLeading(line).contains("ф") + stripLeading(line).contains("⏣") || + stripLeading(line).contains("ф") ) { return stripLeading(line).replace(Regex("[⏣ф]"), "") } @@ -111,9 +117,7 @@ object HypixelUtils { * Gets the item id from an item * @return The item id */ - fun ItemStack.getItemId(): String { - return this.getItemAttributes()?.getString("id") ?: "" - } + fun ItemStack.getItemId(): String = this.getItemAttributes()?.getString("id") ?: "" fun ItemStack.getHypixelEnchants(): Map { val map = HashMap() @@ -133,7 +137,19 @@ object HypixelUtils { * Gets the item attributes from an item * @return The item attributes */ - fun ItemStack.getItemAttributes(): NBTTagCompound? { - return this.tagCompound?.getCompoundTag("ExtraAttributes") + fun ItemStack.getItemAttributes(): NBTTagCompound? = this.tagCompound?.getCompoundTag("ExtraAttributes") + + fun inAdvancedMiningIsland() = IslandType.onIslands(IslandType.DWARVEN_MINES, IslandType.CRYSTAL_HOLLOWS, IslandType.MINESHAFT) + + + @SubscribePSSEvent + fun onTablistUpdate(event: TablistUpdateEvent) { + currentIsland = event.list + .map { it.removeColorCodes().trim() } + .firstOrNull { it.startsWith("Area: ") || it.startsWith("Dungeon: ") } + ?.let { line -> + val islandName = line.replace("Area: ", "").replace("Dungeon: ", "").trim() + IslandType.entries.firstOrNull { it.islandName.equals(islandName, ignoreCase = true) } + } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/ImageUtils.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/ImageUtils.kt index 9e543a970..0653dc5d6 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/ImageUtils.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/ImageUtils.kt @@ -3,7 +3,6 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.utils import cc.polyfrost.oneconfig.config.core.OneColor @@ -18,7 +17,6 @@ object ImageUtils { // Save all images in ./config/partly-sane-skies/image_variants/{name of base image}/{name of coloured image} private const val IMAGE_SAVE_PATH = "./config/partly-sane-skies/image_variants/" - @Throws(IOException::class) fun saveImage(image: BufferedImage, path: Path) { val output = path.toFile() @@ -26,25 +24,16 @@ object ImageUtils { } @Throws(IOException::class) - fun loadImage(path: String): BufferedImage { - return ImageIO.read(File(path)) - } + fun loadImage(path: String): BufferedImage = ImageIO.read(File(path)) - fun replaceColor(image: BufferedImage, oldColor: Color, newColor: Color): BufferedImage { - return replaceColor( - image, OneColor(oldColor), OneColor( - newColor - ) - ) - } + fun replaceColor(image: BufferedImage, oldColor: Color, newColor: Color): BufferedImage = + replaceColor(image, OneColor(oldColor), OneColor(newColor)) - fun replaceColor(image: BufferedImage, oldColor: OneColor, newColor: Color): BufferedImage { - return replaceColor(image, oldColor, OneColor(newColor)) - } + fun replaceColor(image: BufferedImage, oldColor: OneColor, newColor: Color): BufferedImage = + replaceColor(image, oldColor, OneColor(newColor)) - fun replaceColor(image: BufferedImage, oldColor: Color, newColor: OneColor): BufferedImage { - return replaceColor(image, OneColor(oldColor), newColor) - } + fun replaceColor(image: BufferedImage, oldColor: Color, newColor: OneColor): BufferedImage = + replaceColor(image, OneColor(oldColor), newColor) fun replaceColor(image: BufferedImage, oldColor: OneColor, newColor: OneColor): BufferedImage { val width = image.width @@ -61,17 +50,47 @@ object ImageUtils { return image } - fun Color.applyOpacity(opacity: Int): Color { - return Color(this.red, this.green, this.blue, opacity) + fun Color.applyOpacity(opacity: Int): Color = Color(red, green, blue, opacity) + + operator fun Color.plus(color: Color): Color { + val red = if (this.red + color.red > 255) { + 255 + } else { + this.red + color.red + } + val blue = if (this.blue + color.blue > 255) { + 255 + } else { + this.blue + color.blue + } + val green = if (this.green + color.green > 255) { + 255 + } else { + this.green + color.green + } + + return Color(red, green, blue) } - val Color.asHex: Int get() { - // Get RGB components and combine them - val red = this.red - val green = this.green - val blue = this.blue + operator fun Color.minus(color: Color): Color { + val red = if (this.red - color.red < 0) { + 0 + } else { + this.red - color.red + } + val blue = if (this.blue - color.blue < 0) { + 0 + } else { + this.blue - color.blue + } + val green = if (this.green - color.green < 0) { + 0 + } else { + this.green - color.green + } - // Combine into a single integer (shift and bitwise OR) - return red shl 16 or (green shl 8) or blue + return Color(red, green, blue) } + val Color.asHex: Int + get() = red shl 16 or (green shl 8) or blue } diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/MathUtils.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/MathUtils.kt index 59d93f268..8b85ce5c9 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/MathUtils.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/MathUtils.kt @@ -3,7 +3,6 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.utils import me.partlysanestudios.partlysaneskies.PartlySaneSkies @@ -11,36 +10,24 @@ import java.util.concurrent.ThreadLocalRandom import kotlin.math.pow object MathUtils { - fun Number.round(decimalPlaces: Int): Double { - return Math.round(this.toDouble() * 10.0.pow(decimalPlaces)) / 10.0.pow(decimalPlaces) - } + fun Number.round(decimalPlaces: Int): Double = Math.round(this.toDouble() * 10.0.pow(decimalPlaces)) / 10.0.pow(decimalPlaces) - fun Number.floor(decimalPlaces: Int): Double { - return (this.toDouble() * 10.0.pow(decimalPlaces)).toInt() / 10.0.pow(decimalPlaces) - } + fun Number.floor(decimalPlaces: Int): Double = (this.toDouble() * 10.0.pow(decimalPlaces)).toInt() / 10.0.pow(decimalPlaces) - fun Number.ceil(decimalPlaces: Int): Double { - return (this.toDouble() * 10.0.pow(decimalPlaces)).toInt() / 10.0.pow(decimalPlaces) - } + fun Number.ceil(decimalPlaces: Int): Double = (this.toDouble() * 10.0.pow(decimalPlaces)).toInt() / 10.0.pow(decimalPlaces) - fun randInt(min: Int, max: Int): Int { - return ThreadLocalRandom.current().nextInt(min, max + 1) - } + fun randInt(min: Int, max: Int): Int = ThreadLocalRandom.current().nextInt(min, max + 1) - fun Map.sortMap(reverseOrder: Boolean = false): Map { - return if (reverseOrder) { + fun Map.sortMap(reverseOrder: Boolean = false): Map = + if (reverseOrder) { this.entries.sortedByDescending { it.value.toDouble() } } else { this.entries.sortedBy { it.value.toDouble() } }.associate { it.toPair() } - } - /** Takes the last time the event happened in Unix epoch time in milliseconds, * and takes the length that the event should last in millisecond * Returns false if the event is over, returns true if it is still ongoing */ - fun onCooldown(lastTime: Long, length: Long): Boolean { - return PartlySaneSkies.time <= lastTime + length - } + fun onCooldown(lastTime: Long, length: Long): Boolean = PartlySaneSkies.time <= lastTime + length } diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/MinecraftUtils.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/MinecraftUtils.kt index 81c99e5f5..59062ebda 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/MinecraftUtils.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/MinecraftUtils.kt @@ -3,7 +3,6 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.utils import com.google.common.collect.ComparisonChain @@ -42,27 +41,31 @@ object MinecraftUtils { * - Small rewrites * - Translated to kotlin */ - private val playerOrdering = Ordering.from { overlay1: NetworkPlayerInfo?, overlay2: NetworkPlayerInfo? -> - comparePlayers( - overlay1!!, overlay2!! - ) - } + private val playerOrdering = + Ordering.from { overlay1: NetworkPlayerInfo?, overlay2: NetworkPlayerInfo? -> + comparePlayers( + overlay1!!, + overlay2!!, + ) + } @SideOnly(Side.CLIENT) - fun getTabList(): List { - return try { - val players = PartlySaneSkies.minecraft.thePlayer.sendQueue.playerInfoMap.stream() - .sorted(playerOrdering) - .collect(Collectors.toList()) - players.stream() + fun getTabList(): List = + try { + val players = + PartlySaneSkies.minecraft.thePlayer.sendQueue.playerInfoMap + .stream() + .sorted(playerOrdering) + .collect(Collectors.toList()) + players + .stream() .map { info: NetworkPlayerInfo? -> - PartlySaneSkies.minecraft.ingameGUI.tabList.getPlayerName(info) - } - .collect(Collectors.toList()) + PartlySaneSkies.minecraft.ingameGUI.tabList + .getPlayerName(info) + }.collect(Collectors.toList()) } catch (e: Exception) { ArrayList() } - } fun displayGuiScreen(guiScreen: GuiScreen) { Thread { PartlySaneSkies.minecraft.addScheduledTask { PartlySaneSkies.minecraft.displayGuiScreen(guiScreen) } }.start() @@ -71,12 +74,12 @@ object MinecraftUtils { private fun comparePlayers(overlay1: NetworkPlayerInfo, overlay2: NetworkPlayerInfo): Int { val team1 = overlay1.playerTeam val team2 = overlay2.playerTeam - return ComparisonChain.start() + return ComparisonChain + .start() .compare( if (team1 != null) team1.registeredName else "", - if (team2 != null) team2.registeredName else "" - ) - .compare(overlay1.gameProfile.name, overlay2.gameProfile.name) + if (team2 != null) team2.registeredName else "", + ).compare(overlay1.gameProfile.name, overlay2.gameProfile.name) .result() } @@ -85,8 +88,12 @@ object MinecraftUtils { * @return the name of the scoreboard */ fun getScoreboardName(color: Boolean = false): String = - (PartlySaneSkies.minecraft.thePlayer?.worldScoreboard?.getObjectiveInDisplaySlot(1)?.displayName ?: "") - .let { if (color) it else it.removeColorCodes() } + ( + PartlySaneSkies.minecraft.thePlayer + ?.worldScoreboard + ?.getObjectiveInDisplaySlot(1) + ?.displayName ?: "" + ).let { if (color) it else it.removeColorCodes() } fun IInventory.getItemstackList(): ArrayList { val list = ArrayList() @@ -94,9 +101,7 @@ object MinecraftUtils { for (i in 0..53) { try { list.add(this.getStackInSlot(i) ?: continue) - } catch (_: IndexOutOfBoundsException) { - } } @@ -106,8 +111,8 @@ object MinecraftUtils { /** * @return the scoreboard lines */ - fun getScoreboardLines(): List { - return try { + fun getScoreboardLines(): List = + try { val scoreboard = PartlySaneSkies.minecraft.theWorld.scoreboard val objective = scoreboard.getObjectiveInDisplaySlot(1) val scoreCollection = scoreboard.getSortedScores(objective) @@ -116,8 +121,8 @@ object MinecraftUtils { scoreLines.add( ScorePlayerTeam.formatPlayerName( scoreboard.getPlayersTeam(score.playerName), - score.playerName - ) + score.playerName, + ), ) } scoreLines @@ -128,11 +133,8 @@ object MinecraftUtils { e.printStackTrace() emptyList() } - } - fun getCurrentlyHoldingItem(): ItemStack? { - return PartlySaneSkies.minecraft.thePlayer?.heldItem - } + fun getCurrentlyHoldingItem(): ItemStack? = PartlySaneSkies.minecraft.thePlayer?.heldItem /** * @return The inventory of the player at the bottom of the gui. ([GuiChest.upperChestInventory] field) @@ -162,9 +164,12 @@ object MinecraftUtils { get() = (this as GuiPlayerTabOverlayAccessor).`partlySaneSkies$getFooter`() fun ItemStack.getLore(): java.util.ArrayList { - if (!this.hasTagCompound() || !this.tagCompound.hasKey("display") || !this.tagCompound.getCompoundTag( - "display" - ).hasKey("Lore") + if (!this.hasTagCompound() || + !this.tagCompound.hasKey("display") || + !this.tagCompound + .getCompoundTag( + "display", + ).hasKey("Lore") ) { return java.util.ArrayList() } @@ -192,7 +197,7 @@ object MinecraftUtils { slot, 1, 0, - PartlySaneSkies.minecraft.thePlayer + PartlySaneSkies.minecraft.thePlayer, ) } @@ -203,7 +208,7 @@ object MinecraftUtils { slot, 0, 0, - PartlySaneSkies.minecraft.thePlayer + PartlySaneSkies.minecraft.thePlayer, ) } @@ -221,9 +226,7 @@ object MinecraftUtils { /** * @return all the entities loaded in the world */ - fun getAllEntitiesInWorld(): List { - return PartlySaneSkies.minecraft.theWorld?.getLoadedEntityList() ?: ArrayList() - } + fun getAllEntitiesInWorld(): List = PartlySaneSkies.minecraft.theWorld?.getLoadedEntityList() ?: ArrayList() fun getAllPlayersInWorld(): List { val playerEntities: MutableList = java.util.ArrayList() @@ -301,4 +304,3 @@ object MinecraftUtils { return itemCount } } - diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/SkyCryptUtils.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/SkyCryptUtils.kt index 0915698ad..0b9dfb219 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/SkyCryptUtils.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/SkyCryptUtils.kt @@ -11,7 +11,6 @@ import me.partlysanestudios.partlysaneskies.features.debug.DebugKey import me.partlysanestudios.partlysaneskies.utils.SystemUtils.getJsonFromPath object SkyCryptUtils { - private val skyCryptProfileURL: String = "https://sky.shiiyu.moe/api/v2/profile/" private val skyCryptNetworthPath: String = "data/networth/networth" private val skyCryptFirstJoinPath: String = "raw/first_join" @@ -40,16 +39,19 @@ object SkyCryptUtils { private fun obtainSkyCryptPlayerJSONData(username: String): JsonObject { lateinit var skyCryptObject: JsonObject RequestsManager.newRequest( - GetRequest((skyCryptProfileURL + username), + GetRequest( + (skyCryptProfileURL + username), RequestRunnable { r: Request -> if (!r.hasSucceeded()) { - ChatUtils.sendClientMessage("§ePSS is having trouble contacting SkyCrypt's API. Please try again; if this continues please report this to us via §9/discord§e.") + ChatUtils.sendClientMessage( + "§ePSS is having trouble contacting SkyCrypt's API. Please try again; if this continues please report this to us via §9/discord§e.", + ) return@RequestRunnable } if (DebugKey.isDebugMode()) ChatUtils.sendClientMessage("§eSuccessfully contacted SkyCrypt's API.") skyCryptObject = (JsonParser().parse(r.getResponse()) as JsonObject) - } - ) + }, + ), ) return skyCryptObject } @@ -65,4 +67,4 @@ object SkyCryptUtils { } return theProfileDataToReturn } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/StringUtils.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/StringUtils.kt index df03593ba..0438c8262 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/StringUtils.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/StringUtils.kt @@ -3,12 +3,14 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.utils import me.partlysanestudios.partlysaneskies.PartlySaneSkies +import me.partlysanestudios.partlysaneskies.utils.StringUtils.matches import java.awt.Color import java.text.DecimalFormat +import java.util.regex.Matcher +import java.util.Locale import java.util.regex.Pattern object StringUtils { @@ -51,11 +53,13 @@ object StringUtils { val words: MutableList = ArrayList() val chars: MutableList = ArrayList() - for (c in charArray) if (c == ' ') { - words.add(chars.joinToString("")) - chars.clear() - } else { - chars.add(c) + for (c in charArray) { + if (c == ' ') { + words.add(chars.joinToString("")) + chars.clear() + } else { + chars.add(c) + } } words.add(chars.joinToString("")) @@ -211,19 +215,19 @@ object StringUtils { result = result.substring(keyIndex) } - // Gets the first few letters after the key in the pattern val patternEndKeyIndex = keyIndex + key.length val charsAfterKey: String // If the key is the last thing in the pattern, return the result - charsAfterKey = if (patternEndKeyIndex == pattern.length) { - return result - } else if (patternEndKeyIndex + 4 <= pattern.length) { - pattern.substring(patternEndKeyIndex, patternEndKeyIndex + 4) - } else { - pattern.substring(patternEndKeyIndex) - } + charsAfterKey = + if (patternEndKeyIndex == pattern.length) { + return result + } else if (patternEndKeyIndex + 4 <= pattern.length) { + pattern.substring(patternEndKeyIndex, patternEndKeyIndex + 4) + } else { + pattern.substring(patternEndKeyIndex) + } // Uses those characters to get the end of the string in the // input, not the pattern @@ -266,8 +270,8 @@ object StringUtils { } } - fun Char.romanCharToInt(): Int { - return when (this) { + fun Char.romanCharToInt(): Int = + when (this) { 'I' -> 1 'V' -> 5 'X' -> 10 @@ -277,7 +281,6 @@ object StringUtils { 'M' -> 1000 else -> throw IllegalArgumentException("Invalid Roman numeral character: $this") } - } fun String.romanNumeralToInt(): Int { var total = 0 @@ -330,7 +333,7 @@ object StringUtils { "§c" -> Color(255, 85, 85) "§d" -> Color(255, 85, 255) "§e" -> Color(255, 255, 85) - "§f" -> Color(0, 0, 0) + "§f" -> Color(255, 255, 255) "§1" -> Color(0, 0, 170) "§2" -> Color(0, 170, 0) "§3" -> Color(0, 170, 170) @@ -354,9 +357,7 @@ object StringUtils { } fun Int.toRoman(): String { - if (this <= 0 || this > 3999) { - throw IllegalArgumentException("Number out of range (must be between 1 and 3999)") - } + require(this in 1 until 4000) { "Number out of range (must be between 1 and 3999)" } var number = this return buildString { @@ -383,4 +384,25 @@ object StringUtils { } } + fun String.lastUsedColorCode(startIndex: Int = 0, endIndex: Int = this.length): String? { + val colorCodes = "0123456789abcdef" + val regex = Regex("§[${colorCodes}]") + + val subString = this.substring(startIndex, endIndex) + val matches = regex.findAll(subString) + + return matches.lastOrNull()?.value + } + + fun Pattern.matches(string: String): Boolean = matcher(string).matches() + + fun Pattern.getMatcher(string: String, matcher: Matcher.() -> T): T? { + val matched = matcher(string) + return if (matched.matches()) matcher(matched) else null + } + + fun Pattern.matchGroup(string: String, group: String): String? { + val matched = matcher(string) + return if (matched.matches()) matched.group(group) else null + } } diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/SystemUtils.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/SystemUtils.kt index 2397e92dc..070f0a1ec 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/SystemUtils.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/SystemUtils.kt @@ -3,7 +3,6 @@ // See LICENSE for copyright and license notices. // - package me.partlysanestudios.partlysaneskies.utils import com.google.gson.JsonElement @@ -25,9 +24,7 @@ import java.io.InputStreamReader import java.net.* import java.util.* - object SystemUtils { - /** * Logs a message to the console * @param level The level to log the message at @@ -48,7 +45,6 @@ object SystemUtils { return CompressedStreamTools.readCompressed(ByteArrayInputStream(bytes)) } - /** * Copies a string to the clipboard * @param string The string to copy @@ -59,13 +55,9 @@ object SystemUtils { private fun getTransferableString(string: String): Transferable { return object : Transferable { - override fun getTransferDataFlavors(): Array { - return arrayOf(DataFlavor.stringFlavor) - } + override fun getTransferDataFlavors(): Array = arrayOf(DataFlavor.stringFlavor) - override fun isDataFlavorSupported(flavor: DataFlavor): Boolean { - return DataFlavor.stringFlavor.equals(flavor) - } + override fun isDataFlavorSupported(flavor: DataFlavor): Boolean = DataFlavor.stringFlavor.equals(flavor) @Throws(UnsupportedFlavorException::class) override fun getTransferData(flavor: DataFlavor): Any { @@ -77,7 +69,6 @@ object SystemUtils { } } - @Deprecated("Use RequestManager and Requests instead") @Throws(IOException::class) fun getRequest(urlString: String): String { @@ -99,37 +90,36 @@ object SystemUtils { if (PartlySaneSkies.config.printApiErrors) { sendClientMessage( """ - Error: ${httpURLConnection.getResponseMessage()}:${httpURLConnection.getResponseCode()} - Contact PSS admins for more information - """.trimIndent() + Error: ${httpURLConnection.getResponseMessage()}:${httpURLConnection.getResponseCode()} + Contact PSS admins for more information + """.trimIndent(), ) } else { log( Level.ERROR, """ - Error: ${httpURLConnection.getResponseMessage()}:${httpURLConnection.getResponseCode()} - Contact PSS admins for more information - """.trimIndent() + Error: ${httpURLConnection.getResponseMessage()}:${httpURLConnection.getResponseCode()} + Contact PSS admins for more information + """.trimIndent(), ) } log( Level.ERROR, """ - Error: ${httpURLConnection.getResponseMessage()}:${httpURLConnection.getResponseCode()} - URL: $urlString - """.trimIndent() + Error: ${httpURLConnection.getResponseMessage()}:${httpURLConnection.getResponseCode()} + URL: $urlString + """.trimIndent(), ) httpURLConnection.disconnect() "Error$responseCode" } } - /** * Checks if a string is a valid URL */ - fun isValidURL(urlString: String?): Boolean { - return try { + fun isValidURL(urlString: String?): Boolean = + try { // Create a URL object URL(urlString) @@ -139,7 +129,6 @@ object SystemUtils { // MalformedURLException is thrown if the URL is not valid false } - } /** * Opens a link in the default browser @@ -190,4 +179,4 @@ object SystemUtils { * @return True if the environment is a development environment */ fun isDevelopmentEnvironment(): Boolean = (Launch.blackboard["fml.deobfuscatedEnvironment"] as Boolean?) ?: false -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/geometry/orientation/Angle.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/geometry/orientation/Angle.kt index 1ea00cab9..964935969 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/geometry/orientation/Angle.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/geometry/orientation/Angle.kt @@ -12,98 +12,63 @@ class Angle private constructor(private val radians: Double) { /** * @return An angle object given a number of degrees */ - fun Number.toAngleFromDegrees(): Angle { - return Angle((PI / 180) * this.toDouble()) - } + fun Number.toAngleFromDegrees(): Angle = Angle((PI / 180) * this.toDouble()) /** * @return An angle object given a number of radians */ - fun Number.toAngleFromRadians(): Angle { - return Angle(this.toDouble()) - } + fun Number.toAngleFromRadians(): Angle = Angle(this.toDouble()) /** * @return The sine of an angle */ - fun sin(angle: Angle): Double { - return kotlin.math.sin(angle.asRadians()) - } + fun sin(angle: Angle): Double = kotlin.math.sin(angle.asRadians()) /** * @return The cosine of an angle */ - fun cos(angle: Angle): Double { - return kotlin.math.cos(angle.asRadians()) - } + fun cos(angle: Angle): Double = kotlin.math.cos(angle.asRadians()) /** * @return The tangent of an angle */ - fun tan(angle: Angle): Double { - return kotlin.math.tan(angle.asRadians()) - } + fun tan(angle: Angle): Double = kotlin.math.tan(angle.asRadians()) /** * @return The arc sine of an angle */ - fun asin(angle: Angle): Double { - return kotlin.math.asin(angle.asRadians()) - } + fun asin(angle: Angle): Double = kotlin.math.asin(angle.asRadians()) /** * @return The arc cosine of an angle */ - fun acos(angle: Angle): Double { - return kotlin.math.acos(angle.asRadians()) - } + fun acos(angle: Angle): Double = kotlin.math.acos(angle.asRadians()) /** * @return The arc tangent of an angle */ - fun atan(angle: Angle): Double { - return kotlin.math.atan(angle.asRadians()) - } - + fun atan(angle: Angle): Double = kotlin.math.atan(angle.asRadians()) } - /** * @return The number of degrees this angle represents */ - fun asDegrees(): Double { - return (180 / PI) * radians - } + fun asDegrees(): Double = (180 / PI) * radians /** * @return The number of radians this angle represents */ - fun asRadians(): Double { - return radians - } + fun asRadians(): Double = radians + operator fun minus(i: Number): Angle = Angle(radians - i.toDouble()) - operator fun minus(i: Number): Angle { - return Angle(radians - i.toDouble()) - } + operator fun plus(i: Number): Angle = Angle(radians + i.toDouble()) - operator fun plus(i: Number): Angle { - return Angle(radians + i.toDouble()) - } + operator fun div(i: Number): Angle = Angle(radians / i.toDouble()) - operator fun div(i: Number): Angle { - return Angle(radians / i.toDouble()) - } + operator fun times(i: Number): Angle = Angle(radians * i.toDouble()) - operator fun times(i: Number): Angle { - return Angle(radians * i.toDouble()) - } + operator fun rem(i: Number): Angle = Angle(radians % i.toDouble()) - operator fun rem(i: Number): Angle { - return Angle(radians % i.toDouble()) - } - - override fun toString(): String { - return "Angle(radians=$radians, degrees=${this.asDegrees()})" - } -} \ No newline at end of file + override fun toString(): String = "Angle(radians=$radians, degrees=${this.asDegrees()})" +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/geometry/orientation/Axis.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/geometry/orientation/Axis.kt index 05aaed580..79d03fe36 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/geometry/orientation/Axis.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/geometry/orientation/Axis.kt @@ -8,5 +8,5 @@ package me.partlysanestudios.partlysaneskies.utils.geometry.orientation enum class Axis { X_AXIS, Y_AXIS, - Z_AXIS -} \ No newline at end of file + Z_AXIS, +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/geometry/vectors/Point2d.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/geometry/vectors/Point2d.kt index 49b267e9c..c0f4bafb6 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/geometry/vectors/Point2d.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/geometry/vectors/Point2d.kt @@ -9,33 +9,21 @@ import kotlin.math.pow import kotlin.math.sqrt open class Point2d(val x: Double, val y: Double) { - fun getPointX(): Double { - return x - } + fun getPointX(): Double = x - fun getPointY(): Double { - return y - } + fun getPointY(): Double = y - fun distanceTo(point2: Point2d): Double { - return sqrt( + fun distanceTo(point2: Point2d): Double = + sqrt( (point2.getPointX() - this.getPointX()).pow(2.0) + - (point2.getPointY() - this.getPointY()).pow(2.0) + (point2.getPointY() - this.getPointY()).pow(2.0), ) - } - override fun toString(): String { - return "Point2d(x=$x, y=$y)" - } + override fun toString(): String = "Point2d(x=$x, y=$y)" + operator fun plus(point: Point2d): Point2d = Point2d(point.x + this.x, point.y + this.y) - operator fun plus(point: Point2d): Point2d { - return Point2d(point.x + this.x, point.y + this.y) - } - - operator fun minus(point: Point2d): Point2d { - return Point2d(point.x - this.x, point.y - this.y) - } + operator fun minus(point: Point2d): Point2d = Point2d(point.x - this.x, point.y - this.y) override fun equals(other: Any?): Boolean { if (this === other) return true @@ -54,4 +42,4 @@ open class Point2d(val x: Double, val y: Double) { result = 31 * result + y.hashCode() return result } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/geometry/vectors/Point3d.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/geometry/vectors/Point3d.kt index 8505cdaed..5349894e8 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/geometry/vectors/Point3d.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/geometry/vectors/Point3d.kt @@ -12,72 +12,50 @@ import net.minecraft.util.Vec3 import kotlin.math.pow import kotlin.math.sqrt -open class Point3d(x: Double, y: Double, val z: Double) : Point2d(x, y) { +open class Point3d( + x: Double, + y: Double, + val z: Double, +) : Point2d(x, y) { companion object { - fun atPlayer(): Point3d { - return Point3d( + fun atPlayer(): Point3d = + Point3d( minecraft.thePlayer?.posX ?: -1.0, minecraft.thePlayer?.posY ?: -1.0, - minecraft.thePlayer?.posZ ?: -1.0 + minecraft.thePlayer?.posZ ?: -1.0, ) - } - fun Vec3.toPoint3d(): Point3d { - return Point3d(this.xCoord, this.yCoord, this.zCoord) - } + fun Vec3.toPoint3d(): Point3d = Point3d(this.xCoord, this.yCoord, this.zCoord) - fun BlockPos.toPoint3d(): Point3d { - return Point3d(this.x.toDouble(), this.y.toDouble(), this.z.toDouble()) - } + fun BlockPos.toPoint3d(): Point3d = Point3d(this.x.toDouble(), this.y.toDouble(), this.z.toDouble()) } constructor(blockPos: BlockPos) : this(blockPos.x.toDouble(), blockPos.y.toDouble(), blockPos.z.toDouble()) - fun getPointZ(): Double { - return z - } + fun getPointZ(): Double = z - fun distanceToPlayer(): Double { - return this.distanceTo(atPlayer()) - } + fun distanceToPlayer(): Double = this.distanceTo(atPlayer()) - fun toBlockPos(): BlockPos { - return BlockPos(x, y, z) - } + fun toBlockPos(): BlockPos = BlockPos(x, y, z) - fun toBlockPosInt(): BlockPos { - return BlockPos(x.toInt(), y.toInt(), z.toInt()) - } + fun toBlockPosInt(): BlockPos = BlockPos(x.toInt(), y.toInt(), z.toInt()) - fun distanceTo(point2: Point3d): Double { - return sqrt( + fun distanceTo(point2: Point3d): Double = + sqrt( (point2.getPointX() - this.getPointX()).pow(2.0) + - (point2.getPointY() - this.getPointY()).pow(2.0) + - (point2.getPointZ() - this.getPointZ()).pow(2.0) + (point2.getPointY() - this.getPointY()).pow(2.0) + + (point2.getPointZ() - this.getPointZ()).pow(2.0), ) - } - - - override fun toString(): String { - return "Point3d(${super.toString()}, z=$z)" - } + override fun toString(): String = "Point3d(${super.toString()}, z=$z)" - fun getBlockAtPoint(): Block? { - return minecraft.theWorld.getBlockState(this.toBlockPos())?.block - } + fun getBlockAtPoint(): Block? = minecraft.theWorld.getBlockState(this.toBlockPos())?.block - fun toChunk(): Point2d { - return Point2d((this.x / 16).toInt().toDouble(), (this.z / 16).toInt().toDouble()) - } + fun toChunk(): Point2d = Point2d((this.x / 16).toInt().toDouble(), (this.z / 16).toInt().toDouble()) - operator fun plus(point: Point3d): Point3d { - return Point3d(point.x + this.x, point.y + this.y, point.z + this.z) - } + operator fun plus(point: Point3d): Point3d = Point3d(point.x + this.x, point.y + this.y, point.z + this.z) - operator fun minus(point: Point3d): Point3d { - return Point3d(point.x - this.x, point.y - this.y, point.z - this.z) - } + operator fun minus(point: Point3d): Point3d = Point3d(point.x - this.x, point.y - this.y, point.z - this.z) override fun equals(other: Any?): Boolean { if (this === other) return true @@ -94,4 +72,4 @@ open class Point3d(x: Double, y: Double, val z: Double) : Point2d(x, y) { result = 31 * result + z.hashCode() return result } -} \ No newline at end of file +} diff --git a/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/geometry/vectors/Range3d.kt b/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/geometry/vectors/Range3d.kt index 25771d183..201178d05 100644 --- a/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/geometry/vectors/Range3d.kt +++ b/src/main/kotlin/me/partlysanestudios/partlysaneskies/utils/geometry/vectors/Range3d.kt @@ -10,25 +10,25 @@ import kotlin.math.min class Range3d(private val point1: Point3d, private val point2: Point3d) { constructor(x1: Double, y1: Double, z1: Double, x2: Double, y2: Double, z2: Double) : this( Point3d(x1, y1, z1), - Point3d(x2, y2, z2) + Point3d(x2, y2, z2), ) var rangeName: String = "" - private val smallCoordinate = Point3d( - min(point1.x, point2.x), - min(point1.y, point1.y), - min(point1.z, point2.z) - ) - private val largeCoordinate = Point3d( - max(point1.x, point2.x), - max(point1.y, point2.y), - max(point1.z, point2.z) - ) + private val smallCoordinate = + Point3d( + min(point1.x, point2.x), + min(point1.y, point1.y), + min(point1.z, point2.z), + ) + private val largeCoordinate = + Point3d( + max(point1.x, point2.x), + max(point1.y, point2.y), + max(point1.z, point2.z), + ) - fun isInRange(point3d: Point3d): Boolean { - return isInRange(point3d.x, point3d.y, point3d.z) - } + fun isInRange(point3d: Point3d): Boolean = isInRange(point3d.x, point3d.y, point3d.z) fun isInRange(x: Double, y: Double, z: Double): Boolean { if (smallCoordinate.x <= x && x - 1 <= largeCoordinate.x) { @@ -40,20 +40,14 @@ class Range3d(private val point1: Point3d, private val point2: Point3d) { } val sortedPoints: Array - get() { - return arrayOf( - Point3d(smallCoordinate.x, smallCoordinate.y, smallCoordinate.z), - Point3d(largeCoordinate.x, largeCoordinate.y, largeCoordinate.z) - ) - } - + get() = arrayOf( + Point3d(smallCoordinate.x, smallCoordinate.y, smallCoordinate.z), + Point3d(largeCoordinate.x, largeCoordinate.y, largeCoordinate.z), + ) val points: Array - get() { - return arrayOf(Point3d(point1.x, point1.y, point1.z), Point3d(point2.x, point2.y, point2.z)) - } - //POINT 2D AND 3D - + get() = arrayOf(Point3d(point1.x, point1.y, point1.z), Point3d(point2.x, point2.y, point2.z)) + // POINT 2D AND 3D override fun equals(other: Any?): Boolean { if (this === other) return true @@ -68,7 +62,5 @@ class Range3d(private val point1: Point3d, private val point2: Point3d) { return result } - override fun toString(): String { - return "Range3d(smallCoordinate=$smallCoordinate, largeCoordinate=$largeCoordinate, rangeName='$rangeName')" - } -} \ No newline at end of file + override fun toString(): String = "Range3d(smallCoordinate=$smallCoordinate, largeCoordinate=$largeCoordinate, rangeName='$rangeName')" +} diff --git a/src/main/resources/assets/partlysaneskies/sounds.json b/src/main/resources/assets/partlysaneskies/sounds.json index 6768364bf..4188874b9 100644 --- a/src/main/resources/assets/partlysaneskies/sounds.json +++ b/src/main/resources/assets/partlysaneskies/sounds.json @@ -1,461 +1,461 @@ { - "rngdropjingle": { - "category": "master", - "sounds": [ - { - "name": "partlysaneskies:rngdropjingle", - "stream": true - } - ] - }, - "airraidsiren": { - "category": "master", - "sounds": [ - { - "name": "partlysaneskies:airraidsiren", - "stream": true - } - ] - }, - "bell": { - "category": "master", - "sounds": [ - { - "name": "partlysaneskies:bell", - "stream": false - } - ] - }, - "flute_scale": { - "category": "master", - "sounds": [ - { - "name": "partlysaneskies:flute_scale", - "stream": false - } - ] - }, - "tenor_piano": { - "category": "record", - "sounds": [ - { - "name": "partlysaneskies:tenor_piano", - "stream": false - } - ] - }, - "alto_piano": { - "category": "record", - "sounds": [ - { - "name": "partlysaneskies:alto_piano", - "stream": false - } - ] - }, - "bass_piano": { - "category": "record", - "sounds": [ - { - "name": "partlysaneskies:bass_piano", - "stream": false - } - ] - }, - "tenor_clarinet": { - "category": "record", - "sounds": [ - { - "name": "partlysaneskies:tenor_clarinet", - "stream": false - } - ] - }, - "alto_clarinet": { - "category": "record", - "sounds": [ - { - "name": "partlysaneskies:alto_clarinet", - "stream": false - } - ] - }, - "bass_clarinet": { - "category": "record", - "sounds": [ - { - "name": "partlysaneskies:bass_clarinet", - "stream": false - } - ] - }, - "tenor_electric_piano": { - "category": "record", - "sounds": [ - { - "name": "partlysaneskies:tenor_electric_piano", - "stream": false - } - ] - }, - "alto_electric_piano": { - "category": "record", - "sounds": [ - { - "name": "partlysaneskies:alto_electric_piano", - "stream": false - } - ] - }, - "bass_electric_piano": { - "category": "record", - "sounds": [ - { - "name": "partlysaneskies:bass_electric_piano", - "stream": false - } - ] - }, - "tenor_flute": { - "category": "record", - "sounds": [ - { - "name": "partlysaneskies:tenor_flute", - "stream": false - } - ] - }, - "alto_flute": { - "category": "record", - "sounds": [ - { - "name": "partlysaneskies:alto_flute", - "stream": false - } - ] - }, - "bass_flute": { - "category": "record", - "sounds": [ - { - "name": "partlysaneskies:bass_flute", - "stream": false - } - ] - }, - "tenor_organ": { - "category": "record", - "sounds": [ - { - "name": "partlysaneskies:tenor_organ", - "stream": false - } - ] - }, - "alto_organ": { - "category": "record", - "sounds": [ - { - "name": "partlysaneskies:alto_organ", - "stream": false - } - ] - }, - "bass_organ": { - "category": "record", - "sounds": [ - { - "name": "partlysaneskies:bass_organ", - "stream": false - } - ] - }, - "tenor_string_ensemble": { - "category": "record", - "sounds": [ - { - "name": "partlysaneskies:tenor_string_ensemble", - "stream": false - } - ] - }, - "alto_string_ensemble": { - "category": "record", - "sounds": [ - { - "name": "partlysaneskies:alto_string_ensemble", - "stream": false - } - ] - }, - "bass_string_ensemble": { - "category": "record", - "sounds": [ - { - "name": "partlysaneskies:bass_string_ensemble", - "stream": false - } - ] - }, - "tenor_trombone": { - "category": "record", - "sounds": [ - { - "name": "partlysaneskies:tenor_trombone", - "stream": false - } - ] - }, - "alto_trombone": { - "category": "record", - "sounds": [ - { - "name": "partlysaneskies:alto_trombone", - "stream": false - } - ] - }, - "bass_trombone": { - "category": "record", - "sounds": [ - { - "name": "partlysaneskies:bass_trombone", - "stream": false - } - ] - }, - "tenor_trumpet": { - "category": "record", - "sounds": [ - { - "name": "partlysaneskies:tenor_trumpet", - "stream": false - } - ] - }, - "alto_trumpet": { - "category": "record", - "sounds": [ - { - "name": "partlysaneskies:alto_trumpet", - "stream": false - } - ] - }, - "bass_trumpet": { - "category": "record", - "sounds": [ - { - "name": "partlysaneskies:bass_trumpet", - "stream": false - } - ] - }, - "tenor_violin": { - "category": "record", - "sounds": [ - { - "name": "partlysaneskies:tenor_violin", - "stream": false - } - ] - }, - "alto_violin": { - "category": "record", - "sounds": [ - { - "name": "partlysaneskies:alto_violin", - "stream": false - } - ] - }, - "bass_violin": { - "category": "record", - "sounds": [ - { - "name": "partlysaneskies:bass_violin", - "stream": false - } - ] - }, - "tenor_wind_ensemble": { - "category": "record", - "sounds": [ - { - "name": "partlysaneskies:tenor_wind_ensemble", - "stream": false - } - ] - }, - "alto_wind_ensemble": { - "category": "record", - "sounds": [ - { - "name": "partlysaneskies:alto_wind_ensemble", - "stream": false - } - ] - }, - "bass_wind_ensemble": { - "category": "record", - "sounds": [ - { - "name": "partlysaneskies:bass_wind_ensemble", - "stream": false - } - ] - }, - "tenor_live_clarinet": { - "category": "record", - "sounds": [ - { - "name": "partlysaneskies:tenor_live_clarinet", - "stream": false - } - ] - }, - "alto_live_clarinet": { - "category": "record", - "sounds": [ - { - "name": "partlysaneskies:alto_live_clarinet", - "stream": false - } - ] - }, - "bass_live_clarinet": { - "category": "record", - "sounds": [ - { - "name": "partlysaneskies:bass_live_clarinet", - "stream": false - } - ] - }, - "tenor_kazoo": { - "category": "record", - "sounds": [ - { - "name": "partlysaneskies:tenor_kazoo", - "stream": false - } - ] - }, - "alto_kazoo": { - "category": "record", - "sounds": [ - { - "name": "partlysaneskies:alto_kazoo", - "stream": false - } - ] - }, - "bass_kazoo": { - "category": "record", - "sounds": [ - { - "name": "partlysaneskies:bass_kazoo", - "stream": false - } - ] - }, - "tenor_discord_sound": { - "category": "record", - "sounds": [ - { - "name": "partlysaneskies:tenor_discord_sound", - "stream": false - } - ] - }, - "alto_discord_sound": { - "category": "record", - "sounds": [ - { - "name": "partlysaneskies:alto_discord_sound", - "stream": false - } - ] - }, - "bass_discord_sound": { - "category": "record", - "sounds": [ - { - "name": "partlysaneskies:bass_discord_sound", - "stream": false - } - ] - }, - "explosion": { - "category": "record", - "sounds": [ - { - "name": "partlysaneskies:explosion", - "stream": false - } - ] - }, - "prank0": { - "category": "master", - "sounds": [ - { - "name": "partlysaneskies:prank0", - "stream": true - } - ] - }, - "prank1": { - "category": "master", - "sounds": [ - { - "name": "partlysaneskies:prank1", - "stream": true - } - ] - }, - "prank2": { - "category": "master", - "sounds": [ - { - "name": "partlysaneskies:prank2", - "stream": true - } - ] - }, - "prank3": { - "category": "master", - "sounds": [ - { - "name": "partlysaneskies:prank3", - "stream": true - } - ] - }, - "prank4": { - "category": "master", - "sounds": [ - { - "name": "partlysaneskies:prank4", - "stream": true - } - ] - }, - "prank5": { - "category": "master", - "sounds": [ - { - "name": "partlysaneskies:prank5", - "stream": true - } - ] - }, - "prank6": { - "category": "master", - "sounds": [ - { - "name": "partlysaneskies:prank6", - "stream": true - } - ] - } -} \ No newline at end of file + "rngdropjingle": { + "category": "master", + "sounds": [ + { + "name": "partlysaneskies:rngdropjingle", + "stream": true + } + ] + }, + "airraidsiren": { + "category": "master", + "sounds": [ + { + "name": "partlysaneskies:airraidsiren", + "stream": true + } + ] + }, + "bell": { + "category": "master", + "sounds": [ + { + "name": "partlysaneskies:bell", + "stream": false + } + ] + }, + "flute_scale": { + "category": "master", + "sounds": [ + { + "name": "partlysaneskies:flute_scale", + "stream": false + } + ] + }, + "tenor_piano": { + "category": "record", + "sounds": [ + { + "name": "partlysaneskies:tenor_piano", + "stream": false + } + ] + }, + "alto_piano": { + "category": "record", + "sounds": [ + { + "name": "partlysaneskies:alto_piano", + "stream": false + } + ] + }, + "bass_piano": { + "category": "record", + "sounds": [ + { + "name": "partlysaneskies:bass_piano", + "stream": false + } + ] + }, + "tenor_clarinet": { + "category": "record", + "sounds": [ + { + "name": "partlysaneskies:tenor_clarinet", + "stream": false + } + ] + }, + "alto_clarinet": { + "category": "record", + "sounds": [ + { + "name": "partlysaneskies:alto_clarinet", + "stream": false + } + ] + }, + "bass_clarinet": { + "category": "record", + "sounds": [ + { + "name": "partlysaneskies:bass_clarinet", + "stream": false + } + ] + }, + "tenor_electric_piano": { + "category": "record", + "sounds": [ + { + "name": "partlysaneskies:tenor_electric_piano", + "stream": false + } + ] + }, + "alto_electric_piano": { + "category": "record", + "sounds": [ + { + "name": "partlysaneskies:alto_electric_piano", + "stream": false + } + ] + }, + "bass_electric_piano": { + "category": "record", + "sounds": [ + { + "name": "partlysaneskies:bass_electric_piano", + "stream": false + } + ] + }, + "tenor_flute": { + "category": "record", + "sounds": [ + { + "name": "partlysaneskies:tenor_flute", + "stream": false + } + ] + }, + "alto_flute": { + "category": "record", + "sounds": [ + { + "name": "partlysaneskies:alto_flute", + "stream": false + } + ] + }, + "bass_flute": { + "category": "record", + "sounds": [ + { + "name": "partlysaneskies:bass_flute", + "stream": false + } + ] + }, + "tenor_organ": { + "category": "record", + "sounds": [ + { + "name": "partlysaneskies:tenor_organ", + "stream": false + } + ] + }, + "alto_organ": { + "category": "record", + "sounds": [ + { + "name": "partlysaneskies:alto_organ", + "stream": false + } + ] + }, + "bass_organ": { + "category": "record", + "sounds": [ + { + "name": "partlysaneskies:bass_organ", + "stream": false + } + ] + }, + "tenor_string_ensemble": { + "category": "record", + "sounds": [ + { + "name": "partlysaneskies:tenor_string_ensemble", + "stream": false + } + ] + }, + "alto_string_ensemble": { + "category": "record", + "sounds": [ + { + "name": "partlysaneskies:alto_string_ensemble", + "stream": false + } + ] + }, + "bass_string_ensemble": { + "category": "record", + "sounds": [ + { + "name": "partlysaneskies:bass_string_ensemble", + "stream": false + } + ] + }, + "tenor_trombone": { + "category": "record", + "sounds": [ + { + "name": "partlysaneskies:tenor_trombone", + "stream": false + } + ] + }, + "alto_trombone": { + "category": "record", + "sounds": [ + { + "name": "partlysaneskies:alto_trombone", + "stream": false + } + ] + }, + "bass_trombone": { + "category": "record", + "sounds": [ + { + "name": "partlysaneskies:bass_trombone", + "stream": false + } + ] + }, + "tenor_trumpet": { + "category": "record", + "sounds": [ + { + "name": "partlysaneskies:tenor_trumpet", + "stream": false + } + ] + }, + "alto_trumpet": { + "category": "record", + "sounds": [ + { + "name": "partlysaneskies:alto_trumpet", + "stream": false + } + ] + }, + "bass_trumpet": { + "category": "record", + "sounds": [ + { + "name": "partlysaneskies:bass_trumpet", + "stream": false + } + ] + }, + "tenor_violin": { + "category": "record", + "sounds": [ + { + "name": "partlysaneskies:tenor_violin", + "stream": false + } + ] + }, + "alto_violin": { + "category": "record", + "sounds": [ + { + "name": "partlysaneskies:alto_violin", + "stream": false + } + ] + }, + "bass_violin": { + "category": "record", + "sounds": [ + { + "name": "partlysaneskies:bass_violin", + "stream": false + } + ] + }, + "tenor_wind_ensemble": { + "category": "record", + "sounds": [ + { + "name": "partlysaneskies:tenor_wind_ensemble", + "stream": false + } + ] + }, + "alto_wind_ensemble": { + "category": "record", + "sounds": [ + { + "name": "partlysaneskies:alto_wind_ensemble", + "stream": false + } + ] + }, + "bass_wind_ensemble": { + "category": "record", + "sounds": [ + { + "name": "partlysaneskies:bass_wind_ensemble", + "stream": false + } + ] + }, + "tenor_live_clarinet": { + "category": "record", + "sounds": [ + { + "name": "partlysaneskies:tenor_live_clarinet", + "stream": false + } + ] + }, + "alto_live_clarinet": { + "category": "record", + "sounds": [ + { + "name": "partlysaneskies:alto_live_clarinet", + "stream": false + } + ] + }, + "bass_live_clarinet": { + "category": "record", + "sounds": [ + { + "name": "partlysaneskies:bass_live_clarinet", + "stream": false + } + ] + }, + "tenor_kazoo": { + "category": "record", + "sounds": [ + { + "name": "partlysaneskies:tenor_kazoo", + "stream": false + } + ] + }, + "alto_kazoo": { + "category": "record", + "sounds": [ + { + "name": "partlysaneskies:alto_kazoo", + "stream": false + } + ] + }, + "bass_kazoo": { + "category": "record", + "sounds": [ + { + "name": "partlysaneskies:bass_kazoo", + "stream": false + } + ] + }, + "tenor_discord_sound": { + "category": "record", + "sounds": [ + { + "name": "partlysaneskies:tenor_discord_sound", + "stream": false + } + ] + }, + "alto_discord_sound": { + "category": "record", + "sounds": [ + { + "name": "partlysaneskies:alto_discord_sound", + "stream": false + } + ] + }, + "bass_discord_sound": { + "category": "record", + "sounds": [ + { + "name": "partlysaneskies:bass_discord_sound", + "stream": false + } + ] + }, + "explosion": { + "category": "record", + "sounds": [ + { + "name": "partlysaneskies:explosion", + "stream": false + } + ] + }, + "prank0": { + "category": "master", + "sounds": [ + { + "name": "partlysaneskies:prank0", + "stream": true + } + ] + }, + "prank1": { + "category": "master", + "sounds": [ + { + "name": "partlysaneskies:prank1", + "stream": true + } + ] + }, + "prank2": { + "category": "master", + "sounds": [ + { + "name": "partlysaneskies:prank2", + "stream": true + } + ] + }, + "prank3": { + "category": "master", + "sounds": [ + { + "name": "partlysaneskies:prank3", + "stream": true + } + ] + }, + "prank4": { + "category": "master", + "sounds": [ + { + "name": "partlysaneskies:prank4", + "stream": true + } + ] + }, + "prank5": { + "category": "master", + "sounds": [ + { + "name": "partlysaneskies:prank5", + "stream": true + } + ] + }, + "prank6": { + "category": "master", + "sounds": [ + { + "name": "partlysaneskies:prank6", + "stream": true + } + ] + } +} diff --git a/src/main/resources/mcmod.info b/src/main/resources/mcmod.info index ca72e4ea5..61dc2759e 100644 --- a/src/main/resources/mcmod.info +++ b/src/main/resources/mcmod.info @@ -1,19 +1,19 @@ [ - { - "modid": "${mod_id}", - "name": "${mod_name}", - "description": "${mod_description}", - "version": "${mod_version}", - "mcversion": "${mc_version}", - "url": "https://github.com/PartlySaneStudios/partly-sane-skies", - "updateUrl": "", - "authorList": [ - "Su386", - "FlagMaster" - ], - "credits": "Su386 and FlagMaster and the rest of the Partly Sane Studios Team. See CREDITS for more information.", - "logoFile": "", - "screenshots": [], - "dependencies": [] - } + { + "modid": "${mod_id}", + "name": "${mod_name}", + "description": "${mod_description}", + "version": "${mod_version}", + "mcversion": "${mc_version}", + "url": "https://github.com/PartlySaneStudios/partly-sane-skies", + "updateUrl": "", + "authorList": [ + "Su386", + "FlagMaster" + ], + "credits": "Su386 and FlagMaster and the rest of the Partly Sane Studios Team. See CREDITS for more information.", + "logoFile": "", + "screenshots": [], + "dependencies": [] + } ] diff --git a/src/main/resources/mixins.pss.json b/src/main/resources/mixins.pss.json index 8db7437b2..163b733e8 100644 --- a/src/main/resources/mixins.pss.json +++ b/src/main/resources/mixins.pss.json @@ -1,13 +1,13 @@ { - "package": "me.partlysanestudios.partlysaneskies.mixin", - "mixins": [ - "mods.MixinDungeonGuideCollectDiagnostics", - "mods.MixinEssentialsTelemetryManager" - ], - "client": [ - "minecraft.accessors.GuiChestAccessor", - "minecraft.accessors.GuiContainerAccessor", - "minecraft.accessors.GuiPlayerTabOverlayAccessor", - "minecraft.MixinPlayerControllerMP" - ] + "package": "me.partlysanestudios.partlysaneskies.mixin", + "mixins": [ + "mods.MixinDungeonGuideCollectDiagnostics", + "mods.MixinEssentialsTelemetryManager" + ], + "client": [ + "minecraft.MixinPlayerControllerMP", + "minecraft.accessors.GuiChestAccessor", + "minecraft.accessors.GuiContainerAccessor", + "minecraft.accessors.GuiPlayerTabOverlayAccessor" + ] }